repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/ADV1K/ADV1K
https://raw.githubusercontent.com/ADV1K/ADV1K/main/resume/resume.typ
typst
#import "yml.typ": yml_resume #let resume_data = toml("../resume.toml") #yml_resume(resume_data)
https://github.com/chamik/gympl-skripta
https://raw.githubusercontent.com/chamik/gympl-skripta/main/cj-autori/hemingway.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/helper.typ": autor #autor("<NAME>", "1899", "1961 (62 let)", "spisovatel, novinář", "Oak Park and River Forest High School", "ztracená generace, modernismus", "/cj-autori/media/hemingway.jpg") <NAME> byl americký spisovatel, narozený 21. července 1899 a zemřelý 2. července 1961. Jeho život a literární kariéra se odehrály v období mezi první a druhou světovou válkou a během studené války. Hemingway byl silně ovlivněn svými zkušenostmi jako válečný zpravodaj, lovec a cestovatel. Hemingwayho názory byly formovány jeho osobními zkušenostmi a vnímáním světa kolem něj. Byl známý svou maskulinní image a láskou k dobrodružství a riziku. Jeho literatura často reflektovala jeho zájem o témata jako je mužnost, síla lidské vůle a existence v tvrdých podmínkách. Umělecky Hemingway zastupoval literární směr známý jako modernismus, ve kterém byl charakteristický jednoduchým a strohým stylem psaní, který se soustředil na esenciální prvky a vyhýbal se zbytečným zdobením. Jeho díla jsou často považována za příklad tzv. "metody ledovce", kde pod povrchem zdánlivě jednoduchých situací skrývá složité a hluboké emocionální a filozofické témata. Pro víc info viz otázku z angličtiny @hemingway[]. Mezi jeho známá díla patří: 1. *Sbohem, armádo (A Farewell to Arms)* -- Román, který se odehrává během první světové války a sleduje příběh amerického dobrovolníka v italské armádě, který se zamiluje do anglické zdravotní sestry. Utečou spolu, ovšem jeho milenka potratí. Silně autobiografické. 2. *Komu zvoní hrana (For Whom the Bell Tolls)* -- Román, který se odehrává během španělské občanské války a sleduje příběh amerického dobrovolníka, který se zapojí do boje proti fašistům. Hemingway v tomto díle zkoumá téma války, solidarity a lidské morálky. *Současníci*\ _<NAME>_ -- Petr a Lucie, 1920 \ _<NAME>_ -- Na západní frontě klid (@zapadni[]), 1928\ _<NAME>_ -- Osudy dobrého vojáka Švejka, 1923\ #pagebreak()
https://github.com/daskol/typst-templates
https://raw.githubusercontent.com/daskol/typst-templates/main/jmlr/main.typ
typst
MIT License
#import "/jmlr.typ": jmlr #import "/blindtext.typ": blindtext, blindmathpaper #let affls = ( one: ( department: "Department of Statistics", institution: "University of Washington", location: "Seattle, WA 98195-4322", country: "USA"), two: ( department: "Division of Computer Science", institution: "University of California", location: "Berkeley, CA 94720-1776", country: "USA"), ) #let authors = ( (name: "<NAME>", affl: "one", email: "<EMAIL>"), (name: "<NAME>", affl: "two", email: "<EMAIL>"), ) #show: jmlr.with( title: [Sample JMLR Paper], authors: (authors, affls), abstract: blindtext, keywords: ("keyword one", "keyword two", "keyword three"), bibliography: bibliography("main.bib"), appendix: include "appendix.typ", pubdata: ( id: "21-0000", editor: "<NAME>", volume: 23, submitted-at: datetime(year: 2021, month: 1, day: 1), revised-at: datetime(year: 2022, month: 5, day: 1), published-at: datetime(year: 2022, month: 9, day: 1), ), ) = Introduction #set math.equation(numbering: none) // There are no numbers in sample paper. #blindmathpaper Here is a citation @chow68. = Acknowledgments and Disclosure of Funding All acknowledgements go at the end of the paper before appendices and references. Moreover, you are required to declare funding (financial activities supporting the submitted work) and competing interests (related financial activities outside the submitted work). More information about this disclosure can be found on the JMLR website.
https://github.com/MultisampledNight/flow
https://raw.githubusercontent.com/MultisampledNight/flow/main/src/keywords.typ
typst
MIT License
#import "cfg.typ": render #let char-that-does-nothing = "\u{200B}" #let do-not-process(it) = { // this is a hack to make sure other show rules do not process the same `it` // but it works it.text.at(0) char-that-does-nothing it.text.slice(1) } #let normalize(it) = { lower(it.at(0)) it.slice(1) } // Constructs a regex that matches any entry in the `keywords` array, // even if their first characters are capitalized. #let construct-picker(keywords) = regex({ "\b(" keywords .map(word => { // make it irrelevant if the first character is uppercase or lowercase "(" word.at(0) "|" upper(word.at(0)) ")" word.slice(1) }) .join("|") ")\b" }) // Finds the appropriate operation for the given keyword and applies it. #let apply-one(selected, registered) = { let original = normalize(selected.text) let op = registered.at(original) op(selected) } #let process(body, cfg: none) = { if cfg == none or not render { // no words to highlight → nothing to do! return body } // see the schema in src/info.typ for possible types cfg can have if type(cfg) == array { let converted = (:) for word in cfg { converted.insert(word, strong) } cfg = converted } // normalize all keys so the lookup normalization can find something for (word, op) in cfg { let _ = cfg.remove(word) cfg.insert(normalize(word), op) } // then actually run through let picker = construct-picker(cfg.keys()) // skip codeblocks show raw: it => { show picker: do-not-process it } // but do apply to everything else show picker: it => apply-one(it, cfg) body }
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/tests/blocks/test.typ
typst
MIT License
#import "/src/lib.typ": dropcap #set page(width: 6cm, height: auto, margin: 1em) // Test block content within a dropcap. #dropcap(height: 1cm, gap: 4pt)[ Einstein said that mass and energy go like $ E = m c^2 $ and it was true (mostly). ] #dropcap(height: 1cm, gap: 3pt)[ There is a rectangle below #align(center, rect()) but it's still beside the first letter. ]
https://github.com/Dioprz/Notes
https://raw.githubusercontent.com/Dioprz/Notes/main/Scala/Functional_Programming_in_Scala/Chapter_2.typ
typst
#set page(margin: 1.75in) // #set par(leading: 0.55em, first-line-indent: 1.8em, justify: true) #set par(leading: 0.55em, justify: true) #set text(font: "New Computer Modern") #show par: set block(spacing: 1.4em) #show heading: set block(above: 1.4em, below: 1em) #show raw.where(block: false): box.with( fill: luma(220), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 0pt, ) = Capítulo 2: Comenzando con la FP en Scala == Conceptos y observaciones / Objects: Son un _tipo_ singletón que se pueden interpretar como clases con una única instancia. / Higher order function: Funciones que aceptan o retornan otras funciones. / Función polimórfica: Funciones que generalizan sobre los tipos que puede manipular la función, brindando argumentos de tipo. / Trait: Son el equivalente de Scala a las interfaces de Java, aunque estas también permiten definir implementaciones concretas de sus métodos. - En Java se suelen utilizar clases anónimas para crear e instanciar rápidamente una clase que implementa una interfaz particular. Este comportamiento es similar al que tienen los `object` en Scala. #block(inset: 10pt)[_Nota_: Los `object` pueden ser utilizados para simular el comportamiento de la keyword `static` de Java.] - Conforme la complejidad de un proyecto crece, se hace inviable gestionar la compilación (scalac) y administración de cada uno de los archivos del proyecto. Para cubrir esta necesidad se suele usar el Scala Build Tool (_sbt_), que tras declarar y configurar su archivo, trackea y compila apropiadamente los archivos. - Scala no tiene nociones especiales de _operadores_, y a efectos prácticos, *todo* es un objeto (no hay primitivos como en Java, por ejemplo). Por lo tanto `2 + 1` no es más que azucar sintáctico para `2.+(1)`. - Los métodos unarios pueden usar notación infija. Si `abs` calcula el valor absoluto, `abs(42) == abs 42`. - La noción de _namespace_ corresponde a ver cada nombre en la notación clásica de punto (`Object1.Object2.val`), como un espacio que almacena _miembros_. Así, en la expresión `Object1.Object2.val`, `Object2` tiene como _namespace_ `Object1` ya que es un miembro de él. Así mismo, `val` tiene como _namespace_ a `Object1.Object2` y es miembro de `Object2` (y, posiblemente, de `Object1` también). Un objeto cuya única finalidad es ser el namespace de un conjunto de miembros, es llamado _módulo_ (de aquí que tenga sentido llamar también módulo a los `object`). - Es preferible hacer iteraciones mediante funciones recursivas que mediante loops o whiles. En Scala el performance de estos dos últimos es idéntico al obtenido por una función recursiva *cuando* dicha función usa _tail recursion_. (Esto evita añadir llamados a la pila de llamadas (call stack)). El compilador de Scala es capaz de generar un error si una función que debería usar tail recursion, no la está haciendo. Para esto se usa la anotación `@annotation.tailrec`. - La versión más general de función hasta el momento, es la de una _función polimórfica_; estas funciones tienen 2 tipos de argumentos: 1. Variables de tipo, usables en el resto de la firma de la función por las variables ordinarias o el retorno. 2. Variables ordinarias, usables en el cuerpo de la función. Note tambien que las funciones polimórficas o genéricas añaden una restricción importante: _El cuerpo de las funciones sólo puede usar, en general, funciones que les han sido pasadas como argumentos._ Tal característica hace qué, en ocasiones, baste saber la firma con los tipos de una función, para poder construir una implementación _"canónica"_ de esa función. El ejemplo de la aplicación parcial con firma ```scala def partial1[A,B,C](a: A, f: (A,B) => C): B => C ``` es particularmente ilustrativa sobre esto. - Las funciones anónimas de Scala no son más que la creación de un `object` con método `apply`. Este método permite llamar al objeto como si él mismo fuera el método apply. Estos objetos son creados a partir del trait `Function<n>`, un trait de Scala que define el método `apply` n-ario. == Conclusiones - Los `object` de Scala son un 'shortcut' para crear una clase que se instancia inmediatamente. - Las importaciones de un módulo completo usan la notación de variable anónima, por lo qué, para importar todos los miembros de un módulo, basta usar `import MyModule._`. - Las funciones de Scala pueden tener parámetros tanto de tipo como de la función. - Los tipos en funciones genéricas tienen el potencial para determinar su implementación en base únicamente a su firma. Esto es, los tipos permiten derivar una implementación.
https://github.com/goshakowska/Typstdiff
https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_complex/text_formats/text_formats_updated.typ
typst
= Heading1 Paragraph with quotes “This is super quotes.” #strong[Date:] 26.02.2024 \ Date used in paragraph #strong[Date:] 30.12.2022 \ #strong[Topic:] Infrastructure Test \ #strong[Severity:] High \ = Heading3 #emph[emphasis] Some normal TEXT #text(font: "Linux Libertine", style: "italic")[Italic] #upper[*my new text*] \ #upper[ALREADY ALREADY] #link("https://something.app/") = Heading4 #lower("ABC") Link in paragraph: #link("https://something.app/") = Heading5
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/raw-code-03.typ
typst
Other
#set page(width: 180pt) #set text(6pt) ```cpp #include <iostream> int main() { std::cout << "Hello, world!"; } ```
https://github.com/mattheww/tyroshup
https://raw.githubusercontent.com/mattheww/tyroshup/funcalls/funcalls/conf.typ
typst
#let conf(doc) = { let copyright_message = "Copyright © The Ferrocene Developers. Contents released under the MIT or Apache 2.0 license." set page( footer: copyright_message, ) show heading.where(level: 1): content => [ #pagebreak(weak: true) #set block(below: 1em) #content ] show heading.where(level: 2): content => [ #set block(above: 2em, below: 1em) #content ] show heading.where(level: 3): content => [ #set block(below: 1em) #content ] show link: set text(blue) set heading(numbering: "1.1.1") show "%SKIPPING%": name => text(green)[(((...)))] doc }
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/009_Return%20to%20Dominaria%3A%20Episode%209.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Return to Dominaria: Episode 9", set_name: "Dominaria", story_date: datetime(day: 09, month: 05, year: 2018), author: "<NAME>", doc ) Chandra paced back and forth on the loose dirt near Karn's crater, waving her hands. "Are you kidding me? You've been lying all this time? Why?" They were surrounded by piles of smoldering trees and pieces of wrecked automatons, the air heavy with smoke. Furious, she faced Luti. Or Jaya. Or whoever this was. "Why would you do this to me?" "Not everything is about you, Chandra." Jaya was annoyingly calm. Chandra seethed. She really wanted to set something on fire, but had just enough control of her temper to know that would be a bad, bad idea. "So what were you doing in Keral Keep, then?" Jaya looked amused. "I didn't go there for you, believe it or not. I was there years before you showed up." Chandra set her jaw. "Pretending to be Mother Luti? Why?" Jaya sighed. "A long time ago, I went to Regatha, helped a few people, got drunk, talked a lot, apparently did some very impressive pyromancy, then left. Two hundred years later, I went back and found they'd started a religion based on me." She folded her arms and admitted, "It was all a little embarrassing, frankly." Karn looked from Chandra to Jaya and back, and then clearly decided this was not an argument he wanted to be involved in. He turned and strode back toward the crater, the surviving automatons clanking after him. Chandra pressed her hands to her head and tried not to pull her hair out in exasperation. "Then why go back at all? Why stay at Keral Keep pretending to be somebody else?" "I didn't want to be a religious icon, but I had to make sure they weren't misrepresenting me!" Jaya said, as if it was obvious. "And I thought I owed them a little guidance. Where do you think the monastery kept getting those 'long-lost writings of <NAME>' from?" Chandra's jaw dropped. Jaya laughed. "Oh, don't look like that." She sighed and her expression turned serious. "I felt guilty. I never meant them to take me that seriously, but there they were, years later, treating me like an all-knowing deity. But I liked the work they were doing, helping young pyromancers. I'd been aging for sixty years, and I wanted to do something worthwhile for what was left of my life." She eyed Chandra. "You have some idea of how hard it can be to help those kids. They're impatient, reckless, refuse to listen to anyone . . ." Chandra let her breath out. She was still mad, but this was starting to sound almost reasonable. She wasn't sure what she would have done in Jaya's place. #emph[I wouldn't have lied about who I was for years] , she thought sourly. She was pretty sure she wouldn't. Though being worshipped like a god was sure to get old fast, considering how long Chandra had lasted just as abbot. #figure(image("009_Return to Dominaria: Episode 9/01.jpg", width: 100%), caption: [Abbot of Keral Keep | Art by <NAME>], supplement: none, numbering: none) But maybe it didn't matter. Her plan was still intact. She'd found Jaya, and now she could get the help she needed. "All right, so . . . I understand why you did it, mostly. I forgive you." She held out Jaya's goggles, though the gesture was mostly symbolic now. It wasn't like Jaya couldn't have gotten them any time she wanted over the past years. "And now I'll let you tell me what I need to know to be a more powerful pyromancer." Jaya took the goggles, and her expression turned hard as stone. "Absolutely not." The next morning, Chandra woke up in the little tent she'd set up on the far side of the crater. For a moment she thought she was still on the trail through the ridges, filled with hope and excitement about finding <NAME>. Then she remembered where she was and what had happened. She put her hands over her face and groaned. She had spent the rest of yesterday arguing with Jaya. Chandra had tried to tell her about <NAME> and how she needed more power to help defeat him. Jaya had not been impressed with her explanation and had said again that Chandra should have stayed with her friends. "You said that at Keral Keep when I was getting the goggles," Chandra had pointed out. "When you were pretending to be <NAME>." "Right, when you yelled in my face and then disappeared," Jaya had replied, with an expression that should have withered Chandra where she stood. "Or was that some other time you yelled in my face and disappeared? It happens so often, all the occasions blend together!" After that there was a lot of Chandra shouting and Jaya mostly ignoring her. The last thing Jaya had said to her had been, "When I was <NAME>, you dismissed me as a useless old woman. As <NAME>, suddenly I'm worth listening to." Now Chandra was tired of being angry, but she couldn't give up. She didn't know what else to do. #emph[I have to convince her to help me] , Chandra thought. There was no other option. #emph[Maybe this morning she's changed her mind.] She crawled out of the tent into the bright morning light. The deep green forest surrounding the valley was still stationary, but the shadows under the trees were vaguely threatening. The piles of wood had mostly stopped smoldering and the morning breeze carried the smoke away. Jaya was on the far side of the pit, standing on a mound of dirt, facing the forest as she kept watch. Karn stood nearby at the edge of the crater, which looked much deeper than it had yesterday. Some automatons stood guard at the other end of the valley, but most were down in the pit, digging with their scoop-like hands or carrying dirt to the piles. The automatons had been digging all night; Jaya had put some fireballs in the air to light the area for them. As Chandra wandered along the rim, she saw it was full of weird broken metal shapes and blocks of stone. Karn watched her approach, his metal features sober. "Are you all right?" he asked her. His voice was deep and reverberated just a little, like someone speaking inside a metal room. "Sure, I mean . . ." Chandra shrugged. "You always spend half the day shouting?" Karn's tone was wryly amused. Chandra winced. It couldn't have been a fun time for Karn, with all the yelling and recriminations going on in his dig site. "Sorry about that. I guess it was hard to work while all that was going on." She kicked at the churned-up dirt. "What are you digging for?" She had been so busy arguing with Jaya yesterday, she hadn't even thought to ask. "The Sylex," he told her. "It was created by Urza to help defeat the Phyrexians. I intend to take it to New Phyrexia and detonate it there." "So it's like a bomb? A giant bomb?" "Exactly like a giant bomb," Karn said. Chandra looked toward where Jaya stood on the mound of dirt, keeping watch. "And Jaya came to help you?" "Yes, to help protect the excavation from Multani's attacks. In his semiconscious state, he senses that the Sylex is being uncovered, brought closer to the surface, and he fears it. For good reason; it caused great damage to him." Karn looked off toward the forest, where the morning wind stirred the tree canopies. "He does not want Dominaria harmed again. When he wakes, he'll understand that I'm taking it away to end the Phyrexian threat." #figure(image("009_Return to Dominaria: Episode 9/02.jpg", width: 100%), caption: [Nature's Spiral | Art by <NAME>], supplement: none, numbering: none) That sounded important, and Chandra didn't want to interrupt. "I'm going to talk to Jaya again." Karn looked down at her, his metal brows lifted. "Must you?" Chandra bit her lip. "I have to change her mind. I need someone to help me learn the secret to becoming a more powerful pyromancer. It took me a long time to realize it, but I understand that now." Karn sighed. "I see. Good luck." "Thanks." Chandra walked around the crater to Jaya's mound of dirt and climbed to the top. Jaya didn't acknowledge her. Chandra scratched her head and said, "Look, I guess I just don't understand why you won't help me. This is what you said you wanted all this time." Jaya's expression was cold. "Exactly. You had more chances than I can count." She shook her head like someone who was absolutely done with this argument. "I used to be just like you, Chandra. That's why I thought I could help you, but maybe we're too much alike. You told me on Regatha that you didn't want my help, and that's that. I'm not offering again." "Yes, but . . ." Chandra trailed off. That was when she had thought Jaya was <NAME>, an old woman not worth listening to, which was exactly what Jaya had said yesterday. #emph[I really screwed this up] , she thought. If she had listened to <NAME>, tried to be less impatient, Jaya wouldn't be so fed up with her. "But I really need help—" Jaya turned to face her, annoyance written on her features. "I've told you everything you need to know already. There's no secret. To master your power, you need to know what you want, know your true self. You have no idea what you want." Chandra set her jaw. "I want to kill Bolas. It's that simple." "Then why are you here with us instead of your Gatewatch friends?" Jaya's voice was harsh with frustration. "For the last time, Chandra—" A loud crack made them both spin around. Karn, on watch on the far side of the crater, turned and leapt into the pit. Jaya jumped down from the mound and strode to the edge. Chandra followed her. Down in the pit, the big automatons had stopped digging and stood around a broken stone slab still partly covered by dirt and gravel. They moved aside as Karn approached. He knelt in the churned-up dirt and carefully moved sections of the slab aside, then leaned down to brush at something beneath. After a moment, he sat back, looked up at Jaya, and nodded once. "He's found the Sylex." Jaya let her breath out, but she didn't look relieved. "That's good, right?" Chandra said, confused. "That's the bomb thing he's going to take to another plane and kill the Phyrexians with, right?" "Yeah." Still watching Karn, Jaya shook her head a little. "Everyone I've talked to thinks the Phyrexians aren't a threat anymore, but . . . He needs to do this. I just wish he didn't." Chandra frowned. "They destroyed a whole plane, so why is destroying them a bad thing?" The problem with interplanar threats was that by the time you realized you were in danger, it was generally too late to do anything about them. Or that was how it had worked with Bolas on Amonkhet. "Because it means he'll have to go back there." Jaya grimaced. "And that could be a disaster for a number of reasons." Then she glanced up and her eyes widened. "Oh, damn it! Karn, they're coming!" Chandra looked. The treeline roiled with motion. "I hate these things," she muttered. And it looked like there were a lot more of them this time. Trees rose out of the forest, the giant striding ones and the spidery creepers. They rolled toward the crater in an angry wave of leaves and branches. The automatons scrambled toward the sides to climb out, but there were too few of them to defend the site. Karn was still trying to get the Sylex out from under the slab and they had to give him time. Chandra shouted, "Jaya, you take that side, I'll go this way!" As Jaya ran, Chandra circled around in the other direction toward the approaching trees. When she reached the right range, she planted her feet, took a deep breath, and sent fire streaming forward. She blasted the first line of trees, then flung fireballs over their burning canopies to hit the newcomers surging out of the forest. She heard Jaya on the far side of the crater, striking the trees with a barrage of targeted blasts. Out of the corner of her eye she saw that Karn's automatons had managed to climb out of the crater. They threw themselves at the walking trees and punched into the trunks or ripped at the roots. Except more trees came, and more, and more. They were desperate to get to Karn and the Sylex. If they reached him, they'd tear him apart. Chandra kept up the fire streams, digging deep for her power and yelling until her throat was dry and hoarse. The valley filled with smoke and fire. #figure(image("009_Return to Dominaria: Episode 9/03.jpg", width: 100%), caption: [Chandra's Outburst | Art by Yongjae Choi], supplement: none, numbering: none) Finally there were no trees charging at her and Chandra staggered to a stop, wiping sweat off her forehead. As the smoke cleared, she saw pieces of Karn's automatons everywhere. It didn't look like there were any survivors. Jaya had been pushed back toward Chandra and stood only a short distance away. Chandra realized she had been unconsciously backing up too, that the edge of the crater was now only a few feet behind her. She said to Jaya, "Where's Karn? We have to get out of here!" Jaya squinted, trying to see through the haze of smoke. "I lost track of him. I hope he's not in pieces—oh, that's all we need!" Chandra whipped around again and thought, #emph[It's worse] . Rising above the tree canopy was a giant made of roots and branches, its eyes and mouth glowing with yellow light. Its head was jagged on top, the wood shaped into horns, or maybe the remnants of a pointed crown. Chandra said, "What's that?" "I'm pretty sure that's Multani, or what's left of him," Jaya said grimly. "Karn, damn it, where are you?" A pile of smoldering wood near the crater tumbled over as Karn pushed his way free of it. He had something tucked under his arm and his metal body was covered with dirt and soot. As he looked up at Multani, his expression was more sad than angry or worried. "He's still semiconscious. He would never hurt us if he were himself." Multani pushed forward out of the forest and stepped onto the bare scorched earth. He kicked the mounds of broken and burning trees aside as he strode toward them. All around the valley, more animate trees burst out of the forest to gather for a charge. Chandra braced herself. "We can hold them off!" #figure(image("009_Return to Dominaria: Episode 9/04.jpg", width: 100%), caption: [Ancient Animus | Art by Titus Lunter], supplement: none, numbering: none) "We'll have to." Jaya's gaze was determined. "Get ready." Then Multani stopped. Chandra frowned, thinking he was somehow readying himself for an attack. But Multani didn't move. None of the trees moved either. Chandra took a wary step forward. "What's he waiting for?" Jaya straightened up slowly. She pulled her goggles off to squint at Multani. "Look at the forest. He's frozen." Karn's metal brow was furrowed. "It's time magic." "Huh?" Chandra said, baffled. Then she realized the leaves and branches of the stationary trees back in the forest moved slightly in the wind, but Multani and his animate trees were as still as stone. Jaya was right; they had all frozen in place. Then a shadow fell on the ground around them. Startled, Chandra looked up. Overhead was a long narrow shape, like the underside of a sailing ship. It #emph[was] the underside of a ship—a skyship. Jaya climbed a mound of dirt, shading her eyes to gaze up at it. Chandra ran to join her. From this angle she could see the bow, where a man in flowing blue robes stood. He held out his hands, obviously performing a powerful spell. Karn was looking up with an expression of wonder. "This is the #emph[Weatherlight] , and that's Teferi." He shook his head. "I wasn't expecting this." "A time mage with excellent timing." Jaya smiled. "Right, but what's—" Chandra started to ask. Then someone leaned out over the railing to unroll a boarding ladder, and with a shock, she recognized him. "Gideon!" She waved wildly. "Hey, Gideon, what are you doing here?" Liliana stood beside him, looking annoyed. "Chandra?" he called back. "Quick, all of you come aboard. He can't hold it for much longer!" Jaya caught the end of the ladder as it swung toward them and held it out to Chandra. "Here, you go first." But Chandra looked back at Multani. Karn had said he was semiconscious, that he would never do any of this if he was awake and aware. She didn't want to leave him like that. And she thought she knew a solution. "No, you two go. I want to try to fix this." "Fix it?" Jaya asked, startled. "How?" "Something a friend of mine showed me." Chandra started down the hill. She wasn't sure if she could do it for somebody else like Nissa had done it for her, but it was worth a try. It just wasn't fair, or safe for anybody living near here, to leave Multani like this. "I've got to give him a chance." She picked her way over the broken wood and the piles of dirt and debris, until she stood just below Multani. She didn't know how long she had, how long the time mage could hold Multani still, but she couldn't afford to rush, either. She said, "I know you can hear me. I know you don't want to be like this, you don't want to hurt people. That's not what you are. Think about water, still cool water. Flowing over your skin, your bark, into your branches and leaves. You're a light, floating on that water." Just saying the words like Nissa had, visualizing them, made Chandra feel calmer. #emph[I miss her, and I don't know if I'm ever going to see her again.] Chandra imagined the light floating on the water herself and let her emotions still into a calm sadness. She remembered what Jaya had said about knowing your true self and added, "I know you don't want to hurt anyone. Sink into the water, find your true self waiting there. Remember—remember who you are . . ." Time seemed to slow, and Chandra drifted on it like a light herself. After arguing with Jaya and being attacked by trees for most of the past two days, it was a relief. Then she realized Multani, too, was changing. The ashy bark of his skin turned darker and richer, and green plants sprouted along the tops of his hands and arms, running up to his back, up to soften the wooden crown of his head. Flowers in a whole riot of colors appeared in the green, their petals unfurling. The angry gold light from his eyes and mouth faded to a deep blue, and she was sure she saw awareness there. All around him, the roots of the animate trees sank into the disturbed earth. #figure(image("009_Return to Dominaria: Episode 9/05.jpg", width: 100%), caption: [Multani, Yavimaya's Avatar | Art by <NAME>], supplement: none, numbering: none) Chandra backed away, just in case she was wrong, and then called over her shoulder. "Let him go!" There was a hesitation, then a wind scented with smoke and burning washed over Chandra, as if it had been frozen too. Multani looked down at her, then at Karn. He said, "You have the Sylex." His voice was deep and low and had an undertone like wind rushing through leaves. Karn moved forward to stand beside Chandra. "I will take it to New Phyrexia. It will never harm Dominaria, I swear it." Multani relaxed, his body becoming less stiff. The animate trees were rooted to the ground in the valley, like they had always been here, shading the burned earth around the crater. Multani looked up at the #emph[Weatherlight] then, and frowned. "You used Molimo's seed?" "Who's Molimo?" Chandra whispered. "His rival, another tree elemental," Jaya answered, suddenly beside her. She added, "That was good work." Chandra grinned in spite of herself. "A friend of mine showed me how." She hesitated. After calming Multani, she felt pretty calm herself, and everything seemed a lot more clear. She'd been rude and dismissive to <NAME>, and just as reckless and impatient as any other young pyromancer in Keral Keep. "I don't want to fight with you, Jaya. I'm sorry about how I treated you and I understand why you don't want to help me. I wouldn't want to help me, either. But I hope we can still be friends." Jaya eyed her, a small smile tugging at her mouth. From the bow of the skyship, Gideon shouted, "That was impressive, Chandra!" He said something to Liliana that Chandra couldn't make out, but she heard Liliana's reply: "I'll tell her she did a good job if she gets on the damn skyship before we all die of old age." "Those are my friends," Chandra explained to Jaya and Karn. She called up to the #emph[Weatherlight] , "What are you doing here?" "The same thing we were doing when you ran away," Liliana said. "Planning to kill Belzenlok." "I didn't run away! I was trying to—" Chandra hesitated. "She came to find me so I could help her to better master her pyromancy," Jaya called up to them. She waved at the smoking battlefield around them. "We've been getting some practice, as you can see." Chandra turned toward her. "Really? You mean—" Jaya clapped her on the shoulder. "Yes, really. You're not there yet, but what you did with Multani shows me you have potential. Now come on, let's get out of here." #figure(image("009_Return to Dominaria: Episode 9/06.jpg", width: 100%), caption: [Forest | Art by Titus Lunter], supplement: none, numbering: none) As Karn and the two pyromancers climbed the ladders to the deck, Jhoira told Tiana, "Take the wheel. I've got to convince two very stubborn people of something and it may take some time." Tiana smiled wryly. "Good luck." Jhoira took the stairs down to the open deck. Karn stood a little apart from where the other Planeswalkers were talking. Jhoira knew him well enough to see the uncertainty in the angle of his body, and wondered what it must be like for him, to suddenly be standing on the #emph[Weatherlight] again after so long. Teferi strode up to him. "Karn, my old friend!" He clapped Karn on the back, causing a faint clang. "We're glad you're back with us!" "I'm glad for your arrival—" Karn began. "Timely arrival," Teferi prompted. Karn sighed. "You haven't changed." Then he turned and saw Jhoira. She smiled. Gideon and the others were going below, and she waited until they were out of earshot before she said, "It's been so long." Karn took a hesitant step forward. "Jhoira, I must tell you—" "About Venser? I know." She closed the distance between them and put a hand on his arm. "<NAME> came to tell me. Teferi knows, too." Karn regarded her in silence. "I regret . . . I would not have chosen for him to sacrifice himself for me." "But it was his decision," Jhoira said firmly. That was one thing she was certain about. Karn looked from Jhoira to Teferi, hesitating. "So we are back aboard the #emph[Weatherlight] . What is our purpose here?" #figure(image("009_Return to Dominaria: Episode 9/07.jpg", width: 100%), caption: [Weight of Memory | Art by <NAME>], supplement: none, numbering: none) "First to destroy Belzenlok, then to defeat the Cabal," Jhoira told him. "That's why I had the #emph[Weatherlight] reconstructed and recruited a crew. But I had something else in mind for you two." Teferi leaned on his staff, smiling a little. "I'm not surprised. You always have a plan." "I have the Sylex, to destroy New Phyrexia." Karn lifted a bag thick with padding. "That is my plan." Jhoira wasn't surprised Karn was still focused on the Phyrexians. Among all the other reasons, he would want revenge for Venser. "And it's an admirable cause, but before that, I think you should help kill <NAME>." Teferi lifted his brows. "Karn could help. But you forget, I'm no longer a Planeswalker. Unless Bolas comes here . . ." He trailed off as Jhoira lifted her pendant and opened it. His eyes widened. "I'd never forget that," Jhoira said, watching him gravely. The Powerstone in the locket was reflected in Teferi's eyes. He had recognized it immediately, felt its call to him. Karn leaned forward to look. "It's your spark?" Teferi's brow furrowed. "How?" he said. "The Mana Rig." She held it out to him. "Will you take it back?" Teferi pressed his lips together and stepped back. He looked away, frowning. "You ask a lot of me, Jhoira." Jhoira wasn't daunted. She had known this wouldn't be easy. "Do I? Isn't this what you want?" Teferi shook his head and looked away, and Jhoira's frustration boiled up. "Do you know what I'd give to be a Planeswalker?" That got Teferi's attention. He faced her, his expression grave. Jhoira took a sharp breath and said, "This is a precious gift. Don't throw it away." Teferi was silent for a long moment. Then he said, "I'll think about it." He let his breath out, and smiled at Karn again. "But for now, we're just three old friends, with a great deal of catching up to do." Jhoira didn't object. She knew Teferi too well. As the #emph[Weatherlight] sailed over Yavimaya, Gideon told Chandra about their plans and what they had accomplished so far. They were sitting with Liliana and Jaya around the big table in the compartment below the bridge. As he finished, Chandra said, "But you still don't have a way to kill Belzenlok without the Chain Veil, right?" "He didn't tell you about the Blackblade," Liliana said, with an irritated glance at him. "It's a sword that slew an elder dragon, and Gideon is too delicate to allow us to use it." Chandra looked at Gideon, who said pointedly, "It's also a soul-drinker." #figure(image("009_Return to Dominaria: Episode 9/08.jpg", width: 100%), caption: [Blackblade Reforged | Art by Chris Rahn], supplement: none, numbering: none) Chandra winced, but said, "He is a demon, Gideon. We've seen what a demon can do to a plane." "Exactly," Liliana said. Jaya just looked thoughtful, her chin propped on her hand, but she didn't voice any disagreement. Gideon hesitated. He didn't want to argue with them, not when they had found Chandra again and were talking over their plan like sensible people. They had allies, a strategy, everything they needed to kill Belzenlok, except the weapon to do it. He said, "I can't—" A thump of displaced air made him flinch, then with a sudden blaze of blue light, someone else stood in the compartment. Gideon shoved out of his chair and grabbed for his sword. Jaya was already on her feet, Liliana threw herself back against the wall and lifted her hands to cast a spell, and Chandra vaulted on top of the table, fire already crackling around her hair. Then Gideon froze, recognizing the aether trail almost before he recognized the newcomer's face. "Jace!" The door to the compartment was flung open, and Teferi, Jhoira, and Shanna stood there, spells and weapons ready, with Arvad, Karn, and Raff running up behind them. "Stop, it's all right! He's a friend!" Gideon shouted. Teferi flexed his fingers and stepped back, clearly not pleased to be startled. "He should knock first, next time." Shanna called over her shoulder, "It's all right, Tiana!" Gideon turned to Jace, astounded. "How did you find us? You shouldn't have been able to planeswalk onto a moving vessel." "And where have you been?" Liliana added, looking him over incredulously. "Are you all right?" "Yes, what happened to your clothes?" Chandra wondered as she jumped off the table. Jace glanced around at them all, his expression serious. "This ship leaves a trace very like a Planeswalker's aether trail. Your aether trails in Dominaria were close enough to crossing it that I suspected you might have met up with it. I had to do some calculations to adjust for altitude and speed. It was tricky but manageable." The others were silent for a moment. Teferi lifted his brows and exchanged a look with Jhoira. Then Jaya asked, "Who's the bookworm in the bathing suit?" Gideon explained, "This is our friend Jace, another member of the Gatewatch." He gestured toward the others. "These are new allies. We've banded together to destroy Belzenlok." Distracted, Jace nodded to them. "I'm sorry to appear in your ship without warning, but my mission is urgent." He turned to Gideon. "I came here to warn you. Ajani wanted us to meet and regroup, but Bolas is preparing a trap for Planeswalkers." Gideon felt the sick inevitability of it. "A trap?" Jace's expression was grim and remained grim as he explained what he knew of Bolas's plan. Finally, he gestured urgently. "We have to go immediately—Ajani and the others will need all the help they can get." Behind Jhoira, Raff whispered, "He wants them to go to where the trap is? Isn't that the same as being caught in the trap?" Shanna shushed him. "Will you and Chandra come with me?" Jace demanded. Liliana frowned. "What about me?" Gideon should have expected something like this. But he didn't feel their situation had changed. "If this is true, we need Liliana at her full power more than ever." Jace shook his head, frustrated. "You don't understand. You can't trust her." "Oh, yes he can!" Liliana protested, more baffled than angry. #emph[And barely any time ago I was thinking how calmly we were discussing our plans] , Gideon thought wryly. Keeping his expression calm, he said, "I do trust her, Jace. We're committed to destroying Belzenlok, and we have everything we need to attack his Stronghold. It has to be done, and not just to free Liliana. He's close to taking over all of Dominaria." Jace said, "I agree Belzenlok has to be killed, but there's no time. You can come back here after we fight Bolas. I'll be free to help you then." "Jace, that won't work," Liliana said wearily. "With my powers weakened, I can't help you. Not fully. We'll end up routed again, or worse. Just like on Amonkhet, at Bolas's mercy." #figure(image("009_Return to Dominaria: Episode 9/09.jpg", width: 100%), caption: [Liliana's Defeat | Art by <NAME>], supplement: none, numbering: none) Jace ignored her. He said to Gideon, "You must know she's lying, Gideon. Or at least manipulating you, not telling you the full story. I need your help." Gideon knew Jace was sincere, but he had thought a great deal about their strategy, and he knew it was as sound as they could make it. "Jace, we have a plan, we have a commitment to our allies, and we are ready to kill Belzenlok. I have no intention of repeating my mistakes on Amonkhet. When I meet Bolas again, it will be with Liliana, a necromancer capable of destroying any undead force he means to use against us." Jace was obviously unhappy. He turned to Chandra. "Chandra, will you come with me?" Chandra looked back at Jaya, who watched them thoughtfully, then glanced up at Gideon. "My plan was . . . not as great as I thought, but I have a chance to get what I need now. To learn a bit more. About myself. I—I must see this through here." Jace let out his breath in resignation. He stepped back. As blue shadows rose up around him, he glanced at Liliana. "Don't be a fool, Gideon. Like I was." The shadows flew into a whirlwind and he was gone. There was a long moment of silence. Then Raff said, "Are all Planeswalkers like this?" Teferi cleared his throat, took Raff's arm, and turned him around, leading him away toward the bridge. "You should have seen us in the old days, much more exciting." The others followed, Jaya pausing to give Chandra an approving nod as they left Gideon and Chandra alone with Liliana. Liliana pulled out a chair and sat down, dropping her head into her hands. Gideon tried to think of something comforting to say, but everything he could think of sounded like an empty platitude. After a moment, Chandra propped her hip against the table and said, "So I guess we need to hurry." "She's right." Liliana looked up at Gideon. "You said we had everything we need to kill Belzenlok. Does that mean you'll agree to using the Blackblade?" Gideon hesitated. The blade was a soul-drinker. Not that Belzenlok had a soul to drink. But there was no time to waste looking for some other method. Delay meant endangering the other Planeswalkers Ajani had gathered, meant the Cabal gained more footholds on Dominaria, made it harder for Jhoira and Shanna and all the others fighting them to root them out. He said, "If we can find it in the Stronghold, I'll use it." He might have expected Liliana to look triumphant, or to gloat a little over his change of heart. But she just looked tired, and said, "Thank you. For this and . . ." She looked away, uncomfortable. "For . . . everything." Gideon smiled a little. From anyone else, it would have sounded grudging, but he knew how hard it was for Liliana to say those words. "You're welcome." Later, Teferi found Jhoira sitting alone on the bridge. He took a seat across from her and looked out the port. The sun was setting over the green forest of Yavimaya and they were nearing the coast. After a time, Jhoira said softly, "If I could, I would give you all the time you wanted to make this decision." "Time isn't the problem." Teferi smiled a little and glanced at her. "Time is never the problem." Her lips curved in answer. "For you." He looked at the sinking sun, where the distant sea was turning golden in the light. "Do your new friends know I fought Bolas before?" "No. And when I decided to return your spark, I had no idea we would meet Planeswalkers locked in battle with him," Jhoira admitted. "This was not part of my plan." "Then perhaps it's fate, coming full circle." Teferi thought of a young man called Kwende, one of the many who had tried to kill him because of Zhalfir. Kwende had been burdened by a need for revenge for the loss of a place he had never known, a place Teferi had only wanted to protect. Teferi had sworn to himself to return Zhalfir, to make amends for the hubris and certainty of his younger self. Denying the power that his spark would give him toward that goal would be as selfish as time-shifting Zhalfir had been in the first place. He sighed. And held out his hand. Jhoira smiled faintly. "I don't know what the future holds, and this might be a moment we both regret later. But this is a weapon you should have." She pulled the pendant off her neck and dropped it into Teferi's waiting palm. "Welcome back." #figure(image("009_Return to Dominaria: Episode 9/10.jpg", width: 100%), caption: [Opt | Art by <NAME>], supplement: none, numbering: none)
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/048.%20sfp.html.typ
typst
sfp.html What I Did this Summer October 2005The first Summer Founders Program has just finished. We were surprised how well it went. Overall only about 10% of startups succeed, but if I had to guess now, I'd predict three or four of the eight startups we funded will make it.Of the startups that needed further funding, I believe all have either closed a round or are likely to soon. Two have already turned down (lowball) acquisition offers.We would have been happy if just one of the eight seemed promising by the end of the summer. What's going on? Did some kind of anomaly make this summer's applicants especially good? We worry about that, but we can't think of one. We'll find out this winter.The whole summer was full of surprises. The best was that the hypothesis we were testing seems to be correct. Young hackers can start viable companies. This is good news for two reasons: (a) it's an encouraging thought, and (b) it means that Y Combinator, which is predicated on the idea, is not hosed.AgeMore precisely, the hypothesis was that success in a startup depends mainly on how smart and energetic you are, and much less on how old you are or how much business experience you have. The results so far bear this out. The 2005 summer founders ranged in age from 18 to 28 (average 23), and there is no correlation between their ages and how well they're doing.This should not really be surprising. <NAME> and <NAME> were both 19 when they started the companies that made them famous. Young founders are not a new phenomenon: the trend began as soon as computers got cheap enough for college kids to afford them.Another of our hypotheses was that you can start a startup on less money than most people think. Other investors were surprised to hear the most we gave any group was $20,000. But we knew it was possible to start on that little because we started Viaweb on $10,000.And so it proved this summer. Three months' funding is enough to get into second gear. We had a demo day for potential investors ten weeks in, and seven of the eight groups had a prototype ready by that time. One, Reddit, had already launched, and were able to give a demo of their live site.A researcher who studied the SFP startups said the one thing they had in common was that they all worked ridiculously hard. People this age are commonly seen as lazy. I think in some cases it's not so much that they lack the appetite for work, but that the work they're offered is unappetizing.The experience of the SFP suggests that if you let motivated people do real work, they work hard, whatever their age. As one of the founders said "I'd read that starting a startup consumed your life, but I had no idea what that meant until I did it."I'd feel guilty if I were a boss making people work this hard. But we're not these people's bosses. They're working on their own projects. And what makes them work is not us but their competitors. Like good athletes, they don't work hard because the coach yells at them, but because they want to win.We have less power than bosses, and yet the founders work harder than employees. It seems like a win for everyone. The only catch is that we get on average only about 5-7% of the upside, while an employer gets nearly all of it. (We're counting on it being 5-7% of a much larger number.)As well as working hard, the groups all turned out to be extraordinarily responsible. I can't think of a time when one failed to do something they'd promised to, even by being late for an appointment. This is another lesson the world has yet to learn. One of the founders discovered that the hardest part of arranging a meeting with executives at a big cell phone carrier was getting a rental company to rent him a car, because he was too young.I think the problem here is much the same as with the apparent laziness of people this age. They seem lazy because the work they're given is pointless, and they act irresponsible because they're not given any power. Some of them, anyway. We only have a sample size of about twenty, but it seems so far that if you let people in their early twenties be their own bosses, they rise to the occasion.MoraleThe summer founders were as a rule very idealistic. They also wanted very much to get rich. These qualities might seem incompatible, but they're not. These guys want to get rich, but they want to do it by changing the world. They wouldn't (well, seven of the eight groups wouldn't) be interested in making money by speculating in stocks. They want to make something people use.I think this makes them more effective as founders. As hard as people will work for money, they'll work harder for a cause. And since success in a startup depends so much on motivation, the paradoxical result is that the people likely to make the most money are those who aren't in it just for the money.The founders of Kiko, for example, are working on an Ajax calendar. They want to get rich, but they pay more attention to design than they would if that were their only motivation. You can tell just by looking at it.I never considered it till this summer, but this might be another reason startups run by hackers tend to do better than those run by MBAs. Perhaps it's not just that hackers understand technology better, but that they're driven by more powerful motivations. Microsoft, as I've said before, is a dangerously misleading example. Their mean corporate culture only works for monopolies. Google is a better model.Considering that the summer founders are the sharks in this ocean, we were surprised how frightened most of them were of competitors. But now that I think of it, we were just as frightened when we started Viaweb. For the first year, our initial reaction to news of a competitor was always: we're doomed. Just as a hypochondriac magnifies his symptoms till he's convinced he has some terrible disease, when you're not used to competitors you magnify them into monsters.Here's a handy rule for startups: competitors are rarely as dangerous as they seem. Most will self-destruct before you can destroy them. And it certainly doesn't matter how many of them there are, any more than it matters to the winner of a marathon how many runners are behind him."It's a crowded market," I remember one founder saying worriedly."Are you the current leader?" I asked."Yes.""Is anyone able to develop software faster than you?""Probably not.""Well, if you're ahead now, and you're the fastest, then you'll stay ahead. What difference does it make how many others there are?"Another group was worried when they realized they had to rewrite their software from scratch. I told them it would be a bad sign if they didn't. The main function of your initial version is to be rewritten.That's why we advise groups to ignore issues like scalability, internationalization, and heavy-duty security at first. [1] I can imagine an advocate of "best practices" saying these ought to be considered from the start. And he'd be right, except that they interfere with the primary function of software in a startup: to be a vehicle for experimenting with its own design. Having to retrofit internationalization or scalability is a pain, certainly. The only bigger pain is not needing to, because your initial version was too big and rigid to evolve into something users wanted.I suspect this is another reason startups beat big companies. Startups can be irresponsible and release version 1s that are light enough to evolve. In big companies, all the pressure is in the direction of over-engineering.What Got LearnedOne thing we were curious about this summer was where these groups would need help. That turned out to vary a lot. Some we helped with technical advice-- for example, about how to set up an application to run on multiple servers. Most we helped with strategy questions, like what to patent, and what to charge for and what to give away. Nearly all wanted advice about dealing with future investors: how much money should they take and what kind of terms should they expect?However, all the groups quickly learned how to deal with stuff like patents and investors. These problems aren't intrinsically difficult, just unfamiliar.It was surprising-- slightly frightening even-- how fast they learned. The weekend before the demo day for investors, we had a practice session where all the groups gave their presentations. They were all terrible. We tried to explain how to make them better, but we didn't have much hope. So on demo day I told the assembled angels and VCs that these guys were hackers, not MBAs, and so while their software was good, we should not expect slick presentations from them.The groups then proceeded to give fabulously slick presentations. Gone were the mumbling recitations of lists of features. It was as if they'd spent the past week at acting school. I still don't know how they did it.Perhaps watching each others' presentations helped them see what they'd been doing wrong. Just as happens in college, the summer founders learned a lot from one another-- maybe more than they learned from us. A lot of the problems they face are the same, from dealing with investors to hacking Javascript.I don't want to give the impression there were no problems this summer. A lot went wrong, as usually happens with startups. One group got an "exploding term-sheet" from some VCs. Pretty much all the groups who had dealings with big companies found that big companies do everything infinitely slowly. (This is to be expected. If big companies weren't incapable, there would be no room for startups to exist.) And of course there were the usual nightmares associated with servers. In short, the disasters this summer were just the usual childhood diseases. Some of this summer's eight startups will probably die eventually; it would be extraordinary if all eight succeeded. But what kills them will not be dramatic, external threats, but a mundane, internal one: not getting enough done.So far, though, the news is all good. In fact, we were surprised how much fun the summer was for us. The main reason was how much we liked the founders. They're so earnest and hard-working. They seem to like us too. And this illustrates another advantage of investing over hiring: our relationship with them is way better than it would be between a boss and an employee. Y Combinator ends up being more like an older brother than a parent.I was surprised how much time I spent making introductions. Fortunately I discovered that when a startup needed to talk to someone, I could usually get to the right person by at most one hop. I remember wondering, how did my friends get to be so eminent? and a second later realizing: shit, I'm forty.Another surprise was that the three-month batch format, which we were forced into by the constraints of the summer, turned out to be an advantage. When we started Y Combinator, we planned to invest the way other venture firms do: as proposals came in, we'd evaluate them and decide yes or no. The SFP was just an experiment to get things started. But it worked so well that we plan to do all our investing this way, one cycle in the summer and one in winter. It's more efficient for us, and better for the startups too.Several groups said our weekly dinners saved them from a common problem afflicting startups: working so hard that one has no social life. (I remember that part all too well.) This way, they were guaranteed a social event at least once a week.IndependenceI've heard Y Combinator described as an "incubator." Actually we're the opposite: incubators exert more control than ordinary VCs, and we make a point of exerting less. Among other things, incubators usually make you work in their office-- that's where the word "incubator" comes from. That seems the wrong model. If investors get too involved, they smother one of the most powerful forces in a startup: the feeling that it's your own company.Incubators were conspicuous failures during the Bubble. There's still debate about whether this was because of the Bubble, or because they're a bad idea. My vote is they're a bad idea. I think they fail because they select for the wrong people. When we were starting a startup, we would never have taken funding from an "incubator." We can find office space, thanks; just give us the money. And people with that attitude are the ones likely to succeed in startups.Indeed, one quality all the founders shared this summer was a spirit of independence. I've been wondering about that. Are some people just a lot more independent than others, or would everyone be this way if they were allowed to?As with most nature/nurture questions, the answer is probably: some of each. But my main conclusion from the summer is that there's more environment in the mix than most people realize. I could see that from how the founders' attitudes changed during the summer. Most were emerging from twenty or so years of being told what to do. They seemed a little surprised at having total freedom. But they grew into it really quickly; some of these guys now seem about four inches taller (metaphorically) than they did at the beginning of the summer.When we asked the summer founders what surprised them most about starting a company, one said "the most shocking thing is that it worked."It will take more experience to know for sure, but my guess is that a lot of hackers could do this-- that if you put people in a position of independence, they develop the qualities they need. Throw them off a cliff, and most will find on the way down that they have wings.The reason this is news to anyone is that the same forces work in the other direction too. Most hackers are employees, and this molds you into someone to whom starting a startup seems impossible as surely as starting a startup molds you into someone who can handle it.If I'm right, "hacker" will mean something different in twenty years than it does now. Increasingly it will mean the people who run the company. Y Combinator is just accelerating a process that would have happened anyway. Power is shifting from the people who deal with money to the people who create technology, and if our experience this summer is any guide, this will be a good thing.Notes[1] By heavy-duty security I mean efforts to protect against truly determined attackers.The image shows us, the 2005 summer founders, and Smartleaf co-founders <NAME> and <NAME> at the 30-foot table Kate Courteau designed for us. Photo by <NAME>.Thanks to <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this. Romanian TranslationJapanese Translation
https://github.com/dashuai009/dashuai009.github.io
https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/041.typ
typst
#let date = datetime( year: 2023, month: 3, day: 3, ) #metadata(( title: "[USACO Feb. Gold] Problem1. EQUAL SUM SUBARRAYS", subtitle: [usaco], author: "dashuai009", description: "", pubDate: date.display(), ))<frontmatter> #import "../__template/style.typ": conf #show: conf == 题目链接 <题目链接> #link("http://www.usaco.org/index.php?page=viewproblem2&cpid=1305")[USACO] == 题目描述 <题目描述> 有一个长度为$N$的数组$a$,a的$frac(N (N + 1), 2)$的连续子序列的和各不相同。对于每一个$i$,输出“最少需修改(增大或减少)$a_i$,使得$a$的两个连续子序列的和相等”。 == 题目解析 <题目解析> 首先求出$frac(N (N + 1), 2)$个子数组的和$s_i$,进行排序。每个和对应一个子数组。 对于每一个$s_i$,对应于原数组的区间$[l_i , s_i]$,如果通过最少修改$s_i$,让$s_i$等于另一个$s_j$,则$s_j$只能是$s_(i - 1)$或$s_(i + 1)$。维护结果数组$r e s_i$,初始化为最大值,对于每个$s_i$,用$min { lr(|s_i - s_(i - 1)|) , lr(|s_i - s_(i + 1)|) }$去更新$[l_i , r_i]$。最后输出结果即可。
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2004/WS-02.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [ZHANG Yining], [CHN], [2608], [2], [WANG Nan], [CHN], [2549], [3], [NIU Jianfeng], [CHN], [2455], [4], [GUO Yan], [CHN], [2431], [5], [GUO Yue], [CHN], [2375], [6], [LI Ju], [CHN], [2293], [7], [KIM Kyungah], [KOR], [2225], [8], [TIE Yana], [HKG], [2213], [9], [SONG Ah Sim], [HKG], [2191], [10], [LIN Ling], [HKG], [2157], [11], [GAO Jun], [USA], [2147], [12], [STEFF Mihaela], [ROU], [2138], [13], [LAU Sui Fei], [HKG], [2125], [14], [ZHANG Rui], [HKG], [2097], [15], [LI Nan], [CHN], [2092], [16], [FAN Ying], [CHN], [2085], [17], [BOROS Tamara], [CRO], [2085], [18], [PENG Luyang], [CHN], [2084], [19], [LEE Eunsil], [KOR], [2084], [20], [CAO Zhen], [CHN], [2076], [21], [TOTH Krisztina], [HUN], [2066], [22], [JIANG Huajun], [HKG], [2057], [23], [KIM Hyon Hui], [PRK], [2047], [24], [LI Xiaoxia], [CHN], [2035], [25], [LANG Kristin], [GER], [2022], [26], [FUKUHARA Ai], [JPN], [2020], [27], [UMEMURA Aya], [JPN], [2016], [28], [STRUSE Nicole], [GER], [2011], [29], [FUJINUMA Ai], [JPN], [2010], [30], [LI Jiawei], [SGP], [2006], [31], [ZAMFIR Adriana], [ROU], [2004], [32], [LIU Jia], [AUT], [1993], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [HIRANO Sayaka], [JPN], [1993], [34], [KIM Mi Yong], [PRK], [1983], [35], [SUK Eunmi], [KOR], [1982], [36], [#text(gray, "LI Jia")], [CHN], [1970], [37], [KOSTROMINA Tatyana], [BLR], [1968], [38], [SCHOPP Jie], [GER], [1965], [39], [BADESCU Otilia], [ROU], [1954], [40], [SCHALL Elke], [GER], [1949], [41], [WANG Chen], [CHN], [1944], [42], [LI Chunli], [NZL], [1941], [43], [ODOROVA Eva], [SVK], [1933], [44], [<NAME>], [KOR], [1931], [45], [<NAME>], [BLR], [1926], [46], [<NAME>], [JPN], [1924], [47], [STEFANOVA Nikoleta], [ITA], [1923], [48], [<NAME>], [RUS], [1913], [49], [<NAME>], [KOR], [1908], [50], [<NAME>], [CHN], [1904], [51], [BATORFI Csilla], [HUN], [1892], [52], [<NAME>], [HUN], [1876], [53], [<NAME>], [LUX], [1871], [54], [<NAME>], [SGP], [1869], [55], [STRBIKOVA Renata], [CZE], [1859], [56], [<NAME>], [CHN], [1851], [57], [LU Yun-Feng], [TPE], [1849], [58], [<NAME>], [ISR], [1847], [59], [POTA Georgina], [HUN], [1847], [60], [PASKAUSKIENE Ruta], [LTU], [1842], [61], [<NAME>], [ITA], [1841], [62], [<NAME>], [ROU], [1838], [63], [<NAME>], [HUN], [1834], [64], [<NAME>], [SGP], [1833], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [<NAME>], [CRO], [1823], [66], [NEGRISOLI Laura], [ITA], [1817], [67], [<NAME>], [SVK], [1816], [68], [<NAME>], [BLR], [1811], [69], [<NAME>], [TPE], [1810], [70], [KONISHI An], [JPN], [1808], [71], [<NAME>], [CRO], [1807], [72], [<NAME>], [KOR], [1799], [73], [WANG Yu], [ITA], [1798], [74], [HUANG Yi-Hua], [TPE], [1793], [75], [DOBESOVA Jana], [CZE], [1786], [76], [<NAME>], [JPN], [1785], [77], [LOGATZKAYA Tatyana], [BLR], [1775], [78], [<NAME>], [GER], [1774], [79], [LEE Hyangmi], [KOR], [1772], [80], [<NAME>], [KOR], [1772], [81], [<NAME>], [PRK], [1768], [82], [<NAME>], [JPN], [1755], [83], [STEFANSKA Kinga], [POL], [1753], [84], [<NAME>], [GER], [1753], [85], [<NAME>], [GER], [1752], [86], [<NAME>], [SLO], [1748], [87], [<NAME>], [JPN], [1744], [88], [<NAME>], [SLO], [1740], [89], [<NAME>], [KOR], [1740], [90], [<NAME>], [GER], [1738], [91], [<NAME>], [RUS], [1736], [92], [<NAME>], [KOR], [1735], [93], [<NAME>], [JPN], [1733], [94], [<NAME>], [JPN], [1728], [95], [<NAME>], [CZE], [1728], [96], [<NAME>], [SWE], [1725], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [NISHII Yuka], [JPN], [1724], [98], [<NAME>], [KOR], [1724], [99], [ITO Midori], [JPN], [1720], [100], [<NAME>], [FRA], [1717], [101], [MIAO Miao], [AUS], [1712], [102], [<NAME>], [FRA], [1710], [103], [<NAME>], [UKR], [1710], [104], [<NAME>], [HUN], [1707], [105], [<NAME>], [SWE], [1706], [106], [<NAME>], [IND], [1705], [107], [<NAME>], [RUS], [1700], [108], [<NAME>], [RUS], [1697], [109], [<NAME>], [USA], [1696], [110], [<NAME>], [GRE], [1690], [111], [<NAME>], [FRA], [1689], [112], [<NAME>], [FRA], [1686], [113], [<NAME>], [KOR], [1683], [114], [<NAME>], [CAN], [1683], [115], [<NAME>], [USA], [1681], [116], [<NAME>], [SWE], [1680], [117], [<NAME>], [DEN], [1677], [118], [<NAME>], [CAN], [1673], [119], [<NAME>], [CRO], [1671], [120], [<NAME>], [SRB], [1668], [121], [<NAME>], [HUN], [1657], [122], [<NAME>], [TPE], [1652], [123], [<NAME>], [SGP], [1652], [124], [#text(gray, "<NAME>wangsun")], [KOR], [1651], [125], [<NAME>], [POL], [1650], [126], [<NAME>], [CRO], [1649], [127], [#text(gray, "<NAME>")], [JPN], [1647], [128], [<NAME>], [BUL], [1641], ) )
https://github.com/ivaquero/book-control
https://raw.githubusercontent.com/ivaquero/book-control/main/10-状态观测器.typ
typst
#import "@local/scibook:0.1.0": * #show: doc => conf( title: "状态观测器", author: ("ivaquero"), header-cap: "现代控制理论", footer-cap: "github@ivaquero", outline-on: false, doc, ) = Luenberger 观测器 <Luenberger-观测器> 观测器:根据系统输入和输出,估计系统的状态。 == 推导 <推导> 对系统 $ dot(x) = 𝑨 x + 𝑩 u\ y = 𝑪 x + 𝑫 u $ 其中,$u$为输入,$y$为输出。 引入 Luenberger 观测器,有 $ hat(dot(x)) = 𝑨 hat(x) + 𝑩 u + 𝑳 (y - hat(y))\ hat(y) = 𝑪 hat(x) + 𝑫 u $ $(3), (4)$两式联立,得 $ hat(dot(x)) = (𝑨 - 𝑳 𝑪) hat(x) + (𝑩 - 𝑳 𝑫) u + 𝑳 y $ $(1) - (5)$,得 $ dot(x)- hat(dot(x)) = 𝑨 x + 𝑩 u - (𝑨 - 𝑳 𝑪) hat(x) - (𝑩 - 𝑳 𝑫) y - 𝑳 y $ 代入$(2)$,得 $ dot(x)- hat(dot(x)) = (𝑨 - 𝑳 𝑪)(x - hat(x)) $ 令$e_x = x - x ̂$,得 $ dot(e)_x = (𝑨 - 𝑳 𝑪) e_x $ 若像使$e_x → 0$,则需 $ "Re"["Eig"(𝑨 - 𝑳 𝑪)] < 0 $ 即当$|λ 𝑰 - (𝑨 - 𝑳 𝑪)| = 0$的解$λ < 0$,则系统稳定。 #tip[ 通过矩阵的迹的性质,可以确定系统稳定性。 ] == 弹簧阻尼系统 <弹簧阻尼系统> 对弹簧阻尼系统 - $m = 1$ - $K = 1$ - $B = 0.5$ #figure( image("./images/model/vibration.drawio.png", width: 40%), caption: [弹簧阻尼系统], supplement: "图", ) 令 - $z_1 = x$ - $z_2 = dot(x)$(不可测) - $u = F$ 则 $ mat(delim: "[", dot(z)_1; dot(z)_2) = mat(delim: "[", 0, 1; - 1, - 0.5) mat(delim: "[", z_1; z_2) + mat(delim: "[", 0; 1) u $ 同时 $ y = mat(delim: "[", 1, 0) mat(delim: "[", z_1; z_2) $ 引入观测器,有 $ mat(delim: "[", hat(dot(z))_1; hat(dot(z))_2) = mat(delim: "[", - 2.5, 1; 0.25, - 0.5) mat(delim: "[", hat(z)_1; hat(z)_2) + mat(delim: "[", 0; 1) u + mat(delim: "[", 2.5; - 1.25) y $ = 可观测性 <可观测性> == 分离原理 <分离原理> 对系统 $ dot(x) &= 𝑨 x + 𝑩 u\ y &= 𝑪 x $ 引入观测器 $ dot(e)_x = (𝑨 - 𝑳 𝑪) e_x $ 引入控制器 $ u &= -k hat(x) \ dot(x) &= 𝑨 x - 𝑩 k hat(x) = (𝑨 - 𝑩 k) x + 𝑩 k e $ 联立,得 $ mat(delim: "[", dot(e_λ); x ̇) = mat(delim: "[", 𝑨 - 𝑳 𝑪, 0; 𝑩 k, 𝑨 - 𝑩 k) mat(delim: "[", e_x; x ̇) = 𝑴 mat(delim: "[", e_x; x ̇) $ 为使$e_x → 0$,则需 $ "Re"["Eig"(𝑴)] < 0 $ 由于$𝑴$的特征值即是$(𝑨 - 𝑳 𝑪)$和$(𝑨 - 𝑩 k)$的特征值,则系统稳定需同时满足以下条件 - $"Re"["Eig"(𝑨 - 𝑳 𝑪)] < 0$ - $"Re"["Eig"(𝑨 - 𝑩 k)] < 0$ #tip[ 同一系统的观测器的收敛速度远大于控制器的。 ] #theorem("可观测性")[ 若一个系统可观测,则其观测矩阵 $ 𝑫 = mat(delim: "[", 𝑪; 𝑪 𝑨; ⋮; 𝑪 𝑨^(n-1)) $ 满秩。 ]
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/bugs/tinymist-issue640.typ
typst
Apache License 2.0
#for b in "if".at(1) { } #for b in "in".at(1) { }
https://github.com/pluttan/typst-g7.32-2017
https://raw.githubusercontent.com/pluttan/typst-g7.32-2017/main/gost7.32-2017/styles/page.typ
typst
MIT License
#import "../g7.32-2017.config.typ":config #let style_page(content) = { set page( footer: context [ #text(size: config.page.textSize)[ #let (num,) = counter(page).get() #if (num != 1) { align(config.page.alignNum)[#num] } ] ], paper: config.page.paper, margin: config.page.margin, ) set text(font: config.page.font, size: config.page.textSize, lang: "ru") set align(top) set par(justify: true, first-line-indent: config.page.parIndent) content }
https://github.com/rousbound/typst-lua
https://raw.githubusercontent.com/rousbound/typst-lua/main/tests/templates/test.typ
typst
Apache License 2.0
#set text(font: "New Computer Modern") //-- Lua Table test -- Hello #_LUADATA.world\ Hello #_LUADATA.true\ Hello #_LUADATA.at("1")\ LUA //-- JSOAN test Hello #_LUADATA.message\ Hello #_LUADATA.true\ Hello #_LUADATA.at("1")\ LUA //-- Additionas -- Hello #_LUADATA.at("nested_table").at("key")\ LUA //-- Lua Tabley Hello #_LUADATA.at("array").at(0)\ Hello #_LUADATA.at("array").at(1)\ LUA //-- Lua Tabled Types Hello #_LUADATA.at("mixed_types").at("key1")\ Hello #_LUADATA.at("mixed_types").at("key2")\ Hello #_LUADATA.at("mixed_types").at("key3")\
https://github.com/Functional-Bus-Description-Language/Specification
https://raw.githubusercontent.com/Functional-Bus-Description-Language/Specification/master/src/participants.typ
typst
#pagebreak() #text(16pt)[ *Participants* ] #set align(center) <NAME>, _Chair_, _Technical Editor_, #link("<EMAIL>") #set align(left) #pagebreak()
https://github.com/dyc3/good-typst-template
https://raw.githubusercontent.com/dyc3/good-typst-template/main/formats/apa.typ
typst
The Unlicense
#import "util.typ": * // BUG: there is a bug in typst that prevents paragraphs following a heading from being indented // see: https://github.com/typst/typst/issues/311 // as a workaround, just add a #h(2em) in front of the paragraph to indent it #let apa( title: "Paper Title", // A list of authors, each with a name and an optional affiliation: // { name: "<NAME>", affiliation: "Affiliation" } // or an affiliation can be derived from department and organization: // { name: "<NAME>", department: "Department", organization: "Organization" } authors: (), running-head: none, course: none, instructor: none, due-date: none, abstract: none, paper-size: "us-letter", bibliography-file: none, body, ) = { assert(running-head == none or running-head.len() <= 50, message: "running-head must be 50 characters or less") set document(title: title, author: authors.map(author => author.name)) let font-size = 12pt // "STIX Two Text" is a non-proprietary version of Times New Roman set text(font: "STIX Two Text", size: font-size) // APA style requires double-spacing set par( leading: 2em, first-line-indent: 2em, ) // set par( // hanging-indent:-2em, // ) // show par: set block( // inset: ( // left: 3in, // ) // ) set page( paper: paper-size, margin: 1in, header: { if (running-head != none) { upper(running-head) } else { none } h(1fr) counter(page).display("1") }, footer: none, numbering: "1", number-align: right + top, ) show heading: it => { set text(size: font-size, weight: "bold") if it.level == 1 { set align(center) it } else if it.level == 2 { it } else { set align(left) if it.level == 3 { set text(style: "oblique") it } else { panic("unsupported heading level -- level 4 and 5 headings are supposed to be inline headings. Just make the text bold for level 4, and additionally italic for level 5 manually.") // if it.level == 5 { // set text(style: "oblique") // it.body // } else { // it.body // } } } // HACK: there is a bug in typst that prevents paragraphs following a heading from being indented // see: https://github.com/typst/typst/issues/311 par()[#text(size:1em)[#h(0.0em)]] } // APA style has this really annoying requirement for how authors and affiliations are displayed. // https://apastyle.apa.org/style-grammar-guidelines/paper-format/title-page authors = authors.map(author => { if "affiliation" in author { author } else { author.affiliation = (author.department, author.organization).join(", ") author } }) let unique_affiliations = unique(authors.map(author => author.affiliation)) let show_affiliation_refs = unique_affiliations.len() > 1 set align(center) v(6em) heading(title) v(2em) block()[ #authors.map(author => { author.name if show_affiliation_refs { super(str(unique_affiliations.position(aff => aff == author.affiliation) + 1)) } }).join(", ", last: " and ") ] for (i, aff) in unique_affiliations.enumerate() { block()[ #if show_affiliation_refs { super(str(i + 1)) aff } else { aff } ] } if (course != none) { block()[ #course ] } if (instructor != none) { block()[ #instructor ] } if (due-date != none) { block()[ #due-date.display("[month repr:long] [day], [year repr:full]") ] } pagebreak() set align(left) if (abstract != none) { heading("Abstract") abstract pagebreak() } heading(title) body if (bibliography-file != none) { bibliography( bibliography-file, title: "References", style: "apa", ) } }
https://github.com/ist199211-ist199341/devops-nixos-demo
https://raw.githubusercontent.com/ist199211-ist199341/devops-nixos-demo/master/slides/slides.typ
typst
#import "@preview/polylux:0.3.1": * #import themes.clean: * #set document( title: [DevOps Demo: Declarative and Reproducible Deployments with NixOS], author: ("<NAME>", "<NAME>"), keywords: ("nixos", "demo", "devops"), date: datetime(year: 2024, month: 9, day: 25, hour: 13, minute: 00, second: 00) ) // compile .pdfpc wth `polylux2pdfpc {fname}.typ` // then present with, e.g., `pdfpc --windowed both {fname}.pdf` // uncomment to get a "submittable" PDF // #enable-handout-mode(true) #let kthblue = rgb("#000060") #show: clean-theme.with( short-title: [*Demo: Declarative and Reproducible Deployments with NixOS*], color: kthblue, logo: image("common/KTH_logo_RGB_bla.svg"), ) #pdfpc.config(duration-minutes: 7) // consistent formatting + make typstfmt play nice #let notes(speaker: "???", ..bullets) = pdfpc.speaker-note("## " + speaker + "\n\n" + bullets.pos().map(x => "- " + x).join("\n")) #show link: it => underline(stroke: 1pt + kthblue, text(fill: kthblue, it)) #let focus = it => text(kthblue, strong(it)) #let big-picture-slide(content) = { polylux-slide({ place(top + left, image("assets/nix-wallpaper-nineish-dark-gray.svg")) set text(white, 2em) set align(left + horizon) box(width: 40%, align(center + horizon, content)) }) } #let cover = title-slide( title: text(25pt)[Declarative and Reproducible Deployments with NixOS], subtitle: [ DD2482 Automated Software Testing and DevOps *Demo* #smallcaps[KTH Royal Institute of Technology] Wednesday, 25#super[th] of September, 2024 #notes( speaker: "Diogo", "introduce topic", "introduce presenters", ) ], authors: ( [<NAME>\ #link("mailto:<EMAIL>")], [<NAME>\ #link("mailto:<EMAIL>")], ), ) #cover #new-section-slide("Introduction") #slide(title: "What is Nix/NixOS?")[ #side-by-side[ - *Nix*, the (functional) language - *Nix*, the package manager - *NixOS*, the operating system - *Nixpkgs*, the package repository ][ #align(center, image("assets/nix-snowflake-colours.svg", height: 70%)) ] #notes( speaker: "Diogo", "nixlang/nix/nixos/nixpkgs", ) ] #slide(title: "Why Nix/NixOS?")[ #v(1em) #grid( columns: (1fr, 1fr, 1fr), gutter: 1em, align: center + bottom, image("assets/reproducible.svg", height: 50%), image("assets/declarative.svg", height: 50%), image("assets/reliable.svg", height: 50%), [*Reproducible*], [*Declarative*], [*Reliable*], ) #notes( speaker: "Tomás", "Reproducible: works on my machine, works on every machine", "Declarative: infrastructure as code, allows you to copy code from stackoverflow and it will work", "Reliable: if something goes bad, you can always rollback and avoid being fired", ) ] #slide(title: "Demo Outline")[ - *disko*#super[3rd party], declare disk partitions - *nixos-anywhere*#super[3rd party], deploy new host - *nixos-rebuild*, update existing host #notes( speaker: "Tomás", "declare disk partitions with disko", "provision a new host with nixos-anywhere", "update the host with nixos-rebuild", ) ] #big-picture-slide()[ Demo ] #new-section-slide("Conclusion") #big-picture-slide()[ With NixOS, you can declare your infrastructure once and deploy it forever #notes( speaker: "Diogo", "Declare once, deploy forever, wherever" ) ] #cover
https://github.com/dccsillag/moremath.typ
https://raw.githubusercontent.com/dccsillag/moremath.typ/main/README.md
markdown
MIT License
# Moremath Additional notation, constants and utilities for doing math in [Typst](https://typst.app/). To use, just import: ```typst #import "@preview/moremath:0.1.0": * ``` ## Features ### Bracket sizing When parentheses/brackets get too nested, it can be useful to force some of them to be larger. `moremath` provides two helpers for this: **`big`**: instead of writing `[(a + b) + c]`, to make the brackets bigger, you can write `big([(a + b) + c])`. This works for any kind of surrounding brackets/parentheses/braces. **`bigp`**: instead of writing `((a + b) + c)`, to make the external parentheses bigger, you can write `bigp((a + b) + c)`. This is essentially the same as `big`, simply avoiding an extra set of parentheses. ### Numbered equations Until we get better equation numbering built-in (e.g., for numbering only equations that are labelled), we have to manually indicate which equations to number. In order to make this easier, one can use our `numbered` function: ```typst $ f(x) = x^2 $ // non-numbered #numbered[ $ f(x) = x^2 $ <my-label> ] // numbered ``` ### Handy caligraphic letters Caligraphic letters (e.g., `cal(G)`) are very common in math. In order to make them easier to typeset, and akin to Typst's built-in handy blackboard letters (e.g., `RR`), we provide aliases for caligraphic letters via double lowercase letters. So, for example, `gg` becomes `cal(G)`, and `aa` becomes `cal(A)`. Except for `oo`, that's infinity, as in plain Typst. ### Additional notation We also provide a bunch of additional notation for mathematics in general. Do note, however, that what we provide is heavily skewed towards the author's current research interests :) If you have suggestions for more notation to be added, feel free reach out and contribute! #### Probability theory - `indep`: Independence symbol (double perp). - `nindep`: Crossed out `indep`, for denoting non-independence. - `Pr`: alternative notation for probability. - `Ex`: alternative notation for expectation. - `Var`: variance. - `Cov`: covariance. - `ind`: indicator function, denoted by `bb(1)`. - `iid`: text holding "iid". Can be used, e.g., as `X_1, ..., X_n ~^iid P`. #### Analysis - `oh`: small oh - `Oh`: big oh - `ohmega`: small omega - `Ohmega`: big omega - `Thetah`: big theta - `deriv`: general derivative operator - `dist`: upright "d", for metrics #### Misc - `sign`: sign function. - `argmin`: `arg min` operator, supporting limits. - `argmax`: `arg max` operator, supporting limits.
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/parts/main-body-degree-fn.typ
typst
MIT License
#import "../utils/states.typ": part-state #import "../utils/fonts.typ": 字体, 字号 #let main-body-bachelor-conf( thesis-name: [], first-level-title-page-disable-heading: false, // 一级标题页不显示页眉 // 启用此选项后,“第X章 XXXXX” 一级标题所在页面将不显示页眉 doc ) = { set page( header: { set align(center) set text(font: 字体.宋体, size: 字号.小五, lang: "zh") set par(first-line-indent: 0pt, leading: 16pt, justify: true) show par: set block(spacing: 16pt) locate(loc => { // 真正的一级标题会被装入这里,如果是 none 则不渲染本页的页眉 let true-level-1-heading = none // 先确定下一个一级标题 let next-level-1-heading = query( selector(heading.where(level: 1)).after(loc), ).filter( it => it.location().page() == loc.page() ).at(0, default: none) if next-level-1-heading == none { // 如本页不存在下一个一级标题 // 1. 本页不是一级标题所在页面(不需要考虑是否显示的问题) // 2. 本页所在章节由上一个一级标题所定义 true-level-1-heading = query( selector(heading.where(level: 1)).before(loc), ).at(-1, default: none) } else { // 如果在本页,那么就要处理“一级标题是否显示页眉”参数 true-level-1-heading = if first-level-title-page-disable-heading {none} else {next-level-1-heading} } // 取所在章节的逻辑结束 if true-level-1-heading == none { [] } else if calc.even(loc.page()) { thesis-name.heading v(-1em) line(length: 100%, stroke: (thickness: 0.5pt)) } else { if true-level-1-heading.numbering != none { (true-level-1-heading.numbering)( counter(heading.where(level: 1)).at( true-level-1-heading.location(), ).first(), ) h(0.5em) } true-level-1-heading.body v(-1em) line(length: 100%, stroke: (thickness: 0.5pt)) } }) // locate 结束 counter(footnote).update(0) }, numbering: "1", header-ascent: 10%, footer-descent: 10%, ) pagebreak(weak: false) counter(page).update(1) counter(heading.where(level: 1)).update(0) part-state.update("正文") doc }
https://github.com/lebinyu/typst-thesis-template
https://raw.githubusercontent.com/lebinyu/typst-thesis-template/main/template/reference_style.typ
typst
Apache License 2.0
// import heading style #import "global_style.typ": * // make abstract page #let referencepage( mainbody: "", ) = { set page( numbering: "I", ) // counter(page).update(1) show: styleheading_head("Reference", mainbody) set page( margin: (x: 3cm, y:2.5cm), header: none ) // mainbody }
https://github.com/Jollywatt/typst-fletcher
https://raw.githubusercontent.com/Jollywatt/typst-fletcher/master/tests/label-side/test.typ
typst
MIT License
#set page(width: auto, height: auto, margin: 1em) #import "/src/exports.typ" as fletcher: diagram, node, edge #diagram(spacing: (3cm, 1cm), { for (i, a) in (left, center, right).enumerate() { for (j, θ) in (-30deg, 0deg, 50deg).enumerate() { edge((j, 2*i), (j, 2*i - 1), label: a, "->", label-side: a, bend: θ) } } }) #diagram(spacing: 1.5cm, { for (i, a) in (left, center, right).enumerate() { for (j, θ) in (-30deg, 0deg, 50deg).enumerate() { edge((2*i, j), (2*i + 1, j), label: a, "->", label-side: a, bend: θ) } } })
https://github.com/kilpkonn/typst-thesis
https://raw.githubusercontent.com/kilpkonn/typst-thesis/main/authors_declaration.typ
typst
MIT License
#align(center)[ #heading( outlined: false, numbering: none, text(1em, "Author’s Declaration of Originality"), ) ] #v(2em) I hereby certify that I am the sole author of this thesis. All the used materials, references to the literature and the work of others have been referred to. This thesis has not been presented for examination anywhere else.
https://github.com/GolemT/BA-Template
https://raw.githubusercontent.com/GolemT/BA-Template/main/README.md
markdown
# BA-Template Dieses GIT Repository enthält das [Typst](https://typst.app/) Template für die Ausarbeitungen an der [Berufsakademie Rhein-Main](https://studenten.ba-rm.de/).
https://github.com/sora0116/unix_seminar
https://raw.githubusercontent.com/sora0116/unix_seminar/master/exercise/main.typ
typst
#set page(numbering: "1") #set heading(numbering: "1.1") #set text(size: 12pt, font: ("New Computer Modern", "<NAME>")) #[ #align(center + horizon)[ #text(2em)[第10回Unixゼミ\ Cプログラム(デバッグ編)\ 演習] #text(1.3em)[高木 空] #datetime(year: 2024, month: 7, day: 1).display("[year]年[month]月[day]日") ] #pagebreak() ] #outline(title: "目次", indent: 1em) = 演習1 (GDB) この演習は`ex1-2/`に必要なリソースが入っています。`ex1-2/`に移動してください。 以下のことをGDBで実行してください。 1. デバッグ情報を付与して`test.c`をコンパイルしてください。 2. 1. で作成した実行ファイルを読み込んでGDBを起動してください。 3. 以下の場所にブレークポイントを設置してください。 - 63行目 - 35行目 (`i<=j`の条件付き) - 関数`qsort` (`low>high`の条件付き) 4. プログラムを起動してください。(63行目で停止したことを確認) 5. 変数`data`を長さ12の配列として表示してください。 6. 関数の中にステップ実行で入ってください。(関数の先頭で停止したことを確認) 7. 変数`data`を長さ12の配列として表示してください。 8. 次の停止場所まで進んでください。(35行目で停止したことを確認) 9. 変数`i`と`j`の値を表示してください。(5, 11となっていることを確認) 10. 次の停止場所まで進んでください。 11. バックトレースを確認してください。(`main`関数が`#2`であることを確認) 12. 35行目に設置したブレークポイントを削除してください。 13. 次の停止場所まで進んでください。(`low=0, high=-1`の`qsort`呼び出し内であることを確認) 14. ブレークポイントを全て削除してください。 15. 一番最初の`qsort`関数が終了するまで実行してください。 16. 変数`data`を長さ12の配列として表示してください。(ソートされていることを確認) 17. 最後まで実行してGDBを終了してください。 回答 @ans1 = 演習2 (LLDB) この演習は`ex1-2/`に必要なリソースが入っています。`ex1-2/`に移動してください。 演習1と全く同じことをLLDBで行ってください。 回答 @ans2 = 演習3 (Perf) この演習は`ex3/`に必要なリソースが入っています。`ex3/`に移動してください。 `test.c`には2つの行列の和を求めるプログラムが入っています。 アクセスパターンによるキャッシュミスの増減を`perf`を使って確認しましょう。 先ずは`mut_add_a`のコメントアウトを消してコンパイルしてください。 次に`perf stat`でイベント`L1-dcache-load-misses`と`L1-dcache-loads`を集計してください。 次に`mut_add_b`に切り替えて再度コンパイルし、同様にプロファイルを行ってください。 そしてL1キャッシュミスと実行時間を確認してください。 また、いづれかの方で`perf record`を実行し、`perf report`を試してみてください。 = 演習1回答 (GDB) <ans1> ``` $ gcc -g test.c -o a.out $ gdb ./a.out (gdb) break 63 (gdb) break 35 if i<=j (gdb) break qsort if low>high (gdb) run (gdb) print data (gdb) step (gdb) print *data@12 (gdb) continue (gdb) print i (gdb) print j (gdb) backtrace (gdb) delete 2 (2かどうかは設置順に依る) (gdb) continue (gdb) delete (gdb) frame 11 (gdb) finish (gdb) print data (gdb) continue (gdb) quit ``` = 演習2回答 (LLDB) <ans2> ``` $ gcc -g test.c -o a.out $ gdb ./a.out (lldb) breakpoint set -l 63 (lldb) breakpoint set -l 35 -c i<=j (lldb) breakpoint set -n qsort -c low>high (lldb) process launch (lldb) frame variable data (lldb) thread step-in (lldb) frame variable -Z 12 data (lldb) thread continue (lldb) frame variable i j (lldb) thread continue (lldb) thread backtrace (lldb) breakpoint delete 2 (2かどうかは設置順に依る) (lldb) thread continue (lldb) breakpoint delete (lldb) frame select 11 (lldb) thread step-out (lldb) frame variable data (lldb) thread continue (lldb) quit ``` = 演習3回答 (perf) <ans3> ``` $ perf stat -e L1-dcache-load-misses,L1-dcache-loads ./a.out ```
https://github.com/chrischriscris/Tareas-CI5651-EM2024
https://raw.githubusercontent.com/chrischriscris/Tareas-CI5651-EM2024/main/tarea09/src/main.typ
typst
#import "template.typ": conf, question, pseudocode, GITHUB_REPO #show: doc => conf("Tarea 9: Algoritmos probabilísticos y aproximados", doc) #question[ Considere su número de carné (sin el guión) restando 1 si es par, concatenado tres veces, como un número entero. Por ejemplo, si su carné es `12-34567`, entonces el entero a considerar sería: #align(center)[ 123456712345671234567 ] Muestre la ejecución del algoritmo de Miller–Rabin repetido, paso a paso (a nivel del ciclo principal de `MillerRabinRep`), para ver si el número es primo o compuesto, usando $k = 10$. ¿En cuántas iteraciones obtiene el resultado esperado? ¿Ejecutó las $k = 10$ iteraciones? _Nota: Puede usar el generador de números aleatorios que viene con su lenguaje de elección._ ][ En este caso, el carné es `18-10892`, por lo que el número a considerar es $181089118108911810891$. Notemos que, por construcción, para cualquier carnet el número resultante de concatenarlo 3 veces será compuesto, de la siguiente manera: Sea $c > 1$, $c in NN$ un carnet dado, concatenar $c$ 3 veces será equivalente a: $ c + c*10000000 + c*100000000000000 &= c*(1 + 10000000 + 100000000000000)\ &= c*100000010000001 $ Veamos entonces cuál es el resultado de la ejecución del algoritmo de Miller-Rabin: - El número aleatorio $a$ resulta ser $a = 106681647674259816197$ (generado por un dado de 6 caras). - El primer ciclo itera 1 vez: - $t = 90544559054455905445$. - $x = a^t mod 181089118108911810891 = 87323191318267542098$. - El resultado no es 1 ni $n - 1 = 181089118108911810890$. - Como $s = 1$ el segundo ciclo no itera. - Se concluye que el número es compuesto, y no hace falta seguir con las iteraciones restantes. ][ Sea $A$ y $B$ dos matrices $n times n$, para algún entero $n > 0$. Sospechamos que $B = A^(−1)$. Esto es, que $B$ es la matriz inversa de $A$. Diseñe un algoritmo de Monte Carlo que permita confirmar esta sospecha, con un cierto error permitido $epsilon$, usando tiempo $O(n^2 log 1/epsilon)$. _Nota: Puede usar el generador de números aleatorios que viene con su lenguaje de elección._ ][ Queremos saber si $A B = I_n$, sea $I_n$ la matriz identidad de grado $n$. Así, un algoritmo de Monte Carlo que nos permite confirmar esta sospecha con un error arbitrario $epsilon > 0$ y tiempo $O(n^2 log 1/epsilon)$ es ejecutar el método de Freivalds $k$ veces, con $k = lg(1/epsilon)$: #pseudocode[ ```python def freivalds(A: Matriz, B: Matriz, C: Matriz) -> bool: n = A.tamaño x = vector_aleatorio(0, 1, n) return x*A*B == x*C def es_inversa(A: Matriz, B: Matriz, epsilon: Real) -> bool: n = A.tamaño k = ceil(log(1/epsilon)) I = matriz_identidad(n) i = 0 while i < k: if not freivalds(A, B, I): return False i = i + 1 return True ``` ] Una implementación de este algoritmo en Java se puede encontrar #link(GITHUB_REPO + "tarea9/ej2/")[aquí]. ][ Sea un grafo $G = (N, C)$, decimos que $V subset.eq N$ es un cubrimiento de vértices para $G$ si todas las conexiones tienen alguno de sus extremos en V . $ (forall a, b in N : {a, b} in C => {a, b} sect V != emptyset) $ Sea $"MIN−COVER"$ el problema de hallar un cubrimiento de vértices de cardinalidad mínima. Sabemos que $"MIN−COVER"$ es $"NP"$–completo. Diseñe un algoritmo para el problema 1–relativo–$"MIN−COVER"$ asociado. Esto es, diseñe un algoritmo eficiente (en tiempo polinomial) que resuelve el problema del mínimo cubrimiento de vértices, produciendo una respuesta que es a lo sumo el doble de la solución óptima. Debe demostrar que esto último es cierto para su algoritmo propuesto. ][ Para resolver aproximadamente el problema del mínimo cubrimiento de vértices, basta con ir tomando aristas $A$ cualesquiera del grafo y eliminar las aristas incidentes a los vértices de $A$, pues ya estarán cubiertas por los vértices de $A$, que se agregarán al cubrimiento. Si repetimos esto hasta considerar todas las aristas, obtendremos un cubrimiento de vértices. Veamos el algoritmo: #pseudocode[ ```python def min_cover(G: Grafo) -> Conjunto: C = {} for u, v in G.aristas: C.unir({u, v}) G.eliminar_vertice(u) G.eliminar_vertice(v) return C ``` ] Notemos que, como en cada iteración escogemos una arista distinta y eliminamos sus vértices y respectivas aristas incidentes, el cubrimiento $C$ obtenido será equivalete a un _emparejamiento_, y de hecho, uno maximal (si en vez de guardar los vértices guardáramos las aristas). Llamemos $M$ a este emparejamiento. Por otro lado, tenemos también que un cubrimiento de vértices de cardinalidad mínima debe contener por definición al menos un vértice por cada arista del emparejamiento maximal (de no ser así, no cubriría todas las aristas), es decir, sea $C^*$ la solución óptima, entonces $|M| <= |C^*|$. Pero el algoritmo propuesto no guarda aristas, sino los dos vértices de la misma, por lo que $|C| = 2|M|$, y por lo tanto $(|C|)/2 <= |C^*|$, o lo que es lo mismo, $|C| <= 2|C^*|$. Se concluye así que el algoritmo propuesto produce una respuesta que es a lo sumo el doble de la solución óptima. Una implementación de este algoritmo en Typescript se puede encontrar #link(GITHUB_REPO + "tarea9/ej3/")[aquí]. ]
https://github.com/swaits/typst-collection
https://raw.githubusercontent.com/swaits/typst-collection/main/finely-crafted-cv/0.1.0/src/state.typ
typst
MIT License
#let __settings = state("__cv_settings", (:)) #let __set(key, value) = { __settings.update(st => { st.insert(key, value) st }) } #let __get(key) = { __settings.final().at(key, default: none) }
https://github.com/davawen/Cours
https://raw.githubusercontent.com/davawen/Cours/main/Physique/Electricité/circuit_lineaire_regime_continue.typ
typst
#import "@local/physique:0.1.0": * #import elec: * #show: doc => template(doc) #titleb[Étude des circuits linéaires en régime continu] = Influence de la résistance des appareils de mesure #def[Appareil de mesure]: Ampèremètre, voltmètre, etc... #def[Ampèremètre]: Mesure des intensités, en série, dans la branche où on veut mesurer des intensités \ #def[Voltmètre]: Mesure des tension, en parallèle aux bornes de la portion de circuit dont on veut connaître la tension. Exemple, on veut connaitre la tension et l'intensite de ce résistor: #figcan({ resistor((0, 0), u: tenserl($u$), name: "r") node((-1, 0), name: "A") node((1, 0), name: "B") fil("A", "r.l", "B", "r.r") }) == Montages en courte dérivation ou en longue dérivation Branchement en courte dérivation: #figcan({ resistor((0, 0), u: tenserl($u$), name: "r") node((-2, 0), name: "A") node((2, 0), name: "B") voltmetre((0, 1), name: "V") amperemetre((3, 0), name: "Am") fil("A", "r.l", "B", "r.r", i: $i_R$) fil("V.l", "A", "V.r", "B", i: $i_A$) fil("B", "Am.l") fil((-3, 0), "A", "Am.r", (4, 0), i: $i$) }) On mesure la bonne tension, mais une partie de l'intensité va partir dans la branche du voltmètre. Branchement en longue dérivation: #figcan({ node((-4, 0), name: "A") node((4, 0), name: "B") voltmetre((0, 1), name: "V") serie((0, 0), name: "D", i: $i_R$, apply(resistor, u: tenserl($u_R$)), apply(amperemetre, u: tenserl($u_A$)) ) fil("A", (-3, 0), (3, 0), "B", i: $i$) fil((-3, 0), "D.l", "D.r", (3, 0)) fil("V.l", (-3, 0), "V.r", (3, 0), i: $i_V$) }) On mesure la bonne intensité, mais une partie de la tension va venir de l'ampèremètre. == Valeur de la résistance mesurée === Branchement en longue dérivation $ R_"mes" = U_"mes"/I_"mes" = U/I $ L'intensité mesurée est correcte, mais la tension mesurée ne l'est pas: $ U = (R + R_A) I $ D'où $ R_"mes" = R + R_A $ On voit que $R_"mes" approx R$ quand $R_A << R$. On le préferera quand $R$ est grand. === Branchement en courte dérivation La tension mesurée est correcte, mais l'intensité ne l'est pas: $ I = I_V + I_R = U/R_V + U/R = U (R + R_V)/(R R_V) $ D'où: $ R_"mes" = U_"mes"/I_"mes" = U/I = (R R_V)/(R + R_V) $ On voit que $R_"mes" approx R$ quand $R << R_V$. On le préfera quand $R$ est petit. == Valeurs à priviligier pour les appareils Quand on place un ampèremètre sur un circuit, il faut que la tension à ses bornes soit négligable pour ne pas perturber le circuit. Ainsi, la résistance interne de l'ampèremètre doit être le plus faible possible. (de l'ordre de grandeur de quelques $ohm$). De même, pour que le voltmètre ne perturbe pas une mesure, l'intensité qui le parcourt doit être très petite, donc il doit avoir une résistance interne très grande. Il faut connaître l'ordre de grandeur des résistance de voltmètre: quelques M$ohm$. Il faudra aussi faire attention à la résistance interne des générateurs ($approx 50 ohm$) et des oscilloscopes. = Ponts diviseurs de tension et de courant == Pont diviseurs de tension #figcan({ serie((0, 0), rot: -90deg, i: $i$, u: tenserl($u$), inset: 1.5, apply(resistor, label: $R_2$, u: tenserl($u_2$)), apply(resistor, label: $R_1$, u: tenserl($u_1$)) ) }) <NAME> dit: Si on veut appliquer le pont diviseur de tension, il faut identifier le pont diviseur de tension. On considère un pont diviseur de tension si l'intensité partant d'un nœud entre deux résistances est quasi-nulle. On peut donc se permettre de rajouter un dipôle en parallèle de $R_1$, si ce dernier possède une résistance $>> R_1$ (comme un voltmètre). #figcan({ serie((0, 0), rot: -90deg, i: $i$, u: tenserl($u$), inset: 1.2, name: "D", apply(resistor, label: $R_2$, u: tenserl($u_2$)), apply(node, name: "A", round: true), apply(resistor, label: $R_1$, u: tenserl($u_1$)) ) fil("D.A", (rel: (2, 0), to: "D.A"), i: $i = 0$, straight: false) }) On a: $ u = (R_1 + R_2)i \ <=> i = u / (R_1 + R_2) $ $ u_1 = R_1 i = u R_1/(R_1 + R_2) $ $ u_2 = R_2 i = u R_2/(R_1 + R_2) $ == Pont diviseur de courant On a un courant qui arrive. Si on veut le diviser, on va mettre deux résistances en parallèle: #figcan({ derivation((0, 0), i: $i$, u: tenserl($u$), inset: 2, apply(serie, inset: 1.2, i: $i_1$, apply(resistor, label: $R_1$)), apply(serie, inset: 1.2, i: $i_2$, apply(resistor, label: $R_2$)) ) }) On a: $ u = R_1 i_1 = R_2 i_2 \ <=> i_2 = R_1/R_2 i_1 $ $ i = i_1 + i_2 = i_1 + R_1/R_2 i_1 \ = i_1((R_1 + R_2)/R_2) $ $ i_1 = i R_2/(R_1 + R_2) $ // On peut faire les deux en même temps: On peut aussi utiliser une résistance de charge: #figcan({ derivation((0, 0), inset: 2, width: 8, i: $i$, u: tenserl($u$), apply(serie, i: $i_1$, apply(resistor, label: $R_1$), apply(resistor, label: $R_c$) ), apply(serie, i: $i_2$, apply(resistor, label: $R_2$)) ) }) On a: $ u = (R_1 + R_c) i_1 = R_2 i_2 $ $ i_2 = i_1 (R_1 + R_c)/R_2 $ $ i = i_1 + i_2 \ = i_1 + i_1 (R_1 + R_c)/R_2 \ = i_1 (R_1 + R_2 + R_c)/R_2 $ $ i_1 = i R_2/(R_1 + R_2 + R_c) $ En choissisant judicieusement les valeurs de $R_1$ et $R_2$, on peut choisir exactement quelle intensité va parcourir le dipôle de résistance $R_c$. = Exemples d'applications On peut utiliser les ponts pour connaître la tension et l'intensité à n'importe quel point du circuit. == Lois de Kirchehhofhf Example de circuit: #figcan({ serie((0, 0), name: "D", apply(resistor, label: $R_1$), apply(node, name: "A", round: true), apply(resistor, label: $R_2$) ) node((0, -3), name: "B", round: true) resistor((0, -1.5), rot: -90deg, name: "d") fil("D.A", "d.l") fil("d.r", "B") fil("D.l", "B", "D.r", "B", rev: 1) source-ideale((-3.6, -1.5), rot: -90deg, u: tenserl($E_1$), name: "e1") source-ideale((3.6, -1.5), rot: -90deg, u: tenserl($E_2$), name: "e2") maille((-1.5, -1.5), 0.5, rev: true) maille((1.5, -1.5), 0.5) }) On veut retrouver les intensites $i_1$, $i_2$, et $i_3$. On commence par appliquer les loi des nœuds et des mailles: On a: - Lois des nœuds: $i_1 + i_2 + i_3 = 0$ - Lois des mailles (1): $E_1 - R_1 i_1 + R_3 i_3 = 0$ - Lois des mailles (2): $E_2 - R_2 i_2 + R_3 i_3 = 0$ - Lois des mailles (3): $E_1 - R_1 i_1 + R_2 i_2 - E_2 = 0$ $ cases( i_3 = -i_1 - i_2, E_1 - R_1 i_1 + R_3(-i_1 - i_2) = 0, E_2 - R_2 i_2 + R_3 (-i_1 - i_2) = 0 ) \ <=> cases( i_3 = -i_1 - i_2, E_1 - (R_1 + R_3) i_1 - R_3 i_2 = 0 times R_3, E_2 - R_3 i_1 - (R_2 + R_3)i_2 = 0 times -(R_1 + R_3) ) \ <=> cases( i_3 = -i_1 - i_2, R_3 E_1 - R_3^2 i_2 - (R_1 + R_3)E_2 + (R_2 + R_3)(R_1 i R_3) = 0, (R_2 + R_3)E_1 - (R_2 + R_3)(R_1 + R_2)i_1 - R_3 E_2 + R_3^2 i_1 = 0 ) \ <=> cases( i_3 = -i_1 - i_2, i_2 = ((R_1 + R_3)E_2 - R_3 E_1)/(R_1 R_2 + R_1 R_3 + R_2 R_3), i_1 = ((R_2 + R_3)E_1 - R_3 E_2)/(R_1 R_2 + R_1 R_3 + R_2 R_3) ) $ $ (V dot A^(-1) dot V - V dot A^(-1) dot V)/(V^2) \ (V^2 dot A^(-1))/( V^2 dot A^(-2) ) = A $ == Utilisation du pont diviseur de tension #figcan({ carre((0, 0), (branch: ( apply(resistor, label: $R$), apply(source-ideale, label: tenserl($E$)) )), apply(resistor, label: $2R$), (top: "B", down: "A", u: tenserl($u$), branch: apply(resistor, label: $3R$) ), apply(resistor, label: $R$), (branch: (apply(resistor, label: $3R$))), (branch: (apply(resistor, label: $2R$))), ) }) D'abord, on réduit notre circuit au maximum (résistances en série et en parallèle). On a: 1. $ R_2 = R + 2R = 3R $ 2. $ 3R parallel 2R => R_"eq" = 1/(1/(3R) + 1/(2R)) = 1/(6/R) = (6R)/5 $ On réduit les deux résistances maintenant en parallèle: $ R'_"eq" = R + R_"eq" = R + (6R)/5 = 11/5 R $ $ R_1 = 1/(1/(3R) + 1/(R'_"eq")) = 1/(1/(3R) + 5/(11R)) &= (33R)/(11 + 15) \ &= 33/26 R $ Une fois que notre circuit est réduit à: #figcan({ carre((0, 0), branch(apply(source-ideale)), apply(resistor, label: $3R$), branch(top: "B", down: "A", apply(resistor, label: $3R$)), branch(apply(resistor, label: $(6R)/5$)), // (branch: ) ) }) On veut connaître la tension $u_1$. On applique le pont diviseur de tension: $ u _1 = R_1 E(R_1 + R_2) = (33/26 R)/(33/26 R + 3 R) E \ = (3 times 11)/(3 times 11 + 3 times 26)E = 11/37 E $ Mettons qu'on veuille connaître la tension $v$ comme il suit: #figcan({ carre((0, 0), branch( apply(resistor, label: $R$), apply(source-ideale, label: tenserl($E$)) ), apply(resistor, label: $2R$), branch(top: "B", down: "A", apply(resistor, label: $3R$) ), apply(resistor, label: $R$), branch(apply(resistor, label: $3R$)), branch(u: tenserl($v$), apply(resistor, label: $2R$)), ) }) On se place sur la droite du circuit, et on utilise la tension de $u_1$ qu'on a déjà caculé. On trouve: $ v = (R_"eq" u)/(R + R_"eq") = ((6R)/5 (11E)/37)/(R + (6R)/5) = (6E)/37 $ == Utilisation du pont diviseur de courant #figcan({ carre((0, 0), branch(), apply(resistor, label: $2R$), branch(apply(resistor, label: $3R$)), apply(resistor, label: $R$), branch(apply(resistor, label: $3R$)), branch(apply(source-ideale-courant, label: tenserl($I_0$))) ) }) On veut connaître le courant $i_1$ passant par la résistance $R_2$. On va fusionner toutes les autres résistances en une grosse résistance $R_2$, et on va appliquer le pont diviseur de courant pour trouver l'intensité $i_1$. #todo[] On calcule la valeur de la résistance $R_2$: 1. On a l'association en série de $R$ et de $2R$ de résistance $R_"eq" = 3R$ 2. $R_"eq"$ et $3R$ en parallèle, d'où: $ R'_"eq" = 1/(1/R_"eq" + 1/(3R)) = 1/(1/(3 R) + 1/(3R)) = (3 R)/2 $ 3. $R'_"eq"$ et $R$ en série: $R_2 = (3R)/2 + R = 5/2 R$ Il ne reste plus qu'a appliquer le pont diviseur de courant: $ R_1 i_1 = R_2 i_2 <=> i_2 = R_1/R_2 i_1 $ $ I_0 = i_1 + i_2 = i_1 + R_1/R_2 i_1 = i_1 (R_1 + R_2)/R_2 $ $ i_1 = (R_2 I_0)/(R_1 + R_2) $ $ i_1 = (5/2 R I_0)/(3R + 5/2 R) = 5/11 I_0 $ On peut maintenant calculer l'intensité passant par la résistance du milieu: On dit que $R_2$ n'est plus que les deux résistances à la fin On applique la loi des nœuds: $ i_2 = I_0 - i = I_0 - 5/11 I_0 = 6/11 I_0 $ On a $R_1 = 3R$, $R_2 = R + 2R = 3R $ On applique le pont diviseur de courant: $ i' = (3R 6/11 I_0)/(3R + 3R) = 3/11 I_0 $ == Double pont diviseur de tension Ne pas tomber dans le "piège" des doubles ponts diviseur de tension. #todo[Schéma] #figcan({ serie((0, 0), apply(source-ideale), apply(resistor, label: $R_1$), apply(derivation, ) ) }) 1. On nous demande de calculer $u_2$ en fonction de $u_1$: On utilise un pont diviseur de tension: $ u_2 = (R_4 u_1)/(R_3 + R_4) $ 2. On réduit l'association en série de $R_3$ et de $R_4$: $ R_"eq" = (R_2 (R_3 + R_4))/(R_2 + R_3 + R_4) $ $ u_1 = (R_"eq" E)/(R_"eq" + R_1) = (R_2 (R_3 + R_4) E)/(R_2 (R_3 + R_4) + R_1 (R_2 + R_3 + R_4)) $ On substitue: $ u_2 = (R_4)/(R_3 + R_4) u_1 \ = (R_2 R_4 E)/(R_2 (R_3 + R_4) + R_1(R_2 + R_3 + R_4)) $ == Loi des nœuds en terme de potentiel - Théorème de Millman #hp[[Résultat hors-programme: il faudra le démontrer à chaque utilisation]] #figure(caption: [Millman], image("./millman.png", width: 50%)) La loi des nœuds s'exprime en intensité, et ne devrai pas pouvoir s'exprimer en termes de tension. Ici, on a: $ i_1 + i_2 + i_3 + i_4 + i_5 + i_6 + i_7 = 0 $ Or, toutes ces intensités proviennent de résistances, d'où: $ u_1/R_1 + u_2/R_2 + ... + u_7/R_7 = 0 $ Qu'on peut exprimer en terme de potentiel: $ (V_A_1 - V_N)/R_1 + (V_A_2 - V_N)/R_2 + ... + (V_A_7 - V_N)/R_7 = 0 $ Et on sort les $V_N$: $ V_A_1/R_1 + V_A_2/R_2 + ... + V_A_7/R_7 = V_N (1/R_1 + 1/R_2 + ... + 1/R_7) $ On peut l'utiliser: #todo[schéma...] On exprime $V_A$ en appliquant la relation: $ V_A = (V_C/R_1 + V_B/R_3 + V_D/R_2)/(1/R_1 + 1/R_2 + 1/R_3) $ On place la masse en $B$, donc on considère que $V_B = 0$. On a donc $u_3$ la tension de $R_3$ qui est: $ u_3 &= V_A - V_B = V_A \ &= (E_1/R_1 + E_2/R_2)/(1/R_1 + 1/R_2 + 1/R_3) \ &= (R_3 (R_2 E_1 + R_1 E_2))/(R_2 R_3 + R_1 R_3 + R_2 R_1) $ Donc on calcule $i_3$: #figcan({ carre((0, 0), branch(), apply(resistor, label: $R$), (i: $i_1$), branch( apply(resistor, label: $2R$), apply(resistor, label: $2R$) ), apply(resistor, label: $3R$), (i: $i_2$), branch(top: ""), (i: $I_3$), apply(resistor, label: $R$), branch( (inset: 1), apply(derivation, inset: 1.2, width: 4, apply(resistor, label: $2R$), apply(resistor, label: $R$) ), (inset: 1.7) ) ) })
https://github.com/MultisampledNight/interpretation
https://raw.githubusercontent.com/MultisampledNight/interpretation/main/util/graphics.typ
typst
Other
#import "@preview/cetz:0.2.2" #let bg = luma(100%) #let fg = luma(0%) #let canvas(body) = { set par(justify: false) cetz.canvas(body) } #let literature-epochs = canvas({ import cetz.draw: * let diagram = (width: 5) let column-spacing = 0.025 let cell-size = (x: 3, y: 0.075) scale( x: cell-size.x, y: -cell-size.y ) let backdrops = ( solid: fg.transparentize(7.5%), maybe: gradient.linear( fg.lighten(25%), fg.lighten(45%), angle: 45deg, ) .sharp(2) .repeat(3) ) let step = (major: 25, minor: 5) let legend-years = range( 1700, 1950 + 1, // end is exclusive step: step.major, ) for (i, year) in legend-years.enumerate() { let hint(y-offset, paint) = line( (0, year + y-offset), (rel: (diagram.width, 0)), stroke: ( paint: paint, ) ) hint(0, luma(70%)) if i != 0 { for y-offset in range( step.minor, step.major, step: step.minor, ) { hint(-y-offset, luma(90%)) } } let label(x) = content((x, year), box(fill: bg, inset: 0.25em)[#year]) label(0) label(diagram.width) } // this is like super cursed // but on the other hand this way I don't need to worry about scaling // and can easily draw squares content( (0.25, legend-years.last() + 10), anchor: "north-west", canvas({ let part(y, accent, label) = { rect( (0, y), (rel: (0.75, 0.75)), fill: accent, stroke: none, ) content( (0.75, y + 0.75 / 2), anchor: "west", pad(0.5em, label), ) } part(1, backdrops.solid, [Sicher in der Zeit]) part(0, backdrops.maybe, [Kann man sich drüber streiten]) }), ) let normalize(intervals) = { // if there's only 2 items, assume it's solid if intervals.len() == 2 { intervals.insert(1, "solid") } return intervals } let individual(intervals) = { range(int(intervals.len() / 2)) .map(i => intervals.slice(i * 2, count: 3)) } // `intervals` is an array of the form (start, [kind,] {mid, kind}, end) // // `kind` is one of // - "maybe", denoting that it isn't entirely clear // if the epoch is in this interval // - "solid", denoting that the epoch is for sure // during this interval let epoch(column, intervals, name, label) = { let intervals = normalize(intervals) let total-start = intervals.first() let total-end = intervals.last() let y-mid = (total-start + total-end) / 2 rect( (column - 0.5 + column-spacing, total-start), (column + 0.5 - column-spacing, total-end), fill: none, stroke: none, name: name, ) for (start, kind, end) in individual(intervals) { let upper-left = (column - 0.5 + column-spacing, start) let lower-right = (column + 0.5 - column-spacing, end) rect( upper-left, lower-right, fill: backdrops.at(kind), stroke: none, ) if "solid" == kind { let label = box( width: cell-size.x * 1cm - 8pt, align( center, text( fill: bg, size: 0.9em, label, ), ), ) content( (upper-left, 50%, lower-right), label, ) } } } // just put them into 1 array instead of nesting epoch(1, (1715, 1789), "aufklärung")[Aufklärung] epoch(2, ( 1760, "solid", 1780, "maybe", 1785, ), "sud")[Sturm und Drang] epoch(3, ( 1770, "maybe", 1785, "solid", 1805, "maybe", 1830, ), "klassik")[Weimarer Klassik] epoch(4, ( 1805, "solid", 1830, "maybe", 1850, ), "romantik")[Romantik] epoch(1, (1815, 1848), "vormärz")[Vormärz] epoch(2, (1815, 1848), "biedermeier")[Biedermeier] epoch(3, ( 1848, "solid", 1890, "maybe", 1895, ), "realismus")[Poetischer Realismus] epoch(4, (1880, 1900), "naturalismus")[Natural-ismus] epoch(1, (1900, 1910), "gzn")[ GzN #footnote[Gegenströmungen zum Naturalismus] ] epoch(2, ( 1911, "solid", 1933, "maybe", 1940, ), "expressionismus")[Expression-ismus] epoch(3, (1945, 1955), "trümmer")[Trümmer #footnote[Trümmerliteratur]] set-style(stroke: ( thickness: 2pt, join: "round", cap: "round", )) let vert(y) = (rel: (0, y)) let hori(x) = (rel: (x, 0)) let hori-align(anchor) = (horizontal: anchor, vertical: ()) let vert-align(anchor) = (horizontal: (), vertical: anchor) let edge(..points, mark: true) = line( ..points, mark: if mark == "hori" { (end: (symbol: ">", width: 5.5, length: 0.125)) } else if mark { (end: (symbol: ">", length: 5)) }, ) let edge-dotted( side, at, end: none, ) = { let solid(from, to) = edge( from, to, mark: false, ) let dotted(from, to) = edge( from, to, stroke: (dash: "dotted"), mark: false, ) let end = if end == none { hori(0.4) } else { end } if side == left { dotted(at, hori(0.275)) solid((), end) } else if side == right { solid(at, end) dotted((), hori(0.275)) } else { panic("cannot draw dotted edge at " + side) } } edge( "aufklärung.south", vert(-10), hori(2), "klassik.south", ) edge( "sud.south", vert(-20), hori(1), mark: false, ) edge( ("klassik.east", 20%, "klassik.south-east"), hori(0.525), "romantik.south", ) let romantik-out = ("romantik.east", 97.5%, "romantik.south-east") edge-dotted( right, romantik-out, ) edge-dotted( left, (vertical: romantik-out, horizontal: (0, 0)), end: hori-align("vormärz"), ) edge( (), "vormärz.south", ) edge( (horizontal: "vormärz.south", vertical: romantik-out), hori-align("biedermeier"), "biedermeier.south", ) let shift = 35% let realismus-in = ("realismus.west", shift, "realismus.south-west") edge( "vormärz.north", vert-align(realismus-in), realismus-in, mark: "hori", ) edge( "biedermeier.north", vert-align(realismus-in), mark: false, ) let realismus-out = ("realismus.east", shift, "realismus.south-east") edge( realismus-out, hori-align("naturalismus"), "naturalismus.south", ) edge-dotted( right, "naturalismus.east", ) edge-dotted( left, (horizontal: (0, 0), vertical: "naturalismus"), end: hori-align("gzn"), ) edge((), "gzn.south") edge( "gzn.north", vert-align("expressionismus"), "expressionismus.west", mark: "hori", ) edge( "expressionismus.east", hori-align("trümmer"), "trümmer.south", ) }) //#set page(width: auto, height: auto) #set text(size: 14pt, font: "IBM Plex Serif") #literature-epochs
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/005%20-%20Modern%20Masters/001_Preparation.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Preparation", set_name: "Modern Masters", story_date: datetime(day: 29, month: 05, year: 2013), author: "<NAME>", doc ) #emph["There's no such thing as a fair fight."] The artificer had been at work for thirty hours straight, and she was exhausted. This wasn't the longest stretch she had worked on a project, not by half. But those projects had been driven by the muse, by love, or by inspiration. Those had been works of joy. Joy fills the soul during times like those. There was no joy in this work. A dozen different timepieces of varying size and make all ticked away, counting down the hours to her execution. She didn't have the power for a spell like this, so she had to cheat. The first step was the amplification circle: Five feet in diameter, silver filigree etched in fresh black marble. More than six hundred unique runes in the outermost circle, then seven smaller rune circles, perfectly concentric, detailing the precise time, location, and energy level of the spell that would target it. It would need to be flawless. If it worked, it would allow her to pull off a feat of magic that even her old mentor would have hesitated to try. Otherwise, the spell would fail in one of an infinite number of spectacular ways. Almost none of those ways involved her walking away. #figure(image("001_Preparation/01.jpg", width: 100%), caption: [], supplement: none, numbering: none) A small insect-like construct brought her a new chisel, fresh plates of silver inlay, and a glass of cold water. She grabbed a rag, wiped her hands and forehead, and pushed a lock of auburn hair out of her eyes. She had seven hours before she needed to be back in her cell, and she was nowhere near done. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The artificer stared at the spell circle. She squinted. Her eyes burned, dry from too much detail work and not nearly enough sleep. She saw no flaws, but this was worth checking a second time. And a third. She gave it a satisfied nod before turning to her workbench. There sat a small crystal sphere with an orange light swirling inside. She took a deep breath and picked it up very carefully. With slow, deliberate steps, she walked it over to the spell circle, and set it down #emph[very] slowly. It made a small "tink" sound as she let go, and she winced... a long second passed, and she slowly exhaled. She backed away from the sphere and wiped her forehead again. With a mischievous smile, she took a piece of paper from her desk, jotted a quick note on it, and then placed it next to the sphere. Two steps down. Now the hard part. #figure(image("001_Preparation/02.jpg", width: 100%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Channeling this much energy #emph[hurt] . The room was filled with an unearthly blue light—the artificer had conjured an opaque magical dome of force, nearly as tall as she was, that completely covered the spell circle. Her face was locked into a pained grimace, her teeth grinding from the effort, as she put everything she had into creating a perfect barrier. She didn't have any shortcuts for this bit of magic; she just poured everything in her mind and heart and soul into the dome, and held absolutely nothing back. She wanted to stop. She #emph[needed] to stop. But the part of her that had been hammered into steel through decades of tireless work knew something else—she knew that she needed to hold the spell for a few more seconds. Seconds that trickled by like hours. That crept like days. She was screaming now, but she couldn't hear herself. The spell came to an end with an explosion. It sent her flying across the room, skipping off the top of her cluttered workbench, and smashing into a bookshelf. Countless gizmos and half-finished projects were smashed, dozens of beakers shattered, and sheaves of paper were launched into the air. The spell circle, and everything it contained, had been completely annihilated by the device. #figure(image("001_Preparation/03.jpg", width: 100%), caption: [], supplement: none, numbering: none) As the papers fluttered to the ground, the room was filled with the ringing sound of a young woman, flat on her back, bruised and aching, laughing at the top of her lungs. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) The artificer was shaken awake by one of her traveling companions—a merchant who had been captured along with her a week before. Unlike her, he didn't have the good fortune of being able to transport himself away to safety. So when she found out these barbarians were planning on killing her and her companions as part of some crazy solstice ritual, she briefly considered just teleporting away and leaving them to their fate. Briefly. But then she learned that she'd be allowed to fight, champion against champion, as part of the ceremony. #emph[That] sounded like fun, and abandoning these poor people to their deaths did not. A ritually painted and fur-clad man with arms as big around as the artificer's waist glared at her through the bars of her cell. He knew she was a mage, but she had been careful not to cast any spells that would draw attention during her supposed "captivity." She had been transporting herself to and from her laboratory fairly freely at night, but if they had noticed, they hadn't given any sign. The man grunted, opened the cage door, and gestured for the artificer to follow. The camp was clearly prepared for a day of celebration. The rough tents all had some kind of ribbon or ornamentation, and a ring of barricades had been assembled for the contest. If she didn't know the purpose of all of this was to be bloody ritual combat, followed by a series of murderous sacrifices to a sun god, she would have thought the display quite festive. The sun was bright in a perfectly clear sky. She couldn't have asked for a nicer day. She was led to a small pen at the edge of the ring. Her guard grunted and gestured for her to wait. She did. The tribe started to gather around the contest ring, and the barbarian champion was already being prepared by the tribe's shaman and his acolytes. Even from across the field, the artificer could feel the immense power they were wielding. Whether learned in the academy or some stinking mud hut, power was power. Too many at the academy thought that when you bind power in a book, you gain a monopoly over it. Too few of them remained to regret that line of thinking. The assembled crowd started to chant their champion's name, a young warrior who looked to be in the prime of his life—tall, lean, muscled, and unscarred, with thick dark hair in a loose braid down his back. #figure(image("001_Preparation/04.jpg", width: 100%), caption: [], supplement: none, numbering: none) "GRELL! GRELL! GRELL! GRELL!" The shamans concluded their ritual and raised their arms for silence. It was somewhat disquieting just how quickly the tribe went perfectly still. To the artificer's ears, the shaman sounded like any other charlatan preacher—a deep, booming voice with a little edge of menace in his tone to keep the crowd in line. "HEAR ME! We, the children of the light that warms us, we, the children of the summer plains! We give thanks to the most mighty on this, the longest of days, when the one who burns above is mightiest of all!" A roar came up from the crowd, right on cue, then quickly subsided. "In his honor, we offer a show of our strength! In his honor, we offer a show of our devotion! In his honor, we offer the blood of our enemies!" Another cry from the crowd. "We have given our champion all of the sun's blessings! We have given him all of our might!" At this, two men entered the ring, one with what looked to be small tree trunk, and the other a metal bucket. "On this day, our strength can withstand any blow!" The man with the tree trunk swung it like a club, and it shattered into splinters when it struck Grell. The crowd roared. "On this day, our will can withstand any flames!" The man with the bucket threw its contents over Grell—oil—that burst into flames. Grell stood, wreathed in the fire, unmarred. The crowd gasped, then screamed its awed approval. "Son of the tribe, while the light of the longest day shines upon your skin, you are INVINCIBLE!" The artificer swallowed hard. She had been prepared for all this, researched it all as soon as she understood what was planned for the captives, but facing off against an invincible foe was unsettling, despite her precautions. The shaman turned his eyes on her. "You there, challenger of the outlands? I am told you are a great warrior among your people!" A chuckle rippled through the crowd. "I can fight," she said. "And a great wizard as well! This is what your fellows say of you! Are you a great wizard, champion?" "Not nearly as great as some." There was a note of sadness in her voice. "And you willingly take on the fates of the outlanders under your protection? Your fate shall be theirs?" "Let's just get this over with." A variety of weapons were brought forth for her to choose from. She took a small dagger from the rack and strode out into the middle of the ring. Grell had been handed a pair of small stone axes. Drums started to roar, and the crowd followed suit. Grell's face was a manic grin. The artificer had no idea how much energy was being channeled through the man, but it was a lot, and chances were he was feeling good. With a well-practiced gesture, she sent two bolts of flame streaking toward him, and in a shower of embers, they spattered across his chest. He was unharmed, of course. Grell raised his arms in triumph to the crowd. The artificer gritted her teeth. She rushed at him, dagger in a reverse grip. She slashed at his face, and Grell jumped back. The instinct to get out of the blade's path was still there, even though he knew she couldn't hurt him. He leapt at her, taking careful, powerful swings with the axes, but the artificer rolled deftly out of the way. As she rolled through the dust, she palmed a small object from her belt. When he charged at her again, she tossed it at him—a tiny construct, shaped like an ant, with a reservoir of a glowing cyan liquid in its abdomen. It sprang to life, and latched unnoticed on to Grell's loincloth, providing the anchor for the artificer's next spell. #figure(image("001_Preparation/05.jpg", width: 100%), caption: [], supplement: none, numbering: none) She managed to duck under Grell's next swing, but his massive forearm caught her across the chest on the backswing—the force of it lifted her off the ground. She hit the ground hard, and pulled herself up to one knee. Grell raised his arms again in triumph, taking in the adulation of the crowd before delivering the intended killing blow, when the artificer whispered the word of power that released all of her prepared magic. "Let's see if this worked." There was a slight pop, and Grell vanished from sight. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Grell blinked. There air was cold here, and it tasted wrong. He found himself trapped inside an opaque magical dome of force, glowing with blue swirls of arcane energy. On the ground was a small glowing sphere and a handwritten note. He pounded his fists against the barrier, but it absorbed his strikes without making a sound. The glowing sphere was brightening, and the orange light inside looked increasingly... unstable. It began to emit a high-pitched hum, and it started to shake. Frantic, he looked at the note. #emph[The solstice is tomorrow. I win.] #linebreak —Jhoira #figure(image("001_Preparation/06.jpg", width: 100%), caption: [Jhoira of the Ghitu | Art by <NAME>], supplement: none, numbering: none)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/guided-resume-starter-cgc/2.0.0/README.md
markdown
Apache License 2.0
# Resume Starter This template is a starter resume for people looking to focus on the content of their resume, without having to worry about the hassle of formatting. ## Get Started! ### Quickstart: Typst Universe 1. If you haven't already, [create a (free!) Typst account](https://typst.app). 2. Once you have an account, go to the template on [Typst Universe](https://typst.app/universe/package/resume-starter-cgc) 3. Click on "Create Project in App", give your project a title, and press "Create". 4. Start editing! This copy is your own personal copy to edit however you want! There are two files included in this project: - `starter.typ` contains the full template, along with a written guide to help you put your best (single-paged) foot forward! - `resume.typ` is the same template, but without the full guide included. - `templates/resume.template.typ` contains the formatting and style for the underlying pieces. **I would highly recommend reading `starter.typ` or skimming through the [online guide](https://blog.chaoticgood.computer/writing/notes/typst-resume-template) to understand best practices when using the template.** ### Alternative: Typst CLI If you'd prefer to simply download & modify the template, you can use the [Typst CLI](https://github.com/typst/typst) to download it instead: ```sh typst init @preview/resume-starter-cgc ``` ## Layout ### Header The resume can be created with a header with the following attributes: - `author`: Your name - `location`: The city, state/province, and country you reside in. - `contacts`: A list of contact information and additional information #### Header Example ```typ #show: resume.with( author: "Dr. Emmit \"<NAME>", location: "Hill Valley, CA", contacts: ( [#link("mailto:<EMAIL>")[Email]], [#link("https://your-cool-site.com")[Website]], [#link("https://github.com/your-linkedin")[GitHub]], [#link("https://linkedin.com/in/your-linkedin")[LinkedIn]], ) ) ``` ### Education The Education (`#edu`) section can be used to highlight for formal education and certifications. - `institution`: Name of the institution where you study, or have graduated from. - `date`: Your graduation date, or expected graduation date. - `degrees`: The degrees you received at the institution - Each entry is two sections: the **title** of the degree, and the **subject** that you studied. - `gpa` (optional): Your GPA, or other additional information. #### Education Example ```typ #edu( institution: "University of Colombia", date: "Aug 1948", gpa: "3.9 of 4.0, Summa Cum Laude", degrees: ( ("Bachelor's of Science", "Nuclear Engineering"), ("Minors", "Automobile Design, Arabic"), ("Focus", "Childcare, Education") ), ) ``` ### Skills An additional Skills (`#skills`) section to list skills relevant to the job you're applying for. The input is a list of `Label: Skills[]`, in order to easily toggle comments on skills that you may want to leave in but not render for a particular application. #### Skills Example ```typ #skills(( ("Expertise", ( [Theoretical Physics], [Time Travel], [Nuclear Material Management], [Student Mentoring], )), ("Software", ( [AutoDesk CAD], [Delorean OS], [Windows 1], )), ("Languages", ( [C++], [C Language], [MatLab], [Punch Cards], )), )) ``` ### Experience The bulk of your resume, the Experience (`#exp`) sections provide a compact & concise formatting for bulleted details of your previous and current work experience. This section is meant to be flexible, and can also be used to talk about projects and other experiences that may fall outside of the traditional definition of "work." - `role`: The title of your position/role in this experience. - `project`: The company you worked at, or the name of the project you worked on. - `date`: The start and end dates of this experience. - `details`: A description of the work you did in this position - It is **highly encouraged** to use bullet points in this section. - `location` (optional): The location of the experience - `summary` (optional): A brief summary of the company's mission or project goal. #### Experience Example ```typ #exp( role: "Theoretical Physics Consultant", project: "Doc Brown's Garage", date: "June 1953 - Oct 2015", location: "Hill Valley, CA", summary: "Specializing in development of time travel devices and student tutoring", details: [ - Lead development of time travel devices, resulting in the ability to travel back and forth through time - Managed and executed a budget of \$14 million dollars gained from an unexplained family fortune - Oversaw QA testing for time travel devices, minimizing risk of maternal time-travel related incidents ] ) ``` ## Questions & Suggestions Have any questions, comments, or suggestions about the template? Please feel free to reach out at [`<EMAIL>`](mailto:<EMAIL>)!
https://github.com/noahjutz/CV
https://raw.githubusercontent.com/noahjutz/CV/main/body/project.typ
typst
#let project( name, icon: none, url: none, body, ) = { grid( columns: (auto, 1fr), column-gutter: 12pt, row-gutter: 8pt, [], text( fill: gray, size: 12pt, link("https://" + url, url) ), if icon != none {image(icon, width: 24pt)} else {[]}, { set block(below: 8pt) text(weight: "black", name) linebreak() body }, ) }
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2019/WS-10.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [SUN Yingsha], [CHN], [3413], [2], [CHEN Meng], [CHN], [3405], [3], [ZHU Yuling], [MAC], [3360], [4], [LIU Shiwen], [CHN], [3350], [5], [DING Ning], [CHN], [3272], [6], [WANG Manyu], [CHN], [3257], [7], [CHEN Xingtong], [CHN], [3224], [8], [WANG Yidi], [CHN], [3097], [9], [ITO Mima], [JPN], [3094], [10], [#text(gray, "MU Zi")], [CHN], [3091], [11], [HE Zhuojia], [CHN], [3083], [12], [ISHIKAWA Kasumi], [JPN], [3068], [13], [HIRANO Miu], [JPN], [3062], [14], [SUN Mingyang], [CHN], [3060], [15], [#text(gray, "WU Yang")], [CHN], [3058], [16], [FENG Yalan], [CHN], [3050], [17], [GU Yuting], [CHN], [3045], [18], [HAYATA Hina], [JPN], [3010], [19], [KATO Miyu], [JPN], [3003], [20], [#text(gray, "LIU Gaoyang")], [CHN], [2992], [21], [KIM Song I], [PRK], [2974], [22], [#text(gray, "HU Limei")], [CHN], [2972], [23], [HAN Ying], [GER], [2957], [24], [YU Fu], [POR], [2953], [25], [NAGASAKI Miyu], [JPN], [2949], [26], [SATO Hitomi], [JPN], [2949], [27], [FENG Tianwei], [SGP], [2924], [28], [#text(gray, "CHEN Ke")], [CHN], [2918], [29], [LI Qian], [POL], [2911], [30], [ZHANG Rui], [CHN], [2899], [31], [NI Xia Lian], [LUX], [2897], [32], [LI Jiayi], [CHN], [2895], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [ZHANG Qiang], [CHN], [2892], [34], [YU Mengyu], [SGP], [2884], [35], [LIU Weishan], [CHN], [2880], [36], [CHA Hyo Sim], [PRK], [2878], [37], [DOO Hoi Kem], [HKG], [2876], [38], [KIHARA Miyuu], [JPN], [2869], [39], [SZOCS Bernadette], [ROU], [2869], [40], [HASHIMOTO Honoka], [JPN], [2858], [41], [SHIBATA Saki], [JPN], [2853], [42], [LIU Xi], [CHN], [2852], [43], [CHE Xiaoxi], [CHN], [2846], [44], [<NAME>], [JPN], [2845], [45], [SHI Xunyao], [CHN], [2832], [46], [QIAN Tianyi], [CHN], [2826], [47], [#text(gray, "GU Ruochen")], [CHN], [2823], [48], [<NAME>], [ROU], [2815], [49], [KIM Nam Hae], [PRK], [2812], [50], [<NAME>ie], [NED], [2810], [51], [<NAME>], [KOR], [2808], [52], [JEON Jihee], [KOR], [2808], [53], [#text(gray, "HU Melek")], [TUR], [2806], [54], [MITTELHAM Nina], [GER], [2800], [55], [YANG Xiaoxin], [MON], [2799], [56], [LIU Fei], [CHN], [2794], [57], [CHENG I-Ching], [TPE], [2791], [58], [CHEN Szu-Yu], [TPE], [2787], [59], [<NAME>], [ROU], [2784], [60], [CHOI Hyojoo], [KOR], [2782], [61], [MATSUDAIRA Shiho], [JPN], [2781], [62], [EKHOLM Matilda], [SWE], [2765], [63], [#text(gray, "LI Fen")], [SWE], [2760], [64], [FAN Siqi], [CHN], [2759], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [LEE Ho Ching], [HKG], [2758], [66], [SHAN Xiaona], [GER], [2754], [67], [PESOTSKA Margaryta], [UKR], [2746], [68], [POLCANOVA Sofia], [AUT], [2742], [69], [LI Jiao], [NED], [2738], [70], [<NAME>], [JPN], [2736], [71], [KIM Hayeong], [KOR], [2731], [72], [SHAO Jieni], [POR], [2730], [73], [BILENKO Tetyana], [UKR], [2721], [74], [OJIO Haruna], [JPN], [2713], [75], [POTA Georgina], [HUN], [2712], [76], [SOLJA Petrissa], [GER], [2709], [77], [HAMAMOTO Yui], [JPN], [2708], [78], [LIU Hsing-Yin], [TPE], [2706], [79], [SOO Wai Yam Minnie], [HKG], [2701], [80], [LEE Eunhye], [KOR], [2698], [81], [EERLAND Britt], [NED], [2697], [82], [ZENG Jian], [SGP], [2696], [83], [LIU Xin], [CHN], [2695], [84], [DIAZ Adriana], [PUR], [2692], [85], [ODO Satsuki], [JPN], [2686], [86], [GRZYBOWSKA-FRANC Katarzyna], [POL], [2685], [87], [#text(gray, "<NAME>")], [JPN], [2680], [88], [#text(gray, "LI Jiayuan")], [CHN], [2677], [89], [YANG Ha Eun], [KOR], [2676], [90], [MATELOVA Hana], [CZE], [2675], [91], [LEE Zion], [KOR], [2675], [92], [#text(gray, "LANG Kristin")], [GER], [2662], [93], [MAEDA Miyu], [JPN], [2661], [94], [CHENG Hsien-Tzu], [TPE], [2660], [95], [#text(gray, "HUANG Yingqi")], [CHN], [2657], [96], [MIKHAILOVA Polina], [RUS], [2655], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Women's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [ZHANG Lily], [USA], [2654], [98], [ZHANG Mo], [CAN], [2654], [99], [ZHU Chengzhu], [HKG], [2654], [100], [#text(gray, "<NAME>")], [JPN], [2650], [101], [<NAME>ora], [HUN], [2643], [102], [LIU Jia], [AUT], [2642], [103], [<NAME>], [KOR], [2637], [104], [WINTER Sabine], [GER], [2635], [105], [KIM Byeolnim], [KOR], [2635], [106], [<NAME>], [PRK], [2633], [107], [<NAME>], [JPN], [2630], [108], [<NAME>], [THA], [2630], [109], [<NAME>], [JPN], [2626], [110], [#text(gray, "<NAME>")], [JPN], [2622], [111], [<NAME>], [KOR], [2619], [112], [<NAME>ue], [USA], [2618], [113], [<NAME>], [SVK], [2616], [114], [<NAME>], [IND], [2613], [115], [#text(gray, "<NAME>")], [JPN], [2613], [116], [SUN Jiayi], [CRO], [2612], [117], [<NAME>], [KOR], [2611], [118], [TAKAHASHI Bruna], [BRA], [2605], [119], [PAVLOVICH Viktoria], [BLR], [2600], [120], [#text(gray, "PARK Joohyun")], [KOR], [2600], [121], [#text(gray, "KATO Kyoka")], [JPN], [2594], [122], [#text(gray, "KIM Youjin")], [KOR], [2592], [123], [BERGSTROM Linda], [SWE], [2591], [124], [TAILAKOVA Mariia], [RUS], [2586], [125], [HUANG Yi-Hua], [TPE], [2577], [126], [WANG Amy], [USA], [2576], [127], [LI Xiang], [ITA], [2570], [128], [GUO Yuhan], [CHN], [2568], ) )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-18D00.typ
typst
Apache License 2.0
#let data = ( "0": ("<Tangut Ideograph Supplement, First>", "Lo", 0), "8": ("<Tangut Ideograph Supplement, Last>", "Lo", 0), )
https://github.com/eduardz1/Bachelor-Thesis
https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/chapters/raspberries-responsabilities-and-physical-setup.typ
typst
#import "../utils/common.typ": * = Raspberry Pi's Responsibilities and Physical Setup <raspberry-responsabilities-and-physical-setup> In our greenhouse, we use a total of 4 Raspberry Pi 4 but in theory, only one is strictly necessary. The responsibility that each PC has is as follows: - a #link(<controller-setup>)[_Controller_] - an #link(<actuator-setup>)[_Actuator_] - a #link(<router-setup>)[Router] - a #link(<host-setup>)[Host] We will refer to the _Controller_ also as _Data Collector_ because its responsibility is to collect data using sensors attached to the board and send the measurements to the time series database. In case one wants to replicate our setup, any computer can be used as the host machine, these paragraphs will assume the host runs a Debian-based Linux distribution but any major OS should work with minimal changes. The _Controller_ and _Actuator_ can be run on the same Raspberry with minimal changes. A more in-depth guide to exactly replicate our setup was published at https://github.com/N-essuno/greenhouse_twin_project/tree/main/physical-setup. To make it easier to configure the Raspberry Pis we wrote some bash scripts that make it easy to install the necessary dependencies with one click. For example to configure the host (see @host-setup) we can just run the following script that is written to be architecture-independent, given that the host computer does not need to interface with any sensor directly: ```bash #!/bin/bash git clone https://www.github.com/N-essuno/smol_scheduler influxdbversion="2.7.3" arch=$(dpkg --print-architecture) # Checks the architecture and continues the setup only if arch is # either arm64 or amd64 case "$arch" in amd64) wget https://dl.influxdata.com/influxdb/releases/influxdb2-client-$influxdbversion-linux-amd64.tar.gz tar xvzf influxdb2-client-$influxdbversion-linux-amd64.tar.gz sudo cp influxdb2-client-$influxdbversion-linux-amd64/influx /usr/local/bin ;; arm64) wget https://dl.influxdata.com/influxdb/releases/influxdb2-client-$influxdbversion-linux-arm64.tar.gz tar xvzf influxdb2-client-$influxdbversion-linux-arm64.tar.gz sudo cp influxdb2-client-$influxdbversion-linux-arm64/influx /usr/local/bin ;; *) echo "Unsupported architecture: $arch" exit 1 ;; esac # Sets up influxdb with the standard config tool influx setup exit 0 ``` // TODO: check if the info commented is still relevant // / The Server: The host runs an `InfluxDB` instance that holds the data retried from the clients (_data collectors_) and a `Java` program that periodically runs the #link(<smol-twinning-program>)[`SMOL Twinning program`] which is responsible for creating the digital twin and running the FMI simulators. // / The Router: The Raspberry was configured with `hostapd` and `dnsmasq` to act as a router and provide a wireless network for the clients to connect to. The local network is used to access the client via `SSH` and to send data to the server via `HTTP` requests. #_content( [ == OS Choice We used the, at the time, latest distribution of `Raspberry Pi OS 64bit`. Any compatible operating system will work in practice, but it's necessary to use a 64-bit distribution at least for the host computer. It is also recommended to have a desktop environment on the host computer for simpler data analysis. We used, and recommend using the #link("https://www.raspberrypi.com/software")[Raspberry Pi Imager] to mount the OS image on the microSD card. == Host Setup <host-setup> The only thing that is necessary to install and configure on the host computer is an instance of InfluxDB, after that, it's sufficient to clone the repository containing the #link("https://www.github.com/N-essuno/smol-scheduler")[SMOL scheduler]. == Router Setup <router-setup> We used a separate Raspberry Pi 4 as a router but that's not strictly necessary, one could simply use an off-the-shelf router for this purpose or give the host the responsibility of being the wireless access point. The local network is used to enable communication through SSH and send data to the server through HTTP requests. For our purpose we used the `hostapd` and `dnsmasq` softwares but it can also be done via GUI on Raspberry Pi OS very easily, nonetheless, in the guide aforementioned, we provide a step-by-step tutorial. == Controller Setup <controller-setup> The data points from the sensors that the controller needs to manage are the following: - #link(<dht22>)[Temperature] - #link(<dht22>)[Humidity] - #link(<moisture>)[Moisture] - #link(<light-level>)[Light Level] - #link(<ndvi>)[NDVI] For the temperature and moisture, we used a `DHT22` sensor, which is very common and that is reflected in very good software support. === DHT22 <dht22> The following schematics mirror what we did the connect the sensor to the board #image("../img/dht22-schematics.jpeg") We used the #link( "https://raw.githubusercontent.com/adafruit/Raspberry-Pi-Installer-Scripts/master/raspi-blinka.py", )[circuitpython] libraries, which provide a more modern implementation compared to the standard adafruit libraries. The following is a minimal script that illustrates how we read the data from the sensor. ```python import time import board import adafruit_dht # Initialize the dht device, pass the GPIO pin # it's connected to as an argument dhtDevice = adafruit_dht.DHT22(board.D4) try: temperature_c = dhtDevice.temperature humidity = dhtDevice.humidity # Print the values to the console print( "Temp: {:.1f} C Humidity: {}% ".format( temperature_c, humidity ) ) except RuntimeError as error: # Errors happen fairly often # DHT's are hard to read print(error.args[0]) except Exception as error: dhtDevice.exit() raise error dhtDevice.exit() ``` === Moisture <moisture> We used a generic capacitive soil moisture sensor, to convert the analog signal we need to use an analog-to-digital converter. For our purpose, we used the `MCP3008` ADC which features eight channels, thus making it possible to extend our setup with a decent number of other sensors (for example a PH-meter or a LUX-meter). The following schematics illustrate how we connected the ADC to the board and the moisture sensor to the ADC. #image("../img/mcp3008-moisture-schematics.jpeg") We used `SpiDev` as the library of choice to communicate with the ADC, the following class aids in the readout of the connected sensor: // TODO: understand all the bitwise fuckery ```python from spidev import SpiDev class MCP3008: """ Uses the SPI protocol to communicate with the Raspberry Pi. """ def __init__(self, bus=0, device=0) -> None: self.bus, self.device = bus, device self.spi = SpiDev() self.open() # The default value of 125MHz is not # sustainable on a Raspberry Pi self.spi.max_speed_hz = 1000000 # 1MHz def open(self): self.spi.open(self.bus, self.device) self.spi.max_speed_hz = 1000000 # 1MHz def read(self, channel=0) -> float: adc = self.spi.xfer2([ 1, # speed in hertz (8 + channel) << 4, # delay in μs 0 # bits per word ]) data = ((adc[1] & 3) << 8) + adc[2] return data / 1023.0 * 3.3 def close(self): self.spi.close() ``` A minimal example of how one would go about reading from an ADC is the following: ```python from MCP3008 import MCP3008 adc = MCP3008() value = adc.read(channel = 0) print("Applied voltage: %.2f" % value) ``` === Light Level <light-level> The unavailability of a LUX meter meant we had to get creative and use a webcam to approximate the light level readings. This means that the data is only meaningful when compared to the first measurement. We used the `OpenCV` library to interface with the USB webcam due to it being better supported compared to `picamera2`, another popular library used for similar contexts. A minimal example of the scripts we used is the following: ```python import cv2 from time import sleep cap = cv2.VideoCapture(0) sleep(2) #lets the webcam adjust its exposure # Turn off automatic exposure compensation, # this means that the measurements are only # significant when compared to the first one, # to get proper lux reading one should use a # proper light sensor cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0) while True: ret, frame = cap.read() grey = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) avg_light_level = cv2.mean(grey)[0] print(avg_light_level) if cv2.waitKey(1) & 0xFF == ord('q'): break sleep(1) cap.release() cv2.destroyAllWindows() ``` === NDVI <ndvi> #_block( title: "What is NDVI?", text: [ The Landsat Normalized Difference Vegetation Index (NDVI) is used to quantify vegetation greenness and is useful in understanding vegetation density and assessing changes in plant health. NDVI is calculated as a ratio between the red (R) and near-infrared (NIR) values in traditional fashion: @ndvidef $ ("NIR" - "R") / ("NIR" + "R") $ ], ) To better understand how healthy our plants were we decided to use an infrared camera to quantify the NDVI. In our small-scale application, the data were not too helpful because of the color noise surrounding the plants but it will work very well if used on a camera mounted on top of the plants and focussed in an area large enough that the image is filled with only vegetation. Connecting the camera is very straightforward given that we used the `Raspberry Pi NoIR` module. The following is an excerpt of the class we use to calculate the index: ```python import cv2 import numpy as np from picamera2 import Picamera2 class NDVI: def __init__( self, format: str = "RGB888" ) -> None: """Initializes the camera, a config can be passed as a dictionary Args: config (str, optional): refer to https://datasheets.raspberrypi.com/camera/picamera2-manual.pdf for all possible values, the default is RGB888 which is mapped to an array of pixels [B,G,R]" transform (libcamera.Transform, optional): useful to flip the camera if needed. Defaults to Transform(vflip=True). """ self.camera = Picamera2() self.camera.still_configuration.main.format = (format) self.camera.configure("still") self.camera.start() def contrast_stretch(self, image): """Increases contrast of the image to facilitate NDVI calculation """ # Find top 5% and bottom 5% of pixel values in_min = np.percentile(image, 5) in_max = np.percentile(image, 95) # Defines min and max brightness values out_min = 0 out_max = 255 out = image - in_min out *= (out_min - out_max) / ( in_min - in_max ) out += in_min return out def calculate_ndvi(self, image): b, g, r = cv2.split(image) bottom = r.astype(float) + b.astype(float) bottom[ bottom == 0 ] = 0.01 # Make not to divide by zero! ndvi = (r.astype(float) - b) / bottom return ndvi def read(self): return np.mean( self.calculate_ndvi( self.contrast_stretch( self.camera.capture_array() ) ) ) def stop(self): self.camera.stop() self.camera.close() ``` == Actuator Setup <actuator-setup> In general, to connect actuators (like pumps, light switches, or fans) we can rely on a relay. To connect the relay we can refer to the following schematics: #image("../img/relay-pump-schematics.jpeg") #v(600pt) /* FIXME: remove once issue #466 is implemented */ The relay enables us to control modules with a voltage higher than the 5V tolerated by the Raspberry Pi. In our project, we just connected one pump but it's trivial to extend the configuration to multiple pumps (for example we plan to add one dedicated to pumping fertilized water) or other devices, especially with the kind of relay that we used. An example of the code used to interact with the pump is the following: ```python import RPi.GPIO as GPIO from time import sleep def pump_water(sec, pump_pin): print( "Pumping water for {} seconds..." .format(sec) ) # set GPIO mode and set up the pump pin GPIO.setmode(GPIO.BCM) GPIO.setup(pump_pin, GPIO.OUT) try: # turn the pump off for 0.25 seconds GPIO.output(pump_pin, GPIO.LOW) sleep(0.25) # turn the pump on for the given time GPIO.output(pump_pin, GPIO.HIGH) sleep(sec) # turn the pump off GPIO.cleanup() print("Done pumping water.") except KeyboardInterrupt: # stop pump when ctrl-c is pressed GPIO.cleanup() ``` ], )
https://github.com/Henriquelay/pathsec-checker
https://raw.githubusercontent.com/Henriquelay/pathsec-checker/main/presentation/presentation.typ
typst
#import "@preview/polylux:0.3.1": * #import "@preview/fletcher:0.5.0" as fletcher: diagram, node, edge, shapes #import themes.simple: * #set text(font: "New Computer Modern") // #enable-handout-mode(false) #show: simple-theme//.with(footer: [Simple slides]) #title-slide[ = Polka attack simulations #v(2em) <NAME> #footnote[<EMAIL>] #h(1em) June 27 2024 ] #slide[ == Baseline measurements Before we start attacking the network and comparing digests, we need to establish a baseline for correct operation. #pause For that, we will ping host `h10` from host `h1` and measure the packet through all controlled interfaces. Always using the hardcoded timestamp `0x61E8D6E7` unless said otherwise. ] #slide[ In a linear topology passing though 10 core switches, this generates 88 packets: #pause - one digest for entrance edge + 10 core switches (11) #pause - two captures per switch (one for each interface) (22) #pause - two time that for the reply (44) #pause - two times that for the ping and reply the other way (88) ] #slide[ So in a trace, we expect the packets to appear in the following order: #columns(2)[ #columns(2)[ #set text(size: 19pt) #box[ A = #stack([ `0x61E8D6E7 e1` \ `0xAE91434C s1` \ `0x08C97F5F s2` \ `0xEFF1AAD2 s3` \ `0x08040C89 s4` \ `0xAA99AE2E s5` \ `0x7669685E s6` \ `0x03E1E388 s7` \ `0x2138FFD3 s8` \ `0x1EF2CBBE s9` \ `0x99C5FE05 s10`]) ] #colbreak() #box[ B = #stack([ `0x61E8D6E7 e10` \ `0xCFFABC9F s10` \ `0x69409E70 s9` \ `0xF3E992E0 s8` \ `0x8DDE192B s7` \ `0x92B098FA s6` \ `0x1115A62C s5` \ `0x41E1B5E0 s4` \ `0x227F0B72 s3` \ `0x82FC6346 s2` \ `0xD01E3E0F s1`]) ] ] #colbreak() #set text(size: 20pt) #box()[ $ "Order" = "dup"(A), "dup"(B), "dup"(B), "dup"(A) $ / $"dup"([a, b, c])=$: $[a, a, b, b, c, c]$ #pause For brevity, $"dup"$ will be ommited since it's information is irrelevant, but it will be checked regardless ] ] ] #let myswitch(name, digest, expected) = { box[ #set text(size: 12pt, font: "DejaVu Sans Mono") #table( columns: 2, fill: if (digest == expected) { lime } else { red }, align: (right, left), [name], [#name], [digest], [#digest], [expected], [#expected], ) ] } #slide[ == Ping `h1` #sym.arrow.r `h10` #table( columns: 4, stroke: none, inset: 3pt, myswitch([e1], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s1], [0xAE91434C], [0xAE91434C]), myswitch([s2], [0x08C97F5F], [0x08C97F5F]), myswitch([s3], [0xEFF1AAD2], [0xEFF1AAD2]), myswitch([s4], [0x08040C89], [0x08040C89]), myswitch([s5], [0xAA99AE2E], [0xAA99AE2E]), myswitch([s6], [0x7669685E], [0x7669685E]), myswitch([s7], [0x03E1E388], [0x03E1E388]), myswitch([s8], [0x2138FFD3], [0x2138FFD3]), myswitch([s9], [0x1EF2CBBE], [0x1EF2CBBE]), myswitch([s10], [0x99C5FE05], [0x99C5FE05]), ) ] #slide[ == Ping `h1` #sym.arrow.r `h10` Reply #table( columns: 4, stroke: none, inset: 3pt, myswitch([e10], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s10], [0xCFFABC9F], [0xCFFABC9F]), myswitch([s9], [0x69409E70], [0x69409E70]), myswitch([s8], [0xF3E992E0], [0xF3E992E0]), myswitch([s7], [0x8DDE192B], [0x8DDE192B]), myswitch([s6], [0x92B098FA], [0x92B098FA]), myswitch([s5], [0x1115A62C], [0x1115A62C]), myswitch([s4], [0x41E1B5E0], [0x41E1B5E0]), myswitch([s3], [0x227F0B72], [0x227F0B72]), myswitch([s2], [0x82FC6346], [0x82FC6346]), myswitch([s1], [0xD01E3E0F], [0xD01E3E0F]), ) ] #slide[ == Base topology #diagram({ for i in range(1, 11) { let h = "h" + str(i) node((i / 2, 1), h, stroke: 0.5pt, name: label(h), shape: "rect") edge("<->") let e = "e" + str(i) node((i / 2, 0.5), e, stroke: 0.5pt, name: label(e), shape: shapes.pill) edge("<->") let s = "s" + str(i) node((i / 2, 0), s, stroke: 0.5pt, name: label(s), shape: shapes.octagon) } for i in range(1, 10) { edge((i / 2, 0), ((i + 1) / 2, 0), "<->") } node((0 / 2, 1), "h11", stroke: 0.5pt, name: "h11", shape: "rect") edge(auto, <e1>, "<->") }) $s{n} <-> s{n+1}$ connects through port 2:1 \ ] #slide[ == Attacked topology #diagram({ for i in range(1, 11) { let h = "h" + str(i) node((i / 2, 1), h, stroke: 0.5pt, name: label(h), shape: shapes.rect) edge("<->") let e = "e" + str(i) node((i / 2, 0.5), e, stroke: 0.5pt, name: label(e), shape: shapes.pill) edge("<->") let s = "s" + str(i) node((i / 2, 0), s, stroke: 0.5pt, name: label(s), shape: shapes.octagon) } for i in range(1, 10) { edge((i / 2, 0), ((i + 1) / 2, 0), "<->") } node((0 / 2, 1), "h11", stroke: 0.5pt, name: "h11", shape: shapes.rect) edge(auto, <e1>, "<->") node( (5.5 / 2, -0.5), "s555", stroke: 0.5pt, name: "s555", shape: shapes.octagon, ) edge(<s555>, <s6>, "<->") edge(<s5>, <s555>, "<->") }) $"s5" <-> "s555"$ connects through port 2:0 \ $"s555" <-> "s6"$ connects through port 1:2 \ $"s5" <-> "s6"$ connects through port 3:3 \ ] #slide[ == Ping `h1` #sym.arrow.r `h10` #table( columns: 4, stroke: none, inset: 3pt, myswitch([e1], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s1], [0xAE91434C], [0xAE91434C]), myswitch([s2], [0x08C97F5F], [0x08C97F5F]), myswitch([s3], [0xEFF1AAD2], [0xEFF1AAD2]), myswitch([s4], [0x08040C89], [0x08040C89]), myswitch([s5], [0xAA99AE2E], [0xAA99AE2E]), myswitch([attacer], [0xC450DD37], [0x7669685E]), myswitch([s6], [0x5397C754], [0x7669685E]), myswitch([s7], [0xE21DAB66], [0x03E1E388]), myswitch([s8], [0x8C375948], [0x2138FFD3]), myswitch([s9], [0x352F1CF8], [0x1EF2CBBE]), myswitch([s10], [0x3a61c724], [0x99C5FE05]), ) ] /* 0x61E8D6E7 0xCFFABC9F 0x69409E70 0xF3E992E0 0x8DDE192B 0x92B098FA 0x1115A62C 0x41E1B5E0 0x227F0B72 0x82FC6346 0xD01E3E0F */ #slide[ == Ping `h1` #sym.arrow.r `h10` Reply #table( columns: 4, stroke: none, inset: 3pt, myswitch([e10], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s10], [0xCFFABC9F], [0xCFFABC9F]), myswitch([s9], [0x69409E70], [0x69409E70]), myswitch([s8], [0xF3E992E0], [0xF3E992E0]), myswitch([s7], [0x8DDE192B], [0x8DDE192B]), myswitch([s6], [0x92B098FA], [0x92B098FA]), myswitch([s5], [0x1115A62C], [0x1115A62C]), myswitch([s4], [0x41E1B5E0], [0x41E1B5E0]), myswitch([s3], [0x227F0B72], [0x227F0B72]), myswitch([s2], [0x82FC6346], [0x82FC6346]), myswitch([s1], [0xD01E3E0F], [0xD01E3E0F]), ) ] #slide[ == Ping `h10` #sym.arrow.r `h1` #table( columns: 4, stroke: none, inset: 3pt, myswitch([e10], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s10], [0xCFFABC9F], [0xCFFABC9F]), myswitch([s9], [0x69409E70], [0x69409E70]), myswitch([s8], [0xF3E992E0], [0xF3E992E0]), myswitch([s7], [0x8DDE192B], [0x8DDE192B]), myswitch([s6], [0x92B098FA], [0x92B098FA]), myswitch([s5], [0x1115A62C], [0x1115A62C]), myswitch([s4], [0x41E1B5E0], [0x41E1B5E0]), myswitch([s3], [0x227F0B72], [0x227F0B72]), myswitch([s2], [0x82FC6346], [0x82FC6346]), myswitch([s1], [0xD01E3E0F], [0xD01E3E0F]), ) ] /* 0x61E8D6E7 0xAE91434C 0x08C97F5F 0xEFF1AAD2 0x08040C89 0xAA99AE2E 0xC450DD37 0x5397C754 0xE21DAB66 0x8C375948 0x352F1CF8 0x3A61C724 */ #slide[ == Ping `h10` #sym.arrow.r `h1` Reply #table( columns: 4, stroke: none, inset: 3pt, myswitch([e10], [0x61E8D6E7], [0x61E8D6E7]), myswitch([s10], [0xAE91434C], [0xAE91434C]), myswitch([s9], [0x08C97F5F], [0x08C97F5F]), myswitch([s8], [0xEFF1AAD2], [0xEFF1AAD2]), myswitch([s7], [0x08040C89], [0x08040C89]), myswitch([s6], [0xAA99AE2E], [0xAA99AE2E]), myswitch([attacker], [0xC450DD37], [0x7669685E]), myswitch([s5], [0x5397C754], [0x7669685E]), myswitch([s4], [0xE21DAB66], [0x03E1E388]), myswitch([s3], [0x8C375948], [0x2138FFD3]), myswitch([s2], [0x352F1CF8], [0x1EF2CBBE]), myswitch([s1], [0x3A61C724], [0x99C5FE05]), ) ]
https://github.com/liuguangxi/erdos
https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/figures/p233.typ
typst
#import "@preview/cetz:0.2.1" #cetz.canvas({ import cetz.draw: * rect((0, 0), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((1, 0), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((0, 1), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((1, 1), (rel: (1, 1)), stroke: luma(100)+1.5pt) line((0, 1), (1, 2), stroke: red+1.5pt) line((0, 0), (2, 0), (2, 2), stroke: blue+3pt) let os = 2.5 rect((0+os, 0), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((1+os, 0), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((0+os, 1), (rel: (1, 1)), stroke: luma(100)+1.5pt) rect((1+os, 1), (rel: (1, 1)), stroke: luma(100)+1.5pt) line((0+os, 1), (1+os, 2), stroke: red+1.5pt) line((0+os, 0), (1+os, 0), (1+os, 1), (2+os, 1), (2+os, 2), stroke: blue+3pt) })
https://github.com/LucaCiucci/tesi-triennale
https://raw.githubusercontent.com/LucaCiucci/tesi-triennale/main/img/slide_1/dirac_monopole.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/cetz:0.2.2" #let fig(step) = cetz.canvas(length: 1mm, { import cetz: draw import cetz.draw: * line((0, 0), (10, 10), stroke: (thickness: 0.4pt, cap: "round")) let r = 30 circle((50, 50), radius: r, stroke: (thickness: 0.5pt)) line((50, 50), (50, 10)) circle((50, 50), radius: 1.5, fill: red.darken(20%), stroke: none) let n = 4 let ratio = 1 / 10 for i in range(-n + 1, n) { let z = i * r / n let a = 1 - i / n let rx = calc.sqrt(r*r - z*z) circle((50, z + 50), radius: (rx, rx * ratio), stroke: (thickness: 0.5pt, cap: "round", paint: gray)) draw.line((50, z + 50 - rx * ratio), (50 + a * 5 + 3, z + 50 - rx * ratio), stroke: (thickness: 2pt, paint: orange), mark: (end: ">", fill: orange)) } draw.rect( (0, 0), (100, 100), stroke: none, ) }) //#set page(margin: 0pt, width: 1000pt, height: 1000pt) //#set page(width: auto, height: auto, margin: 1cm) //#rect(fig, inset: 0pt, width: 8cm, height: 6cm) #rect(fig(0))
https://github.com/csimide/SEU-Typst-Template
https://raw.githubusercontent.com/csimide/SEU-Typst-Template/master/seu-thesis/parts/main-body-bachelor-fn.typ
typst
MIT License
#import "../utils/states.typ": part-state #import "../utils/fonts.typ": 字体, 字号 #let main-body-bachelor-conf(doc) = { set page( header: { set align(center) set text(font: 字体.宋体, size: 字号.小五, lang: "zh") set par(first-line-indent: 0pt, leading: 16pt, justify: true) show par: set block(spacing: 16pt) [东南大学本科毕业设计(论文)] v(-12pt) line(length: 100%, stroke: (thickness: 0.5pt)) counter(footnote).update(0) }, numbering: "1", footer: { set align(center) set text(font: 字体.宋体, size: 字号.小五, lang: "zh") h(16pt) counter(page).display() }, header-ascent: 10%, footer-descent: 10%, ) pagebreak(weak: false) counter(page).update(1) counter(heading.where(level: 1)).update(0) doc }
https://github.com/EGmux/PCOM-2023.2
https://raw.githubusercontent.com/EGmux/PCOM-2023.2/main/lista2/lista2q16.typ
typst
=== Quatro canais são multiplexados usando TDM. Se a capacidade individual dos canais for 100 bytes/s e multiplexarmos 1 byte por canal, apresente: \ ==== a) O esquema de viagem dos frames no enlace. \ #figure( image("../assets/esquemaviagem.png", width: 80%), caption: [Esquema viagem], ) <fig-esquemaviagem> ==== b) O tamanho de cada frame \ o tamanho é de 4 bytes visto que temos 4 canais conectados ao MUX ==== c) O tempo de duração de um frame \ temos 100 bytes/canal em um segundo e cada frame leva 1 byte, logo precisamos de 100 frames em um segundo logo invertendo a relação , obtemos: #math.equation(block: true, $ tau_f = 1/100 = 0.01 "s/frame" $) ==== d) A taxa de transmissão de dados no enlace \ a taxa de transmissão é bits/s, o famoso *$R_b$* só que agora usando frames como taxa #math.equation(block: true, $ R_b &= R_f "frames/s" dot l_f "bytes/frames" && \ &= 400 "bytes/s" && \ $)
https://github.com/Its-Alex/resume
https://raw.githubusercontent.com/Its-Alex/resume/master/lib/components/link_with_icon.typ
typst
MIT License
#let linkWithIcon( icon, url, linkName ) = [ #link(url)[ #grid( inset: (x: 0pt, y: 0pt), columns: 2, align: horizon, gutter: 4pt, { text(fill: red)[#image("../../assets/"+icon, height: 10pt)] }, { linkName } ) ] ]
https://github.com/Hyiker/report-typst
https://raw.githubusercontent.com/Hyiker/report-typst/master/report.typ
typst
Creative Commons Attribution 4.0 International
#import "@preview/linguify:0.4.1": set-database, linguify // i18n #let lang_data = toml("lang.toml") #set-database(lang_data) #let i18n(key) = { linguify(key, from: lang_data) } #let buildMainHeader(mainHeadingContent) = { [ #align(center, smallcaps(mainHeadingContent)) #line(length: 100%) ] } #let buildSecondaryHeader(mainHeadingContent, secondaryHeadingContent) = { [ #smallcaps(mainHeadingContent) #h(1fr) #emph(secondaryHeadingContent) #line(length: 100%) ] } #let isAfter(secondaryHeading, mainHeading) = { let secHeadPos = secondaryHeading.location().position() let mainHeadPos = mainHeading.location().position() if (secHeadPos.at("page") > mainHeadPos.at("page")) { return true } if (secHeadPos.at("page") == mainHeadPos.at("page")) { return secHeadPos.at("y") > mainHeadPos.at("y") } return false } #let getHeader() = { locate( loc => { // Find if there is a level 1 heading on the current page let nextMainHeading = query(selector(heading).after(loc), loc).find(headIt => { headIt.location().page() == loc.page() and headIt.level == 1 }) if (nextMainHeading != none) { return buildMainHeader(nextMainHeading.body) } // Find the last previous level 1 heading -- at this point surely there's one :-) let lastMainHeading = query(selector(heading).before(loc), loc).filter(headIt => { headIt.level == 1 }).last() // Find if the last level > 1 heading in previous pages let previousSecondaryHeadingArray = query(selector(heading).before(loc), loc).filter(headIt => { headIt.level > 1 }) let lastSecondaryHeading = if (previousSecondaryHeadingArray.len() != 0) { previousSecondaryHeadingArray.last() } else { none } // Find if the last secondary heading exists and if it's after the last main heading if ( lastSecondaryHeading != none and isAfter(lastSecondaryHeading, lastMainHeading) ) { return buildSecondaryHeader(lastMainHeading.body, lastSecondaryHeading.body) } return buildMainHeader(lastMainHeading.body) }, ) } #let font-heading() ={ let lang = context text.lang if lang == "en" { return ("New Computer Modern") } else { return ("New Computer Modern", "Noto Sans CJK SC") } } #let font-body() ={ let lang = context text.lang if lang == "en" { return ("New Computer Modern") } else { return ("New Computer Modern", "Noto Serif CJK SC") } } // Project part #let project( title: "", authors: (), subtitle: "", department: "", institute: "", logo: none, abstract: none, subject: "", language: "zh", body, ) = { // Set global language set text(lang: language, region: "cn") if language == "zh" set text(lang: language, region: "us") if language == "en" // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set page(paper: "a4", margin: (top: 1in, bottom: 1in, left: 1in, right: 1in)) set text(font: font-heading()) set par(justify: true) // Title row. v(.10fr) if language == "en" { align(center)[ #text(12pt, strong(smallcaps(subject))) \ \ #text(30pt, weight: 900, smallcaps(title)) \ \ #text(14pt, weight: 200, subtitle) ] } else { align(center)[ #text(12pt, strong(subject)) \ \ #text(36pt, weight: 600, title) \ \ #text(14pt, weight: 500, subtitle) ] } pad(top: 2em, for i in range(calc.ceil(authors.len() / 3)) { let end = calc.min((i + 1) * 3, authors.len()) let is-last = authors.len() == end let slice = authors.slice(i * 3, end) grid( columns: slice.len() * (1fr,), gutter: 12pt, ..slice.map(author => align(center, { if language == "en" { text(12pt, strong(author.name)) } else { text(12pt, author.name, weight: 500) } if "rollno" in author [ \ #author.rollno ] if "department" in author [ \ #author.department ] if "email" in author [ \ #link("mailto:" + author.email) ] })), ) if not is-last { v(16pt, weak: true) } }) v(1cm) v(0.75fr) if logo != none { align(center)[ #image(logo, width: 26%) \ #text(12pt, strong(smallcaps(department))) \ #text(14pt, institute) ] } else { align(center)[ #text(12pt, strong(smallcaps(department))) \ #text(14pt, institute) ] } set page(margin: (top: 1in, bottom: 1in, left: 1.5in, right: 1in)) if abstract != none { pagebreak() align(right)[ #text(34pt, underline(smallcaps(strong(i18n("Abstract"))))) ] set par(justify: true) set text(font: font-body()) abstract } pagebreak() // Main body. set text(font: font-body()) outline(depth: 3, indent: true) // Formatting the headings // General First and then specific headings show heading: it => [ #set align(left) #set text(14pt) #block(smallcaps(it.body)) ] show heading.where(level: 1): it => [ #pagebreak(weak: true) #set align(right) #set text(34pt, font: font-heading()) if language == "en" #set text(28pt, font: font-heading()) if language == "zh" #underline(extent: 2pt)[ #block(smallcaps(it.body)) #v(3em) ] ] show heading.where(level: 2): it => [ #set text(24pt, font: font-heading()) if language == "en" #set text(22pt, font: font-heading()) if language == "zh" #block(counter(heading).display() + " " + smallcaps(it.body)) ] show heading.where(level: 3): it => [ #set text(20pt, font: font-heading()) if language == "en" #set text(18pt, font: font-heading()) if language == "zh" #block(counter(heading).display() + " " + smallcaps(it.body)) ] show heading.where(level: 4): it => [ #set text(16pt, font: font-heading()) #block(smallcaps(it.body)) ] show heading.where(level: 5): it => [ #set text(14pt, font: font-heading()) #block(smallcaps(it.body)) ] set par(justify: true) set heading(numbering: "1.1") counter(page).update(1) set page(header: getHeader()) set page(numbering: "1", number-align: center) body }
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history_CN/2015/MS-06.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [1], [马龙], [CHN], [3594], [2], [许昕], [CHN], [3329], [3], [樊振东], [CHN], [3316], [4], [张继科], [CHN], [3287], [5], [方博], [CHN], [3216], [6], [蒂姆 波尔], [GER], [3205], [7], [水谷隼], [JPN], [3156], [8], [#text(gray, "王皓")], [CHN], [3147], [9], [闫安], [CHN], [3084], [10], [迪米特里 奥恰洛夫], [GER], [3059], [11], [弗拉基米尔 萨姆索诺夫], [BLR], [3043], [12], [朱世赫], [KOR], [3028], [13], [唐鹏], [HKG], [3011], [14], [马克斯 弗雷塔斯], [POR], [2955], [15], [丹羽孝希], [JPN], [2949], [16], [帕特里克 弗朗西斯卡], [GER], [2936], [17], [于子洋], [CHN], [2932], [18], [高宁], [SGP], [2926], [19], [周雨], [CHN], [2922], [20], [黄镇廷], [HKG], [2921], [21], [吉村真晴], [JPN], [2920], [22], [帕特里克 鲍姆], [GER], [2916], [23], [塩野真人], [JPN], [2897], [24], [庄智渊], [TPE], [2889], [25], [梁靖崑], [CHN], [2888], [26], [帕纳吉奥迪斯 吉奥尼斯], [GRE], [2879], [27], [李尚洙], [KOR], [2876], [28], [金珉锡], [KOR], [2860], [29], [郑荣植], [KOR], [2856], [30], [徐晨皓], [CHN], [2844], [31], [MONTEIRO Joao], [POR], [2838], [32], [卢文 菲鲁斯], [GER], [2832], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [33], [#text(gray, "ZHAN Jian")], [SGP], [2829], [34], [吉田海伟], [JPN], [2825], [35], [汪洋], [SVK], [2808], [36], [KOU Lei], [UKR], [2805], [37], [利亚姆 皮切福德], [ENG], [2803], [38], [LI Hu], [SGP], [2802], [39], [陈卫星], [AUT], [2801], [40], [李廷佑], [KOR], [2800], [41], [斯特凡 菲格尔], [AUT], [2791], [42], [CHEN Feng], [SGP], [2791], [43], [安德烈 加奇尼], [CRO], [2787], [44], [罗伯特 加尔多斯], [AUT], [2787], [45], [LI Ping], [QAT], [2785], [46], [蒂亚戈 阿波罗尼亚], [POR], [2772], [47], [奥马尔 阿萨尔], [EGY], [2766], [48], [LIU Yi], [CHN], [2765], [49], [森园政崇], [JPN], [2760], [50], [巴斯蒂安 斯蒂格], [GER], [2749], [51], [沙拉特 卡马尔 阿昌塔], [IND], [2742], [52], [松平健太], [JPN], [2741], [53], [HABESOHN Daniel], [AUT], [2741], [54], [MACHI Asuka], [JPN], [2735], [55], [大岛祐哉], [JPN], [2735], [56], [WANG Zengyi], [POL], [2735], [57], [周恺], [CHN], [2733], [58], [西蒙 高兹], [FRA], [2733], [59], [KIM Donghyun], [KOR], [2732], [60], [丁祥恩], [KOR], [2728], [61], [GERALDO Joao], [POR], [2722], [62], [林高远], [CHN], [2722], [63], [周启豪], [CHN], [2722], [64], [PERSSON Jon], [SWE], [2722], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [65], [陈建安], [TPE], [2720], [66], [HE Zhiwen], [ESP], [2719], [67], [克里斯坦 卡尔松], [SWE], [2719], [68], [吉田雅己], [JPN], [2712], [69], [江天一], [HKG], [2709], [70], [PATTANTYUS Adam], [HUN], [2707], [71], [<NAME>], [SGP], [2706], [72], [TSUBOI Gustavo], [BRA], [2703], [73], [SHIBAEV Alexander], [RUS], [2703], [74], [DRINKHALL Paul], [ENG], [2699], [75], [雨果 卡尔德拉诺], [BRA], [2696], [76], [及川瑞基], [JPN], [2689], [77], [博扬 托基奇], [SLO], [2688], [78], [<NAME>], [POL], [2685], [79], [王臻], [CAN], [2684], [80], [吴尚垠], [KOR], [2679], [81], [BOBOCICA Mihai], [ITA], [2678], [82], [斯蒂芬 门格尔], [GER], [2669], [83], [KANG Dongsoo], [KOR], [2665], [84], [雅克布 迪亚斯], [POL], [2665], [85], [#text(gray, "KIM Hyok Bong")], [PRK], [2664], [86], [ELOI Damien], [FRA], [2663], [87], [村松雄斗], [JPN], [2661], [88], [赵胜敏], [KOR], [2659], [89], [夸德里 阿鲁纳], [NGR], [2654], [90], [#text(gray, "约尔根 佩尔森")], [SWE], [2652], [91], [HO Kwan Kit], [HKG], [2652], [92], [尚坤], [CHN], [2650], [93], [阿德里安 克里桑], [ROU], [2650], [94], [OYA Hidetoshi], [JPN], [2649], [95], [朴申赫], [PRK], [2648], [96], [PROKOPCOV Dmitrij], [CZE], [2648], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [排名], [运动员], [国家/地区], [积分], [97], [艾曼纽 莱贝松], [FRA], [2646], [98], [#text(gray, "KIM Nam Chol")], [PRK], [2646], [99], [VLASOV Grigory], [RUS], [2643], [100], [特里斯坦 弗洛雷], [FRA], [2643], [101], [HUANG Sheng-Sheng], [TPE], [2643], [102], [MATTENET Adrien], [FRA], [2642], [103], [SEO Hyundeok], [KOR], [2641], [104], [张禹珍], [KOR], [2641], [105], [维尔纳 施拉格], [AUT], [2637], [106], [HACHARD Antoine], [FRA], [2637], [107], [KIM Minhyeok], [KOR], [2634], [108], [张一博], [JPN], [2631], [109], [KONECNY Tomas], [CZE], [2630], [110], [OUAICHE Stephane], [ALG], [2630], [111], [詹斯 伦德奎斯特], [SWE], [2629], [112], [SAKAI Asuka], [JPN], [2629], [113], [SKACHKOV Kirill], [RUS], [2627], [114], [薛飞], [CHN], [2624], [115], [CHO Eonrae], [KOR], [2622], [116], [MATSUDAIRA Kenji], [JPN], [2618], [117], [米凯尔 梅兹], [DEN], [2618], [118], [TAKAKIWA Taku], [JPN], [2615], [119], [CHOE Il], [PRK], [2615], [120], [诺沙迪 阿拉米扬], [IRI], [2613], [121], [<NAME>], [CRO], [2611], [122], [<NAME>], [FIN], [2611], [123], [<NAME>], [GER], [2606], [124], [阿列克谢 斯米尔诺夫], [RUS], [2606], [125], [乔纳森 格罗斯], [DEN], [2601], [126], [上田仁], [JPN], [2599], [127], [<NAME>], [TPE], [2598], [128], [ROBLES Alvaro], [ESP], [2596], ) )
https://github.com/SkytAsul/trombinoscope
https://raw.githubusercontent.com/SkytAsul/trombinoscope/main/problem-demo.typ
typst
MIT License
#set page(width: 5cm, height: 2cm) #show heading: {} Page 1 that should *not* have a header. #pagebreak() #heading("Random hidden heading") #set page(header: "This is the header") Page 2 that *should* have a header. #pagebreak() Page 3 that *should* also have the header.
https://github.com/xichen1/typst-resume
https://raw.githubusercontent.com/xichen1/typst-resume/main/template.typ
typst
// The project function defines how your document looks. // It takes your content and some metadata and formats it. // Go ahead and customize it to your liking! #let project(title: "My Resume", authors: "ppx", body) = { // Set the document's basic properties. set document(author: authors, title: title) set page(margin: (left: 8mm, right: 8mm, top: 7mm, bottom: 7mm)) set text(font: "Linux Libertine", lang: "en") set par(justify: true) set text(hyphenate: true, size: 10pt) body } #let chiline() = {v(-3pt); line(length: 100%); v(-5pt)}
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/label-02.typ
typst
Other
// Test labelled text. #show "t": it => { set text(blue) if it.has("label") and it.label == <last> it } This is a thing #[that <last>] happened.
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Analyse_1_Cours_3.typ
typst
#import "@preview/bubble:0.1.0": * #import "@preview/fletcher:0.4.3" as fletcher: diagram, node, edge #import "@preview/cetz:0.2.2": canvas, draw, tree #import "@preview/cheq:0.1.0": checklist #import "@preview/typpuccino:0.1.0": macchiato #import "@preview/wordometer:0.1.1": * #import "@preview/tablem:0.1.0": tablem #show: bubble.with( title: "Analyse 1 Cours 3", subtitle: "18/09/2024", author: "<NAME>", affiliation: "EPFL", year: "2024/2025", class: "Génie Mécanique", logo: image("JOJO_magazine_Spring_2022_cover-min-modified.png"), ) #set page(footer: context [ #set text(8pt) #set align(center) #text("page "+ counter(page).display()) ] ) #set heading(numbering: "1.1") #show: checklist.with(fill: luma(95%), stroke: blue, radius: .2em) #let fa=sym.forall #let ex=sym.exists #let eps= sym.epsilon #let eqi = sym.arrow.l.r.double.long = Rappel Si $A$ est minoré son infimum est le réel $s$ + $s<= x, fa x in A$ + $fa eps > 0, ex x in A, s<= x <= s+eps$ = Solutions de $x^2=2$ == Théorème $ex x > 0, x^2 = 2$ == Preuve Soit $A = {x in RR_+^*: x^2 < 2}$ Ex: $1 in A, 2 in.not A$ *Lemme* $A$ n'a pas de $max(A)$ *Preuve* Soit $x in A$, $x' colon.eq x+1/n, n in NN^*$ On a $x'^2 = (x+1/n)^2 = x^2 + 2x/n + 1/n^2$ $ x'^2 <= x^2+(2x+1)/n $ Prenons $n$ tq $n>(2x+1)/(2-x^2)$ sachant que $2-x²>0$ $ x'^2 <= x^2+(2x+1)/n < x² + 2-x² = 2$ Ainsi $x' in A$ $A$ n'a pas de $max(A)$ *Remarque* $A$ est majoré, par $M = 2$. En effet $forall x > 3, x² > 9 > 2, x in.not A$ Considérons $s colon.eq sup(A)$ *Lemme 2* $s² = 2$ *Preuve 2* On va montrer que #linebreak() $s²>= 2$ Comme $A$ n'a pas de $max$. $s²<= 2$ Soit $M colon.eq (2+s²)/(2s)$ $ x² = (s+ (x-s))² = s² + 2s(x-s) + (x-s)² $ $ >= s²+2s(x-s) $ $ > s²+2s(M-s) $ $ = s²+2s((2+s²)/(2s) -s) $ $ = 2 $ $x in.not A$ alors $x<= M$ donc $M$ majore $A$. Or $s$ est le $sup(A)$ donc $s<= M$ $ s <= (2+s²)/2s $ $ 2s² <= 2+s² $ $ s² <= 2 $ Ainsi $s² = 2$ On appelle $s = sqrt(2)$ == Théorème $ fa y > 0 space ex x > 0, x^2 = y $ Donc $f: RR⁺ arrow RR⁺, x arrow f(x) = x²$ est une bijection. Sa réciproque s'appelle la fonction racine carrée. $f^(-1): RR⁺ arrow RR⁺, y arrow f^(-1)(y) = sqrt(y)$ == Théorème $ fa y > 0 space ex x > 0, x^n = y $ Donc $f: RR⁺ arrow RR⁺, x arrow f(x) = x^n$ est une bijection. Sa réciproque s'appelle la fonction racine carrée. $f^(-1): RR⁺ arrow RR⁺, y arrow f^(-1)(y) = root(n,y)$ = Densité == Définition Un sous-ensemble $E subset RR$ est dense (dans $RR$) si $fa x,y in RR, x < y, ex z in E "tq" x< z < y$ == Théorème $QQ$ est dense dans $RR$ == Définition $fa x in RR, floor(x) colon.eq "plus grand entier n" in ZZ "tq" n<=x$ $ floor(x) <= x <= floor(x) + 1 $ $ x-1 < floor(x) <= x $ === Preuve Soit $x,y in RR, x < y$ Posons $r colon.eq (floor(n x) +1)/n$ $n in NN$ tq $n> 1/(y-x)$ $r in QQ$ $ (n x)/n < r <= (n x+1)/n $ $ x < r <= x + 1/n $ $ x < r <= x + y -x $ $ x < r < y $ Ainsi $ QQ$ est dense dans $RR$ == Corollaire $ fa x in RR, fa eps > 0, ex r = p/q in RR "tq" abs(x-p/q) <= eps $ == Théorème 2 $RR without QQ$ est dense dans $RR$ = Ensembles ouverts et fermés == Définition $G subset RR$ est ouvert si $fa x in G, ex eps > 0 "tq", ]x-eps, x+eps[ subset G $ $F subset RR$ est fermé si son complémentaire $F^c := RR without F$ est ouvert === Ex + $G = ]0,1[$ est ouvert + $A = {x in RR | x²<2}$ == Propriété Soit $ G, F subset RR$ ouvert alors $G union F $ est ouvert === Ex + $ ZZ$ est fermé car $ZZ^c = union_(n in ZZ) ]n, n+1[$ ouvert + $[a,b[$ n'est pas ouvert car $fa eps > 0, ] a -eps, a+eps[ subset.not [a,b[ $ $([a,b[)^c = ]-infinity, a[ union [b, + infinity[$ n'est pas ouvert donc $[a,b[$ n'est pas fermé + $QQ$ n'est pas ouvert, ni fermé pareil pour $RR without QQ$ = Suites réelles == Définition Une suite est une famille infinie de réels indexée par des entiers $eqi f: F subset.eq NN arrow RR$
https://github.com/1sSay/USPTU_conspects
https://raw.githubusercontent.com/1sSay/USPTU_conspects/main/src/philosophy/ModernTime.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()[28.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 *Основная Характеристика*: #def[#text(red)[Крайний рационализм, скептицизм и гносеологический оптимизм]] - Идея прогресса - Антиклирикализм (против церкви) - Особый интерес к политико-правовым проблемам - Идея самоуправляющейся рыночной экономики - Деистический материализм = Фрэнсис Бэкон (1561 - 1626) #def[*Фрэнсис Бэкон* -- английский философ, юрист, государственный и придворный деятель. Жил и творил в эпоху мощного экономического и культурного подъёма Англии] - Фрэнсис поставил перед собой задачу разработки научного метода на основе материалистического понимания науки. Написал труд "Новый Органон" впротивовес Органону Аристотеля, где излагается новая логика мышления. Его метод опирается прежде всего на чувствах (*сенсуализм*) - Основной принцип его философии выражен в тезисе: *"Нет ничего в разуме, чего бы не было до этого в чувствах"* - Логику Бэкон понимает как орудие познания. Его логика отличается от логики Аристотеля (*дедукция* -- от общего к частному). В её основе лежит индукция -- от частного к общему - Основоположник *Эмпиризма* (Эмпиризм идёт рука об руку с сенсуализмом) - Индуктивная методология научного исследования (когда явления и сопровождающие их обстоятельства исследуются, а случайные обстоятельство исключается) \ \ \ == Идолы Френсиса Бэкона *Истину искажают идолы (ложные представления, предрассудки)*: + *Идолы рода* -- врождённые искажения, коренящиеся в наших органах чувтсв + *Идолы пещеры* -- это предрассудки, вызванные установками каждого отдельного человека + *Идолы рынка* -- неправильное, неточное употребление речевого, понятийного аппарата + *Идолы театра* -- заблуждения, вызванные авторитетами = Дуализм <NAME> (1596 - 1650) #def[*Я мыслю, следовательно я существую*] - Обосновал ведущую роль разума в познании - Стал автором теории дуализма, то есть попытался примирить материалистические и идеалистические направление - Выдвинул теорию о научном методе познания и врожденных идеях - Основной метод -- *дедукция* - Единственный субстанцией, коя не нуждается ни в чем кроме самой себя явялется Бог, который вечен, несотворим, неуничтожим - Две субстанции существуют вместе. Ничто не первично #def[*Достоверное знание, учил Декарт, состоит в усмотрении размом ясных и очевидных отношений между ясными и раздельными идеями: где разум через сравнение идей не усматривает таких отношений, там может быть только мнение, а не знание: достоверные истины получаются разумом непосрдественно или через вывод из других истин, почему знание бывает интуитивным и дедуктивным*] = Субъективный идеализм <NAME> (1685-1753) - Философское учение Беркли направлено на опровержение материализма и обоснование религии - Разделения восприятия и существования -- нет! - Быть -- значит существовать в чьём-то восприятии - Идеи общие и абстрактные -- сводятся к общим -- существуют только восприятии человека - Идеи существуют в духе и могут быть похожи только за идеи #def[*Бытие -- это или то, что воспринимается, или тот, кто воспринимает*] - Беркли отвергает все пространственные чувства, они определяются способностями наших органов чувтсва и не имеют объективного характера. Отвергнув бытие материи, Беркли признает существование только духовного бытия (Бога) - Идеи (воспринимаемые нами субъективные качества) - Духи (подлинные носители идей, из которых состоят вещи ощущаемого мира)#def[Бог вкладывает в сознание отдельных субъектов содержание ощущений, возникающих у них при созерцании мира] - Философия Беркли послужила важнейшим переходным моментом к учению *Юма* о субъективных психологических основаниях идей субстанции и причинности, далее к учению *Канта* о субъективных формах восприятия и мышления, и еще далее к учению *Шопенгауэра* о возможности познать суть мира только из внтуренней интуиции нашей воли.
https://github.com/julius2718/tempura
https://raw.githubusercontent.com/julius2718/tempura/main/README.md
markdown
MIT License
# tempura A Typst template for Japanese documents
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/012%20-%20Conspiracy/004_Blood%20Will%20Have%20Blood.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Blood Will Have Blood", set_name: "Conspiracy", story_date: datetime(day: 04, month: 06, year: 2014), author: "<NAME>", doc ) Some of the grubs were no bigger than a coin. Pale and fleshy, they squirmed their way along the cracks in the floor. Beetles with wiry, clicking legs scurried over them, hissing at each other as they passed. Centipedes, long as a human’s arm, curled in the dry ribcages of long-dead prisoners. For being in isolation, Selvala certainly didn’t feel alone. "Little fawn." The voice was a gnarled whisper seeping in through the cell door. She hadn’t seen the dungeon keeper, but she’d heard that voice, pooling its sound deep in her ears. For the first two days, there had been a parade of goblins knocking at her door, screaming in their tinny voices. She’d dealt with each of them in turn. "Wee faaawn." Selvala stood in place and focused on the swarming insects. When she didn’t watch them, vertigo overtook her—the individual insects would disappear and instead the floor and walls seemed to writhe and breathe like she was in the stomach of some great animal. "Happy faaaaawn." And when she didn’t watch them, tiny things would start to crawl up the leather of her boots. She wondered if they were drawn by the scent of dried blood. Three days later, it was all she could smell. "Sweet faaaaaaawn." That blood had drawn a crowd three days before as well, but then it was wet and red and ran down her knife like water. She didn’t want to think about that. She didn’t want to listen to the dungeon keeper’s voice. She focused on the swarm. Her mouth was parched. "Killer faaaaaaaaaawn." Now, soaked into her gloves, the blood was the color of rust. Three coats had been added on top of that. Goblin blood. Black. Viscous. Sticky. She wondered if she should offer the gloves to her cellmates. They might chew the gloves clean again. Three days felt like a long time ago. "Deadly fawn. Vicious fawn. Murder fawn." She focused on her breathing and tried not to listen to the sound of the dungeon keeper just beyond her cell door. She knew he was watching from the bars, squat face pressed close, keys clanking at his side. "Don’t you want your supper, Fawn?" She wondered if she could move fast enough to reach the door before he could react, wondered if she could get a shard of bone into his skull while he was still so close. "Certainly," said Selvala. She swallowed. She hadn’t spoken in three days and her voice was like rocks. "Why don’t you come in here and give it to me?" The dungeon keeper chortled. His disembodied voice echoed from beyond the heavy door. "Oh fawn, what do you take me for? You took the eye of one my best agents. What do you have smuggled in there, knitting needles?" Selvala smiled and fingered the crudely sharpened weapon at her side. "A femur." "Ha!" he cried. "Bone to the eye! I knew you would be good. A master! The others said you were all talk, yet here you are: my perfect assassin." Her smile dissipated. She didn’t look at her jailer’s face, but she imagined it. Yellow teeth, bulging eyes, breath hot and putrid. He wasn’t made for Paliano either. "Well, your uncle Grenzo forgives you," said the dungeon keeper. "What’s a little blood between friends?" #figure(image("004_Blood Will Have Blood/02.jpg", width: 100%), caption: [Grenzo, Dungeon Warden | Art by <NAME>], supplement: none, numbering: none) She turned her attention finally toward the door. His smiling, bloated face watched from between the bars of the narrow window. "Why don’t you get out of here?" she asked. "I’m formulating my escape." His smile grew until it showed all his rotting teeth. He asked, "What’s it like to kill a man you love?" She turned away, back to the beetles that crunched under her boots. She’d been to the lowlands, she’d survived in the wild, she could stand the taste of insect. Had bluebloods starved to death in here, refusing to deign to eat from the floor? "Answer me that one question, dainty fawn, and I’ll unlock this door." She tensed her muscles. All it would take was one quick lunge and this conversation would be over. Her shard of bone was no rapier, but he was a lump of a thing and it would do the job. She said, "I’m sure you don’t need me to answer that question." "Oh, but I do. My hands are clean." She eyed the skull that lay in the corner. Its empty sockets would stare forever at the dripping ceiling of this cell. He said, "All I do is turn some keys and talk." She contemplated the stories she’d heard about the dungeon keeper, about his agents swarming in the sewers, crawling through the night—mercenary killers and spies, dispatching problems and watching for opportunities to blackmail. He waited for her to speak. When she didn’t, he said, "And I’ll turn this key here—I’ve done it before—if you answer your dear old uncle Grenzo’s question: What’s it like to kill a friend?" Selvala said, "All too easy." He scoffed. She waited. Above the hiss of beetles, the jangle of keys, the click of the lock. The door slid open with a creak. "Next time, maybe it will stick," he said from the hallway. She turned her attention to the door. No one came. Beyond, she could hear the keeper’s labored breathing in the passage. She didn’t understand, didn’t know his game. She knew she was being manipulated, but to what end? #figure(image("004_Blood Will Have Blood/04.jpg", width: 100%), caption: [Backup Plan | Art by <NAME>], supplement: none, numbering: none) "Come on out," he said. "I’ve got a skin of water and a jug of wine. You’ve split your time between the low city and the high. Didn’t know which one you’d want." Selvala took a light step toward the door. The shadows trembled in the torchlight. Grenzo had a huge frame for a goblin, but he was hunched over, like his bones were rebelling against him. He clutched his staff and she wondered if he could walk a step without it. He held the waterskin aloft. She waited for the trap—a dozen agents around the corner? Poisoned gifts? Some dark magic? Grenzo turned his head from side to side as if considering the tunnels. "You can run, Fawn, but the trail is treacherous. I’ll take you on your way." She gripped the shard of bone and contemplated his jugular. It was thick, like a snake sleeping in his neck. "Well, go on then," she said, nodding. "Lead the way." Grenzo was right. The tunnels were like arteries, forever branching and changing direction. Selvala was studied in tracking and tried to make sense of the paths, looking for exits with which to escape or landmarks in case she needed to double back to lose pursuers in the tunnels. But the stonework was relentless. The only guide points were the occasional chatter of goblins—averting their gaze from Grenzo as he passed—and the moans of the prisoners—pleading with Grenzo for his keys. They walked for a long time. Every so often, Grenzo would stop and poke at the ceiling above them. "Palace," he would say and laugh. Or "Brago’s bedchamber. Won’t need that anymore!" "Sydri’s shop—at least since sundown yesterday." Slowly, the map of Paliano began to make sense to her, but still she didn’t know where he was leading her or to what end. "Secret council chamber," he said, and watched her face to see if she knew. At one point, he stopped and sniffed the air. He lofted his staff and banged it against the ceiling above them. "Treasury," he announced. Then he pointed his staff like a long, bony finger. "Take that passage and it leads straight into the vault. Take a handful of gold for your trip if you want. Fill your boots if you want. It’s free for the taking." He stared at her, waiting for a reaction. "Doesn’t it excite you? The thought that we’re in the secret heart of Fiora?" She stared at him, tried to make her face neutral, offering him nothing. "Did you ever want to see the king’s private sculpture collection? Ever eat poached egg of paradise bird? Not of this world! There are stairs into that kitchen, too. Every secret door, every secret lock is known to me!" He held his keys aloft and shook them at her. "What do you want, Little Fawn? What’s your price? I know it’s not gold, but I can offer you heaps. Access? Do you want to leave the high city? Or free it? Open the secret gates and let the rabble below up into our streets? Great pulleys to hoist up the beasts from the old world? Information? Just think what it would have been to spy on your dear friend, Brago, and peer into his secret plots. Then maybe you wouldn’t have been so quick to stab. Or you would have been quicker! Gotten the job done while you still had the chance." He stepped closer and hoisted himself level with her face. She gritted her teeth. "Another chance to kill a friend? Is that what you want? More murder? I can provide that as well. We can make these sewers run red from the carnage of it all." He smiled and his eyes watched her closely. "What about the opportunity to kill an enemy for a change?" "What," she said, "am I being asked to do?" He laughed triumphantly. It was loud and unfettered. She didn’t know how deep the tunnels ran, but it must be deep enough to mask the cackling of a madman. He scurried down a passage, then stopped, motioning for her to follow. He put an ear to the wall and she followed suit. There was sound there, although she couldn’t place it—low and resonant, like a great elephant dragging a chain, but there were other sounds too. Soft, rhythmic clicks and whirs. They reminded her of bird calls, but there was something off about them—something impossibly regular. Grenzo sorted through key after key, looking for one in particular. With a grin, he found it and tucked it into a secret lock in the stones. The wall swung open. Grenzo, dancing with excitement, waved her up the stairs. The nightingale was wound from wire, its beak two brass clasps that opened as it sung out seven perfect notes. It then waved its false wings and spun once in a circle to sing again. Those same seven notes carried through the library, rising high up toward the vaulted ceiling. All around Selvala, ornate automata clanked and whirred. Metal, spidery limbs sorted books into the shelves. Glass eyes on long wrought necks followed them, twisting back and forth as if checking for errors. In the corner, a shell of iron shaped like a human ran thin paintbrushes over a canvas in even circles, a landscape taking slow shape in their wake. "Muzzio’s library?" asked Selvala in a whisper. "There’s a terrible order to it all, isn’t there?" said Grenzo. His breath was labored, as if the air were thinner. "The grand tyrant architect, Muzzio—student of Daretti, who looked down at his legs one morning and said, ‘I can do better.’ He promised us a new world. One that was perfectly crafted. One that was programmed and understood. One that he would build to replace us all." #figure(image("004_Blood Will Have Blood/08.jpg", width: 100%), caption: [Muzzio, Visionary Architect | Art by Volkan Baga], supplement: none, numbering: none) Against the far wall, towering nearly two stories in height, was a beast of a machine. Pulleys stretched across its wooden limbs like sinews. A maw of terrible gears seemed to smile at them. The beast was still as a statue, but between its legs, Selvala could see a great red door. "So what do you want, Little Fawn? Your world is doused in mud and blood and bile. These shining animals would be a new menagerie for a new world." "What am I being asked to do?" she repeated. "It’s a new world, Fawn. You’ve set it in motion. We have a king with no blood. We have beasts with iron flesh. The future is deathless, inorganic, unless you act now." Grenzo held up his key ring and picked out a single key. It was decorated with interlocking spiral patterns—an artisan’s object, like everything there. Grenzo’s smiled and his eyes bulged, ready to escape his skull. With heavy, excited breath, he said, "Through that door, Muzzio lies sleeping." Selvala pulled away from him. "Is that what you’re asking me? To eliminate your rival? What? As thanks for turning a little key?" "Not my rival. One who would see your bleeding world swept away and replaced." She stared at Grenzo, holding the gaze of those yellow eyes. He smiled wider and she kicked at his staff, sending it sailing. Grenzo crumpled to the floor. She reached for the bone blade at her side with one hand and knelt to grip the goblin’s leathery throat with the other. "I should cut you open right here. I will not be your hired thug. I will not help you mutilate Paliano into your twisted image." And then she saw the yellow glow. She turned her head to watch the great construct rise from its spiritless slumber. Its gears wound faster and faster. Its pulleys stretched themselves taut as it prepared to spring forward. #figure(image("004_Blood Will Have Blood/12.jpg", width: 100%), caption: [Lurking Automaton | Art by Yeong-Hao Han], supplement: none, numbering: none) Letting go of Grenzo, Selvala tumbled from the path of the machine. Grenzo moved too, scurrying away with a speed she had not expected from his haggard frame. The machine swiped with a great paw. She ducked low and books went flying overhead, tomes raining down on her. The mechanical librarians scurried to collect the debris. Selvala looked at the cracked femur in her hand. It wasn’t much of a weapon. She knew where to strike on something human, knew how to hunt the great animals, but the femur wouldn’t even dent the machine’s casing. She hurried between the machine’s legs and scanned for the dungeon keeper. He was back down the secret staircase, pulling closed the trap door concealed in the floorboards. "What world do you want, Selvala?" he yelled and, with a great laugh, slammed the door closed. She dove and tried to pry her fingers into the secret lock of the secret door that led back down into Grenzo’s undercity. Behind her, Muzzio’s guardian was twisting its wooden limbs, readying itself to strike again. She sunk her weapon into the lock, crudely forcing harder and harder as the beast descended. Then, with a snap, the bone cracked in half and the lock gave way. Selvala felt like she was falling as she stumbled through the sewers. Behind her, she could hear the clomping of great machine legs. In her mind, she could feel the beast’s cold breath on her neck, but she knew that was just her imagination. In her arms, she carried Muzzio’s tomes. They spilled from her arms as she ran, but that was the point. An army of artificial librarians chased after her, filling the dark tunnels with the clicking of their limbs. Somewhere, she could hear the squeal of goblins, their tunnels opened and filling with things not of their world. Soon they would clash—Grenzo’s secret killers and Muzzio’s artificial animals—and she didn’t know which side would win. She hoped both sides might find their secrets laid bare for all of Paliano to see, but she knew that too might not succeed. When Selvala had run far enough that she couldn’t hear the battle behind her, she collapsed. She found an unlocked cell and crawled into the corner with the beetles. The next day, she would leave the High City and go back to the wild places far below and far beyond. Her boots would be caked with mud, her limbs tired and sweaty as she ran through the trees, picked fruit, and watched the wild beasts. But, at the time, her task was to hide in the darkness with the insects and sleep. #figure(image("004_Blood Will Have Blood/16.jpg", width: 100%), caption: [Worldknit | Art by <NAME>], supplement: none, numbering: none)
https://github.com/connachermurphy/typst-slides
https://raw.githubusercontent.com/connachermurphy/typst-slides/main/README.md
markdown
MIT License
# typst-slides Slides template for Typst. # Planned Improvements _to add_
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1900.typ
typst
Apache License 2.0
#let data = ( ("LIMBU VOWEL-CARRIER LETTER", "Lo", 0), ("LIMBU LETTER KA", "Lo", 0), ("LIMBU LETTER KHA", "Lo", 0), ("LIMBU LETTER GA", "Lo", 0), ("LIMBU LETTER GHA", "Lo", 0), ("LIMBU LETTER NGA", "Lo", 0), ("LIMBU LETTER CA", "Lo", 0), ("LIMBU LETTER CHA", "Lo", 0), ("LIMBU LETTER JA", "Lo", 0), ("LIMBU LETTER JHA", "Lo", 0), ("LIMBU LETTER YAN", "Lo", 0), ("LIMBU LETTER TA", "Lo", 0), ("LIMBU LETTER THA", "Lo", 0), ("LIMBU LETTER DA", "Lo", 0), ("LIMBU LETTER DHA", "Lo", 0), ("LIMBU LETTER NA", "Lo", 0), ("LIMBU LETTER PA", "Lo", 0), ("LIMBU LETTER PHA", "Lo", 0), ("LIMBU LETTER BA", "Lo", 0), ("LIMBU LETTER BHA", "Lo", 0), ("LIMBU LETTER MA", "Lo", 0), ("LIMBU LETTER YA", "Lo", 0), ("LIMBU LETTER RA", "Lo", 0), ("LIMBU LETTER LA", "Lo", 0), ("LIMBU LETTER WA", "Lo", 0), ("LIMBU LETTER SHA", "Lo", 0), ("LIMBU LETTER SSA", "Lo", 0), ("LIMBU LETTER SA", "Lo", 0), ("LIMBU LETTER HA", "Lo", 0), ("LIMBU LETTER GYAN", "Lo", 0), ("LIMBU LETTER TRA", "Lo", 0), (), ("LIMBU VOWEL SIGN A", "Mn", 0), ("LIMBU VOWEL SIGN I", "Mn", 0), ("LIMBU VOWEL SIGN U", "Mn", 0), ("LIMBU VOWEL SIGN EE", "Mc", 0), ("LIMBU VOWEL SIGN AI", "Mc", 0), ("LIMBU VOWEL SIGN OO", "Mc", 0), ("LIMBU VOWEL SIGN AU", "Mc", 0), ("LIMBU VOWEL SIGN E", "Mn", 0), ("LIMBU VOWEL SIGN O", "Mn", 0), ("LIMBU SUBJOINED LETTER YA", "Mc", 0), ("LIMBU SUBJOINED LETTER RA", "Mc", 0), ("LIMBU SUBJOINED LETTER WA", "Mc", 0), (), (), (), (), ("LIMBU SMALL LETTER KA", "Mc", 0), ("LIMBU SMALL LETTER NGA", "Mc", 0), ("LIMBU SMALL LETTER ANUSVARA", "Mn", 0), ("LIMBU SMALL LETTER TA", "Mc", 0), ("LIMBU SMALL LETTER NA", "Mc", 0), ("LIMBU SMALL LETTER PA", "Mc", 0), ("LIMBU SMALL LETTER MA", "Mc", 0), ("LIMBU SMALL LETTER RA", "Mc", 0), ("LIMBU SMALL LETTER LA", "Mc", 0), ("LIMBU SIGN MUKPHRENG", "Mn", 222), ("LIMBU SIGN KEMPHRENG", "Mn", 230), ("LIMBU SIGN SA-I", "Mn", 220), (), (), (), (), ("LIMBU SIGN LOO", "So", 0), (), (), (), ("LIMBU EXCLAMATION MARK", "Po", 0), ("LIMBU QUESTION MARK", "Po", 0), ("LIMBU DIGIT ZERO", "Nd", 0), ("LIMBU DIGIT ONE", "Nd", 0), ("LIMBU DIGIT TWO", "Nd", 0), ("LIMBU DIGIT THREE", "Nd", 0), ("LIMBU DIGIT FOUR", "Nd", 0), ("LIMBU DIGIT FIVE", "Nd", 0), ("LIMBU DIGIT SIX", "Nd", 0), ("LIMBU DIGIT SEVEN", "Nd", 0), ("LIMBU DIGIT EIGHT", "Nd", 0), ("LIMBU DIGIT NINE", "Nd", 0), )
https://github.com/TomVer99/FHICT-typst-template
https://raw.githubusercontent.com/TomVer99/FHICT-typst-template/main/CONTRIBUTING.md
markdown
MIT License
# Contributing to the FHICT (Fontys Hogeschool ICT) Typst Template Project I'd love your input! I want to make contributing to this project as easy and transparent as possible, whether it's: - Reporting a bug - Discussing the current state of the code - Submitting a fix - Proposing new features - Discussing documentation ## I Develop with Github I use github to host code, to track issues and feature requests, as well as accept pull requests. ## I Use [Github Flow](https://docs.github.com/en/get-started/using-github/github-flow), So All Code Changes Happen Through Pull Requests Pull requests are the best way to propose changes to the codebase (I use [Github Flow](https://docs.github.com/en/get-started/using-github/github-flow)). I actively welcome your pull requests: 1. Fork the repo and create your branch from `master`. 2. Test your changes. 3. Issue that pull request! ## Any contributions you make will be under the MIT Software License In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. ## Report bugs using Github's [issues](https://github.com/TomVer99/FHICT-typst-template/issues) I use GitHub issues to track public bugs. Report a bug by [opening a new issue](https://github.com/TomVer99/FHICT-typst-template/issues); it's that easy! ## Write bug reports with detail, background, and sample code **Great Bug Reports** tend to have: - A quick summary and/or background - Steps to reproduce - Be specific! - Give sample code if you can. - What you expected would happen - What actually happens - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) People *love* thorough bug reports. I'm not even kidding. ## License By contributing, you agree that your contributions will be licensed under its MIT License. ## References This document was adapted from briandk's [template](https://gist.github.com/briandk/3d2e8b3ec8daf5a27a62).
https://github.com/mumblingdrunkard/mscs-thesis
https://raw.githubusercontent.com/mumblingdrunkard/mscs-thesis/master/src/berkeley-out-of-order-machine/index.typ
typst
= The Berkeley Out-of-Order Machine <ch:boom> The Berkeley Out-of-Order Machine (BOOM) is an open-source-software (OSS) project from the University of California, Berkeley (UC Berkeley). It is an implementation of a 64-bit RISC-V processor == RISC-V The BOOM uses the RISC-V ISA, which is also developed at UC Berkeley @bib:riscv. RISC-V is, as its name might imply, a RISC architecture. The ISA has many variants and different extensions. The BOOM uses the 64-bit base variant of RISC-V, rv64. This variant specifies a base machine with 32 64-bit registers and instructions operating on 64-bit and 32-bit values. Several instruction format variants are defined for different instruction types. Some instructions require no destination register, while others require immediate values encoded in the instructions. Instructions have a fixed size of 32 bits. The PC is aligned at a four-byte boundary (the lower two bits of the PC are always 0). RISC-V is a so-called register-register architecture where the only instructions that access memory are load and store instructions#footnote[... and atomic instructions which may write a value, read a value, and update a register all at once]. Additionally, all instructions write to one architectural register or do not write a value at all. === Compressed Instructions RISC-V supports instructions shorter than 32 bits through the C-extension. The C-extension specifies a 16-bit instruction format for several common instructions and reduces the alignment requirement of the PC to a two-byte boundary (the lowest bit is always 0). Even 32-bit instructions may start on any two-byte boundary. The BOOM supports this extension, among many others. === Privileged Architecture The RISC-V specification is split in a user-level architecture, and a privileged architecture. The user-level architecture contains functionality most relevant to pure computation like branches, arithmetic, and memory instructions. The privileged architecture contains functionality that is only available when executing in a privileged mode. The privileged architecture specifies a scheme for virtual memory using pages of 4096 bytes (4 KiB). Additionally, the privileged architecture specifies a number of _control and status registers_ (CSRs) that control the behaviour of the processor. By writing different values to these registers, a programmer can manage the current execution mode, set up and control virtual memory, and control many other aspects of execution. The CSR file additionally contains a number of _hardware performance counters_ (HPMs) to allow tracking things like time, the number of cycles, and the number of executed instructions. == Development Development of the BOOM project uses various tools for development, testing, and deployment. === Chisel Chisel @bib:chisel-paper is a library of components and operations on those components written in Scala @bib:scala-lang. Scala is a functional programming language built on top of the _java virtual machine_ (JVM). Scala allows defining arbitrary operators which has enabled the developers of Chisel to create a system of various components that can be connected together with something that resembles a _domain-specific language_ (DSL), but is still fundamentally "just Scala". Because Chisel is not its own language, but embedded in Scala, it is what is referred to as an _embedded_ DSL (eDSL). Chisel in combination with Scala becomes its own eDSL HDL. Similar projects exist in other functional languages like HardCaml in OCaml @bib:hardcaml and Clash in Haskell @bib:clash. When writing a program in Scala using Chisel, the compiled code is a Scala program. When running the Scala program, a Chisel _graph_ is generated by going through the code and instantiating components and connecting them together as specified by the program. The code can include things like loops, variable reassignments, and everything else that normal Scala has to offer. This is the real genius of Chisel: Scala can be used as a very powerful meta-programming language around Chisel. The Chisel graph is verified against certain rules such as no disconnected inputs to modules and no combinational loops. The Chisel graph might go through rudimentary optimisations by eliminating unused signals and other restructuring. Finally, the graph can be used for purposes like simulation by tweaking input and output signals from code written in Scala. However, the built-in simulator for the Chisel graph can be slow. The graph can be used to output structural code in other HDLs such as VHDL or SystemVerilog which can in turn be used by other tools. _Structural_ code is different from _behavioural_ code in that it describes circuits in terms of multiplexers, adders, and gates instead of === Verilator Verilator is a program that accepts SystemVerilog and translates the code to a multithreaded implementation of a simulator in C++ @bib:verilator. This code is then compiled to create the final simulator. Verilator gives a much faster simulator than simulating the Chisel graph directly and still preserves some of the nice debugging features that are available directly in Chisel such as printing debug information while simulating. === FireSim FireSim is a platform for simulating circuits on FPGAs @bib:firesim. Note that this is slightly different from simply implementing circuits on FPGAs. FireSim includes various tools for debugging and profiling while running on the FPGA itself, features that have to be otherwise explicitly included in the RTL code otherwise. This obviously leads to more complex circuits/systems, but these simulations are still much faster than in something like Verilator. == Architecture and Implementation of Key Components The BOOM uses, as the name would imply, an OoO microarchitecture. Here, we present the components of the BOOM that are relevant to this text. We may mention other components that are not fully explained, but their naming should give clear hints to their operation. === High-Level Architecture and Code Organisation The BOOM source code is organised into a few directories: `common`, `exu`, `ifu`, `lsu`, and `util`. The directory names hint at their contents. For example: `common` contains `micro-op.scala` and `parameters.scala`, files that are used throughout the entire project and don't belong to one specific unit, or collection of units. `util` has various utility components. `exu` can be said to contain the actual processor and has files like `core.scala`, `decode.scala`, `rob.scala`, and all the files for various execution units, issue units, and register renaming. `ifu` contains the front of the frontend such as the instruction cache implementation and various modules for fetching instructions, figuring out their alignments, and wrapping them up in packets for decoding down the line. This is called the _instruction fetch unit_ (IFU). `lsu` contains the files for the _load-store unit_ (LSU) described later. #figure( ```monosketch ┌───────────────────────────┐ │ IF │ └────────────┬──────────────┘ ┌────────────▼──────────────┐ ┌────┤ ID │ │ └────────────┬──────────────┘ ┌──────────────▼─┐ ┌────────────▼──────────────┐ │ │ │ RR │ │ ROB │ └───┬──────────────┬────────┘ │ │ ┌───▼───┐ ┌────────▼────────┐ │ │ │ mIQ │ │ iIQ │ └────────┬───────┘ └───┬───┘ └───┬─────────┬───┘ ▼ ┌───▼─────────▼─────────▼───┐ commit ┌─────▶ PRF │ │ └───┬─────────┬─────────┬───┘ ┌─────────────┴──┐ ▼ ┌───▼───┐ ┌───▼───┐ │ LSU ◀─── AGU │MUL/DIV│ │ ALU │ └───────▲────────┘ ├───────┤ └───┬───┘ │ │MUL/DIV│ ▼ ┌───────▼────────┐ ├───────┤ to PRF │ │ │MUL/DIV│ │ D$ │ └───┬───┘ │ │ ▼ └────────────────┘ to PRF ```, kind: image, caption: "High-level overview of BOOM microarchitecture", ) === Anatomy of a Micro-operation The BOOM uses a single class to represent most of the control signals that flow through the processor. With few exceptions, the control signals for each stage are either derived from, or directly embedded within the `MicroOp` class found inside `common/micro-op.scala`. This uOP class contains various flags and fields that inform later units of the type of instruction, which architectural registers it reads and writes, which physical registers it depends upon and writes to, which branches the instruction is currently speculated under, and more. Not all signals are used in all stages, but Chisel optimises out these signals and only keeps those that need to be brought along. This is a big advantage for development and debugging because it allows for assigning a signal as early as instruction fetch, and reading it back out at commit. It also has the downside of it being very easy to accidentally rely on a signal that is not meant to be available at a certain stage. For example, at commit, the information in the uOP comes from the ROB. Depending on a signal at commit that was previously optimised away has the often unintended effect of increasing the size of each entry in the ROB. === Instruction Fetch Because the BOOM is a superscalar implementation, the frontend must be able to fetch multiple instructions per cycle. The BOOM fetches a number of bytes from the L1i and performs rudimentary pre-decoding to determine instruction boundaries and to be able to perform branch prediction. It places raw instructions in a buffer that is read by the instruction decode stage. === Instruction Decode The ID stage decodes raw instructions from the fetch buffer and allocates various necessary resources. === Re-Order Buffer The documentation for the BOOM outlines the organisation of the ROB. The ROB is stored as a $w$ wide table where $w$ is the width of the processor. Instructions that are decoded together are consecutive in memory and can be stored in the same row in the ROB. The rationale for this is that the high-order bits of the PC can be shared across entries in each row, yielding major savings in the number of bits needing to be stored. An obvious downside is the requirement that instructions in the same row must be consecutive, leaving bubbles if there are a lot of branches in the code. Documentation states that the low-order bits of each instruction in the ROB are determined by the index within each row, but this information is likely outdated and from a time when the BOOM did not support compressed instructions. Now the uOP class contains an explicit field `pc_lob` which can be concatenated with the high-order bits stored per row. The high-order bits of the PC in each ROB row are stored in the _fetch target queue_ (FTQ) in the IFU and is used for referencing in other parts of the pipeline; for example when instructions have to be replayed and the frontend has to be redirected to some point in the past. Entries in the ROB are allocated during instruction decode. === Issue Queues The base BOOM configuration has two issue queues. One for memory operations (mIQ), and a separate one for integer operations (iIQ). If operations on floating point numbers are supported, there is a separate queue for those too. The IQ slots hold instructions and listen for when dependencies become available. Once all dependencies are available, the instructions are issued to various FUs. === Address Generation Units The _address generation units_ (AGUs) are the functional units that calculate addresses for instructions that access memory. These units are not pipelined unlike most other units in the BOOM. In the same cycle that the uOPs are issued, the address exits the AGU and is sent to the load-store unit. === Load-Store Unit The _load-store unit_ (LSU) is where we have made most of our changes, besides the predictor itself. It consists of various components and a lot of logic to determine which operation to perform next. ==== Load Queue The _load queue_ (LDQ) holds information about the load instructions currently active in the system. It is implemented as a circular buffer. Entries are allocated at the tail during decode and are freed at commit. LDQ entries consist of a few crucial signals such as the address, whether the address is virtual or physical, if the load has been executed (sent to the cache), and whether the load succeeded. The LDQ entries also store the associated uOP to access fields like the physical destination register during writeback. ==== Translation Lookaside Buffer The BOOM has a TLB to cache virtual address translations. All addresses that enter the LSU from the AGUs go through the TLB. If virtual addressing is not enabled, the TLB simly simply passes the address through without any translation and always succeeds. ==== Deciding Which Operations to Perform In any one cycle, the LSU must decide what action to perform. Possible cases the LSU has to handle are: - fire a store or load for an address arriving from an AGU, - retry a store or load whose address already arrived but failed translation by the TLB, or - wake up a store or load whose address already arrived and succeeded translation but was not acknowledged by the data cache. For these various signals, addresses from the AGU always have priority as the AGUs have no mechanism to apply back-pressure and stall. Addresses from AGUs are attempted to be translated by the TLB and the result is stored in the LDQ. If translation fails, the untranslated address is stored instead to be retried later. The LDQ and STQ are scanned to find entries that require waking up or retrying. The LSU code contains a method to generate code that prioritises different signals depending on their resource needs. The LSU can schedule multiple operations if their resource needs do not overlap. For example: a load in need of retrying the address translation could be translated at the same time as a load with an already translated address is woken up. This interaction in particular is not handled, but is a good example of how the LSU scheduling might work when resource needs are separate. ==== Other Management As various operations leave the LSU and are headed for the data cache, the addresses are compared with those in the LDQ and STQ to determine whether any forwarding should happen or if any ordering violations are visible. If an outgoing load instruction is found to overlap with a store instruction in the STQ, the load is squashed and the value is forwarded from the store instruction instead. ==== Tracking Load Instructions When load instructions are sent to the data cache and are not denied, the corresponding entry is marked as "executed" in the LDQ. uOPs are tracked based on their LDQ index so that when responses arrive from the data cache, the relevant information for what to do next can be found partly in the LDQ. There is some latency between the uOP issuing to the cahe and the entry being marked as executed. This is to give the data cache time to locate the value and inform the LSU of a lack of capacity to handle a miss, called a _nack_ for "not acknowledged". In the meantime, a mask is set to prevent the load being selected for wakeup. If the uOP is not nack'ed, the "executed" flag is finally set and the data cache takes over. ==== Responses When responses arrive for loads, they contain data that must be written back to the PRF. The response contains the LDQ index and the physical destination register index is stored in the LDQ. The LSU uses a writeback port to the PRF to write back the result. ==== Speculative Load Wakeups The BOOM supports speculatively waking up dependent instructions a cycle before the values from loads are returned. This is done by assuming the load hits in the first-level cache and informing the IQs early. This allows dependent instructions to issue in the same cycle that the values are being written back to the PRF. === Data Cache The data cache of the BOOM is slightly underdocumented at the time. The documentation that exists is for an old version of the cache where the implementation was intended for an in-order processor and a shim was in charge of handling the out-of-order requests. The current implementation is a more classic out-of-order cache with hit-under-miss and other optimisations. ==== Miss Status Holding Registers The _miss status holding registers_ (MSHRs) hold the operations that missed in the first-level cache and wait for responses from lower levels. These are a finite resource and if an operation misses while the MSHRs are full, it causes the operation to be nack'ed, requiring the LSU to replay the request later on.
https://github.com/yonatanmgr/university-notes
https://raw.githubusercontent.com/yonatanmgr/university-notes/main/0366-%5BMath%5D/03661111-%5BLinear%20Algebra%201A%5D/src/lectures/03661111_lecture_13.typ
typst
#import "/template.typ": * #import "@preview/colorful-boxes:1.2.0": * #show: project.with( title: "אלגברה לינארית 1א׳ - שיעור 13", authors: ("<NAME>",), date: "15 בפברואר, 2024", ) #set enum(numbering: "(1.א)") = כפל מטריצות == תזכורת - העתקת הקואורדינטות ומטריצות מייצגות === העתקת הקואורדינטות $[v]_B = vec(a_1, dots.v, a_n) iff v = sum_(i=1)^n a_i v_i$ עבור $B = (v_1, dots, v_n)$ בסיס של מ״ו $V$. === מטריצה מייצגת המטריצה המייצגת של הה״ל $T$ במעבר מהבסיס $B$ לבסיס $C$ היא: $ [T]_underbracket(C, space"הטווח")^overbracket(B, "התחום") = (a_(i j)) = mat(|,,|; [T v_1]_C, dots.h.c, [T v_n]_C; |, , |) $ כאשר $C = (v_1, dots, v_n)$ בסיס של $U$ ו-$T: V->U$. === $hom(V,U) tilde.eq M_(m xx n)(F)$ ע״י $T |-> [T]_C^B$. === תזכורת נוספת מתקיים $forall v in V, [T v]_C = [T]_C^B dot [v]_B$, כאשר הגדרנו $A=(a_(i j))_(&i=1,dots,m \ &j=1,dots,n )$ ו-$v=vec(x_1, dots.v,x_n) in F^n$, אז: $ A dot v = vec(sum_(j=1)^n a_(1 j) x_j, dots.v, sum_(j=1)^n a_(m j) x_j) $ ומתקיים: $ mat(a_(1 1), dots.h.c, a_(1 n); dots.v,, dots.v; a_(m 1), dots.h.c, a_(m n)) dot vec(x_1, dots.v, x_n) = vec(a_(1 1) x_1 + dots.h.c + a_(1 n)x_n, dots.v, a_(m 1) x_1 + dots.h.c + a_(m n)x_n) $ == מוטיבציה לכפל מטריצות בהינתן $B$ בסיס של $V$ ו-$C$ בסיס של $U$ יש לנו איזומורפיזם $hom(V,U) -> M_(m xx n) (F)$. נראה כי אגף שמאל הוא הרכבה, ולכן נרצה שכפל מטריצות יהיה הדבר המתאים להרכבה. == הגדרה יהיו $M=(a_(i j))_(&i=1,dots,m \ &j=1,dots,s ) in M_(m xx s) (F)$ ו-$N=(b_(i j))_(&i=1,dots,s \ &j=n,dots,n ) in M_(s xx n)(F)$. נגדיר כפל, כלומר מטריצה חדשה: $M N = M dot N = (c_(i j)) in M_(m xx n) (F)$, כאשר $c_(i j) = sum_(k=1)^s a_(i k) dot b_(k j)$ לכל $i in {1, dots, m}$ ולכל $j in {1, dots, n}$. #pagebreak() === דוגמאות + כפל מטריצות מגודל $1 xx s$ ו-$s xx 1$: נסמן $m=1, n=1$, $s$ כלשהו. נקבל $mat(a_1, dots, a_s) dot mat(b_1;dots.v;b_s) = a_1 b_1 + a_2 b_2 + dots.h.c + a_s b_s in M_(1 xx 1)(F)$. + אם $M_(i->) in M_(1 xx s) $ זו השורה ה-$i$ של $M$, ו-$N_(j arrow.t) in M_(s xx 1)$ העמודה ה-$j$ של $N$ אז $M N = (M_(i ->) N_(j arrow.t))_(i j)$. + נסמן $e_i = vec(0,dots.v, 1, dots.v, 0) in M_(n xx 1) (F)$ כש-$1$ בשורה ה-$i$. נסמן $e_i^t = mat(0, dots.h.c, 1, dots.h.c, 0) in M_(1 xx m)(F)$ כש-$1$ בעמודה ה-$i$. אז $e^t_i dot M = M_(i->)$, כלומר השורה ה-$i$-ית של $M$, ו-$N dot e_j = N_(j arrow.t)$, כלומר העמודה ה-$j$-ית של $N$. + $ mat(1, -1, 2; 3, -2, 1)mat(5,2;0,-3;-1,4) = mat(5+0-2, 2 + 3 + 8; 15 +0-1, 6+6+4) = mat(3,13;14,16) in M_(2 xx 2)(F) $ + $ mat(1;2;3) mat(1,2,3,4) = mat(1,2,3,4;2,4,6,8;3,6,9,12) in M_(3 xx 4)(F) $ === (טענה) יהיו $V, U, W$ מ״ו מעל שדה $F$ עם בסיסים סופיים $B,C,D$ בהתאמה ויהיו $T:V->U$ ו-$S:U->W$ העתקות לינאריות. אזי $[S of T]_D^B=[S]_D^C dot [T]_C^B$. ==== הוכחה נסמן $B=(v_1, dots, v_n), C=(u_1, dots, u_s), D=(w_1, dots, w_m)$. נבצע "בדיקת שפיות": $ [S]_D^C & in M_(m xx s)(F) \ [T]_C^B & in M_(s xx n)(F) \ [S of T]_D^B & in M_(m xx n)(F) $ ולכן הגדלים באמת מסתדרים. נבדוק בכל אחד מהאגפים האם הרכיב ה-$i,j$ שווה או לא. נסמן: $ [S]_D^C &= (s_(i j))_(&i=1, dots, m\ &j=1,dots,s) \ [T]_C^B &= (t_(i j))_(&i=1, dots, s\ &j=1,dots,n) \ [S of T]_D^B &= (x_(i j))_(&i=1, dots, m\ &j=1,dots,n) $ לפי ההגדרות: $ T v_i = sum_(k=1)^s t_(k i) u_k \ S of T v_i = S(T(v_i)) = S (sum_(k=1)^s t_(k i) u_k ) = sum_(k=1)^s t_(k i) S(u_k) = sum_(k=1)^s sum_(j=1)^m t_(k i) s_j k w_j = sum_(k=1)^m (sum_(k=1)^s s_(j k) t_(k i)) w_j $ מצד שני, $sum_(k=1)^s s_(j k) t_(k i)$ הוא האיבר ה-$j,i$ של המכפלה $[S]_D^C dot [T]_C^B$, כנדרש. #QED #pagebreak() === (מסקנה) כפל של מטריצות הוא אסוציאטיבי ודיסטריבוטיבי. כלומר: + $(A B) C = A(B C)$ לכל שלוש מטריצות מסדרים בהם הכפל מוגדר. + $(A+B) C = A C + B C, A (B + C) = A B + A C$ עבור מטריצות בגודל בו הכפל והחיבור מוגדרים. ==== הוכחה + אפשר להוכיח ע״י נוסחאות או #underline[ע״י העתקות והקשר למטריצות]. נבחר העתקות ובסיסים כך ש-$A,B,C$ יהיו המטריצות המייצגות. למשל, $A in M_(m xx s), B in M_(s xx n), C in M_(n xx r)$. נסמן: $ &T_A: F^s->F^m &&wide T_A (v) = A v wide [T_A]_E^E = A space(E "הבסיס הסטנדרטי") \ &T_B: F^n->F^s &&wide T_B (v) = B v \ &T_C: F^r->F^n &&wide T_C (v) = C v $ $ A dot (B C) = [T_A] dot [T_B of T_C] = [T_A of (T_B of T_C)] = [T_A of T_B of T_C] = [(T_A of T_B) of T_C] = (A B) dot C $ + הוכחה זהה לסעיף הקודם. #QED ==== (הערה) הכפל אינו חילופי: $ A = mat(0,1;0,0), B=mat(0,0;0,1), A B = mat(0,1;0,0) != mat(0,0;0,0) = B A $ - אתגר - ליצור דוגמה כזו מסדר $n xx n$ לכל $n>1$. - עבור $n = 1$ $M_(1 xx 1) (F) tilde.eq F$ ולכן חילופי. === (הגדרה) מטריצת היחידה $ I_n = mat(1,0,dots.h.c,0; 0, dots.down, dots.down, dots.v; dots.v, dots.down, dots.down, 0; 0, dots.h.c, 0, 1) in M_(n xx n) (F) $ נראה ישירות ש-$I_n dot A = A$ ו- $B dot I_n = B$ לכל $A_(n xx s), B_(s xx n)$. ואכן $A=(a_(i j))$ ונסמן $I = (delta_(i j))$ כאשר $delta_(i j) = cases(0 "if" i != j, 1 "if" i = j)$. $ underbrace((I_n dot A)_(i j), i j"סימון לרכיב ה-") = sum_(k=1)^n delta_(i k) dot a_(k j) = delta_(i i) a_(i j) = a_(i j) $ לכן $I_n dot A = A$. - נשים לב: אם $V$ עם בסיס $B=(v_1, dots, v_n)$ אז העתקת הזהות $id(V): V->V$ מקיימת $[id(V)]_B^B = I_n$. #pagebreak() = כתיב מטריציוני של מערכות משוואות נסמן מערכת משוואות: $ ast.circle = cases(a_(1 1)x_1 &+ a_(1 2)x_2 &&+ dots.h.c + a_(1 n)x_n &&&= b_1, dots.v, a_(m 1)x_1 &+ a_(m 2)x_2 &&+ dots.h.c + a_(m n)x_n &&&= b_m) $ נסמן $underline(x) = vec(x_1, dots.v, x_n) in F^n, A = (a_(i j)) in M_(m xx n)(F)$ ו-$underline(b) = vec(b_1, dots.v, b_n) in F^m$. אז $ast.circle$ שקול ל-$A underline(x) = underline(b)$. זה שקול ללהשוות עם משוואה לינארית אחת עם משתנה $a x = b$. ==== מסקנה: הוכחה חדשה לזה שקבוצת הפתרונות של מערכת משוואות היא מ״ו: במערכת הומוגנית: $A underline(x) = 0 iff T_A underline(x) = 0$ ומכך קבוצת הפתרונות היא $ker T_A $. \ במערכת לא הומוגנית: $A_x = b iff T_A x = b$ ומכך קבוצת הפתרונות היא $inv(T_A) (b)$. == המטריצה המשוחלפת (Transpose) בהינתן מטריצה $A in M_(m xx n) (F)$ נגדיר $A^t in M_(n xx m)(F)$ ע״י $A=(a_(i j))$ $arrl$ $A^t = (a_(j i))$. כלומר, אנחנו מחליפים שורות ועמודות. לדוגמה: $mat(pi, e, i; -1, 0, 1)^t = mat(pi, -1; e, 0; i, 1)$. === (טענה) פעולות עם מטריצות משוחלפות יהיו $A, B in M_(m xx s)(F)$ ו-$lambda in F$. + $(A^t)^t = A$. + $(lambda A)^t = lambda A^t$. + $(A+B)^t = A^t + B^t$. + $(A B)^t = B^t A^t$ (כשהכפל מוגדר, בגדלים המתאימים). כלומר $dot^t : M_(m xx s)(F) -> M_(s xx m)$ (כאשר $dot^t$ סימון לפונקציה $(dot^t)(A)=A^t$, בדומה לפונקציה $[dot]_B: V->F^n$ שהתמונה של $v$ היא $[v]_B$ כלומר $[dot]_B (v) = [v]_B$) היא לינארית. ==== הוכחה + $((A^t)^t)_(i j) = (A^t)_(j i) = A_(i j)$. + $(lambda A)_(i j)^t = (lambda A)_(j i) = lambda A_(j i) = lambda(A^t)_(i j)$. + $(A+B)^t_(i j) = (A+B)_(j i) = A_(j i) + B_(j i) = (A^t)_(i j) + (B^t)_(i j)$. + $(A B)^t_(i j) = (A B)_(j i) = sum_(k=1)^n a_(j k) dot b_(k i) = sum_(k=1)^n A^t_(k j) dot B_(i k)^t =(B^t A^t)_(i j)$. #QED
https://github.com/WinstonMDP/knowledge
https://raw.githubusercontent.com/WinstonMDP/knowledge/master/cfg.typ
typst
#let cfg(it) = { show math.equation.where(block: false): it => math.display(it) set math.equation(numbering: "(I)") it }
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/text/raw.typ
typst
// Test raw blocks. --- raw-empty --- // Empty raw block. Empty raw block:``. --- raw-consecutive-single-backticks --- // No extra space. `A``B` --- raw-typst-lang --- // Typst syntax inside. ```typ #let x = 1``` \ ```typ #f(1)``` --- raw-block-no-parbreaks --- // Multiline block splits paragraphs. Text ```rust fn code() {} ``` Text --- raw-more-backticks --- // Lots of backticks inside. ```` ```backticks``` ```` --- raw-trimming --- // Trimming. // Space between "rust" and "let" is trimmed. The keyword ```rust let```. // Trimming depends on number backticks. (``) \ (` untrimmed `) \ (``` trimmed` ```) \ (``` trimmed ```) \ (``` trimmed```) \ --- raw-single-backtick-lang --- // Single ticks should not have a language. `rust let` --- raw-dedent-first-line --- // First line is not dedented and leading space is still possible. ``` A B C ``` --- raw-dedent-empty-line --- // Do not take empty lines into account when computing dedent. ``` A B ``` --- raw-dedent-last-line --- // Take last line into account when computing dedent. ``` A B ``` --- raw-tab-size --- #set raw(tab-size: 8) ```tsv Year Month Day 2000 2 3 2001 2 1 2002 3 10 ``` --- raw-syntaxes --- #set page(width: 180pt) #set text(6pt) #set raw(syntaxes: "/assets/syntaxes/SExpressions.sublime-syntax") ```sexp (defun factorial (x) (if (zerop x) ; with a comment 1 (* x (factorial (- x 1))))) ``` --- raw-theme --- // Test code highlighting with custom theme. #set page(width: 180pt) #set text(6pt) #set raw(theme: "/assets/themes/halcyon.tmTheme") #show raw: it => { set text(fill: rgb("a2aabc")) rect( width: 100%, inset: (x: 4pt, y: 5pt), radius: 4pt, fill: rgb("1d2433"), place(right, text(luma(240), it.lang)) + it, ) } ```typ = Chapter 1 #lorem(100) #let hi = "Hello World" #show heading: emph ``` --- raw-show-set --- // Text show rule #show raw: set text(font: "Roboto") `Roboto` --- raw-align-default --- // Text inside raw block should be unaffected by outer alignment by default. #set align(center) #set page(width: 180pt) #set text(6pt) ```py def something(x): return x a = 342395823859823958329 b = 324923 ``` --- raw-align-specified --- // Text inside raw block should follow the specified alignment. #set page(width: 180pt) #set text(6pt) #align(center, raw( lang: "typ", block: true, align: right, "#let f(x) = x\n#align(center, line(length: 1em))", )) --- raw-align-invalid --- // Error: 17-20 expected `start`, `left`, `center`, `right`, or `end`, found top #set raw(align: top) --- raw-inline-multiline --- #set page(width: 180pt) #set text(6pt) #set raw(lang:"python") Inline raws, multiline e.g. `for i in range(10): # Only this line is a comment. print(i)` or otherwise e.g. `print(j)`, are colored properly. Inline raws, multiline e.g. ` # Appears blocky due to linebreaks at the boundary. for i in range(10): print(i) ` or otherwise e.g. `print(j)`, are colored properly. --- raw-highlight-typ --- ```typ = Chapter 1 #lorem(100) #let hi = "Hello World" #show heading: emph ``` --- raw-highlight-typc --- #set page(width: auto) ```typ #set hello() #set hello() #set hello.world() #set hello.my.world() #let foo(x) = x * 2 #show heading: func #show module.func: func #show module.func: it => {} #foo(ident: ident) #hello #hello() #box[] #hello.world #hello.world() #hello().world() #hello.my.world #hello.my.world() #hello.my().world #hello.my().world() #{ hello } #{ hello() } #{ hello.world() } #if foo [] ``` --- raw-highlight-typm --- #set page(width: auto) ```typm 1 + 2/3 a^b hello hello() box[] hello.world hello.world() hello.my.world() f_zeta(x), f_zeta(x)/1 emph(hello.my.world()) emph(hello.my().world) emph(hello.my().world()) #hello #hello() #hello.world #hello.world() #box[] ``` --- raw-highlight-rust --- #set page(width: auto) ```rust /// A state machine. #[derive(Debug)] enum State<'a> { A(u8), B(&'a str) } fn advance(state: State<'_>) -> State<'_> { unimplemented!("state machine") } ``` --- raw-highlight-py --- #set page(width: auto) ```py import this def hi(): print("Hi!") ``` --- raw-highlight-cpp --- #set page(width: auto) ```cpp #include <iostream> int main() { std::cout << "Hello, world!"; } ``` --- raw-highlight-html --- #set page(width: auto) ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <h1>Topic</h1> <p>The Hypertext Markup Language.</p> <script> function foo(a, b) { return a + b + "string"; } </script> </body> </html> ``` --- raw-blocky --- // Test various raw parsing edge cases. #let empty = ( name: "empty", input: ``, text: "", ) #let backtick = ( name: "backtick", input: ``` ` ```, text: "`", block: false, ) #let lang-backtick = ( name: "lang-backtick", input: ```js ` ```, lang: "js", text: "`", block: false, ) // The language tag stops on space #let lang-space = ( name: "lang-space", input: ```js test ```, lang: "js", text: "test ", block: false, ) // The language tag stops on newline #let lang-newline = ( name: "lang-newline", input: ```js test ```, lang: "js", text: "test", block: true, ) // The first line and the last line are ignored #let blocky = ( name: "blocky", input: { ``` test ``` }, text: "test", block: true, ) // A blocky raw should handle dedents #let blocky-dedent = ( name: "blocky-dedent", input: { ``` test ``` }, text: "test", block: true, ) // When there is content in the first line, it should exactly eat a whitespace char. #let blocky-dedent-firstline = ( name: "blocky-dedent-firstline", input: ``` test ```, text: "test", block: true, ) // When there is content in the first line, it should exactly eat a whitespace char. #let blocky-dedent-firstline2 = ( name: "blocky-dedent-firstline2", input: ``` test ```, text: "test", block: true, ) // The first line is not affected by dedent, and the middle lines don't consider the whitespace prefix of the first line. #let blocky-dedent-firstline3 = ( name: "blocky-dedent-firstline3", input: ``` test test2 ```, text: "test\n test2", block: true, ) // The first line is not affected by dedent, and the middle lines don't consider the whitespace prefix of the first line. #let blocky-dedent-firstline4 = ( name: "blocky-dedent-firstline4", input: ``` test test2 ```, text: " test\ntest2", block: true, ) #let blocky-dedent-lastline = ( name: "blocky-dedent-lastline", input: ``` test ```, text: " test", block: true, ) #let blocky-dedent-lastline2 = ( name: "blocky-dedent-lastline2", input: ``` test ```, text: "test", block: true, ) #let blocky-tab = ( name: "blocky-tab", input: { ``` test ``` }, text: "\ttest", block: true, ) // This one is a bit problematic because there is a trailing tab below "test" // which the editor constantly wants to remove. #let blocky-tab-dedent = ( name: "blocky-tab-dedent", input: eval("```\n\ttest\n \n ```"), text: "test\n ", block: true, ) #let cases = ( empty, backtick, lang-backtick, lang-space, lang-newline, blocky, blocky-dedent, blocky-dedent-firstline, blocky-dedent-firstline2, blocky-dedent-firstline3, blocky-dedent-lastline, blocky-dedent-lastline2, blocky-tab, blocky-tab-dedent, ) #for c in cases { let block = c.at("block", default: false) assert.eq(c.text, c.input.text, message: "in point " + c.name + ", expect " + repr(c.text) + ", got " + repr(c.input.text) + "") assert.eq(block, c.input.block, message: "in point " + c.name + ", expect " + repr(block) + ", got " + repr(c.input.block) + "") } --- raw-line --- #set page(width: 200pt) ```rs fn main() { println!("Hello, world!"); } ``` #show raw.line: it => { box(stack( dir: ltr, box(width: 15pt)[#it.number], it.body, )) linebreak() } ```rs fn main() { println!("Hello, world!"); } ``` --- raw-line-alternating-fill --- #set page(width: 200pt) #show raw: it => stack(dir: ttb, ..it.lines) #show raw.line: it => { box( width: 100%, height: 1.75em, inset: 0.25em, fill: if calc.rem(it.number, 2) == 0 { luma(90%) } else { white }, align(horizon, stack( dir: ltr, box(width: 15pt)[#it.number], it.body, )) ) } ```typ #show raw.line: block.with( fill: luma(60%) ); Hello, world! = A heading for good measure ``` --- raw-line-text-fill --- #set page(width: 200pt) #show raw.line: set text(fill: red) ```py import numpy as np def f(x): return x**2 x = np.linspace(0, 10, 100) y = f(x) print(x) print(y) ``` --- raw-line-scripting --- // Test line extraction works. #show raw: code => { for i in code.lines { test(i.count, 10) } test(code.lines.at(0).text, "import numpy as np") test(code.lines.at(1).text, "") test(code.lines.at(2).text, "def f(x):") test(code.lines.at(3).text, " return x**2") test(code.lines.at(4).text, "") test(code.lines.at(5).text, "x = np.linspace(0, 10, 100)") test(code.lines.at(6).text, "y = f(x)") test(code.lines.at(7).text, "") test(code.lines.at(8).text, "print(x)") test(code.lines.at(9).text, "print(y)") test(code.lines.at(10, default: none), none) } ```py import numpy as np def f(x): return x**2 x = np.linspace(0, 10, 100) y = f(x) print(x) print(y) ``` --- issue-3601-empty-raw --- // Test that empty raw block with `typ` language doesn't cause a crash. ```typ ``` --- issue-3841-tabs-in-raw-type-code --- // Tab chars were not rendered in raw blocks with lang: "typ(c)" #raw("#if true {\n\tf()\t// typ\n}", lang: "typ") #raw("if true {\n\tf()\t// typc\n}", lang: "typc") ```typ #if true { // tabs around f() f() // typ } ``` ```typc if true { // tabs around f() f() // typc } ``` --- issue-4662-math-mode-language-for-raw --- // Test lang: "typm" syntax highlighting without enclosing dollar signs #raw("pi^2", lang: "typm") --- issue-2259-raw-color-overwrite --- // Test that the color of a raw block is not overwritten #show raw: set text(fill: blue) `Hello, World!` ```rs fn main() { println!("Hello, World!"); } ``` --- issue-3191-raw-indent-shrink --- // Spaces in raw blocks should not be shrunk as it would mess up the indentation // of code. #set par(justify: true) #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, ) #block( width: 60%, ```py for x in xs: print("x=",x) ``` ) --- issue-3191-raw-normal-paragraphs-still-shrink --- // In normal paragraphs, spaces should still be shrunk. // The first line here serves as a reference, while the second // uses non-breaking spaces to create an overflowing line // (which should shrink). ~~~~No shrinking here ~~~~The~spaces~on~this~line~shrink --- issue-3820-raw-space-when-end-with-backtick --- ```typ `code` ``` ```typ `code` ``` --- raw-theme-set-to-auto --- ```typ #let hi = "Hello World" ``` #set raw(theme: "/assets/themes/halcyon.tmTheme") ```typ #let hi = "Hello World" ``` #set raw(theme: auto) ```typ #let hi = "Hello World" ``` --- raw-theme-set-to-none --- #set raw(theme: none) ```typ #let foo = "bar" ``` --- raw-unclosed --- // Test unterminated raw text. // // Note: This test should be the final one in the file because it messes up // syntax highlighting. // // Error: 1-2:1 unclosed raw text `endless
https://github.com/kaarmu/splash
https://raw.githubusercontent.com/kaarmu/splash/main/doc/main.typ
typst
MIT License
#import "../src/palettes.typ" #import "util.typ": * // Document start #make-title( title: "Palettes", description: [ A library of color palettes for Typst. ], author: "<NAME>", date: "April 22, 2023", ) #outline(target: heading.where(level: 3)) #pagebreak() #show heading.where(level: 2): body => { pagebreak(weak: true) body } // xcolor #section( cols: 3, title: "xcolor", name: "xcolor", palettes.xcolor, ) == Paul Tol's Colors The following section includes palettes created Paul Tol. `typst-palettes` only package his work for ease-of-use in Typst. #section( cols: 4, title: "Tol's Bright", description: [ Bright qualitative colour scheme that is colour-blind safe. The main scheme for lines and their labels. ], name: "tol-bright", palettes.tol-bright, do-page-break: false, ) #section( cols: 4, title: "Tol's High-contrast", description: [ High-contrast qualitative colour scheme, an alternative to the bright scheme of Fig. 1 that is colour-blind safe and optimized for contrast. The samples underneath are shades of grey with the same luminance; this scheme also works well for people with monochrome vision and in a monochrome printout. ], name: "tol-high-contrast", palettes.tol-high-contrast, do-page-break: false, ) #section( cols: 4, title: "Tol's Vibrant", description: [ Vibrant qualitative colour scheme, an alternative to the bright scheme of Fig. 1 that is equally colour-blind safe. It has been designed for data visualization framework TensorBoard, built around their signature orange FF7043. That colour has been replaced here to make it print-friendly. ], name: "tol-vibrant", palettes.tol-vibrant, do-page-break: false, ) #pagebreak(weak: true) #section( cols: 4, title: "Tol's Muted", description: [ Muted qualitative colour scheme, an alternative to the bright scheme of Fig. 1 that is equally colour-blind safe with more colours, but lacking a clear red or medium blue. Pale grey is meant for bad data in maps. ], name: "tol-muted", palettes.tol-muted, do-page-break: false, ) #section( cols: 3, title: "Tol's Medium-contrast", description: [ Medium-contrast qualitative colour scheme, an alternative to the high-contrast scheme of Fig. 2 that is colour-blind safe with more colours. It is also optimized for contrast to work in a monochrome printout, but the differences are inevitably smaller. It is designed for situations needing colour pairs, shown by the three rectangles, with the lower half in the greyscale equivalent. ], name: "tol-medium-contrast", palettes.tol-medium-contrast, do-page-break: false, ) #section( cols: 3, title: "Tol's Light", description: [ Light qualitative colour scheme that is reasonably distinct in both normal and colour-blind vision. It was designed to fill labelled cells with more and lighter colours than contained in the bright scheme of Fig. 1, using more distinct colours than that in the pale scheme of Fig. 6 (top), but keeping black labels clearly readable (see Fig. 10). However, it can also be used for general qualitative maps. ], name: "tol-light", palettes.tol-light, do-page-break: false, ) == Google Workspace #section( title: "Google Slides", name: "google", palettes.google, ) #section( title: "Google Slides: Simple Light Theme", name: "google-simple-light", palettes.google-simple-light, do-page-break: false, ) #section( title: "Google Slides: Simple Dark Theme", name: "google-simple-dark", palettes.google-simple-dark, do-page-break: false, ) == University profiles // KTH #section( cols: 2, title: "KTH (RGB)", name: "kth-rgb", palettes.kth-rgb, do-page-break: false, ) #section( cols: 2, title: "KTH (CMYK)", name: "kth-cmyk", palettes.kth-cmyk, ) == Misc // Typst Syntax Highlighting #section( title: "Typst Syntax Highlighting", name: "typst-highlighting", palettes.typst-highlighting, ) // Gruvbox #section( cols: 3, title: "Gruvbox", name: "gruvbox", palettes.gruvbox, ) // Tailwind CSS #section( cols: 3, title: "Tailwind CSS", name: "tailwind", palettes.tailwind, ) // Okabe-Ito #section( cols: 3, title: "Okabe-Ito", name: "okabe-ito", palettes.okabe-ito, ) // XKCD #section( cols: 3, description: "These colors were named in the XKCD Color Survey.", // TODO link title: "XKCD Color Survey", name: "xkcd_rgb", palettes.xkcd_rgb, ) == Seaborn The following section shows qualitative palettes created by the seaborn project. `typst-palettes` only package his work for ease-of-use in Typst. Visit the #link("https://seaborn.pydata.org/tutorial/color_palettes.html")[seaborn documentation] for a discussion of these palettes. All of these palettes come in a default 10-color and a reduced six color version. #section( cols: 4, title: "Seaborn Bright", name: "seaborn.bright", palettes.seaborn.bright, do-page-break: false, ) #section( cols: 3, title: "Seaborn Bright 6", name: "seaborn.bright6", palettes.seaborn.bright6, do-page-break: false, ) #section( cols: 4, title: "Seaborn Colorblind", name: "seaborn.colorblind", palettes.seaborn.colorblind, do-page-break: false, ) #section( cols: 3, title: "Seaborn Colorblind 6", name: "seaborn.colorblind6", palettes.seaborn.colorblind6, ) #section( cols: 4, title: "Seaborn Dark", name: "seaborn.dark", palettes.seaborn.dark, do-page-break: false, ) #section( cols: 3, title: "Seaborn Dark 6", name: "seaborn.dark6", palettes.seaborn.dark6, do-page-break: false, ) #section( cols: 4, title: "Seaborn Deep", name: "seaborn.deep", palettes.seaborn.deep, do-page-break: false, ) #section( cols: 3, title: "Seaborn Deep 6", name: "seaborn.deep6", palettes.seaborn.deep6, ) #section( cols: 4, title: "Seaborn Muted", name: "seaborn.muted", palettes.seaborn.muted, do-page-break: false, ) #section( cols: 3, title: "Seaborn Muted 6", name: "seaborn.muted6", palettes.seaborn.muted6, do-page-break: false, ) #section( cols: 4, title: "Seaborn Pastel", name: "seaborn.pastel", palettes.seaborn.pastel, do-page-break: false, ) #section( cols: 3, title: "Seaborn Pastel 6", name: "seaborn.pastel6", palettes.seaborn.pastel6, do-page-break: false, )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/book.typ
typst
Apache License 2.0
#import "@preview/shiroa:0.1.1": * #import "./templates/page.typ": main-color #show: book #let main-color = main-color // #let section-numbers = state("book-section", ()) #let section-numbers = () #let get-section(level) = { // section-numbers.update(it => { // while it.len() < level { // it.push(0) // } // if it.len() >= level { // let last-level = it.at(level - 1) // it = it.slice(0, level - 1) + (last-level, ) // } // }) // locate(loc => { // let l = section-numbers.query(loc) // return l.map(str).join(".") // }) } #book-meta( title: "reflexo-typst Documentation", summary: [ #prefix-chapter("introduction.typ")[Introduction] = Guidance - #chapter("get-started.typ", section: "1")[Get started] - #chapter("guide/all-in-one.typ", section: "1.1")[All-in-one (Simplified) Library for Browsers] - #chapter("guide/all-in-one-node.typ", section: "1.2")[All-in-one Library for Node.js] - #chapter("direction/main.typ", section: "2")[Technical Directions] - #chapter("direction/responsive.typ", section: "2.1")[Static, Responsive rendering] - #chapter("direction/incremental.typ", section: "2.2")[Streaming, Incremental rendering] - #chapter("direction/serverless.typ", section: "2.3")[Serverless rendering] - #chapter("guide/compilers.typ", section: "3")[Compilers] - #chapter("guide/compiler/ts-cli.typ", section: "3.1")[Command Line Interface] - #chapter("guide/compiler/service.typ", section: "3.2")[Compiler in Rust] - #chapter("guide/compiler/node.typ", section: "3.3")[Compiler in Node.js] - #chapter("guide/compiler/bindings.typ", section: "3.3")[Compiler in Wasm (Web)] - #chapter("guide/renderers.typ", section: "4")[Renderers] - #chapter("guide/renderer/ts-lib.typ", section: "4.1")[JavaScript/TypeScript Library] - #chapter("guide/renderer/node.typ", section: "4.2")[Node.js Library] - #chapter("guide/renderer/react.typ", section: "4.3")[React Library] - #chapter("guide/renderer/solid.typ", section: "4.4")[Solid Library] - #chapter("guide/renderer/angular.typ", section: "4.5")[Angular Library] - #chapter("guide/renderer/vue3.typ", section: "4.6")[Vue3 Library] - #chapter("guide/renderer/hexo.typ", section: "4.7")[Hexo Plugin] - #chapter("guide/trouble-shooting.typ", section: "5")[Trouble Shooting] // = Advanced development // - #chapter("guide/env-setup.typ", section: "5")[Environment Setup] // - #chapter("guide/env-setup/renderer.typ", section: "5.1")[For Renderer] // - #chapter("guide/env-setup/compiler.typ", section: "5.2")[For Compiler] // - #chapter("dev/shims/core.typ", section: "6")[Wasm Shim - typst.ts] // - #chapter(none, section: "6.1")[Lazy Loading Wasm Modules] // - #chapter("dev/shims/renderer.typ", section: "6.2")[Low-level Renderer APIs] // - #chapter("dev/shims/compiler.typ", section: "6.3")[Low-level Compiler APIs] // - #chapter(none, section: "6.4")[Topic: Font Loading] // - #chapter(none, section: "6.5")[Topic: Tree Shaking] // - #chapter("dev/services/main.typ", section: "7")[Compiler service] // - #chapter(none, section: "7.1")[Build a Precompiler] // - #chapter("dev/services/editor-server.typ", section: "7.2")[Build a Editor Server] // - #chapter("dev/services/cloud-compiler.typ", section: "7.3")[Build a Serverless Compiler] // - #chapter(none, section: "7.4")[Topic: Preprocessing Dynamic Layout] // - #chapter(none, section: "7.5")[Topic: Incremental Compilation] // - #chapter(none, section: "8")[Write your Owned Exporter] // - #chapter(none, section: "8.1")[Native Exporters] // - #chapter(none, section: "8.2")[Vector Representation] // - #chapter(none, section: "8.3")[Topic: SVG Exporter/Renderer] = Deeper dive into typst.ts - #chapter(none, section: "5")[Core Concepts] - #chapter(none, section: "5.1")[Exporter Trait] - #chapter(none, section: "5.2")[Compiler Trait] - #chapter(none, section: "6")[Vector Represented Document] - #chapter(none, section: "6.1")[Data Structure] - #chapter(none, section: "6.2")[Binary Protocol] - #chapter(none, section: "6.3")[Render Virtual Machine] - #chapter(none, section: "6.4")[Topic: Partially Accessible Document] - #chapter(none, section: "6.5")[Topic: BBox Calculation] - #chapter(none, section: "6.6")[Topic: Semantic Layer Rendering] - #chapter(none, section: "7")[Compiler Infrastructure] - #chapter(none, section: "7.1")[Split World Models] - #chapter(none, section: "7.2")[Virtual File System] - #chapter(none, section: "7.3")[Font Management] - #chapter(none, section: "7.4")[Typst Package Registry] - #chapter(none, section: "7.5")[Compile Driver] - #chapter(none, section: "7.6")[Editor Workspace] = Project samples - #chapter(none, section: "8")[shiroa] - #chapter(none, section: "9")[typst-preview] - #chapter(none, section: "10")[hexo-renderer-typst] = Trouble Shooting - #chapter(none, section: "11")[Targeting Browser] - #chapter(none, section: "11.1")[Build Wasm Modules] - #chapter(none, section: "11.2")[typst.ts] - #chapter(none, section: "11.3")[tpyst.node] - #chapter(none, section: "11.4")[typst-ts-renderer] - #chapter(none, section: "11.5")[typst-ts-web-compiler] - #chapter(none, section: "12")[Installation] - #chapter(none, section: "12.1")[npm install/link] = References - #chapter(none, section: "13")[Routing to Renferences] ], ) #get-book-meta() // re-export page template #import "/docs/cookery/templates/page.typ": project #let book-page = project
https://github.com/floriandejonckheere/utu-thesis
https://raw.githubusercontent.com/floriandejonckheere/utu-thesis/master/proposal/proposal.typ
typst
#import "template.typ": * #show: template.with( // Document title title: "Research Proposal", // Document subtitle subtitle: "Master's Thesis in Technology (DTEK1002)", // List of authors authors: ((name: "<NAME>", email: "<EMAIL>"),), // Date of publication date: datetime.today().display("[month repr:long] [day], [year]"), // Bibliography bibliography-file: "proposal.yml", // Institution logo (SVG) logo-file: "logo-fi.svg", // Abstract abstract: [ *Working title*: _Identification of Module Boundaries in a Modular Monolith Architecture using Automated technologies_ The modular monolith architecture emerged in recent years as the harmonization of the monolithic and microservices architectures. The paradigm offers a compromise between modularity, flexibility, and scalability. Many monolithic applications are being migrated to modular monoliths or microservices entirely, to satisfy increasingly complex and volatile business requirements. This process is labour-intensive, slow, and may take months to years for larger codebases. Modularization of a codebase typically requires the developer to have an intimate knowledge of both the application code and domain. In this thesis, we investigate the modular monolith software architecture, and how modules are typically determined as part of the modularization efforts. We propose an automated solution based on dependency analysis and machine learning algorithms to aid in the identification of module boundaries, and evaluate its effectiveness using a case study. We discuss the results and draw conclusions about the propsed solution. ], ) = Aims and goals The thesis can be divided into two parts: a literary part and a more practical part. For the literary part, I first analyze the origins and characteristics of the modular monolith software architecture, and compare it to similar software architectures. Then, I investigate how the identification of module boundaries is typically done, and how it could be improved through using automated technologies. For the practical part, I design a solution in the form of a tool for developers that automatically identifies optimal module boundaries in a monolithic codebase. Then, I apply the proposed solution to a real-world use case, and evaluate how effective it is. The use case I intend to use for the proof-of-concept is called NephroFlow Link, part of the #link( "https://www.nipro-group.com/en/our-offer/products-services/nephroflowtm-product-suite", )[NephroFlow Product Suite]. NephroFlow Link is a middleware application written in Ruby that acts as a data broker between connected dialysis machines and the NephroFlow cloud platform. It is currently designed as a monolithic application, and is deployed as a single process on a single server. However, the application is becoming increasingly complex which slows down the development velocity and increases the maintenance burden on the developers. Furthermore, the requirements in regard to scalability and extensibility are increasing rapidly, which leads me to believe the application would benefit from a modular monolith architecture. I intend to develop the proposed solution using NephroFlow Link as a case study. #pagebreak() == Research questions *Research Question 1*: What is the modular monolith architecture, and what sets it apart from monolithic and microservices architectures? *Motivation*: Explore why the modular monolith architecture is becoming increasingly popular, and why it is considered a viable alternative to monolithic and microservices architectures. *Research Question 2*: Which challenges and opportunities arise when considering adoption of the modular monolith architecture for an existing codebase? *Motivation*: Investigate how restructuring an existing codebase as a modular monolith would impact the development process and resulting product. *Research Question 3* (optional): Which automated technologies exist to help modularize a monolithic architecture? *Motivation*: Investigate technologies based on dependency analysis and semantic clustering to automatically determine optimal module boundaries in a modular monolith architecture. Choose one technology to focus on, and justify the choice. *Research Question 4*: How can _(automated technology)_ effectively identify optimal module boundaries in a modular monolith architecture? *Motivation*: Implement _(automated technology)_ for the given use case and compare to manual modularization efforts in terms of accuracy, efficiency, development velocity. #pagebreak() == Methodology To find an answer for the first three research questions, a thorough literature study is done, and relevant work is mentioned and summarized. The fourth research question is answered using an empirical study on the use case. Based on the principles of the modular monolith architecture, module boundaries are manually identified within the application. This is done by experienced developers that have an intimate knowledge of both the codebase and the application domain. Next, using the proposed solution, module boundaries are automatically identified within the application. To evaluate the effectiveness of the proposed solution, key criteria are identified. Certain key criteria are selected and the selection is justified. + *Accuracy*: how close do the module boundaries of the automated technologies align with the manually identified ones? The degree of alignment is measured using metrics such as Jaccard similarity. + *Modularity*: how modular are the boundaries identified by the automated technologies? The degree of modularity is measured using metrics such as the modularity $Q$, the clustering coefficient, and the Fenton and Melton metric. + *Efficiency*: how much effort is required to implement the automatically identified module boundaries compared to manual modularization? Feedback from experienced developers is gathered using surveys and interviews. + *Adaptibility*: how well do the modules react to changes in the codebase and evolving requirements? The impact is measured empirically by introducing changes in the environment or requirements, and observing how well the boundaries adapt to the change using metrics such as code churn and defect density. By measuring these key criteria quantitatively and qualitatively for the module boundaries of the automated and the manual modularization, I can assess the effectiveness of the automated technologies in a thorough and objective manner. #pagebreak() = Contents + *Abstract* + *Introduction*: general introduction to the topic, and identification of challenges and obstacles related to the topic. Explanation about why and for whom the topic is relevant, and what the expected outcome of the research is. Scope of the research thesis. + *Background*: historical background of the topic, and theoretical background needed to understand the thesis. + *Related work*: relevant work and research related to the topic. + *Monolithic architecture*: definition and explanation of monolithic architecture. + *Microservices architecture*: definition and explanation of monolithic architecture. + *Methodology*: explanation of the research methodology used. + *Modular monolith*: definition and explanation of modular monolith architecture. + *Architecture*: definition and explanation of modular monolith architecture. Answer to Research Question 1. Justification for choice of modular monolith in this thesis. + *Challenges and opportunities*: answer to Research Question 2. + *Modularization*: problem statement regarding identification of optimal module boundaries. + *Proposed solution*: investigation and design of a proposed solution for identification of optimal boundary identification. Answer to Research Questions 3 and 4. + *Case study*: application of the proposed solution to a real-world use case. + *Background*: background information about the use case. + *Analysis*: analysis and proposed solution to the problem, design and implementation choices. + *Evaluation*: evaluation of the proposed solution in the context of the use case. + *Results*: results of the evaluation. + *Discussion*: analysis and discussion of the results. Ability of the proposal solution to generalize. Justify the reason for existence of the modular monolith paradigm. + *Conclusion and future work*: summary of the thesis, and possible future work related to the topic + *Bibliography* #pagebreak()
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/api/content.typ
typst
MIT License
#import "@preview/codelst:2.0.1" #import "@preview/showybox:2.0.1": showybox #import "../util/util.typ" #import "../util/typst.typ" #import "../util/args.typ" #import "../core/base.typ": appendix #import "../theme.typ" // Setzt den Inhalt als Anhang für das Dokument. // Die Kopfzeile und die Nummerierung der Überschriften wird angepasst. // // Der Anhang wird als neuer Seitenabschnitt erstellt und kann daher im Format vo Hauptteil abweichen. Die Argumente werden direkt an #cmd-[page] weitergegeben. // // Beispielsweise lässt sich der Anhang so im Querformat in zwei Spalten setzen: // ```typst // #anhang(flipped: true, columns: 2)[ // #lorem(500) // ] // ``` // // - ..page-args: Alle Argumente werden an #cmd[page] weitergegeben, um das Seitenformat des Anhangs zu ändern. // -> content #let anhang = appendix // Auszeichnung von Operatoren: // // #example[``` // #operator[Entwirf] einen Algorithmus und #operator[stelle] ihn in geeigneter Form #operator[dar]. // // #operator[Implementiere] den Algorithmus nach deinem Entwurf. // ```] // // - body (string, content): Operator zum hervorheben. // -> content #let operator(body) = smallcaps(body) // Darstellung eines Namens: // - #shortex(`#name[<NAME>]`) // - #shortex(`#name[<NAME>]`) // - #shortex(`#name[<NAME>]`) // - #shortex(`#name("Adriaan", last:"<NAME>")`) // // - name (string, content): Name, der dargestellt werden soll. // - last (string): Optionaler Nachname, falls dieser aus mehreren Teilen besteht. // -> content #let name(name, last: none) = { if type(name) == content { name = name.text } if last == none { let parts = name.split() last = parts.pop() name = parts.join(" ") } [#name #smallcaps(last)] } // Formatierung von Tasten. // - #shortex(`#taste("Enter")`) // // - label (string, content): Aufschrift der Taste. // -> content #let taste( label, ) = box( stroke: .5pt + gray, inset: (x: .25em), outset: (y: .25em), radius: 2pt, // fill: gradient.linear(luma(100%), theme.bg.muted, angle:90deg), fill: gradient.linear(luma(100%), luma(88%), angle:90deg), text(.88em, font:theme.fonts.code, label)) ) // Formatierung von Tastenkürzeln. // - #shortex(`#tastenkuerzel("Strg","C")`) // - #shortex(`#tastenkuerzel("Strg","Cmd")`, sep:"/") // - #shortex(`#tastenkuerzel("Strg","Shift","C", sep:"")`) // // - ..labels (string, content): Aufschriften der Tasten. // - sep (string): Separator zwischen Tasten. // -> content #let tastenkuerzel(..labels, sep: box(inset: (x: .1em), "+")) = { labels.pos().map(taste).join(sep) } // Formatierung von Dateinamen. // - #shortex(`#datei("beispiel.typ")`) // // - name (string, content): Name der Datei. // -> content #let datei(name) = [#emoji.page#h(.1em)#typo.code(name)] // Formatierung von Ordnernamen. // - #shortex(`#ordner("arbeitsblaetter")`) // // - name (string, content): Name des Ordners. // -> content #let ordner(name) = [#emoji.folder#h(.1em)#typo.code(name)] /// Formatierung von Programmnamen. /// - #shortex(`#programm("VSCode")`) /// /// - name (string, content): Name des Programms. /// -> content #let programm(name) = text(theme.primary, weight: 400, name) // Symbols #let icon = ( // Sozialformen einzel: emoji.person.stand, partner: emoji.handholding.woman.man, gruppe: emoji.family, // Geräte stift: emoji.pencil, heft: emoji.book.open, mappe: emoji.book.spiral, tablet: emoji.phone, computer: emoji.laptop ) #let aufg-neu(prefix) = (..aufg-args) => [#prefix #util.combine-ranges(aufg-args.pos(), last: " und ")] #let seiten = aufg-neu("S.") #let aufg = aufg-neu("Aufg.") #let quelle-neu( name, seiten-format: seiten, aufgaben-format: aufg, sep: ": ", ) = { (..q-args) => { let pages = () let tasks = () if type(q-args.pos().first()) == array { pages = q-args.pos().first() if q-args.pos().len() > 1 { tasks = q-args.pos().at(1) } } else { pages = q-args.pos() } if tasks.len() > 0 [ #name #seiten-format(..pages)#sep#aufgaben-format(..tasks) ] else [ #name #seiten-format(..pages) ] } } #let bu = quelle-neu("Buch") #let ah = quelle-neu("AH") #let ab = quelle-neu("", seiten-format: aufg-neu("AB")) // ============================ // Misc // ============================ /// === Verschiedenes /// Textlücken. /// - #shortex(`#luecke()`) /// - #shortex(`#luecke(width: 2cm, offset: 5pt)`) /// - #shortex(`#luecke(text: "Hal<NAME>!", stroke: .5pt+red)`) /// /// - width (length): Breite der Textlücke, wenn #arg[text] nicht gegeben ist. /// - text (length): Text, anhand dessen die Breite der Textlücke bestimmt werden soll. Falls angegeben, wird #arg[width] ignoriert. /// - stroke (length): Linienstil der Unterstreichung. /// - offset (length): Abstand der Linie zur Basislinie des umliegenden Textes. /// -> content #let luecke(width: 4cm, stroke: 1pt + black, offset: 2pt, text: none) = { if text != none { box(stroke: (bottom: stroke), inset: (bottom: offset), baseline: offset, text) } else { box(width: width, stroke: (bottom: stroke), inset: (bottom: offset), baseline: offset, []) } } // ============================ // Code // ============================ /// === Quelltexte /// Zeigt Quelltext mit Zeilennummern und in einem #cmd[frame] an. /// Alias für #cmd("sourcecode", module:"codelst"). /// #example[```` /// #sourcecode[```python /// print("Hello, World!") /// ```] /// ````] /// /// - ..args (any): Argument für #cmd-("sourcecode", module:"codelst"). /// -> content #let sourcecode(..args) = codelst.sourcecode(frame: codelst.code-frame.with(fill: theme.bg.code), ..args) #let lineref = codelst.lineref.with(supplement: "Zeile") #let lineref- = codelst.lineref.with(supplement: "") #let linerange-(from, to, sep: [ -- ]) = [#lineref-(from)#sep#lineref-(to)] #let linerange(from, to, supplement: "Zeilen", sep: [ -- ]) = [#supplement #linerange-(from, to)] /// Inline-Code mit Syntax-Highlighting. Im Prinzip gleichwertig /// mit der Auszeichungsvariante mit drei Backticks: /// - #shortex(`#code(lang:"python", "print('Hallo, Welt')")`) /// - #shortex(raw("```python print('Hallo, Welt')```")) #let code(body, lang: none) = raw(block: false, lang: lang, util.get-text(body)) // ============================ // Frames and Boxes // ============================ /// === Kästen und Rahmen /// Eine generische Box um Inhalte. Verwendet #package[Showybox]. /// Im Allgemeinen werden die spezifischeren Boxen benutzt: /// - @@rahmen /// - @@kasten /// - @@schattenbox /// - @@infobox /// - @@warnungbox /// /// - width (length): Breite der Box. /// - stroke (stroke): Rahmenlinie um die Box. /// - fill (color): Hintergrundfarbe der Box. /// - inset (length, dictionary): Innenabstände der Box. /// - shadow (length): Schattenabstand. /// - radius (length): Radius der abgrundeten Ecken. /// - ..args (any): Weitere Argumente, die an #package[Showybox] weitergereicht werden. /// -> content #let container( width: 100%, stroke: 2pt + black, fill: white, inset: 8pt, shadow: 0pt, radius: 3pt, ..box-args, body, ) = showybox( frame: ( border-color: typst.stroke(stroke).paint, title-color: typst.stroke(stroke).paint, footer-color: fill, body-color: fill, radius: radius, thickness: typst.stroke(stroke).thickness, ), shadow: ( offset: shadow, color: args.if-auto(silver, typst.stroke(stroke).paint).darken(40%), ), ..box-args, body, ) /// Ein Rahmen um Inhalte. /// #example[``` /// #rahmen[#lorem(10)] /// ```] /// /// - ..args (any): Argumente für @@container. /// -> content #let rahmen = container.with(stroke: 2pt + theme.secondary) /// Ein Kasten um Inhalte. /// #example[``` /// #kasten[#lorem(10)] /// ```] /// /// - ..args (any): Argumente für @@container. /// -> content #let kasten(..args) = container.with(fill: theme.bg.muted, stroke: 2pt + theme.secondary)(..args) /// Eine Box mit Schatten um Inhalte. /// #example[``` /// #schattenbox[#lorem(10)] /// ```] /// /// - ..args (any): Argumente für @@container. /// -> content #let schattenbox(..args) = container.with(shadow: 3pt)(..args) /// Eine Infobox um Inhalte. /// #example[``` /// #infobox[#lorem(10)] /// ```] /// /// - ..args (any): Argumente für @@container. /// -> content #let infobox(..args, body) = container.with( radius: 4pt, fill: theme.bg.primary, stroke: 2pt + theme.primary, shadow: 3pt, )(..args)[ #set text(fill: theme.primary, weight: 400) #body ] /// Eine Warnungsbox um Inhalte. /// #example[``` /// #warnungbox[#lorem(10)] /// ```] /// /// - ..args (any): Argumente für @@container. /// -> content #let warnungbox(..args, body) = container.with( radius: 4pt, fill: cmyk(0%, 6%, 18%, 2%), stroke: 2pt + cmyk(0%, 30%, 100%, 0%), shadow: 3pt, )(..args)[ #set text(fill: cmyk(0%, 20.72%, 74.77%, 56.47%), weight: 400) #body ] // ============================ // Hints // ============================ /// === Hinweise /// Zeigt einen hervorgehobenen Hinweis an. /// #example[``` /// #pad(left:10pt, hinweis[#lorem(8)]) /// /// #hinweis(typ:"Tipp", icon:emoji.face.halo)[#lorem(8)] /// ```] /// /// - typ (string): Art des Hinweises. /// - icon (symbol): Ein Symbol für den Hinweis.. /// - body (content): Inhalte des Hinweises. /// -> content #let hinweis(typ: "Hinweis", icon: emoji.info, body) = { util.marginnote[#text(fill: theme.secondary)[#icon]] text(fill: theme.secondary)[*#typ:* ] body } #let tipp(body) = hinweis(typ: "Tipp", icon: emoji.lightbulb, body) // ============================ // Lists and enums // ============================ /// === Listen und Aufzählungen /// Setzt das Nummernformat für Aufzählungen im #arg[body] auf `a)`. /// #example[``` /// #enuma[ /// + Eins /// + Zwei /// + Drei /// ] /// ```] /// /// - body (content): Inhalte mit Aufzählungen. /// -> content #let enuma(body) = { set enum(numbering: "a)") body } /// Setzt das Nummernformat für Aufzählungen im #arg[body] auf `1)`. /// #example[``` /// #enumn[ /// + Eins /// + Zwei /// + Drei /// ] /// ```] /// /// - body (content): Inhalte mit Aufzählungen. /// -> content #let enumn(body) = { set enum(numbering: "1)", tight: false, spacing: 1.5em) body } /// Setzt das Nummernformat für Aufzählungen im #arg[body] auf `(1)`. /// #example[``` /// #enumnn[ /// + Eins /// + Zwei /// + Drei /// ] /// ```] /// /// - body (content): Inhalte mit Aufzählungen. /// -> content #let enumnn(body) = { set enum(numbering: "(1)") body }
https://github.com/EpicEricEE/typst-droplet
https://raw.githubusercontent.com/EpicEricEE/typst-droplet/master/README.md
markdown
MIT License
# droplet A package for creating dropped capitals. ## Usage This package exports a single `dropcap` function that is used to create dropped capitals. The function takes one or two positional arguments, and several optional keyword arguments for customization: | Parameter | Type | Description | Default | |------------------|-------------------------------|-----------------------------------------------------------|---------| | `height` | `integer`, `length`, `auto` | The height of the dropped capital. | `2` | | `justify` | `boolean`, `auto` | Whether the text should be justified. | `auto` | | `gap` | `length` | The space between the dropped capital and the text. | `0pt` | | `hanging-indent` | `length` | The indent of lines after the first. | `0pt` | | `overhang` | `length`, `relative`, `ratio` | How much the dropped capital should hang into the margin. | `0pt` | | `depth` | `integer`, `length` | The space below the dropped capital. | `0pt` | | `transform` | `function`, `none` | A function to be applied to the dropped capital. | `none` | | `..text-args` | | How to style the `text` of the dropped capital. | | Some parameters allow values of different types for maximum flexibility: - If `height` is given as an integer, it is interpreted as a number of lines. If given as `auto`, the dropped capital will not be scaled and remain at its original size. - If `overhang` has a relative part, it is resolved relative to the width of the dropped capital. - If `depth` is given as an integer, it is interpreted as a number of lines. - The `transform` function takes the extracted or passed dropped capital and returns the content to be shown. If two positional arguments are given, the first is used as the dropped capital, and the second as the text. If only one argument is given, the dropped capital is automatically extracted from the text. ### Extraction If no explicit dropped capital is passed, it is extracted automatically. For this to work, the package looks into the content making up the first paragraph and extracts the first letter of the first word. This letter is then split off from the rest of the text and used as the dropped capital. There are some special cases to consider: - If the first element of the paragraph is a `box`, the whole box is used as the dropped capital. - If the first element is a list or enum item, it is assumed that the literal meaning of the list or enum syntax was intended, and the number or bullet is used as the dropped capital. Affixes, such as punctuation, super- and subscripts, quotes, and spaces will also be detected and stay with the dropped capital. ### Paragraph Splitting To wrap the text around the dropped capital, the paragraph is split into two parts: the part next to the dropped capital and the part after it. As Typst doesn't natively support wrapping text around an element, this package splits the paragraph at word boundaries and tries to fit as much in the first part as possible. This approach comes with some limitations: - The paragraph is split at word boundaries, which makes hyphenation across the split impossible. - Some elements cannot be properly split, such as containers, lists, and context expressions. - The approach uses a greedy algorithm, which might not always find the optimal split. - If the split happens at a block element, the spacing between the two parts might be off. To determine whether an elements fits into the first part, the position of top edge of the element is crucial. If the top edge is above the baseline of the dropped capital, the element is considered to be part of the first part. This means that elements with a large height will be part of the first part. This is done to avoid gaps between the two parts of the paragraph. ### Styling In case you wish to style the dropped capital more than what is possible with the arguments of the `text` function, you can use a `transform` function. This function takes the extracted or passed dropped capital and returns the content to be shown. The function is provided with the context of the dropped capital. Note that when using `em` units, they are resolved relative to the font size of the dropped capital. When the dropped capital is scaled to fit the given `height` parameter, the font size is adjusted so that the _bounds_ of the transformed content match the given height. For that, the `top-edge` and `bottom-edge` parameters of `text-args` are set to `bounds` by default. ## Example ```typ #import "@preview/droplet:0.3.0": dropcap #set par(justify: true) #dropcap( height: 3, gap: 4pt, hanging-indent: 1em, overhang: 8pt, font: "Curlz MT", )[ *Typst* is a new markup-based typesetting system that is designed to be as _powerful_ as LaTeX while being _much easier_ to learn and use. Typst has: - Built-in markup for the most common formatting tasks - Flexible functions for everything else - A tightly integrated scripting system - Math typesetting, bibliography management, and more - Fast compile times thanks to incremental compilation - Friendly error messages in case something goes wrong ] ``` ![Result of example code.](assets/example.svg)
https://github.com/Karolinskis/KTU-typst
https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/sections/testtext.typ
typst
#set text(lang: "lt", region: "lt") = First section <first-section> == Subsection <subsection> #figure( align( center, )[#table( columns: 5, align: (col, row) => (center, center, center, center, center,).at(col), inset: 6pt, [S], [A], [T], [O], [R], [A], [R], [E], [P], [O], [T], [E], [N], [E], [T], [O], [P], [E], [R], [A], [R], [O], [T], [A], [S], )], caption: [Dummy table], ) #figure( align( center, )[#table( columns: 5, align: (col, row) => (center, center, center, center, center,).at(col), inset: 6pt, [S], [A], [T], [O], [R], [A], [R], [E], [P], [O], [T], [E], [N], [E], [T], [O], [P], [E], [R], [A], [R], [O], [T], [A], [S], )], caption: [Long caption: Dummy table Dummy table Dummy table Dummy table Dummy table Dummy table Dummy table Dummy table Dummy table], ) #figure( image("/images/ktu-logo.png", width: 2cm), caption: [KTU logo], )
https://github.com/jassielof/typst-templates
https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/capítulos/5.estudio%20de%20mercado.typ
typst
MIT License
= Estudio de Mercado == Descripción Comercial del Producto == Análisis de la Oferta === Método de Estudio ==== Universo ==== Unidad de Análisis y Respuesta ==== Proceso de Selección de la Unidad Estudiada === Cuantificación y Proyección de la Oferta === Mezcla Comercial == Análisis de la Demanda === Método de Estudio ==== Universo ==== Unidad de Análisis y Respuesta ==== Método de Selección de la Unidad Investigada === Cuantificación y Proyección de la Demanda === Mezcla Comercial === Posicionamiento y Participación === Variables que Inciden en la Decisión de Compra === Satisfacción y Fidelidad === Perfil del Cliente == Balance Oferta -- Demanda == Canales de Comercialización === Método de Estudio === Característica de las Condiciones de Comercialización por Canal === Posibilidades de Acceder a Cada Canal === Selección de los Canales Idóneos == Análisis PESTAL == Análisis de las 5 Fuerzas Competitivas == Análisis FODA == Segmentación y Selección del Nicho de Mercado === Segmentación === Selección del Nicho de Mercado == Diseño de la Estrategia Comercial === Fuente de la Ventaja Competitiva === Estrategias con Respecto al Mercado y la Competencia ==== Mercado ==== Competencia === Análisis de Igor Ansoff == Mezcla Comercial Propuesta == Plan de Ventas === Proyección de la Demanda Total === Supuestos a Utilizar === Proyección de la Demanda de la Empresa === Plan de Ventas
https://github.com/yd4dev/APL-Summary
https://raw.githubusercontent.com/yd4dev/APL-Summary/main/summary.typ
typst
#show math.equation: set text(blue) #set text(font: "Archivo") #set page(footer: context [ #align(center)[ #counter(page).display( " - 1 / 1 -", both: true, )] ]) #show heading.where(level: 1): set text(orange) #show heading.where(level: 2): set text(purple) #show par: set block(spacing: 0.65em) #set par( first-line-indent: 1em, justify: true, ) #show heading.where(level: 3): set text(rgb(10, 150, 10)) #let AL = text("AL") #let ar = text("ar") #let FO = text("FO") #let name(body) = { set text(red) set align(right) [*#body*] } #let definition(arr, num: false) = { let l = () let r = () for entry in arr [ #l.push(entry.at(0))) #r.push(entry.at(1)) ] let l_index = 1 return grid( columns: (1fr, auto), rows: (auto), align(left)[ #for entry in l [ #if num [ #enum(entry, start: l_index) #(l_index = l_index + 1)] else [ #list(entry) ] ] ], align(right)[ #for entry in r [ #name(entry) ] ], ) } #set heading(numbering: "1.") #show outline.entry.where(level: 1): it => { v(12pt, weak: true) strong(it) } #outline(depth: 2, indent: auto, title: "Inhalt") = Logik == Komponenten - *Syntax*: Definiert die Form und Struktur logischer Ausdrücke. einschließlich der Regeln zum Bilden gültiger Aussagen. - *Semantik*: Legt die Bedeutung der Aussagen fest und wie diese Ausdrücke interpretiert werden sollen. - *Deduktives System/Beweiskalkül*: Beschreibt die Methoden und Regeln, mit denen aus wahren Aussagen weitere wahre Aussagen abgeleitet oder bewiesen werden können. = Aussagenlogik Ermöglicht Formalisierung von Argumenten. Grundlage für Boolesche Algebra und Schaltkreise. Mögliche Anwendung: Software-Verifikation, Datenbanken, KI. == Syntax #definition(( ( $V := {p_1, p_2, ...}$, "Aussagenvariablen", ), ( $O := {not,and,or,arrow.r,arrow.l.r}$, "Junktoren", ), ( $K := {(,)}$, "Klammern", ), ( $Sigma := {0, 1} union V union O union K$, "Alphabet", ), )) Die *Formeln* (Aussagen) sind folgendermaßen definiert: #definition( ( ( $0, 1 in AL$, "Konstanten", ), ( $V subset.eq AL$, "Variablen", ), ( $text("Wenn") phi, psi in AL text("dann")$ + definition(( ( $(not psi) in AL$, "Negation", ), ( $(phi and psi) in AL$, "Konjunktion", ), ( $(phi or psi) in AL$, "Disjunktion", ), ( $(phi arrow.r psi) in AL$, "Implikation", ), ( $(phi arrow.l.r psi) in AL$, "Äquivalenz", ), )), "", ), ), num: true, ) === Klammerbalancierung + Jedes echte nicht-leere Präfix $psi$ einer Formel hat mehr öffnende als schließende Klammern: $\#_(\() (psi)> \#_(\)) (psi)$. + Alle Formeln haben gleich viele öffnende wie schließende Klammern: $\#_(\() (psi)= \#_(\)) (psi)$. Daraus folgt: - Ein echtes Präfix einer Formel liegt nicht in $AL$. - Jede Formel beginnt mit $($ und endet mit $)$. === Eindeutigkeitssatz Jede Formel $phi$ ist atomar oder entsteht auf eindeutige Weise aus kürzeren Formeln. === Klammern weglassen Um Formeln wie $((not phi) or ((not psi) and (not phi)))$ zu vermeiden, lassen wir Klammern weg. \ Dabei gilt folgende Operatorenpräzedenz in absteigender Reihenfolge: + $not$ + $and$ + $or$ + $arrow.r$ + $arrow.r.l$ Bei aufeinander folgenden $and$ oder $or$ von links nach rechts. == Semantik Die Semantik einer Logik ordnet den Formeln eine Bedeutung zu. \ Um den Wahrheitswert von Formeln zu bestimmen, definieren wir unsere Aussagenvariablen $BB := {0, 1}$ als die Menge der *Booleschen Konstanten*. === Interpretationen (Belegungen) Eine Belegung der Variablen bezeichnen wir mit $frak(I): V arrow.r BB$. \ Dadurch erhält $phi^frak(I)$ einen offensichtlichen Wahrheitswert in $BB$. === Modell Eine Interpretation $frak(I)$ einer Formel $phi$ mit $phi^frak(I) = 1$. #grid( columns: (1fr, 1fr, 1fr), [ Schreibweisen: \ #definition(( ( $frak(I) models phi$, "Modell", ), ( $frak(I) cancel(models) phi$, "Kein Modell", ), )) ], [], [ Sprechweisen: \ Gilt $frak(I) models phi$ so sagen wir: - $frak(I)$ erfüllt $phi$, - $frak(I)$ ist Modell von $phi$, - $phi$ ist wahr unter $frak(I)$. ], ) === Irrelevanz nicht vorkommender Variablen (Koinzidenzlemma) Der Wahrheitswert einer Formel $phi$ hängt nur von der Belegung der in $phi$ vorkommenden Variablen ab. - Wir schreiben $phi(p_1,dots,p_t)$, um anzudeuten, dass die Variablen ${p_1,dots,p_t}$ in der Formel $phi$ vorkommen. === Erfüllbarkeit, Tautologien und Widersprüchlichkeit + Eine Formel $phi$ heißt *Tautologie* (oder *allgemeingültig*), geschrieben $models phi$, falls $phi^frak(I) = 1$, falls $phi^frak(I) = 1$ für jede Belegung $frak(I)$. + $phi$ heißt *erfüllbar*, falls es eine Belegung $frak(I)$ gibt mit $phi^frak(I) = 1$. + $phi$ heißt *widerspruchsvoll* (oder *widersprüchlich*), falls $phi^frak(I) = 0$ für jede Belegung $frak(I)$. Selbiges gilt für Mengen von Formeln $Phi$. \ Die *Menge der Tautologien TAUT* ist eine Teilmenge von *SAT, der Menge aller erfüllbaren Formeln*. TAUT $subset.eq$ SAT. == Semantische Folgerung Die Formel $phi$ ist *logische Folgerung* von $Phi$, falls für jede Interpretation $frak(I)$, die $Phi$ erfüllt, $phi^frak(I) = 1$ gilt. Wir schreiben $Phi models phi$. === Entscheidbarkeit semantischer Fragen + Es ist entscheidbar, ob eine endliche Menge $Phi subset.eq AL$ erfüllbar ist. + Es ist entscheidbar, ob für eine gegebene endliche Menge $Phi subset.eq AL$ und ein $phi in AL$ gilt, dass $Phi models phi$. + Die Mengen $text("TAUT")$ und $text("SAT")$ sind entscheidbar. === Deduktionstheorem (semantische Version) - $Phi union {phi} models psi$ genau dann, wenn $Phi models (phi arrow.r psi)$ gilt. === Modus Ponens (semantische Version) - ${phi, phi arrow.r psi} models psi$ == Logische Äquivalenz Formeln heißen *logisch äquivalent*, geschrieben $phi equiv psi$, falls für jede Belegung $frak(I)$ gilt: $phi^frak(I) = psi^frak(I)$. === Gesetze von De Morgan - $not(phi and psi) equiv not phi or not psi$ und - $(phi or psi) equiv not phi and not psi$. === Operatorenvermeidung - $phi arrow.r psi equiv not phi or psi$, - $phi arrow.l.r psi equiv (phi arrow.r psi) and (psi arrow.r phi)$, - $phi or psi equiv not phi arrow.r psi$ und - $phi and psi equiv not(phi arrow.r not psi)$. Zu jeder Formel $phi$ gibt es äquivalente Formeln, die nur + $arrow.r$ und $not$ als Verknüpfungen enthält, + $and$ und $not$ als Verknüpfungen enthält und + $or$ und $not$ als Verknüpfungen enthält. == Normalformen Eine Normalform einer Formel $phi$ ist eine äquivalente Formel $T(phi)$, die gewissen Einschränkungen unterliegt. - *Einschränkungen* können strukturell sein oder Eindeutigkeit erfordern. - *Äquivalenz* kann bedeuten - logisch äquivalent: $phi equiv T(phi)$ - erfüllbarkeitsäquivalent: $phi$ ist erfüllbar genau dann, wenn $T(phi)$ erfüllbar ist - Für jede Formel existiert eine Formel in Normalform. - Jede Formel in Normalform gehört zur Logik selbst. === Negationsnormalform - Für $p in V$ sind $p$ und $not p$ in Negationsnormalform. - Sind $phi, psi$ in Negationsnormalform, dann sind auch $(phi or psi)$ und $(phi and psi)$ in Negationsnormalform. === Konjunktive und Disjunktive Normalformen - *Literal*: Variable oder negierte Variable - *Klausel*: Disjunktion von Literalen. - Hat eine Klausel höchstens höchstens $k$ Literale, heißt sie *k-Klausel*. - 1-Klauseln werden *Unit-Klauseln* genannt. - Eine Formel $phi$ ist in *konjunktiver Normalform*, wenn $phi$ eine Konjunktion von Klauseln ist. - Analog: Eine Formel ist in *disjunktiver Normalform*, wenn sie eine Disjunktion von Konjunktionen ist. === Konjunktive Normalform als Menge - Da Konjunktionen und Disjunktionen assoziativ sind, ist die Reihenfolge der Literale in Klauseln und der Klauseln in einer Formel in KNF irrelevant. - Daher können wir Klauseln als *Mengen von Literalen* auffassen und KNF-Formeln als *Mengen von Klauseln*. Beispiel: $(p or q) and (p or not q)$ wird zu ${{p,q}, {p,not q}}$. = Der Kompaktheitssatz Die Formelmenge $Phi$ ist genau dann erfüllbar, wenn jede *endliche* Teilemge von $Phi$ erfüllbar ist. = Kalküle und Algorithmen für die Aussagenlogik == Deduktive Systeme und Kalküle Ein *deduktives System* (auch *Beweiskalkül*) besteht aus Axiomen und Regeln, mit denen wir wahre Aussagen/Formeln ableiten (formal beweisen). \ \ Ein *deduktives System* $cal(F)$ besteht aus #definition( ( ( $text("einem endlichen Alphabet ") Sigma text(",")$, " ", ), ( $text("einer Formelmenge") F subset.eq Sigma^* text(",")$, "(wohlgeformte Formeln)", ), ( $text("einer Menge von Axiomen") A x subset.eq F text("und")$, "(Axiome)", ), ( $text("einer Menge") R subset.eq F^* text("von Regeln.")$, "(Regeln)", ), ), num: true, ) Die Formeln $phi_1,dots,phi_n$ heißen *Prämissen*, und die Formel $phi$ heißt *Konklusion* von $r$. \ Das System heißt *entscheidbar*, wenn die Mengen $F, A x$ und $R$ entscheidbar sind. Ein deduktives System heißt - *korrekt*, wenn alle herleitbaren Aussagen gültig sind, und - *vollständig*, wenn alle gültigen Aussagen herleitbar sind. Für eine Regel $r = (phi_1,dots,phi_n,phi) in R$ schreiben wir auch $frac(phi_1\,dots\,phi_n,phi)$. === Herleitbarkeit in Deduktiven Systemen Die Menge $T(cal(F))$ der *Theoreme* des deduktiven Systems $cal(F)$ ist induktiv definiert durch: #definition(( ( $A x subset.eq T(cal(F)).$, "(alle Axiome sind Theoreme)", ), ( "Sind " + $phi_1,dots,phi_n in T( cal(F) )$ + " und ist " + $frac(phi_1\,dots\,phi_n,phi)$ + " in " + $R$ + ", dann ist " + $phi in T(cal(F))$ + ".", " ", ), ( $T$ + " ist die kleinste Menge von Formeln, die 1 und 2 erfüllt.", " ", ), )) Wir schreiben $tack.r \ _cal(F) phi$, falls $phi in T(cal(F))$, und sagen, $phi$ ist in $cal(F)$ herleitbar. \ === Deduktiver Folgerungsbegriff Sei $Phi subset.eq F, phi in F$. Dann ist $phi$ in $cal(F)$ aus $Phi$ herleitbar, geschrieben $Phi tack.r\ _cal(F)phi$, falls $tack.r\ _((Sigma,F,A x union Phi, R)) phi$ gilt. \ Geht $cal(F)$ aus dem Kontext hervor, schreiben wir auch $tack.r\ _phi$ bzw. $Phi tack phi$. === Das deduktive System $cal(P)_2$ *Axiome*: \ Ax1: $A arrow.r (B arrow.r A)$ \ Ax2: $(A arrow.r (B arrow.r C)) arrow.r ((A arrow.r B) arrow.r (A arrow.r C))$ \ Ax3: $(not A arrow.r not B) arrow.r (B arrow.r A)$ \ *Regeln*: \ MP: $frac(A\,(A arrow.r B), B)$ (modus ponens) \ \ Das System $cal(P)_2$ ist korrekt und vollständig. === Der Sequenzenkalkül Sei $F$ eine Menge von Formeln. \ Eine *Sequenz* ist ein Paar $(Gamma, Delta)$, geschrieben $Gamma arrow.double\ _G Delta$, wobei $Gamma,Delta subset.eq F$ endliche Mengen sind. \ Die Sequenz ${phi_1,dots,phi_n} arrow.double\ _G {psi_1,dots,psi_m}$ entspricht semantisch $(phi_1 and dots and phi_n) arrow.r (psi_1 or dots or psi_m)$ \ Die Menge der *Sequenzen* bezeichnen wir mit $F_G$. \ *Axiome* #grid( columns: (1fr, 1fr, 1fr), align: center, [ $(A x) frac("",Gamma\, A arrow.double\ _G A\, Delta)$ ], [ $(0-A x)frac("",Gamma\,0 arrow.double\ _G Delta)$ ], [ $(1-A x)frac("",Gamma arrow.double\ _G 1\, Delta)$ ], ) *Regeln* #grid( columns: (1fr, 1fr), align: center, [ $ &(L_not) &&frac(Gamma arrow.double\ _G A\, Delta,Gamma\, not A arrow.double\ _G Delta) \ &(L_and) &&frac(Gamma\, A\, B arrow.double\ _G Delta, Gamma\, A and B arrow.double\ _G Delta) \ &( L_or ) &&frac(Gamma\, A arrow.double\ _G Delta\;space.quad Gamma\, B arrow.double\ _G Delta, Gamma\,A or B arrow.double\ _G Delta) \ &( L_arrow.r ) &&frac(Gamma arrow.double\ _G A\,Delta\; space.quad Gamma\, B arrow.double\ _G Delta, Gamma\, A arrow.r B arrow.double\ _G Delta) $ ], [ $ &(R_not) &&frac(Gamma\, A arrow.double\ _G Delta,Gamma arrow.double\ _G not A\, Delta) \ &( R_and ) &&frac(Gamma arrow.double\ _G A\, Delta\; space.quad Gamma arrow.double\ _G B\, Delta, Gamma arrow.double\ _G A and B\, Delta) \ &(R_or) &&frac(Gamma arrow.double\ _G A\, B\, Delta, Gamma arrow.double\ _G A or B\, Delta) \ &(R_arrow.r) &&frac(Gamma\, A arrow.double\ _G Delta\,B, Gamma arrow.double\ _G A arrow.r B\, Delta) $ ], ) === Die Schnittregel im Sequenzenkalkül #align(center)[ $ frac(Gamma arrow.double\ _G A\,Delta\; space.quad Gamma'\, A arrow.double\ _G Delta', Gamma\,Gamma' arrow.double\ _G Delta\, Delta') text(" (Cut)") $ ] Da der Kalkül vollständig ist und die Schnittregel gültig, sind alle Sequenzen, die mit Schnittregel herleitbar sind, auch ohne Schnittregel herleitbar (wenn möglicherweise auch nur deutlich umständlicher). === Resolution Resolution ist ein Beweiskalkül, mit dem wir die Unerfüllbarkeit von Formeln in konjunktiver Normalform nachweisen können. \ Kann die *leere Klausel* $union.sq$ abgeleitet werden, dann ist die ursprüngliche Klauselmenge nicht erfüllbar. \ Für zwei Klauseln $phi_1, phi_2$ und eine Variable $p_i in V$ heißt die Klausel $phi = (phi_1 \\ {p_i}) union (phi_2 \\ {not p_i})$ die *Resolvente* von $phi_1$ und $phi_2$ nach $p_i$. Die einzige *Regel im Resolutionskalkül* ist wie folgt: - Aus zwei Klauseln können wir deren Resolvente (nach einem beliebigen $p_i$) ableiten. === Horn-Klauseln - Eine Klausel ist *positiv*, wenn sie eine Disjunktion von positiven Literalen ist. - Eine Klausel ist *negativ*, wenn sie eine Disjunktion von negativen Literalen ist. - Eine *Horn-Klausel* ist eine Klausel mit höchstens einem positiven Literal === Der DPLL-Algorithmus *Substitution*: Einsetzen eines Wahrheitswertes in eine Formel \ *DPLL-Algorithmus*: - rekursiver Algorithmus für SAT - Erfüllbarkeit von $phi$ wird zurückgeführt auf Erfüllbarkeit von $phi[p arrow.r.bar 0]$ und $phi[p arrow.bar.r 1]$. = Prädikatenlogik Erweitert die Aussagenlogik durch - Funktionen und Konstanten - Prädikate und Relationen - Quantoren == Signaturen und Strukturen - Eine *Struktur* beschreibt:\ eine Menge zusammen mit Operationen oder Beziehungen auf der Menge. - Eine *Signatur* legt fest, welche Art von Konstanten, Funktionen und Relationen bei den Strukturen von Interesse vorkommen sollen. === Signaturen Eine Signatur ist ein 4-Tupel $S = (cal(C), cal(F), cal(R), ar)$, wobei #definition(( ($cal(C)$ + " eine Menge ist,", "Konstanten"), ($cal(F)$ + " eine Menge ist,", "Funktionssymbole"), ($cal(R)$ + " eine Menge ist und", "Relationssymbole/Prädikatssymbole"), ($ar: cal(F) union cal(R) arrow.r NN_(gt 0)$ + " eine Abbildung ist", "Arität / Stelligkeit"), )) Hierbei verlangen wir, dass die Mengen $cal(C), cal(F) text("und") cal(R)$ disjunkt sind. - Eine Funktion $f$ ist *$n$-stellig* und hat *Arität* $n$, wenn $ar(f) = n$ gilt. - Eine Funktion $R$ ist *$n$-stellig* und hat *Arität* $n$, wenn $ar(R) = n$ gilt. *Zusatzvoraussetzungen für die Prädikatenlogik*: - Es gibt eine Variablenmenge $V$. - Die Symbole $cal(C), cal(F)$ und $cal(R)$ kommen nicht in der Variablenmenge $V$ und nicht in der Menge ${not, and, or, arrow.r, arrow.l.r, exists, forall, =, (,)}$ vor. === Strukturen zu Signaturen Sei $S = (cal(C), cal(F), cal(R), ar)$ eine Signatur. Eine *Struktur der Signatur $S$* auch ($S$-Struktur) ist ein Paar $cal(A) = (A,frak(a))$ bestehend aus - einer nicht-leeren Menge $A$, dem *Träger* (auch *Trägermenge* oder *Datenbereich*), und - einer Funktion $frak(a)$, genannt *Interpretation der Symbole*, die - jedem Konstantensymbol $c in cal(C)$ ein Element $frak(a)(c) in A$ zuordnet, - jedem Funktionssymbol $f in cal(F)$ eine Funktion $frak(a)(f): A^(ar(f)) arrow.r A$ zuorndet und - jedem Relationssymbol $R in cal(R)$ eine Relation $frak(a)(R) subset.eq A^(ar(R))$ zuordnet. Wir schreiben auch jeweils $c^cal(A), f^cal(A), R^cal(A)$ statt $frak(a)(c), frak(a)(f), frak(a)(R)$. === Vereinfachte Sprech- und Schreibweisen - Wir werden auch einfach von Strukturen sprechen, wenn aus dem Kontext klar wird, dass es sich um $S$-Strukturen für eine bestimmte Signatur $S$ handelt. - Wir schreiben für eine Signatur $ S = ({c_1,dots,c_(|cal(C)|)},{f_1,dots,f_(|cal(F)|)},{r_1,dots,r_(|cal(R)|)}, ar)$ auch einfach - $S = (c_1,dots,c_(|cal(C)|), f_1,dots,f_(|cal(F)|),r_1,dots,r_(|cal(R)|)$, wenn die Aufteilung auf Konstanten, Funktionen und Relationen sowie die Aritäten aus dem Kontext klar werden. - Ebenso schreiben wir eine Struktur - $cal(A) = (A, frak(a))$ auch vereinfacht als - $cal(A) = (A, c_1^cal(A),dots,c_(|cal(C)|)^cal(A), f_1^cal(A),dots,f_(|cal(F)|)^cal(A),R_1^cal(A),dots,R_(|cal(R)|)^cal(A)$, wenn dadurch keine Verwechselungen entstehen können. == Syntax === Terme Für eine Signatur $S = (cal(C), cal(F), cal(R), ar)$ existiert die Menge der $S"-Terme"$, geschrieben $T(S)$. \ Ein Term wird gebildet aus *Variablen*, *Konstanten* und *Funktionen*. \ \ *Beispiele* für die Signatur $S = ({e}, {circle.small},{},ar)$ mit $ar(circle.small) = 2$: #grid( columns: (1fr, 1fr, 1fr), [- $e$], [- $x_1$], [- $circle.small(x_1, circle.small(e, x_1))$], ) === Formeln Für eine Signatur $S = (cal(C), cal(F), cal(R), ar)$ existiert die Menge der *S-Formeln der Logik erster Stufe*, geschrieben $FO(S)$. \ Eine *atomare Formel* wird gebildet aus *Termen* mit *Relationen und Gleichheit*: #grid( columns: (1fr, 1fr, 1fr), [- $x tilde y$], [- $R(x_1,x_2,x_3)$], [- $x = y$], ) Eine *Formel* beinhaltet zusätzlich *logische Junktoren* und *Quantoren*: #grid( columns: (1fr, 3fr), [- $forall x. exists y. x > y$], [- $forall epsilon. exists delta. (epsilon > 0 and delta > 0) arrow.r ( forall x. |x - x_0| lt.eq delta arrow.r |f(x) - f(x_0)| lt.eq epsilon )$], ) === Vorkommende, freie und gebundene Variablen Die Menge der *vorkommenden Variablen $"var"(t)$* ($"var"(phi)$) für einen Term $t$ (Formel $phi$) ist die Menge der $p in V$, die in $t$ ($phi$) vorkommen.\ Die Menge $"free"(phi)$ einer Formel $phi$ beinhaltet alle freien Variablen, also jene vor denen kein Quantor steht.\ Die Menge $"bound"(phi)$ einer Formel $phi$ beinhaltet alle Variablen, vor denen ein Quantor steht.\ Es gilt: $"var"(phi) = "free"(phi) union "bound"(phi)$.\ Formeln die keine freien Variablen haben, heißen *abgeschlossen*. === Eindeutigkeitssatz - Jeder Term und jede atomare Formel lässt sich *eindeutig* aus Teiltermen bilden. - Jede nicht-atomare Formel lässt sich *eindeutig* aus Teilformeln bilden. === Notationen #grid( columns: (1fr, 1fr), [ *Präfixnotation* \ Beispiele: - $f x y z$ steht für $f(x, y, z)$, wobei $ar(f) = 3$. - $+a+b c$ steht für $(a+(b+c))$. - $++a b c$ steht für $((a+b) +c)$. - $R a b$ steht für $(a,b) in R$. ], [ *Infix-Notation* \ Beispiele: - $a f b$ steht für $f(a,b)$ (falls $ar(f) = 2$). - $a R b$ steht für $(a,b) in R$. ], ) *Weitere Konventionen*: Wir legen fest, dass die aussagenlogischen Operatoren stärker binden als $exists$ und $forall$. \ Direkt aufeinanderfolgende gleiche Quantoren können wir ausfallen lassen. - Die Zeichenfolge $forall x_1x_2x_3.phi$ steht für die Formel $forall x_1.forall x_2.forall x_3.phi$. === Quantorenrang Misst die Schachtelungstiefe der Quantoren der Formel.\ - $"qr"((exists x.(not x = y arrow.r forall z.x > z)) or (exists x.x > y)) = 2$. == Semantik === Belegung Eine *Belegung* in einer Struktur $cal(A) = (A, frak(a))$ ist eine Abbildung $beta: V arrow.r A$. \ Die *Menge aller Belegungen* wird mit $A^V$ bezeichnet. === Interpretation Für eine Signatur $S$ ist eine *$S$-Interpretation* ein Paar $frak(I) = (cal(A), beta)$ bestehend aus einer $S$-Struktur $cal(A)$ und einer Belegung $beta$ in $cal(A)$. === Semantik von Termen Sei $S = (cal(C), cal(F), cal(R), ar)$ eine Signatur und $frak(I) = (cal(A), beta)$ eine *$S$-Interpretation* (bestehend aus einer $S$-Struktur $cal(A) = (A, frak(a))$ und einer Belegung $beta$). \ Die *Semantik* $t^frak(I) in A$ eines Terms $t in T(S)$ ist folgendermaßen definiert: $ c^frak(I) &:= c^cal(A) &&"für " t = c in cal(C)\ x^frak(I) &:= beta(x) &&"für " t = x in V\ f(t_1,dots,t_(ar(f)))^frak(I) &:= f^cal(A)(t_1^frak(I),dots,t_(ar(f))^frak(I)) &&"für " t = f( t_1,dots,t_(ar(f)) ) "mit" f in cal(F). $ === Semantik von Formeln *Modifikation*: $ beta[x arrow.bar a](y) := brace &a, &&"falls" y = x \ &beta(y), space.quad &&"sonst". $ *Semantik von Formeln*:\ Die Semantik $phi^frak(I) in BB$ einer Formel $phi in FO(S)$ für eine Signatur $S = (cal(C), cal(F), cal(R), ar)$ und eine $S$-Interpretation $frak(I) = (cal(A), beta)$ ist intuitiv gibt $phi$ intuitiv einen Wahrheitswert.\ Beispiel:\ Wir betrachten die Formel $ forall a. exists b. 2 dot b = a. $ - Die Formel ist mit einer Interpretation der natürlichen Zahlen und der üblichen Multiplikation nicht erfüllt. - Über den rationalen Zahlen ist sie mit der üblichen Multiplikation erfüllt. === Irrelevanz nicht-freier Variablen *Koinzidenzlemma* === Notation für relevante Variablen - Wir schreiben $t(x_1,dots,x_n)$, um anzudeuten, dass ${x_1,dots,x_n} supset.eq "var"(t)$ für einen Term $t in T(S)$. - Wir schreiben $phi(x_1,dots,x_n)$, um anzudeuten, dass ${x_1,dots,x_n} supset.eq "free"(phi)$ für eine Formel $phi in FO(S)$. === Die Modellbeziehung Ein *Modell* einer Formel $phi in FO(S)$ ist eine $S$-Interpretation $frak(I)$ mit $phi^frak(I) = 1$.\ $frak(I) models phi$ == Semantische Folgerung und Äquivalenz === Semantischer Folgerungsbegriff Die Formel $phi$ ist *logische Folgerung* der Formelmenge $Phi$, falls für jede $S$-Interpretation $frak(I)$, die $Phi$ erfüllt, $phi^frak(I) = 1$ gilt. Wir schreiben $Phi models phi$. === Logische Äquivalenz Formeln $phi, psi in FO(S)$ heißen *logisch äquivalent*, geschrieben $phi equiv psi$, wenn $phi models psi$ und $psi models phi$ gelten. === Vertauschung von Quantoren $ &"Für jede Formel gilt" &&exists x forall y phi models forall y exists x phi.\ &"Es gibt Formeln für die gilt" space.quad space.quad &&forall x exists y phi cancel(models) exists y forall x phi. $ == Substitution Mit einer simultanen Substitution $[x_1 arrow.r.bar t_1, dots, x_r arrow.r.bar t_r]$ ersetzen wir freie Vorkommnisse von Variablen $x_1,dots,x_r$ jeweils durch Terme $t_1, dots, t_r$. \ Wir betrachten zuerst die Substitution in Termen.\ *Beispiel*: $ &"Es ist" f(x_1,x_2)[x_2 arrow.bar x_3] &&"gleich" f(x_1,x_3)\ &"Es ist" (x+y)\/c [x arrow.bar y, y arrow.bar c dot x] space.quad &&"gleich" (y+c dot x)\/c $ === Substitution in Formeln Um innerhalb des Geltungsbereichs eines Quantors zu substituieren, benennen wir (falls nötig) erst die gebundene Variable $x$ zu einer Variable $u$ um, die nicht vorkommt, und substituieren dann. = Normalformen == Pränexnormalform Eine Formel ist *bereinigt*, wenn - keine Variable sowohl frei als auch gebunden vorkommt und - jede Variable höchstens einmal gebunden wird.\ In der *Pränexnormalform* stehen Quantoren am Anfang der Formel (also möglichst weit außen).\ Eine Formel ist in *bereinigter Pränexnormalform (BPF)*, wenn sie in Pränexnormalform und bereinigt ist. == Skolemnormalform Für unsere nächste Normalform werden wir keine logische Äquivalenz verlangen, sondern nur Erfüllbarkeitsäquivalenz. Zwei Formeln heißen *erfüllbarkeitsäquivalent*, wenn beide erfüllbar sind oder keine der Formeln erfüllbar ist.\ \ === Skolemisierung Ziel: existenzielle Quantoren in einer Formel eliminieren - Wir werden von der neuen Formel nur *Erfüllbarkeitsäquivalenz* verlangen. - Wir werden die Signatur erweitern. Die Ersetzung existenzieller Quantoren durch neue Funktionssymbole heißt *Skolemisierung*. \ \ === Skolemform Folgender Algorithmus berechnet eine Skolemform einer Formel in Pränexnormalform, indem die Existenzquantoren von vorne nach hinten ersetzt werden.\ *Input*: Eine Formel $phi$ in bereinigter Pränexnormalform.\ *Output*: Eine erfüllbarkeitsäquivalente Formel in Skolemform.\ \ 1: *while* $phi$ enthält Existenzquantoren *do*\ 2: $space.quad$ Zerlege $phi = forall y_1 dots forall y_n exists z.psi$. \// möglicherweise n = 0\ 3: $space.quad$ Sei $f in "Sko"$ ein Skolemsymbol, das nicht in $psi$ vorkommt.\ 4: $space.quad$ Setze $ar(f) = n$.\ 5: $space.quad$ Ersetze $phi$ durch $forall y_1 dots forall y_n (psi[z arrow.bar f(y_1, dots , y_n)])$.\ 6: *end while*\ 7: *return* $phi$ in Skolem-Normalform.\ \ === Existenzieller und universeller Abschluss Sei $phi in FO(S)$ eine Formel mit $"free"(phi) = {x_1,dots,x_n}$. - Die Formel $forall x_1 , dots forall x_n . phi$ heißt *universeller Abschluss* von $phi$. - Die Formel $exists x_1 , dots exists x_n . phi$ heißt *existenzieller Abschluss* von $phi$. Der universelle Abschluss von $phi$ ist genau dann *allgemeingültig*, wenn $phi$ *allgemeingültig* ist.\ Der existentielle Abschluss von $phi$ ist genau dann *erfüllbar*, wenn $phi$ *erfüllbar* ist. \ \ = Berechnungsprobleme in der Prädikatenlogik Gibt es einen Algorithmus, der entscheidet, ob eine gegebene Formel erfüllbar (allgemeingültig) ist? == Herbrand-Strukturen - Um zu entscheiden, ob eine Formel $phi in FO(S)$ allgemeingültig (oder unerfüllbar) ist, müssen wir a priori alle $S$-Strukturen $cal(A) = (D, frak(I))$ in Betracht ziehen. Wir werden nun argumentieren, dass es ausreicht, sich auf bestimmte, algorithmisch handhabbare Strukturen, die sogenannten *Herbrand-Strukturen*, einzuschränken. === Variablenfreie Terme und Formeln Wir bezeichnen mit $FO_"abg" (S)$ die Menge der abgeschlossenen Formeln (also Formeln ohne freie Variablen) in $FO(S)$. \ Für eine abgeschlossene Formel $phi$ ist $phi^frak(I)$ mit $frak(I) = (cal(A), beta)$ unabhängig von der Belegung $beta$.\ *Schreibweisen*: Sei $cal(A)$ eine $S$-Struktur. - Für eine abgeschlossene Formel bezeichne $phi^cal(A)$ den Wahrheitswert von $phi^frak(I)$ für eine (und damit alle) Interpretationen der Form $frak(I) = (cal(A), beta)$. - Wir schreiben auch $cal(A) models phi$, wenn $phi^cal(A) = 1$. === Einschränkung auf gleichheitsfreie Skolemform Für Fragen der Erfüllbarkeit können wir uns auf Formeln in Skolemform beschränken.\ Der Einfachheit halber werden wir uns im Folgenden auf Formeln in $FO^eq.not (S)$ beschränken, also Formeln ohne Gleichheitszeichen. === Herbrand-Struktur Für eine Signatur $S$ definieren wir den Datenbereich $D_cal(H)$, das *Herband-Universum*, als die kleinste Menge, für die gilt: $ &c in D_cal(H) &&"für alle Konstanten" c "von" S "und"\ &f( t_1,dots,t_ar(f) ) in D_cal(H), space.quad space.quad &&"falls" t_1,dots,t_ar(f) in D_cal(H) "und" f "eine Funktion von" S "ist." $ \ Eine $S$-Struktur der Form $cal(H) = (D_cal(H), frak(a))$ heißt *Herbrand-Struktur*, wenn für die Interpretation $frak(a)$ der Symbole gilt: - Für jede Konstante $c$ in $S$ ist $frak(a)(c)$ das Element $frak(a)(c) := c$ des Datenbereichs. - Für jede Funktion $f$ in $S$ ist $frak(a)(f)$ die Funktion $frak(a)(f): D_cal(H)^ar(f) arrow D_cal(H)$, für die gilt $frak(a)(f)(t_1,dots,t_ar(f)) := f(t_1,dots,t_ar(f))$. Falls $cal(H) models phi$ gilt, so heißt $cal(H)$ *Herbrand-Modell* von $phi$.\ \ *Theorem* (Herbrand)\ Sei $S$ eine Signatur mit mindestens einem Konstantensymbol. Eine abgeschlossene Formel $phi in FO^eq.not (S)$ in Skolemform ist genau dann erfüllbar, wenn sie ein Herbrand-Modell hat. \ Wenn $phi in FO^eq.not (S)$ erfüllbar ist, dann besitzt $phi$ ein Modell mit abzählbarem (möglicherweise endlichem) Datenbereich. == Semi-Entscheidbarkeit der Allgemeingültigkeit === Herbrand-Expansion Sei $phi equiv forall y_1 dots forall y_n.psi in FO^eq.not (S)$ eine abgeschlossene Formel in Skolemform, so dass $psi$ quantorenfrei ist. Die *Herbrand-Expansion* $E(phi)$ von $phi$ ist definiert als die Menge der Formeln $ E(phi) := {psi[y_1 arrow.bar t_1, dots, y_n arrow.bar t_n] | t_1,dots,t_n in D_cal(H)}, $ die aus $psi$ durch Substitution der Variablen $psi$ durch Terme in $D_cal(H)$ entstehen. === Die Expansionsformeln als Aussagen
https://github.com/FurryAcetylCoA/biyelunwen
https://raw.githubusercontent.com/FurryAcetylCoA/biyelunwen/main/thesis.typ
typst
MIT License
#import "nju-thesis/template.typ": documentclass, tablex, fig, tlt, indent #import "nju-thesis/utils/style.typ": 字号, 字体 #import "@preview/tablex:0.0.6": * #import "@preview/cuti:0.2.1": show-cn-fakebold //#show: show-cn-fakebold // 双面模式,会加入空白页,便于打印 #let twoside = false #let ( doc, preface, mainmatter, mainmatter-end, appendix, fonts-display-page, cover, decl-page, abstract, abstract-en, outline-page, list-of-figures, list-of-tables, notation, acknowledgement, bib ) = documentclass( // anonymous: true, // 盲审模式 twoside: twoside, // 双面模式,会加入空白页,便于打印 // 可自定义字体,先英文字体后中文字体,应传入「宋体」、「黑体」、「楷体」、「仿宋」、「等宽」 fonts: (楷体: ("Times New Roman", "LXGW WenKai GB"), 仿宋: ("Times New Roman", "Zhuque Fangsong (technical preview)"),), info: ( title: ("基于Chisel的精简指令集微处理器设计"), title-en: ("Chisel Implementation of a RISC Microprocessor"), grade: "20物联网工程 2 班", student-id: "19125042040", author: "荀阳霖", department: "信息工程学院", major: "物联网工程", supervisor: ("王娜", "讲师"), begin-date: "2023年9月", end-date: "2024年6月" ), ) // 文稿设置 #show: doc // 字体展示测试页 //#fonts-display-page() // 封面页 #cover() // 前言 #show: preface // 中文摘要 #abstract( keywords: ("RISC-V指令集", "Chisel语言", "敏捷开发", "芯片设计","片上系统") )[ 针对当前处理器芯片领域面临的高技术壁垒、人才短缺、物联网时代多元化需求以及安全挑战等问题,结合开源指令集架构RISC-V的兴起,提出并实现了一款基于Chisel语言的精简指令集微处理器设计,具备模块化、可扩展的架构特点,适用于物联网应用的多样性和安全性要求。Chisel语言的采用显著提升了设计效率与代码质量,降低了芯片设计门槛,体现了敏捷开发在芯片设计领域的优势。通过严谨的验证流程与仿真分析,证明了所设计处理器的正确性和有效性。为物联网领域提供了定制化、低成本、高能效的处理器解决方案,同时为我国芯片设计人才培养与核心技术掌握提供了实践范例。 ] #pagebreak() // 英文摘要 #abstract-en( keywords: ("RISC-V instruction set", "Chisel", "Agile development", "Chip design","System on chip") )[ In response to the high technological barriers, talent shortages, diverse demands of the Internet-of-Things (IoT) era, and security challenges confronting the processor chip domain, this work proposes and realizes a modular and extensible Reduced Instruction Set Computer (RISC) microprocessor design based on the Chisel language, tailored to accommodate the variety and security requisites of IoT applications. The adoption of Chisel significantly enhances design efficiency and code quality, lowering the entry barrier for chip design while exemplifying the benefits of agile development within the realm of semiconductor engineering. Through rigorous verification processes and simulation analyses, the correctness and efficacy of the designed processor are substantiated. This effort furnishes the IoT sector with a customizable, cost-effective, and energy-efficient processor solution, concurrently providing a practical exemplar for cultivating talent in chip design and mastering core technologies within our nation. ] // 目录 #outline-page() // 插图目录 //#list-of-figures() // 表格目录 //#list-of-tables() // 正文 #show: mainmatter //使用外文缩写代替某一名词术语,首次出现时应在括号内注明其含义 /* #show figure.where(kind: "i-figured-raw"): it => { let dic = it.fields() let _ = if "body" in dic { dic.remove("body") } let _ = if "label" in dic { dic.remove("label") } let _ = if "counter" in dic { dic.remove("counter") } let fig = figure(text(par(it.body,justify: false,leading:0.65em),size: 12pt), ..dic,kind: "f" + repr(it.kind)) fig }*/ = 绪论 == 研究工作的背景与意义 高质量芯片人才需要掌握计算机整体的软硬件理论知识与全程工程技术。既要在“学中做”,也要在“做中学” @ooicci 。 完成知识的有机融合,打通从数字电路、组成原理、体系结构、操作系统、嵌入式开发的全流程知识点。 世界正在加速转型进入数字经济时代。而做为数字化引擎的处理器芯片,则是一切的基石。虽然信息领域市场巨大,竞争强烈, 但十几年来却已经形成了“赢家通吃”的场面。高精尖技术与人才长期被把握在少数西方大公司的壁垒之中。 随着中美贸易环境的变化和技术封锁措施,一些中国企业和高校被列入美国政府的“实体清单”,这对中国芯片技术研发和人才培养带来了显著影响。 目前,我国的计算机专业人才培养面临着较大的结构问题。顶层应用开发者过多,而底层软硬件研发人员缺乏。 特别是芯片设计人才严重不足。2022年间我国集成电路产业人才缺口达到3.5万#cite(<供需报告>)。 这与当前芯片设计门槛过高,导致中国大学无法开展芯片相关教学与研究密切相关#cite(<方法思考与实践>)。 晶体管性能高速提升的时代即将结束,半导体行业即将进入后摩尔时代。提升芯片性能与能效的压力逐渐转移到了架构设计师与电路设计师上#cite(<golden>)。 对领域特定架构(DSA)的需求日渐增加,产业界急需一种更加快速、灵活的研发方法和基础架构。 RISC-V(第五代精简指令集)是一款开源且免费的精简指令集架构。自从该指令集架构发布以来,在国内外吸引了许多关注。 中国工程院院士倪光南表示,RISC-V具有模块化、可扩展、易定制的优势,以及不受垄断制约、供应链安全容易保障的优势,基于RISC-V架构的DSA服务器是中国的机遇 @ngn-2023 @ngn-2024。 如今,已有来自70多个国家的3900多个实体加入了RISC-V联盟,其中高级成员有超过40%来自中国。 国内外越来越多的公司、组织和开发人员正在支持和贡献RISC-V。 包括芯片设计商、软件开发商、工具提供商以及三星电子、西部数据和英伟达等行业巨头。 开放的RISC-V架构鼓励了全球范围内的协作和技术创新,降低了进入壁垒,极大地促进学术界和创业公司在芯片设计领域的创新活动。 其开源免费、模块化、容易定制等特点,为我国芯片设计的发展带来了新的机遇。 有助于我国掌握核心关键技术的同时开放地对待国际交流与合作。 物联网时代的到来对处理器芯片提出了更多的需求。 RISC-V的模块化设计允许制造商根据特定应用场景进行裁剪或扩展,设计出高度优化的芯片解决方案, 降低功耗、提升性能并缩小芯片面积,进而降低成本。从而满足物联网行业中多样化、碎片化的市场需求。 同时, 鉴于物联网设备数量庞大且分布广泛,其安全问题愈发凸显。RISC-V因其透明的架构设计,有利于定制深度的防御策略,确保从硬件层面强化安全特性。 诸如“港华芯” @v5 这样的RISC-V物联网安全芯片的成功案例表明,RISC-V能够有效应对物联网安全挑战,并在能源、智慧城市等多个领域实现关键突破。 == 国内外研究现状 RISC-V指令集具有简洁,现代的特点,自2010年推出以来,受到了国内外的广泛关注。 很多高校和企业都开始基于RISC-V指令集设计设计了各式的处理器核。 在国际上,伯克利大学基于RISC-V指令集,使用Chisel语言构建来开源的SoC生成器,Rocket Chip @rocket 。由伯克利大学的研究团队于2012年推出。该生成器支持生成有序执行内核(Rocket)与乱序执行内核(Boom),还支持指令集扩展,协处理器等功能。 用户通过配置文件描述设计后,Rocket Chip生成器可以自动挑选所需的模块组合到设计中。 Tenstorrent公司通过组合大量精简的RISC-V核,使用片上网络技术,实现根据负载动态开关,在降低功耗的同时支持大规模的AI加速计算。 在国内,睿思芯科仅用了7个月的时间 @rsxk ,就完成了一款基于RISC-V的64位可编程终端AI芯片。这相比传统芯片设计效率提高了大概三倍。 中科院香山团队在2021年成功设计并流片了第一版雁栖湖架构处理器。在28nm 的工艺节点下达到 1.3GHz 的频率。 而后在2023年成功设计并流片了第二版南湖架构处理器,在 14nm 工艺节点下频率达到 2GHz。 香山处理器的目标是成为面向世界的体系结构创新开源平台,基础能力、设施、流程的建立是香山处理器长期高质量发展的关键, 香山团队设计了丰富的基础工具支撑起了这一复杂度量级的敏捷验证流程。 中国科学院软件研究所发布基于RISC-V的开源笔记本电脑“如意BOOK”,搭载C910处理器,在openEuler操作系统上流畅运行钉钉、Libre Office等大型办公软件。 阿里巴巴旗下公司平头哥的玄铁RISC-V处理器核,5年间发布3个系列9款产品,覆盖高性能、高能效、低功耗等不同场景,在AI、5G通信、自动驾驶、金融等领域展开广泛应用创新,出货已超40亿颗。 算能公司于2023年推出的基于RISC-V处理器SG2042,主频2GHz,拥有64个核心, 达到高性能处理器梯队。 兆易创新生产的GD32V系列微控制器(MCU)也使用了RISC-V核心,广泛在国内嵌入式领域使用。 == 一生一芯计划 为应对我国芯片人才培养中遇到的设计门槛高、课程间关联弱、实践不足、学习坡度陡等挑战。 缓解我国芯片被“卡脖子”等形势。秉承“科研为国分忧,创新与民造福的理念。 循着“设计一种新的教学体系,降低芯片设计门槛,让学生能设计自己的芯片并成功流片”的思路。 在中国科学院-先进计算机系统研究中心联与中国科学院大学的大力支持下。 由孙凝晖院士部署,包云岗团队牵头设计并组织了“一生一芯”计划。 计划的目标是突破传统课程的边界,构建一套软硬件协同,理论和实践并发,打通前后端的全链条处理器芯片教学流程。 让学生理解从体系结构设计、开发,到集成验证、综合、物理设计,最终生成可流片的版图的全过程。籍此提高我国处理器芯片设计的人才培养质量,培养更多紧缺的芯片人才。 “一生一芯”计划不限学校、年级、专业,只要学生对处理器芯片设计感兴趣,都能报名参加,并资助完成学习计划的在校生免费流片。 通过开放式的教育,打破教育资源壁垒,加速培养我国处理器芯片紧缺的人才。 = 处理器架构与敏捷开发 == 指令集架构 === 复杂指令集与精简指令集 指令集发明于1960年代, 当时 IBM 为了解决该公司不同计算机产品线的程序无法通用的情况。 推出了完全独立于硬件架构的指令集架构(ISA)这一概念。 在当时,程序员通常直接使用汇编语言进行开发。市场普遍认为指令集应当更加丰富,每条指令本身应该能实现更多功能。 因此,当时一些高级语言中常见的概念,如函数调用、循环、数组访问等都有直接对应的机器指令。 这使得早期的指令集均为复杂指令集(CISC)。 1980年开始,随着存储器成本大幅下降、指令数目持续增加、高级语言的普及,CISC的一些缺陷开始暴露。 指令利用率低、控制电路趋于复杂、研发周期过长、验证难度增加等 @theDawnofRisc 催生了对于精简指令集(RISC)的研究。 与CISC不同,RISC强调每条指令的功能单一化。通过指令的组合来完成复杂操作。 由于指令复杂程度下降,编译器更容易进行代码生成。同时节约的电路面积可以用于缓存或流水线等高级结构, 使得RISC获得了优秀的能效比。 === RISC-V 指令集 2010年,<NAME>等人出于教学目的,在仔细评估了市面上各类指令集后,发现它们都存在设计上的不足 @waterman2016design 。 决定重头开始,吸取指令集架构领域25年期间的经验教训。设计了一款新的开源指令集架构—— RISC-V。 RISC-V 指令编码格式如下图: #fig(image("images/riscv_code_format.png", height: 14%) , caption: [RISC-V指令格式]) <inst_format> #indent RISC-V指令编码尽可能将含义相同的数据放在指令的同一位置,简化了指令译码。 如:指令存在目标寄存器字段时,其一定在指令的[11,7]位。 指令存在立即数时,立即数的符号位一定在指令的[31]位从而使符号扩展与指令译码并行展开。 当立即数在指令中的位置被其他字段切断时,指令编码的设计使得切断后数位的排布在不同指令间尽可能重叠。 允许工程师使用更少的多路选择器实现立即数的提取,简化了电路设计。 === RISC-V 指令集的优势 - 基础加扩展式的ISA: RISC-V架构以模块化的方式组合在一起,用户可以根据需求选择不同模块以满足不同场景的应用。 #fig( tlt( columns: 4, [RISC-V指令集], [名称], [指令数], [描述], rowspanx(4)[基础指令集], [RV32I], [47], [基本整数指令,寻址空间32位,必须实现], (), [RV32E], [47], [指令同上,寄存器减少为16个,用于嵌入式领域], (), [RV64I], [59], [整数指令,寻址空间位64位,包含RV32I], (), [RV128I], [71], [整数指令,寻址空间位128位,包含RV64I], rowspanx(5)[扩展指令集], [M], [8], [整数乘除法], (), [A], [11], [原子存储指令], (), [F], [26], [32位单精度浮点指令], (), [D], [26], [64位双精度浮点指令], (), [C], [46], [高密度指令,长度为正常指令的一半] ), caption: [RISC-V 指令集模块(节选)], ) <rvExts> - 紧凑的代码体积: 智能物联网产品对成本和存储空间通常较为敏感,RISC-V提供统一的指令压缩扩展, 可以在同样的大小下存储更多指令,并且不对成本产生显著影响。 - 开放: 传统ISA高额的授权费和严格的使用限制对于学术界和初创企业来说是巨大的负担。 而RISC-V是开源架构,其规范可公开获取,无需支付专利费或许可费, 有助于减少行业依赖于少数专有指令集架构的风险,促进公平竞争和市场活力。 - 简洁: RISC-V在设计之初参考了大量现有ISA的经验与缺点,设计更加现代化,基础指令只有40余条。 避免了对某一特定微架构的过度优化,允许研究者在不被各类复杂的兼容性需求约束的情况下,自由探索各类微架构设计。 - 灵活:RISC-V允许自定义和扩展指令集架构,使芯片设计师能够根据业务需求量身定制架构。 这种灵活性使RISC-V在物联网设备到高性能计算系统等广泛应用领域都具有吸引力。 - 便于教育和研究:RISC-V作为简洁且现代的开源架构,使其成为体系结构教学与研究的绝佳平台。 许多大学和学术机构已采用RISC-V进行教学,并开发创新的硬件和软件解决方案。 - 完整的软件支持:RISC-V提供完整的软件堆栈,编译器工具链以及继承开发环境和操作系统支持。 == 敏捷开发及应用 敏捷开发是一种现代软件开发方法论,它倡导迭代、增量开发,强调灵活性和响应变化的能力。 这种方法论源于对传统瀑布模型的反思与改进,后者往往在一个阶段结束后才转入下一个阶段,各个阶段间耦合度较高,且不易适应需求变更。 进而发展为项目延期,客户需求无法满足,甚至项目失败。 在敏捷开发中,项目被分解为一系列短周期(称为冲刺或迭代),每个周期专注于交付可用的产品增量。 团队在整个开发过程中持续集成、测试和交付,保证软件质量。 敏捷开发的核心价值观和原则体现在《敏捷宣言》#cite(<fowler2001agile>) 中, 包括重视个体和交互胜过流程和工具、可工作的软件高于详尽的文档、与客户协作并积极响应变化、以及持续交付并欢迎更改需求。 === 敏捷开发的意义 与传统互联网时代相比,智能物联网时代(AIoT)的设备成本功耗受限,专用性强。 传统上追求性能和通用的计算芯片不再适用。需要根据细分领域的需求,软硬件件协同优化,深度定制领域专用处理器(XPU)。 以满足特定场景对于芯片的成本,性能与能效需求。 #cite(<bao_1>) 这将使不同AIoT设备对芯片的需求差异化、专一化、碎片化。 如果继续沿用传统的瀑布式开发流程,过长的芯片研发和上市时间显然无法满足海量AIoT设备的快速定制需要。 === 芯片设计与敏捷开发 传统的芯片设计流程包含一个固定的 “代码冻结” 阶段,在此阶段之后,代码修订受到严格限制。 这就导致了后端物理设计团队的反馈不能及时有效地帮助前端架构团队改进设计。 而使用敏捷思想指导开发的芯片,在完成每一个功能点的编写后,前后端团队都会一起进行测试与验证。为快速改进设计提供了可能。 敏捷开发可大幅降低芯片的设计周期,并在市场需求变化时快速响应。通过敏捷开发,伯克利大学的研究团队成功在五年内开发并生产了11种不同的处理器芯片 #cite(<7436635>)。 === 芯片行业的敏捷开发 在芯片设计领域中,敏捷开发意味着在设计初期就利用高级语言快速构建模拟器原型,软件的灵活性允许工程师快速尝试各种设计方案, 尽早获得反馈,并迅速迭代设计。 设计成熟后,敏捷开发流程允许团队在较短时间内将设计迁移到FPGA上进行验证和调试, FPGA的高速和高准确性允许工程师在这一步运行完整的操作系统与测试程序。 同时与客户紧密合作,确保芯片设计能满足客户需求。 设计过程中, 设计完成后,可以通过电子设计自动化(EDA)工具对芯片电路的面积、功耗和时序进行细致的分析。 整个过程中,前端架构和后端物理团队同步协作,共同参与每次迭代的验证和优化,从而显著缩短了设计周期,提高了产品质量。 当芯片电路设计敲定后,就可以与晶圆厂对接,准备进行投片生产。 整个设计流程如 @fig:circle 所示。其前三步都可以通过敏捷开发大幅提高效率与质量。 #fig(image("images/circle.png", height: 38%) , caption: [芯片开发流程]) <circle> == Chisel语言在芯片设计中的优势及其实现原理 目前,最流行的两种硬件定义语言(HDL)是Verilog和VHDL @vhdlverilog 。硬件工程师通过HDL描述硬件电路的具体行为与结构。 Verilog与VHDL最初都是为硬件仿真而创建的,后来才被用于综合。这些语言缺乏抽象能力,使得组件难以在项目之间重复使用。 Chisel #cite(<Chisel2012>) 是一种基于高级编程语言Scala @odersky2004overview 的新型硬件构造语言(HCL) 。由伯克利大学的研究团队于2012年推出。 Chisel在Scala中提供了各类硬件原语的抽象,使得工程师可以用Scala类型描述电路接口,以Scala函数操作电路组件。 这种元编程可实现表现力强、可靠、类型安全的电路生成器,从而提高逻辑设计的效率和稳健性。而基于生成器的设计促进了模块在项目之间的重用。 需要说明的是,虽然Chisel具有许多传统硬件描述语言不具备的高级特性,但其还是一门硬件构造语言,而不是高层次综合。 Chisel代码在运行后会生成对应硬件的形式化描述,以寄存器传输语言灵活中间码(Flexible Intermediate Representation for RTL,FIRRTL)形式记录 #cite(<Li:EECS-2016-9>) 。 FIRRTL随后被输入硬件编译框架(Hardware Compiler Framework,HCF) CIRCT @circt2021。 经过多次递降变换(lowering transformations) @mlir2021,逐级去除高层次的抽象,最终输出优化后的底层RTL代码(如Verilog)。 使用HCF的好处之一是其内置了大量的优化器,可进行常量传播、共用表达式合并、不可达代码消除或向专用集成电路(ASIC)与现场可编程门阵列(FPGA)提供针对性的优化#cite(<8203780>) 。 这些特点使工程师能够更专注于逻辑功能的设计,从而显著提升设计效率与代码质量。 Chisel语言具有以下优点: + 开发高效 Chisel语言的高效主要体现在四个方面: - 信号整体连接: Chisel丰富的类型系统和连接功能。允许工程师以组件化的方式声明和连接多个信号线,并进行整体连接。 从而简化了总线接口修改的工作流程。 避免了在使用传统HDL开发时,修改总线需要手动更新多个模块的端口而产生潜在错误。 - 元编程: Chisel可以抽象出多份相似模块的共用部分,通过使用参数化的硬件模板,工程师可以创建出可复用的硬件库。 有效减少了代码冗余。SystemVerilog虽然提供类似的功能,但仅用于验证 @SV不可综合代码,属于不可综合代码。 - 面向对象:Chisel中可以将常用的电路组件封装成类,并通过继承与派生的方式定义常用变体,便于代码重用,减少冗余。 籍此,Chisel内置了大量的预定义组件供工程师使用。 以描述一个32位带使能端带复位的寄存器为例, @lst:d1_chisel , @lst:d1_verilog 表明,Chisel实现不仅更加简短,并且明确表示了这个寄存器的行为。 而Verilog实现需要工程师阅读Always块的内容才能确定该寄存器的行为。 #figure(text(par(```scala val delay1_r = RegEnable(io.in, 0.U(32.W), io.enable) io.out := delay1_r ```,justify: false,leading:0.65em),size: 12pt),caption: [Chisel实现]) <d1_chisel> #figure(text(par(```verilog reg [31:0] delay1_r; assign io_out = delay1_r; always @(posedge clock) begin if (reset) begin delay1_r <= 32'h0; end else if (io_enable) begin delay1_r <= io_in; end end ```,justify: false,leading:0.65em),size: 12pt),caption: [Verilog实现]) <d1_verilog> - 函数式:Chisel的函数式特性将允许工程师使用map或zip算子实现电路级联的批处理操作,可以简洁地描述数据流。 如 @fig:functional 所示,级联的算子操作可以直接对应生成后的电路。 与Verilog的数据流建模相比,工程师不再需要关心运算符优先级。 #fig(image("images/functional.png", height: 38%) , caption: [函数式操作与电路设计紧密对应]) <functional> + 代码质量更优 余子濠等人(2019)的研究 @标签化 指出。 在FPGA上,与经验丰富的专职工程师使用Verilog相比,经训练的本科生使用Chisel的高级特性开发同样功能一致的缓存模块。 无论能效、频率或资源占用,均优于Verilog实现,且代码可维护性优更优。 #fig( tlt( columns: 3, [类型], [Verilog], [Chisel], [最高频率/MHz], [135], [154], [功耗/W], [0.77], [0.74], [LUT 逻辑], [5676], [2594], [LUT RAM], [1796], [1492], [触发器], [4266], [747], [代码长度], [618], [155], ), caption: [资源占用与性能对比], ) <verilogVSchisel> #indent 在开发速度方面,专职工程师使用Verilog,消耗至少6周完成开发。而另一位有Chisel经验的本科生则在3天内完成了所有工作, 而且代码长度显著短于前者。 而在芯片整体设计方面,吕治宽(2022)的研究@lzk 表明,使用两种语言开发同一微结构的RISC-V处理器。Verilog的时间消耗是Chisel的3倍。 = 处理器微架构设计与实现 本文将首先实现一个单发射,无流水线,顺序执行的基本RV32E扩展处理器芯片微架构。 为方便拓展,本微架构各级之间使用异步定时方式通信,通过握手信号控制数据是否流动。 各级的行为只取决于自身和下游模块的状态, 各级均可以独立工作。 通过这种设计,避免了对全局控制器的需求,进而简化添加指令和流水化的难度。 也为探索乱序执行做好了准备。 在逻辑上,为了方便优化, 本微架构分为以下几个基础单元: 取指单元,译码单元,执行单元,访存单元,写回单元。 处理器核的设计方案如 @fig:main_flow 所示。 #fig(image("images/main_flow.png"), caption: [处理器核设计]) <main_flow> 片上系统的设计如 @fig:soc 所示。 #fig(image("images/soc_1.png",height:25%), caption: [片上系统设计]) <soc> #pagebreak() //手动孤页控制 == 信号握手 如 @fig:ready_valid 所示,每个基础单元均可以根据自身情况产生 "准备/有效(Ready / Valid)" 握手信号。 Valid标识模块当前的数据(Data)是否有效,Ready标识本模块是否能接收Data输入。 模块间遵循 @tbl:ready_valid_tbl 的语义进行传输握手。 此外,为防止数据丢失,当模块表示当前数据有效后,除非数据成功传输,否则不能撤销有效信号。 本级有效而下级忙,导致数据暂时无法向下传输的情况称为发生数据反压(Back pressure)。 #fig(image("images/ready_valid.png", height: 15%), caption: [Ready / Valid 握手信号]) <ready_valid> #fig( tlt( columns: 3, [下级Ready], [本级Valid], [数据传输行为], [有效], [有效], [数据成功传输至下级模块], [有效], [无效], [当前数据无效 下级模块需等待], [无效], [有效], [下级模块忙 本级需保持Data并等待], [无效], [无效], [不发生数据传输], ), caption: [握手信号行为说明], ) <ready_valid_tbl> == 取指单元 取指单元的总体架构如@fig:cpu_img0。 #fig(image("images/cpu_fetch.png", height: 25%) , caption: [取指单元总体架构]) <cpu_img0> #indent 取指单元根据上一条指令的译码、执行结果修改程序计数器(PC),并取出下一条指令。 整个取值单元分成PC生成器及指令访存器。 === PC生成器 PC生成器将根据当前处理器的状态以及指令来确定下一执行周期的程序计数器的值。 目前,程序计数器生成器支持以下行为: + 顺序执行 + 普通跳转(不切换特权级) + 暂停执行 + 自陷指令——陷入 + 自陷指令——返回 RISCV架构支持比较两个通用寄存器的值并根据比较结果进行分支跳转(B系列指令)。无条件跳转(J系指令), 也支持在异常发生时进入异常处理程序并返回。PC寄存器的结构如@fig:cpu_pc_structure 所示,其行为如@tbl:next_pc_gen 所示。 #fig( tlt( columns: 5, [类型], [add1], [add2], [next_pc] ,[PC寄存器], [顺序执行], [pc], [4], [sum_next_pc] ,[允许写入], [无条件跳转], [pc], [立即数], [sum_next_pc] ,[允许写入], [条件跳转], [pc], [据结果选择], [sum_next_pc] ,[允许写入], //todo:RV的条件跳转是这样吗。确认一下 [异常陷入], [无关], [无关], [mtVec] ,[允许写入], [异常返回], [无关], [无关], [mePC ] ,[允许写入], [反压暂停], [无关], [无关], [无关 ] ,[禁止写入], ), caption: [PC生成表], ) <next_pc_gen> #fig(image("images/cpu_pc.png", height: 31%) , caption: [PC生成器结构]) <cpu_pc_structure> === 指令访存器 指令访存器的任务是根据当前PC,向处理器核内的AXI @axiSpecification 主机仲裁单元发起访存请求。其结构如@fig:imem_fsm 所示。 在复位后,指令访存控制器在`idle`状态等待有效的访存事务发生。收到访存请求后,按照@tbl:imem_fsm_tlb 的行为对取指器的输出端口进行操作。需要注意的是,该状态机的输出均来自寄存器。 由于AXI协议规定在读事务完成时不再保持数据有效信号。在读取完成后,指令执行中的若干周期, 指令有效信号将由此状态机提供。 #fig(image("images/inst-mem_stateMachine.png", height: 28%), caption: [取指状态机]) <imem_fsm> #fig( tlt( columns: 3, [状态名], [说明], [离开条件], [idle], [当前未在访问指令存储器], [存储器AXI读握手成功], [waiting], [读请求已发出。等待指令存储器回复], [存储器回复数据], [sending], [向CPU下游部件提供指令码], [下游部件汇报准备完成] ), caption: [取指单元状态机转移说明], ) <imem_fsm_tlb> #fig(image("images/inst-mem.png", height: 18%), caption: [指令访存器结构]) <imem> == 译码单元 译码单元的任务是任务是根据当前指令,通过译码器产生各类控制信号;从寄存器组中读出数据。 #fig(image("images/cpu_decode.png", height: 30%) , caption: [取指单元总体架构]) <cpu_decode> 译码器主要功能如下: - 访问寄存器: 如@tbl:rvExts 所示, RISC-V指令集中,对于需要访问寄存器的指令, 其寄存器编号均在指令的固定位置。 为简化电路,译码器被设计为不对当前指令类型进行判断,固定将 24~20 与 19~15段的内容视为寄存器编号,进行寄存器访问。 - 立即数产生与符号扩展: 如@tbl:rvExts 所示, RISC-V指令集中,对于具有立即数的指令, 无论立即数长度,其符号位固定位31位。 为简化电路,符号扩展被设计为固定使用31位做为符号进行扩展,各下级模块由解码结果决定是否使用。 在后续设计中,将根据时序报告决定是否将本部件移动到执行单元。 - 控制信号生成: 根据指令类型和具体指令操作。为下级模块提供控制信号。 == 执行单元 执行阶段是微架构数据流的核心,如 @fig:cpu_execute 所示。其任务是根据译码单元产生的控制信号,对操作数进行运算。 #fig(image("images/cpu_execute.png", height: 30%) , caption: [执行单元总体架构]) <cpu_execute> == 访存单元 访存单元是为了装载(LOAD)与储存(STORE)指令设计的。整体结构如 @fig:cpu_memory 所示。 为了提高流水线化后各阶段的效率,设计时分析了LOAD/STORE指令的资源需求, 决定将CSR的读写合并于本模块内。 根据当前执行的指令不同,模块顶层的 Ready/Valid 生成器会选择旁路或使用来自数据访存器的 Ready/Valid 信号。 在执行访存指令时AluOut输出的是目标内存地址。 #fig(image("images/cpu_memory.png", height: 38%) , caption: [访存单元总体架构]) <cpu_memory> 数据访存器架构如下。 #fig(image("images/cpu_memory_exmem.png", height: 38%) , caption: [数据访存器架构]) <cpu_memory_exmem> == 写回单元 写回单元负责将指令运行结果写入寄存器。 #fig(image("images/cpu_writeback.png", height: 28%) , caption: [写回单元总体架构]) <cpu_writeback> == Chisel实现 本段节选了部分模块的具体实现代码,并说明Chisel对开发带来的便利与好处。 === 顶层模块 在Verilog中,顶层模块通常充斥着大量的模块间连线与冗长的实例化端口连接。 人工编写不仅耗费时间,且容易出错。 如 @lst:code_zhengti 所示, 通过Chisel的整体连接,可以使用少量代码完成安全可靠的连接。 #figure(text(par(```scala class Top extends Module { val fetch = Module(new Fetch) val decode = Module(new Decode) val execute = Module(new Execute) val memory = Module(new Memory) val writeback = Module(new Writeback) fetch.io.out <> decode.io.in decode.io.out <> execute.io.in execute.io.out <> memory.io.in memory.io.out <> writeback.io.in fetch.io.in <> writeback.io.out } ```,justify: false,leading:0.65em),size: 12pt), caption: [顶层模块主要代码]) <code_zhengti> === 寄存器组 由于线束(Bundle)的存在,声明寄存器组的IO接口变得更加容易,且当Idu或Csr 增加新的控制寄存器组的信号时,不需要改动寄存器组的IO接口声明。 //使用VecInit #figure(text(par(```scala class Reg extends Module { val io = IO(new Bundle { val fIdu = Flipped(new IduRegBundle()) val wValid = Input(Bool()) val op1 = Output(UInt(32.W)) val op2 = Output(UInt(32.W)) val r10 = Output(UInt(32.W)) // for ebreak val mem = Input(UInt(32.W)) val csr = Input(UInt(XLEN.W)) }) val regs = RegInit(VecInit(Seq.fill(16)(0.U(32.W)))) io.r10 := regs(10) // for ebreak val wdata = Wire(UInt(XLEN.W)) wdata := MuxLookup(io.fIdu.W.wdataSel, io.mem) { Seq( RegWdataSel.csr -> io.csr, RegWdataSel.mOut -> io.mem ) } when(io.fIdu.W.wen === 1.U & io.wValid) { regs(io.fIdu.W.rd(3,0)) := wdata } io.op1 := regs(io.fIdu.R.rs1(3,0)) io.op2 := regs(io.fIdu.R.rs2(3,0)) regs(0) := 0.U } ```,justify: false,leading:0.65em),size: 12pt), caption: [REG模块整体代码]) <code_reg> === 译码单元 译码单元关键部分代码节选如下。根据指令类型的不同,alu操作码由不同的子电路生成, 对应电路将指令码解析成不同的bundle。 再按照该类型指令的格式从bundle中提取所需信息,形成操作码。 #figure(text(par(```scala io.toAlu.aluOp := MuxLookup(opType, AluOpTypes.unknown) { Seq( Optypes.I -> opI(io.inst), ... ... Optypes.B -> opB(io.inst), ) } def opB(inst: UInt) = { val i = inst.asTypeOf(new Inst_B_bundle) val r = WireDefault(AluOpTypes.unknown) switch(i.fun3) { is("b000".U) { r := AluOpTypes.eq } //beq is("b001".U) { r := AluOpTypes.neq } //bne ... ... is("b101".U) { r := AluOpTypes.s_ge } //bge } r } def opI(inst: UInt) = { val i = inst.asTypeOf(new Inst_I_bundle) val r = WireDefault(AluOpTypes.unknown) when(opCode === Opcodes.LOAD) { switch(i.fun3) { is("b000".U) { r := AluOpTypes.add } //lb ... ... is("b101".U) { r := AluOpTypes.add } //lhu } }.elsewhen(opCode === Opcodes.JALR) { r := AluOpTypes.op1p4 //jalr }.otherwise { switch(i.fun3) { is("b000".U) { r := AluOpTypes.add } //addi is("b010".U) { r := AluOpTypes.s_less } //slti ... ... is("b111".U) { r := AluOpTypes.and } //andi is("b101".U) { switch(inst(31, 26)) { // srli, srai have unique I-type format is("b000000".U) { r := AluOpTypes.sr } //srli is("b010000".U) { r := AluOpTypes.s_sr } //srai }}}} r } ... ... class Inst_I_bundle extends Bundle { val imm11_0 = UInt((31 - 20 + 1).W) val rs1 = UInt((19 - 15 + 1).W) val fun3 = UInt((14 - 12 + 1).W) val rd = UInt((11 - 7 + 1).W) val op = UInt((6 - 0 + 1).W) } ```,justify: false,leading:0.65em),size: 12pt), caption: [译码单元代码节选]) <code_idu> === 算数逻辑单元 算数逻辑模块(ALU)的代码如 @lst:code_alu 所示。 通过使用枚举类型,代码可读性增加,ALU操作一目了然,代码可读性显著提高。 同时Chisel可以进行类型检查,防止使用错误的数据类型进行匹配。 使用MuxLookup则有效提高了代码密度。 #figure(text(par(```scala object AluOpTypes extends ChiselEnum { val sub,add, and, xor, neq, ge, ... ... less, op1p4, unknown = Value } class Alu extends Module { ... ... io.out := MuxLookup(io.fIdu.aluOp, 0.U(XLEN.W)) { Seq( AluOpTypes.sub -> (op1 - op2), AluOpTypes.add -> (op1 + op2), AluOpTypes.neq -> (op1 =/= op2), AluOpTypes.less -> (op1 < op2), AluOpTypes.ge -> (op1 >= op2), AluOpTypes.and -> (op1 & op2), AluOpTypes.xor -> (op1 ^ op2), ... ... ) } } ```,justify: false,leading:0.65em),size: 12pt), caption: [ALU模块Chisel代码节选]) <code_alu> === AXI 读分用器 AXI 读分用器的代码展现了Chisel对可变端口与函数式编程的支持。 在 Verilog中,数目可变端口往往需要大量的generate语句块来实现具体操作, 工程师容易写出可读性差的代码。 Chisel中,搭配函数式编程,可变数量端口的操作不会引起太多整体代码的变化。 有助于工程师编写更加通用化的模块。 @lst:code_axidecoder 展示了本处理器总线部分的AXI 读分用器实现。 //NOTE:这里我把那些Vecinit去掉了。否则太长视觉效果不好 #figure(text(par(```scala object AXIDecoder{ val maps = Seq(DMap("h8000_0000".U, "h8800_0000".U), // SRAM DMap("hA000_03F8".U, "hA000_03F8".U), // UART DMap("hA000_0048".U, "ha000_004C".U), // RTC ) } case class DMap(val begin: UInt, val end: UInt){ def hit(addr: UInt):Bool = { addr >= begin && addr <= end } } class AXIReadDecoder(val n: Int) extends Module{ val io = IO(new Bundle{ val in = new AXIReadOnly val out = Vec(n, Flipped(new AXIReadOnly)) }) val decodedOH = Wire(UInt(n.W)) // One hot code val lastSelectedOH = RegEnable(decodedOH, 0.U(n.W), io.in.ar.arready) decodedOH := AXIDecoder.maps.map( _.hit( io.in.ar.araddr ) && io.in.ar.arvalid ) io.in.ar.arready := (decodedOH & io.out.map( _.ar.arready )).orR val lastSelected = OHToUInt(lastSelectedOH) io.in.r.exclude(_.rvalid) :<= io.out(lastSelected).r.exclude(_.rvalid) io.in.r.rvalid := ( lastSelectedOH & io.out.map(_.r.rvalid) ).orR for((out, selected) <- io.out.zip(decodedOH.asBools)){ out.ar.arvalid := selected io.in.ar.exclude(_.arvalid) :>= out.ar.exclude(_.arvalid) out.r.rready <> io.in.r.rready } } ```,justify: false,leading:0.65em),size: 12pt), caption: [AXI 读分用器代码节选]) <code_axidecoder> #indent AXI读分用器(AXIReadDecoder)是一种一对多信号分配器件, 当输入端请求AXI读操作时,根据操作的地址范围,将请求分配到合适的外设中,并记录当前选择。 本实现还可以根据实例化时提供的参数_n_决定输出端口数量。 _AXIDecoder.maps_ 按连线顺序保存了各个外设对应的地址。其独立于分用器主体代码外, 便于在开发过程中增加新的外设。 _decodedOH_ 使用独热码保存根据当前输入地址选择的输出端口号。它具有n位,对应n个端口。 在计算 _decodedOH_ 的代码中, _AXIDecoder.maps.map(...)_ 会取出AXIDecoder.maps列表中的所有对象,逐一运行括号中指定的函数。 该函数会将当前输入地址araddr送入列表的各个成员的hit函数, hit函数会根据输入和自身保存的地址范围返回是否命中。各结果分别和io.in.ar.arvalid进行与操作, 确保分用器只在输入地址有效时进行解码。 按照AXI标准,io.in.ar.arready会向主机汇报所选的外设是否准备完成。 其产生逻辑如下:1. 当前输入地址落在某个从机的地址范围内; 2.该从机准备完成 ; 3.当前输入地址有效 ; io.out.map(\_.ar.arready) 会从所有输出中选出arready端口, 并将其和_decodedOH_ 按位与。最终结果进行规约或操作,即可生成符合语义的io.in.ar.arready 。 例如,主机发出了向属于UART外设地址的AXI读取请求, 当前SRAM,UART外设空闲,RTC外设正忙。 _decodedOH_ 与 io.in.ar.arready 的生成过程如 @fig:axidecode_OH 所示。 #fig(image("images/axidecode_OH.png", height: 28%) , caption: [选择UART时 独热码与有效信号的生成]) <axidecode_OH> #indent 通过使用_zip_算子,输出信号端口使能独热码逐一对与输出端口对象绑定,一起进入循环体。 循环体内的代码则会将解码结果派发给各个输出接口所连接的外设。 = 验证 由于芯片生产费用高昂,所以在正式投片前, 需要进行严格的测试,确保功能正确。 本文采用软硬件协同的方式对芯片设计进行验证。首先在Linux下搭建了测试框架, 然后通过实际编译器产生的测试例,使用自动化测试平台批量测试。 == 验证流程 验证平台使用Makefile脚本,KConfig脚本,标准参考实现及以测试例组成。 整体验证流程如 @fig:test_flow 所示。 #fig(image("images/test_flow.png"), caption: [验证平台结构]) <test_flow> #indent 测试开始前,Chisel代码经过CIRCT编译为Verilog代码。 并根据处理器芯片信号结构,设计C++测试台提供运行期间所需要的输入信号。 自制调试器可以记录调用栈,访存信息,在测试失败时辅助分析。 通过Verilator将前述代码生成为周期等价的仿真程序。 仿真分析可以读入编译好的测试程序,在执行时自动与标准参考实现进行比对。 若比对结果没有差异,表明当前设计功能正确。 == 硬件验证环境 接下来对验证流程中的主要模块进行讲解。 #pagebreak() //手动孤页控制 === Difftest Difftest方法源于软件工程领域, 全称Differential Testing(差分测试)。 其核心思想是: 对于根据同一规范的两种实现, 给定相同的有定义的输入, 它们的行为应当一致 @dft。 在测试环境中,仿真环境每执行一条指令,都会让标准RISC-V模拟器_Spike_也执行一遍。 通过对比两侧执行后的通用寄存器与控制寄存器即可判断Chisel实现是否正确。 === Verilator Verilator 是一款基于周期的开源 Verilog 仿真工具,可以将 Verilog 代码转化为 C++ 代码,继而编译成可执行文件,从而实现 Verilog 代码的仿真。它支持使用C++开发测试台,并能导出仿真期间的波形文件。 === 自制调试器 为了最大限度地加速排错,作者在此期间也制作了一些专用调试工具。 - mtrace: 访存监视单元,支持监视指定内存区间的读/写活动。使用方法如附录 @fig:mtrace 所示。 - 单指令执行: 为验证通用性,模拟的存储器读写具有一个随机延迟。 这导致单条指令的执行周期长度不确定。而传统的单步仿真不能适配这一点。 为此,作者在测试台中设计了按指令为单位的执行方式,相关代码如附录 @fig:sdb_exec 所示。 - 调用栈分析:为了确定客户程序在仿真器上的执行情况,作者设计了调用栈分析模块。 在仿真开始前,读取输入程序的符号表,确认所有函数的地址。 当CPU进行跳转时,根据目标地址和指令形式区分函数调用与函数返回,生成调用栈。该模块可以识别尾递归。 - 波形分析器插件:波形产生后,指令只能以十六进制机器码的形式展示。不便于阅读。作者为波形分析器设计了一个插件。 使用反汇编工具将机器码转换为易读的汇编指令。如@fig:after , @fig:before 所示。相关代码已发布@wave。 #fig(image("images/before.png",width: 80%), caption: [在波形软件中的原始显示]) <before> #fig(image("images/after.png",width: 80%), caption: [使用插件后可显示对应汇编]) <after> - 自动化性能分析:为提高仿真效率,作者设计了专用于性能分析的Makefile脚本, 可自动将仿真器编译为分析模式,运行测试程序并呈现可读的性能报告。相关代码如附录 @fig:make_prof 所示。 === 仿真界面 仿真环境支持自动运行或用户手动控制。@fig:fzjm 演示了仿真环境运行时的界面, 在本演示中,用户通过 _si 5_ 要求仿真环境执行5条指令后显示当前的寄存器信息 _info r_。 仿真环境可以成功显示执行指令的反汇编,并以可读的方式输出当期的寄存器信息。 #fig(image("images/npc-sdb.png",height: 30%), caption: [仿真界面演示]) <fzjm> #indent 仿真环境亦可设置断点或直接查看内存,方便开发者观察特定代码区间执行前后的变化。 #figure(text(par(```C volatile int fib[40] = {1, 1}; int main() { int i; for(i = 2; i < 40; i ++) { fib[i] = fib[i - 1] + fib[i - 2]; } return 0; } ```,justify: false,leading:0.65em),size: 12pt),caption:[简单斐波那契数列程序]) <fib> #indent 以@lst:fib 中所示的简单斐波那契数列程序为例, 通过反汇编找出循环体内写入fib数组的指令后,设置断点_b 0x200000b8_, 即可观察到该写入指令执行前后的内存变化,如@fig:ddts 所示。 #fig(image("images/fib-debug.png",width:75%),caption:[断点调试]) <ddts> == 软件验证环境 === 抽象计算机 鉴于本文所设计的处理器是RISC-V架构,而整体开发环境搭建在X86_64平台中。 因此,为了验证处理器功能,需要使用交叉编译器,生成RISC-V的目标代码。 交叉编译指的是在当前编译平台下,编译能运行在其他平台下的程序。本文使用 _riscv64-linux-gnu-gcc_ 通过指定_march=rv32e_zicsr_ 约束编译器只生成RV32E指令。 由于当前设计的处理器性能较弱,且只能执行RISC-V的核心部分,无法运行现代操作系统。 本文使用了南京大学提供的abstract-machine @am (抽象计算机 简称:AM)框架做为裸机运行时环境。 AM将计算机功能分为以下层级 - 图灵机: 仅限于纯计算任务 (TRM) - 冯诺伊曼机: 含有复杂的输入输出扩展(IOE) - 批处理系统: 含有上下文管理能力(CTE) - 分时多任务: 含有虚拟内存管理功能(VME) - 多处理机: 含有多个硬件线程(MPE) #indent 通过实现更加复杂的CPU功能,可以开启更多的AM层级,进而运行更多更复杂的程序。 而当CPU功能较弱时,则可以关闭一些AM层级,使得系统可以继续运行基础应用程序。 CPU提供硬件功能,AM提供运行时环境。 客户程序使用AM提供的统一接口,面向抽象的计算机体系进行编程,AM向客户程序屏蔽底层细节。 在本架构中,只要完成AM对某个环境的适配,为AM编写的程序就可以运行在其上。 如@fig:AM 所示。 #fig(image("images/AM.png",width:90%),caption:[AM整体层次]) <AM> === 适配抽象计算机 通过在硬件中实现某种机制,然后在AM中使用该机制填充相应的API。 就可以完成AM对该架构的一部分支持。AM大部分由C语言写成。 由于CPU复位完成后不具备C语言的运行条件,需要使用汇编准备堆栈后才能进入AM。 启动脚本如 @lst:start 所示 。由以下几个步骤组成: + 清空帧寄存器 + 设置栈指针到链接脚本指定的栈起始区 + 跳转到 \_trm_init。进入C环境 #figure(text(par(```asm .section entry, "ax" .globl _start .type _start, @function _start: mv s0, zero la sp, _stack_pointer jal _trm_init ```,justify: false,leading:0.65em),size: 12pt),caption:[start.S]) <start> #indent 在进入C环境后,AM需要完成以下操作: + 实现基本字符输出函数 putch + 初始化串口输出 + 调用客户程序主函数 + 根据主函数返回值,向硬件发出停机指令。 #figure(text(par(```c #define DEVICE_BASE 0x10000000 #define SERIAL_PORT (DEVICE_BASE + 0x0000000) void uart_init(){ outb(SERIAL_PORT + 3, 0b10000011); // 8N1 with Divisor Latch Access outb(SERIAL_PORT + 1, 0x00); // No interrupt outb(SERIAL_PORT + 0, 0x21); // Set Divisor outb(SERIAL_PORT + 3, 0b00000011); // 8N1 without Divisor Latch Access } void putch(char ch) { while((inb(SERIAL_PORT + 5) & 0b01000000) == 0){} // busy outb(SERIAL_PORT, ch); } void halt(int code) { asm volatile("mv a0, %0; ebreak" : :"r"(code)); while (1); // should not reach here } void _trm_init() { uart_init(); int ret = main(mainargs); halt(ret); } ```,justify: false,leading:0.65em),size: 12pt),caption:[trm.c]) <start2> === 适配存储结构 由于程序所在的ROM在运行时是只读的,因此,为了支持全局变量的写入操作。 需要在系统启动时将数据段(data,bss)从ROM加载到可读写的RAM中。 为了实现这一点,需要在链接时标记各个段的加载地址(LMA)与运行地址(VMA)。 并编写bootloader程序完成初始化时的数据加载操作。 本设计的内存布局如 @fig:linker_layout 所示,对应的链接脚本和bootloader程序节如下。 #fig(image("images/linker_layout.png"),caption: [内存布局]) <linker_layout> #figure(text(par(```c SECTIONS { _sldata = LOADADDR(.data); .text : { *(entry) *(.text*) } > MROM .rodata : { *(.rodata*) } > MROM .data : ALIGN(4) { _sdata = .; *(.data*) _edata = .; } >SRAM AT> MROM .bss : { _sbss = .; *(.bss*) _ebss = .; } >SRAM .heap_stack : { _stack_top = ALIGN(4); . = _stack_top + 0x1200; _stack_pointer = .; _heap_start = ALIGN(8); _heap_end = ORIGIN(SRAM) + LENGTH(SRAM) - 1; } >SRAM } ```,justify: false,leading:0.65em),size: 12pt), caption: [链接脚本节选]) <linker> #figure(text(par(```asm _loader: la a0, _sldata la a1, _sdata la a2, _edata 0: beq a1, a2, 1f lw a3, 0(a0) sw a3, 0(a1) addi a0, a0, 4 addi a1, a1, 4 j 0b 1: la a0, _sbss la a1, _ebss 2: beq a0, a1, 3f sw x0, 0(a0) addi a0, a0, 4 j 2b 3: ret ```,justify: false,leading:0.65em),size: 12pt), caption: [bootloader节选]) <bootloader> == 运行仿真测试 基础测试包括基本的算数运算、跳转、加载储存等指令。使用C语言编写,全部测试列表见 @tbl:basic_test 。 #fig(tlt( columns: 4, repeat-header: true, [测试程序名称] , [测试内容], vlinex() , [测试程序名称] , [测试内容], [add],[普通加法], [add-longlong],[长加法], [bit],[位操作], [bubble-sort],[冒泡排序], [crc32],[循环冗余校验], [div],[软除法], [dummy],[空函数跳转], [fact],[阶乘], [fib],[斐波那契数列], [goldbach],[歌德巴赫猜想], [hello-str],[字符串输出], [if-else],[分支语句], [leap-year],[闰年], [load-simple],[读内存], [load-store],[读写内存], [matrix-mul],[矩阵乘法], [max],[大小比较], [mersenne],[梅森数], [min3],[排列], [mov-c],[写后读], [movsx],[32位写后读], [mul-longlong],[长乘法], [pascal],[帕斯卡算法], [prime],[素数], [quick-sort],[快速排序], [recursion],[递归], [select-sort],[选择排序], [shift],[移位计算], [shuixianhua],[水仙花数], [simple],[1+1], [string],[字符串操作], [sub-longlong],[长减法], [sum],[求和], [switch],[switch语句], [to-lower-case],[小写转换], [unalign],[不对齐访存], [wanshu],[完数], ), caption:[基本测试程序]) <basic_test> #indent 由@fig:basic_test_result 可见,CPU顺利通过基本测试。 #fig(image("images/basic_test.png",height : 47% ), caption: [基本测试结果]) <basic_test_result> #indent CoreMark @coremark 是一个业界用来衡量嵌入式系统中CPU性能的测试程序。它主要测试CPU的整数性能, 含有列表处理、矩阵操作、状态机和 CRC等几个测试子项。 本文设计的CPU可以正确运行CoreMark,并在合理的时间内完成测试。 #fig(image("images/coremark.png", width: 100%), caption: [仿真环境CoreMark测试结果]) <coremark_img> //=== 特权指令集测试 //特权指令集使用yield-os进行测试。yield-os是一个具有3个线程的协作式操作系统。 //线程需要调用`yield()`函数主动让出处理器,操作系统提供一个基本的上下文保护和任务切换。 //#fig(image("images/cte_switch.png"), caption: [线程切换流程]) //==== 特权指令集实现 //=== 启动RT-thread //== 性能分析 = 原型验证 == 片上系统 为了实现包括输入输出在内的完整功能,需要将单一处理器核封装到SoC(System on Chip,片上系统)中。 SoC不仅仅只包含一个处理器, 还有诸多的片上外围设备, 以及连接处理器和外围设备之间的总线。 本文使用ysyxSoC框架@ysyxsoc 作为SoC部分的实现。 其主要结构如 @fig:soc_arc 所示 #fig(image("images/SoC_Arc.png", width: 76%), caption: [ysyxSoC架构]) <soc_arc> #indent SoC整体架构由CPU核,总线,外设接口,复位与时钟四部分组成。 CPU核通过AXI总线与片上外设接口进行数据交互,AXI交叉桥将根据访存地址将请求转发到不同的外设, 直接与AXI交叉桥相连接的是高速外设。对于低速外设, AXI总线通过AXI 转 APB 桥接器在转换成APB协议后连接到APB交叉桥。由APB总线负责低速外设, 这些外设通过片上控制器经IO连接到片外外设中。 在外设地址空间方面,目前主要有两种方式来实现CPU核与外设的通信。 第一种方式是端口映射I/O(PIO), CPU使用专门的I/O指令对设备进行访问, 并把设备的地址称作端口号。 第二种方式是内存映射IO(MMIO)。外设将自己的设备寄存器做为内存地址提供。 当需要访问外设寄存器时,CPU核读取或写入该地址,通过总线桥将指令转发到对应的外设中。 由于PIO把端口号作为I/O指令的一部分。指令集为了兼容已经开发的程序, 端口号只能添加而不能修改。 这意味着, 端口映射I/O所能访问的I/O地址空间的大小, 在设计I/O指令的那一刻就已经决定下来了。 随着设备越来越多, 功能越来越复杂, I/O地址空间有限的端口映射I/O已经逐渐不能满足需求了。 因此,目前的主流设计均采用内存映射IO的方式来实现设备交互。 ysyxSoC的MMIO映射如@tbl:mmio_map 所示。 #fig( tlt( columns: 2, [设备], [地址空间], [GPIO], [0x1000_2000~0x1000_200f], [MROM], [0x2000_0000~0x2000_0fff], [UART], [0x1000_0000~0x1000_0fff], [SPI], [0x1000_1000~0x1000_1fff], [SRAM], [0x0f00_0000~0x0f00_1fff], [VGA], [0x2100_0000~0x211f_ffff], [FLASH], [0x3000_0000~0x3015_ffff], ), caption: [MMIO映射], ) <mmio_map> == 现场可编程门阵列 现场可编程门阵列(FPGA),是一种半定制的集成电路,其具有高度可编程性,并且接近专用集成电路(ASIC)的特点, 其经常用于在流片前的验证阶段中。 与微控制器(MCU)不同,FPGA不含固定的逻辑。需要开发者使用硬件描述语言设计电路后才会呈现具体电路的行为。 因此,通过将ysyxSoC与CPU核烧录至FPGA,可以在真实的硬件上测试设计的正确性。 本文选择了基于Altera EP4CE10的野火征途开发板。其核心EP4CE10F17C8具有1万组逻辑元素,179个可编程IO口。 #fig(image("images/product.png", width: 65%), caption: [开发板实物图]) #indent 限于时间及技术水平。本文主要使用 @fig:fpga_Arc 所示的外设。 #fig(image("images/fpga_Arc.png",height: 20% ), caption: [开发板外设架构图]) <fpga_Arc> == FPGA环境迁移 为了从基于Verilator的软件仿真环境迁移到基于FPGA的硬件仿真环境。 首先必须在FPGA提供的集成开发环境Quartus中导入工程,并去除不可综合代码。 导入后如 @fig:quartus_import 所示。 #fig(image("images/questa_import.png", height: 28%), caption: [导入后的SoC]) <quartus_import> #indent 得益于Chisel与CIRCT的抽象与迁移能力,通过在Chisel代码中将SRAM声明为同步读写存储体。 可生成符合规范的RTL代码,允许综合工具的识别推断功能自动将其替换为标准同步存储器 IP。 即优化了时序,也节省了逻辑资源。 #fig(image("images/infer_ip.png", height: 20%), caption: [存储体自动推断]) 在时钟适配方面,开发板使用一个固定为50MHz的不可调晶振为FPGA提供时钟信号。 经过Quartus Timing Analyzer分析 (@fig:clock),SoC核最高能承受的频率约为15.5MHz。 因此,需要使用锁相环(PLL)降低输入频率。 为了稳定性,本设计选用了较为保守的5MHz作为SoC核的时钟频率 (@fig:pll2)。 #fig(image("images/clock.png"), caption: [时钟分析报告]) <clock> #fig(image("images/PLL1.png"), caption: [配置PLL输入时钟]) <pll1> #fig(image("images/PLL2.png"), caption: [配置PLL输出时钟]) <pll2> #pagebreak() //手动孤页控制 == GPIO控制器 === 寄存器设计 GPIO控制器的设计较为简单,仅有两个寄存器,分别对应开发板上的Led灯和按键。 Led寄存器直接驱动对应的IO管脚,写入后立即生效。 而按键寄存器会在读取的第一周期将IO口电平读入至keys_reg寄存器,并在第二周期将其送回总线。 #fig( tlt( columns: 5, [名称], [地址], [宽度], [访问], [说明], [Led], [0x0], [32], [只写], [开发板上的LED灯], [Key], [0xC], [32], [只读], [开发板上的按键], ), caption: [GPIO控制器寄存器表], ) <imemwsm_tlb> === 主体代码 #figure(text(par(```scala class gpioChisel extends Module { val io = IO(new GPIOCtrlIO) val addr = io.in.paddr(3,0) val led_reg = RegInit("hF".U(4.W)) val keys_reg = Reg(UInt(6.W)) io.in.prdata := 0.U io.in.pready := 0.U io.gpio.led := led_reg when(io.in.psel & io.in.pwrite & io.in.penable){ switch(addr){ is("h0".U){ led_reg := io.in.pwdata(3,0) } } io.in.pready := 1.B } when(io.in.psel & ~ io.in.pwrite){ when(~ io.in.penable){ switch(addr){ is("hC".U){ keys_reg := io.gpio.keys } } }.otherwise{ io.in.prdata := keys_reg io.in.pready := 1.B } } } ```,justify: false,leading:0.65em),size: 12pt),caption: [GPIO控制器代码]) #pagebreak() // 手动孤页控制 === 测试程序 通过MMIO,CPU核上运行的程序可以直接控制Led灯。 通过编写移位程序,可编写基础的流水灯测试程序。 其中 a4 寄存器存储着GPIO的MMIO地址,而a0寄存器负责记录当前点亮的Led灯。 wait子程序提供简单的软件延迟,确保流水效果可被肉眼观测到。 #figure(text(par(```asm _start: li a4, 0x10002000 li a0, 0x00000001 shift: srli a1, a0, 4 slli a0, a0, 1 or a0, a0, a1 not a3, a0 sw a3, 0(a4) jal wait j shift wait: li t0, 0x7fff 0: addi t0, t0, -1 nop bne t0, zero, 0b ret ```,justify: false,leading:0.65em),size: 12pt),caption: [流水灯测试代码]) <gpio> #fig(image("images/liushui.png", width: 75%), caption: [流水灯测试]) == UART 控制器 UART控制器采用兼容16550串口控制芯片的设计。 === 寄存器设计 #fig( tlt( columns: 5, [名称], [地址], [宽度], [访问], [说明], [发送], [0x0], [8], [只写], [发送缓冲区], [中断控制], [0x1], [8], [读写], [中断使能与屏蔽], [串口配置], [0x3], [8], [读写], [设置串口的数据格式], [线路状态], [0x5], [8], [读写], [获取或清除传输状态], ), caption: [UART控制器寄存器表], ) === 测试程序 结合AM提供的支持,程序可直接使用C语言标准库输出到串口。串口初始化程序见 @lst:start2。 #figure(text(par(```c int printf(const char *fmt, ...) { char buffer[1024]; va_list ap; va_start(ap, fmt); int ret = vsprintf(buffer, fmt, ap); va_end(ap); putstr(buffer); return ret; } int main(){ printf("Yanglin Xun from Shaoguan university\n"); printf("1234:%s\n", "abcd"); } ```,justify: false,leading:0.65em),size: 12pt),caption: [UART测试代码节选]) #fig(image("images/uart_test.png", width: 50%), caption: [串口助手接收UART数据]) == SPI控制器 SPI,即Serial Peripheral Interface(串行外设接口),是一款经典的同步、低成本、双工总线接口。 因其使用广泛,容易学习,能以较低的成本完成中低速外设连接而受到开发者的欢迎。 本开发板使用SPI总线连接Flash芯片。 为方便上层软件使用,本文作者为SPI控制器添加了就地执行(XIP)功能,使得SPI控制器可以自行生成Flash芯片的控制信号。 完成读取后返回给片内总线。 总线交叉桥被配置成为纯SPI命令与Flash地址空间均分配给SPI控制器处理。 因此,当SPI控制器收到读写请求时,首先会对地址进行判断。 如果是纯SPI命令。则直接送入SPI相关电路,如果是Flash访问,则启动状态机,代替软件操作SPI相关电路完成访问操作。 由于片上ROM容量较小,在不接入Flash存储器的情况下,只能执行体积不超过4KB的微型测试程序。 因此,在接入Flash后,可运行的程序规模大大增长。能运行Coremark等实际测试程序。 在FPGA上运行Coremark的结果如@fig:coremark_fpga 所示。 #fig(image("images/coremark_fpga.png", width: 50%), caption: [FPGA上运行Coremark]) <coremark_fpga> #indent 可以看到,上板后的SoC能正确运行完整的Coremark。 = 总结与展望 == 总结 本研究成功完成了基于Chisel的精简指令集微处理器设计,该处理器具备RISC-V指令集的模块化、可扩展特性,适应物联网应用的多样化需求和安全性要求。并通运行测试程序和跑分程序,证实了所设计处理器的正确性和有效性。 在此基础上,又成功实现了SoC化和对FPGA的支持,开发了UART和SPI控制器, 详细规定了寄存器设计、主体代码以及测试程序,确保处理器与外设间的协同工作。并完成了板级验证。 能实现基本输入输出、硬件线程切换、图灵等价,具备良好的可拓展性。 借助Chisel的抽象化和敏捷开发的特性。快速地完成了处理器的整体设计与SoC接入。 主要内容列举如下: + 通过阅读大量国内外文献,对RISC-V指令集架构的设计与发展现状和优缺点进行了分析。阅读各类相关的英文文档以确定处理器核的实现与标准文档一致。 + 介绍了Chisel语言,敏捷开发对芯片设计领域的好处。着重介绍了Chisel语言如何通过提供丰富硬件原语抽象、支持类型描述电路接口以及使用函数操作电路组件,实现电路生成器的高效、可靠与类型安全性,从而显著提升逻辑设计效率与稳健性。 + 搭建了软件测试平台,通过Verilator与Difftest。仔细验证了处理器功能与行为的正确性, 通过运行多种测试程序,确保处理器设计可以在各类工作负载下正常运行。 + 完成了仿真环境到FPGA上板验证的迁移。以及对外设模块的仿真测试。学习了仿真环境与FPGA的不同, 并掌握了基础的FPGA开发技能,包括IP核调用,添加引脚约束,简单时序约束,片上逻辑分析仪的使用,通过调试器 对FPGA进行编程及固化。 + 期间遇到了指令实现不正确或对标准文档错误解读导致的程序行为异常。通过完善的测试环境与difftest支持, 快速地完成了错误的定位与排除。 #pagebreak() //手动孤页控制 == 展望 虽然本文实现了基于Chisel的RV32E指令集的处理器设计。搭建了测试平台并完成上板验证,达到了期望的研究效果。 但仍存在诸多缺陷,还需要进一步的学习、设计与调试。 主要缺陷内容列举如下: + 处理器核不支持外部中断,导致所有功能必须通过轮询实现,在某些情况下会浪费处理器计算能力,并导致外部事件不能及被处理。 + 处理器核为多周期非流水线设计,单一模块工作时其他模块只能等待。导致从译码单元到回写单元的时序路径极长, 不利于提升处理器各模块的利用率与整体时钟频率。 + 无缓存功能,造成CPU每次在存储数据时都必须等待外部存储器响应,降低了运行效率。 且不支持MMU,导致无法运行现代操作系统(如Linux)。 + 译码器的设计仍有优化空间。 #indent 在今后的工作中,我将继续完成本设计中还未完善的地方,尝试为处理器搭建流水线和Cache,进一步提升性能。将本设计拓展成真正完善而可用的处理器。 并探索如乱序执行,多发射,分支预测等高级体系结构的内容。争取启动Linux等实际操作系统。 // 手动分页 #if (twoside) { pagebreak() + " " } // 参考文献 #bib(path:("bibs/ex01.bib", "bibs/ymlex.yml")) // 手动分页 #if (twoside) { pagebreak() + " " } #show: appendix #fig(image("images/Screenshot_mtrace.png", height: 32%), caption: [mtrace使用截图]) <mtrace> #fig(image("images/sdb_exec.png", height: 40%), caption: [单指令执行相关代码]) <sdb_exec> #fig(image("images/Screenshot_profile.png"), caption: [自动性能分析相关代码]) <make_prof> #if (twoside) { pagebreak() + " " } // 致谢 #acknowledgement[ 回顾在韶关学院的四年时光,收获甚多。不仅是在专业既能方面有了拓展和精进。更是结实了诸多良师益友。 首先要感谢我的导师王娜,她在大一期间就鼓励我及早参加比赛,让我早早地接触到了项目开发。 在我的方向陷入困境时,总能给我支持以及新的思考方向。 也要感谢信工之星工作室的蒋昌金指导老师,他带领了一批热爱技术的学生,排除诸多困难, 一直维护工作室的良好氛围,并不断鞭策我们。 也要感谢中国科学院-先进计算机系统研究中心的包云岗,余子濠,解壁伟老师。 他们带领的“一生一芯”计划、开源高性能处理器“香山”项目。 为我国处理器人才培养做出了极大的贡献。本文作者是“一生一芯”计划的正式成员。在研究期间得到了该计划的宝贵指导与资助。 感谢 NJU-LUG,提供 NJUThesis Typst 论文模板。 ] // 正文结束标志,不可缺少 #mainmatter-end()
https://github.com/Otto-AA/definitely-not-tuw-thesis
https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/src/styles/main-matter.typ
typst
MIT No Attribution
#let main-matter-styles = rest => { set page(numbering: "1") counter(page).update(1) counter(heading).update(0) set heading(numbering: "1.") rest }
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/model/numbering.typ
typst
// Test integrated numbering patterns. --- numbering --- #let t(pat: "1", step: 1, ..vals) = { let num = 0 for val in vals.pos() { if type(val) == int { num = val } else { test(numbering(pat, num), val) num += step } } } // Arabic. #t(pat: "1", "0", "1", "2", "3", "4", "5", "6", 107, "107", "108") // Symbols. #t(pat: "*", "-", "*", "†", "‡", "§", "¶", "‖", "**") // Hebrew. #t(pat: "א", step: 2, 9, "ט׳", "י״א", "י״ג") // Chinese. #t(pat: "一", step: 2, 9, "九", "十一", "十三", "十五", "十七", "十九") #t(pat: "壹", step: 2, 9, "玖", "拾壹", "拾叁", "拾伍", "拾柒", "拾玖") // Japanese. #t(pat: "イ", "-", "イ", "ロ", "ハ", 47, "ス", "イイ", "イロ", "イハ", 2256, "スス", "イイイ") #t(pat: "い", "-", "い", "ろ", "は", 47, "す", "いい", "いろ", "いは") #t(pat: "あ", "-", "あ", "い", "う", "え", "お", "か", "き", "く") #t(pat: "ア", "-", "ア", "イ", "ウ", "エ", "オ", "カ", "キ", "ク") // Korean. #t(pat: "가", "-", "가", "나", "다", 47, "다마", "다바", "다사", "다아") #t(pat: "ㄱ", "-", "ㄱ", "ㄴ", "ㄷ", 47, "ㄷㅁ") // Arabic Indic. #t(pat: "\u{0661}", 1475, "١٤٧٥") #t(pat: "\u{06F1}", 1475, "۱۴۷۵") // Devanagari. #t(pat: "\u{0967}", 1, "१") #t(pat: "\u{0967}", 10, "१०") #t(pat: "\u{0967}", 123456789, "१२३४५६७८९") // Bengali. #t(pat: "\u{09E7}", 1, "১") #t(pat: "\u{09E7}", 10, "১০") #t(pat: "\u{09E7}", 123456789, "১২৩৪৫৬৭৮৯") // Bengali Consonants. #t(pat: "\u{0995}", 1, "ক") #t(pat: "\u{0995}", 32, "হ") #t(pat: "\u{0995}", 32*2 , "কহ") // Circled number. #t(pat: "①", 1, "①") #t(pat: "①", 50, "㊿") // Double-circled number. #t(pat: "⓵", 1, "⓵") #t(pat: "⓵", 10, "⓾") --- numbering-negative --- // Error: 17-19 number must be at least zero #numbering("1", -1)
https://github.com/katamyra/Notes
https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS2110/Modules/BitsDataTypes.typ
typst
#import "../../../template.typ": * = Bits, Data Types, and Operations == Bits #definition(footer: "In reality, electronic circuits differ from voltages close to zero to voltages far from zero")[ *Bits*, or _binary digits_ represent either the presence (1) or absence of a voltage (0). One wire can differentiate between a zero or one, but in order to differentiate a large number of distinct values and to assign them unique representations, we need a large number of bits. ] == Data Types Using bits, there are many different ways to represent the same value. For example, to represent 5, you can have the number 5, or five fingers held up, 5 tally marks, the string 5, roman numerals, etc. #definition[ *Data type*: a particular representation where operations in the computer can operate on information encoded in the representation. ] === Unsigned Integers #definition[ *Unsigned Integers*: data type with no sign, only a magnitude. ] We can represent unsigned integers as strings of binary digits. To do this we use the binary system, similar to the decimal system. #note[ Unsigned integers are useful when we know that we know for sure that we don't need negative numbers. ] #theorem[ *Range for unsigned integers*: 0 to $2^k-1$ ]
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/058.%20randomness.html.typ
typst
randomness.html See Randomness April 2006, rev August 2009Plato quotes Socrates as saying "the unexamined life is not worth living." Part of what he meant was that the proper role of humans is to think, just as the proper role of anteaters is to poke their noses into anthills.A lot of ancient philosophy had the quality — and I don't mean this in an insulting way — of the kind of conversations freshmen have late at night in common rooms: What is our purpose? Well, we humans are as conspicuously different from other animals as the anteater. In our case the distinguishing feature is the ability to reason. So obviously that is what we should be doing, and a human who doesn't is doing a bad job of being human — is no better than an animal. Now we'd give a different answer. At least, someone Socrates's age would. We'd ask why we even suppose we have a "purpose" in life. We may be better adapted for some things than others; we may be happier doing things we're adapted for; but why assume purpose?The history of ideas is a history of gradually discarding the assumption that it's all about us. No, it turns out, the earth is not the center of the universe — not even the center of the solar system. No, it turns out, humans are not created by God in his own image; they're just one species among many, descended not merely from apes, but from microorganisms. Even the concept of "me" turns out to be fuzzy around the edges if you examine it closely.The idea that we're the center of things is difficult to discard. So difficult that there's probably room to discard more. Richard Dawkins made another step in that direction only in the last several decades, with the idea of the selfish gene. No, it turns out, we're not even the protagonists: we're just the latest model vehicle our genes have constructed to travel around in. And having kids is our genes heading for the lifeboats. Reading that book snapped my brain out of its previous way of thinking the way Darwin's must have when it first appeared.(Few people can experience now what Darwin's contemporaries did when The Origin of Species was first published, because everyone now is raised either to take evolution for granted, or to regard it as a heresy. No one encounters the idea of natural selection for the first time as an adult.)So if you want to discover things that have been overlooked till now, one really good place to look is in our blind spot: in our natural, naive belief that it's all about us. And expect to encounter ferocious opposition if you do.Conversely, if you have to choose between two theories, prefer the one that doesn't center on you.This principle isn't only for big ideas. It works in everyday life, too. For example, suppose you're saving a piece of cake in the fridge, and you come home one day to find your housemate has eaten it. Two possible theories: a) Your housemate did it deliberately to upset you. He knew you were saving that piece of cake.b) Your housemate was hungry. I say pick b. No one knows who said "never attribute to malice what can be explained by incompetence," but it is a powerful idea. Its more general version is our answer to the Greeks: Don't see purpose where there isn't. Or better still, the positive version: See randomness.Korean Translation
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-0300.typ
typst
Apache License 2.0
#let data = ( ("COMBINING GRAVE ACCENT", "Mn", 230), ("COMBINING ACUTE ACCENT", "Mn", 230), ("COMBINING CIRCUMFLEX ACCENT", "Mn", 230), ("COMBINING TILDE", "Mn", 230), ("COMBINING MACRON", "Mn", 230), ("COMBINING OVERLINE", "Mn", 230), ("COMBINING BREVE", "Mn", 230), ("COMBINING DOT ABOVE", "Mn", 230), ("COMBINING DIAERESIS", "Mn", 230), ("COMBINING HOOK ABOVE", "Mn", 230), ("COMBINING RING ABOVE", "Mn", 230), ("COMBINING DOUBLE ACUTE ACCENT", "Mn", 230), ("COMBINING CARON", "Mn", 230), ("COMBINING VERTICAL LINE ABOVE", "Mn", 230), ("COMBINING DOUBLE VERTICAL LINE ABOVE", "Mn", 230), ("COMBINING DOUBLE GRAVE ACCENT", "Mn", 230), ("COMBINING CANDRABINDU", "Mn", 230), ("COMBINING INVERTED BREVE", "Mn", 230), ("COMBINING TURNED COMMA ABOVE", "Mn", 230), ("COMBINING COMMA ABOVE", "Mn", 230), ("COMBINING REVERSED COMMA ABOVE", "Mn", 230), ("COMBINING COMMA ABOVE RIGHT", "Mn", 232), ("COMBINING GRAVE ACCENT BELOW", "Mn", 220), ("COMBINING ACUTE ACCENT BELOW", "Mn", 220), ("COMBINING LEFT TACK BELOW", "Mn", 220), ("COMBINING RIGHT TACK BELOW", "Mn", 220), ("COMBINING LEFT ANGLE ABOVE", "Mn", 232), ("COMBINING HORN", "Mn", 216), ("COMBINING LEFT HALF RING BELOW", "Mn", 220), ("COMBINING UP TACK BELOW", "Mn", 220), ("COMBINING DOWN TACK BELOW", "Mn", 220), ("COMBINING PLUS SIGN BELOW", "Mn", 220), ("COMBINING MINUS SIGN BELOW", "Mn", 220), ("COMBINING PALATALIZED HOOK BELOW", "Mn", 202), ("COMBINING RETROFLEX HOOK BELOW", "Mn", 202), ("COMBINING DOT BELOW", "Mn", 220), ("COMBINING DIAERESIS BELOW", "Mn", 220), ("COMBINING RING BELOW", "Mn", 220), ("COMBINING COMMA BELOW", "Mn", 220), ("COMBINING CEDILLA", "Mn", 202), ("COMBINING OGONEK", "Mn", 202), ("COMBINING VERTICAL LINE BELOW", "Mn", 220), ("COMBINING BRIDGE BELOW", "Mn", 220), ("COMBINING INVERTED DOUBLE ARCH BELOW", "Mn", 220), ("COMBINING CARON BELOW", "Mn", 220), ("COMBINING CIRCUMFLEX ACCENT BELOW", "Mn", 220), ("COMBINING BREVE BELOW", "Mn", 220), ("COMBINING INVERTED BREVE BELOW", "Mn", 220), ("COMBINING TILDE BELOW", "Mn", 220), ("COMBINING MACRON BELOW", "Mn", 220), ("COMBINING LOW LINE", "Mn", 220), ("COMBINING DOUBLE LOW LINE", "Mn", 220), ("COMBINING TILDE OVERLAY", "Mn", 1), ("COMBINING SHORT STROKE OVERLAY", "Mn", 1), ("COMBINING LONG STROKE OVERLAY", "Mn", 1), ("COMBINING SHORT SOLIDUS OVERLAY", "Mn", 1), ("COMBINING LONG SOLIDUS OVERLAY", "Mn", 1), ("COMBINING RIGHT HALF RING BELOW", "Mn", 220), ("COMBINING INVERTED BRIDGE BELOW", "Mn", 220), ("COMBINING SQUARE BELOW", "Mn", 220), ("COMBINING SEAGULL BELOW", "Mn", 220), ("COMBINING X ABOVE", "Mn", 230), ("COMBINING VERTICAL TILDE", "Mn", 230), ("COMBINING DOUBLE OVERLINE", "Mn", 230), ("COMBINING GRAVE TONE MARK", "Mn", 230), ("COMBINING ACUTE TONE MARK", "Mn", 230), ("COMBINING GREEK PERISPOMENI", "Mn", 230), ("COMBINING GREEK KORONIS", "Mn", 230), ("COMBINING GREEK DIALYTIKA TONOS", "Mn", 230), ("COMBINING GREEK YPOGEGRAMMENI", "Mn", 240), ("COMBINING BRIDGE ABOVE", "Mn", 230), ("COMBINING EQUALS SIGN BELOW", "Mn", 220), ("COMBINING DOUBLE VERTICAL LINE BELOW", "Mn", 220), ("COMBINING LEFT ANGLE BELOW", "Mn", 220), ("COMBINING NOT TILDE ABOVE", "Mn", 230), ("COMBINING HOMOTHETIC ABOVE", "Mn", 230), ("COMBINING ALMOST EQUAL TO ABOVE", "Mn", 230), ("COMBINING LEFT RIGHT ARROW BELOW", "Mn", 220), ("COMBINING UPWARDS ARROW BELOW", "Mn", 220), ("COMBINING GRAPHEME JOINER", "Mn", 0), ("COMBINING RIGHT ARROWHEAD ABOVE", "Mn", 230), ("COMBINING LEFT HALF RING ABOVE", "Mn", 230), ("COMBINING FERMATA", "Mn", 230), ("COMBINING X BELOW", "Mn", 220), ("COMBINING LEFT ARROWHEAD BELOW", "Mn", 220), ("COMBINING RIGHT ARROWHEAD BELOW", "Mn", 220), ("COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW", "Mn", 220), ("COMBINING RIGHT HALF RING ABOVE", "Mn", 230), ("COMBINING DOT ABOVE RIGHT", "Mn", 232), ("COMBINING ASTERISK BELOW", "Mn", 220), ("COMBINING DOUBLE RING BELOW", "Mn", 220), ("COMBINING ZIGZAG ABOVE", "Mn", 230), ("COMBINING DOUBLE BREVE BELOW", "Mn", 233), ("COMBINING DOUBLE BREVE", "Mn", 234), ("COMBINING DOUBLE MACRON", "Mn", 234), ("COMBINING DOUBLE MACRON BELOW", "Mn", 233), ("COMBINING DOUBLE TILDE", "Mn", 234), ("COMBINING DOUBLE INVERTED BREVE", "Mn", 234), ("COMBINING DOUBLE RIGHTWARDS ARROW BELOW", "Mn", 233), ("COMBINING LATIN SMALL LETTER A", "Mn", 230), ("COMBINING LATIN SMALL LETTER E", "Mn", 230), ("COMBINING LATIN SMALL LETTER I", "Mn", 230), ("COMBINING LATIN SMALL LETTER O", "Mn", 230), ("COMBINING LATIN SMALL LETTER U", "Mn", 230), ("COMBINING LATIN SMALL LETTER C", "Mn", 230), ("COMBINING LATIN SMALL LETTER D", "Mn", 230), ("COMBINING LATIN SMALL LETTER H", "Mn", 230), ("COMBINING LATIN SMALL LETTER M", "Mn", 230), ("COMBINING LATIN SMALL LETTER R", "Mn", 230), ("COMBINING LATIN SMALL LETTER T", "Mn", 230), ("COMBINING LATIN SMALL LETTER V", "Mn", 230), ("COMBINING LATIN SMALL LETTER X", "Mn", 230), )
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/visualize/polygon.typ
typst
// Test polygons. --- polygon --- #set page(width: 50pt) #set polygon(stroke: 0.75pt, fill: blue) // These are not visible, but should also not give an error #polygon() #polygon((0em, 0pt)) #polygon((0pt, 0pt), (10pt, 0pt)) #polygon.regular(size: 0pt, vertices: 9) #polygon((5pt, 0pt), (0pt, 10pt), (10pt, 10pt)) #polygon( (0pt, 0pt), (5pt, 5pt), (10pt, 0pt), (15pt, 5pt), (5pt, 10pt) ) #polygon(stroke: none, (5pt, 0pt), (0pt, 10pt), (10pt, 10pt)) #polygon(stroke: 3pt, fill: none, (5pt, 0pt), (0pt, 10pt), (10pt, 10pt)) // Relative size #polygon((0pt, 0pt), (100%, 5pt), (50%, 10pt)) // Antiparallelogram #polygon((0pt, 5pt), (5pt, 0pt), (0pt, 10pt), (5pt, 15pt)) // Self-intersections #polygon((0pt, 10pt), (30pt, 20pt), (0pt, 30pt), (20pt, 0pt), (20pt, 35pt)) #polygon(fill-rule: "non-zero", (0pt, 10pt), (30pt, 20pt), (0pt, 30pt), (20pt, 0pt), (20pt, 35pt)) #polygon(fill-rule: "even-odd", (0pt, 10pt), (30pt, 20pt), (0pt, 30pt), (20pt, 0pt), (20pt, 35pt)) // Regular polygon; should have equal side lengths #for k in range(3, 9) {polygon.regular(size: 30pt, vertices: k,)} --- polygon-line-join --- // Line joins #stack( dir: ltr, spacing: 1em, polygon(stroke: (thickness: 4pt, paint: blue, join: "round"), (0pt, 20pt), (15pt, 0pt), (0pt, 40pt), (15pt, 45pt)), polygon(stroke: (thickness: 4pt, paint: blue, join: "bevel"), (0pt, 20pt), (15pt, 0pt), (0pt, 40pt), (15pt, 45pt)), polygon(stroke: (thickness: 4pt, paint: blue, join: "miter"), (0pt, 20pt), (15pt, 0pt), (0pt, 40pt), (15pt, 45pt)), polygon(stroke: (thickness: 4pt, paint: blue, join: "miter", miter-limit: 20.0), (0pt, 20pt), (15pt, 0pt), (0pt, 40pt), (15pt, 45pt)), ) --- polygon-bad-point-array --- // Error: 10-17 point array must contain exactly two entries #polygon((50pt,))
https://github.com/gaetanserre/Typst-templates
https://raw.githubusercontent.com/gaetanserre/Typst-templates/main/beamer/1.0.0/beamer.typ
typst
/* * Created in 2023 by <NAME> */ // Utils functions #let range(n) = { let ret = () let i = 0 while i < n { ret += (i,) i += 1 } ret } #let TODO(it) = { text(fill: red, weight: "extrabold", [TODO #it]) } /**********************************BEAMER ENVIRONMENT*********************************************/ /*************************************************************************************************/ #let s_lang = state("lang", "en") #let bib_wording = ("en": [Bibliography], "fr": [Bibliographie]) #let outline_wording = ("en": [Outline], "fr": [Table des matières]) #let thanks_wording = ( "en": [Thank you for your #text(fill: rgb("#937bf1"),[attention])!], "fr": [Merci pour votre #text(fill: rgb("#937bf1"),[attention]) !] ) #let past_bib(loc) = { let previous_heading_bodies = query(selector(heading).before(loc), loc).map(h => {h.body}) return previous_heading_bodies.contains(bib_wording.at(s_lang.at(loc))) } #let get_last_page_before_bib(loc) = { if past_bib(loc) { return counter("page").final(loc).at(0) } let headings = query(selector(heading).after(loc), loc) let bib_page_nb = counter("page").final(loc).at(0) for heading in headings { if heading.body == bib_wording.at(s_lang.at(loc)) { bib_page_nb = counter("page").at(heading.location()).at(0) } } return bib_page_nb - 1 } #let title_color = rgb("#503fa1") #let subtitle_color = rgb("#937bf1") #let s_title_color = state("title_color", title_color) #let s_subtitle_color = state("subtitle_color", subtitle_color) #let has_previous_title(title) = { let headings = query(selector(heading).before(here())) for heading in headings { if heading.body == title { return true } } return false } #let has_previous_subtitle(title, subtitle) = { let headings = query(selector(heading).before(here())) let h = none for i in range(headings.len()) { if headings.at(i).level == 1 or h == none { h = headings.at(i) } if headings.at(i).body == subtitle and headings.at(i).level == 2 and h.body == title { return true } } return false } #let title_style(title) = context { text(size: 25pt, fill: s_title_color.final(), [#v(-0.5em) #title]) } #let subtitle_style(subtitle) = context { text(style: "italic", fill: s_subtitle_color.get(), [#v(-0.5em) #subtitle #v(-0.555em)]) } #let slide( title: none, subtitle: none, content: none, h_block_align: center, v_block_align: horizon, breakpage: true, ) = context { set par(leading: 20pt) if title != none { if has_previous_title(title) { title_style(title) } else { [= #title] } } if subtitle != none { if has_previous_subtitle(title, subtitle) { subtitle_style(subtitle) } else { [== #subtitle] counter("page").step() } } else if not has_previous_title(title) { counter("page").step() } set par(leading: 0.65em) align(h_block_align + v_block_align, box([ #content ])) if breakpage { pagebreak() } } #let columns_slide( title: none, subtitle: none, h_block_align: center, v_block_align: horizon, contents: (), common_content: none, columns: none, column_gutter: 2em, stroke: none, breakpage: true, ) = { if columns == none { columns = () for content in contents { columns += (auto,) } } let content = grid( columns: columns, column-gutter: column_gutter, stroke: stroke, rows: (auto), ..contents ) + common_content slide( title: title, subtitle: subtitle, h_block_align: center, v_block_align: horizon, content: content, breakpage: breakpage, ) } #let init_bullet_list( items: (), numbered: false, ) = { (numbers, last_bullet: none) => { let counter = 0 for i in numbers { if numbered { if counter == (numbers.len() - 1) and last_bullet != none [ + #last_bullet(items.at(i)) ] else [ + #items.at(i) ] } else { if counter == (numbers.len() - 1) and last_bullet != none [ - #last_bullet(items.at(i)) ] else [ - #items.at(i) ] } counter += 1 } } } #let unfold_bullet(items, title: none, numbered:false, last_bullet: none) = { let bullet = init_bullet_list( items: items, numbered: numbered ) let idx = () for i in range(items.len()) { idx += (i,) slide( title: title, content: align(left, bullet( idx, last_bullet: last_bullet )), ) } } #let title_slide( title: [Title], subtitle: [Subtitle], authors: [Authors], emails: [Emails], date: none, background: none) = { slide( title: none, content: [ #text(size: 30pt, [#title])\ #text(15pt, style: "italic", subtitle)\ #authors\ #emails\ #date ], breakpage: false ) counter("page").update(0) } #let get_n_space(n) = { for i in range(n) { $space space space$ } } #let check_heading_in_unique(h, hs) = { if h.body in hs { let elem = hs.find(e => e.body == h.body) return elem.level == h.level } return false } #let outline_slide(size: none, v_align: horizon) = context { set page(footer: [], background: []) set par(first-line-indent: 0em) [= #outline_wording.at(s_lang.at(here()))] let headings = query(selector(heading).after(here()), here()).slice(1, none) let unique_headings = () align(v_align, for heading in headings { if not check_heading_in_unique(heading, unique_headings) { let heading_loc = heading.location() unique_headings += (heading,) let nb_page = { let tmp = counter("page").at(heading_loc).at(0) if heading.body == bib_wording.at(s_lang.at(here())) { tmp } else { tmp + 1 } } let content = get_n_space(heading.level - 1) + link(heading_loc)[#heading.body] + box(width: 1fr, repeat([.$space$])) + link(heading_loc)[#nb_page] + [ \ ] if size != none { text(size: size, content) } else { content } } }) } #let thanks_slide() = context { set page(footer: [], background: none) let wording = thanks_wording.at(s_lang.at(here())) align(center + horizon, text(size: 20pt, wording)) } #let trans_slide(it, subtitle: none) = { set page(footer: [], background: none) align(center + horizon, text(size: 20pt, title_style(it) + subtitle_style(subtitle))) } /***********************************MATHS ENVIRONMENT*********************************************/ /*************************************************************************************************/ #let math_block(supplement, name, it, lb, stroke_color, eq_numbering) = context { set text(font: "New Computer Modern") let body = { set math.equation(numbering: eq_numbering) if name == none { [*#supplement(here()).* ] + it } else { [*#supplement(here())* (#emph(name))*.* ] + it } } let fig = figure( rect( width:100%, stroke: ("left": 1pt+stroke_color, "rest": none), fill: rgb("#f8f6fb"), inset: (bottom: 10pt, rest: 5pt), align(left, body) ), caption: none, kind: supplement(here()), supplement: supplement(here()), ) if lb != none [ #fig #label(lb) ] else [ #fig ] } // Math blocks #let lem_wording = ("en": "Lemma", "fr": "Lemme") #let prop_wording = ("en": "Proposition", "fr": "Proposition") #let thm_wording = ("en": "Theorem", "fr": "Théorème") #let cor_wording = ("en": "Corollary", "fr": "Corollaire") #let def_wording = ("en": "Definition", "fr": "Définition") #let re_wording = ("en": "Remark", "fr": "Remarque") #let ex_wording = ("en": "Example", "fr": "Exemple") #let lemma(name, it, label: none, eq_numbering: none) = { math_block(l => lem_wording.at(s_lang.at(l)), name, it, label, rgb("#b287a3"), eq_numbering) } #let proposition(name, it, label: none, eq_numbering: none) = { math_block(l =>prop_wording.at(s_lang.at(l)), name, it, label, rgb("#b1255d"), eq_numbering) } #let theorem(name, it, label: none, eq_numbering: none) = { math_block(l => thm_wording.at(s_lang.at(l)), name, it, label, rgb("#5f072a"), eq_numbering) } #let corollary(name, it, label: none, eq_numbering: none) = { math_block(l => cor_wording.at(s_lang.at(l)), name, it, label, rgb("#ffc300"), eq_numbering) } #let definition(name, it, label: none, eq_numbering: none) = { math_block(l => def_wording.at(s_lang.at(l)), name, it, label, rgb("#bfb1c1"), eq_numbering) } #let remark(name, it, label: none, eq_numbering: none) = { math_block(l => re_wording.at(s_lang.at(l)), name, it, label, rgb("#8380b6"), eq_numbering) } #let example(it, label: none, eq_numbering: none) = { math_block(l => ex_wording.at(s_lang.at(l)), none, it, label, rgb("#9bc4cb"), eq_numbering) } #let proof(it) = { set par(first-line-indent: 0em) set align(center) set math.equation(numbering: none) block( width: 90%, align(left, [_Proof._ $space$] + it + align(right, text()[$qed$])) ) } /*********************************ALGORITHM ENVIRONMENT*******************************************/ /*************************************************************************************************/ #let code_block( identifier: none, comment: none, content: [], has_stroke: true, inset: 1em ) = { if comment == none { identifier } else { [#identifier #box(width: 1fr, repeat(" ")) #text(fill: rgb("#6c6c6c"), style: "italic", comment)] } block(width: auto, above: 0.5em, below:0.5em, { let stroke = ("left": 1pt, "rest": none) if not has_stroke { stroke = none } rect( stroke: stroke, outset: -0.1em, inset: (right: 0em, rest: inset), )[#content] }) } #let for_loop( variable: "i", start: "1", end: "n", comment: none, content: [], ) = { code_block(identifier: [*for* #variable $=$ #start *to* #end *do*], comment: comment, content: content) [*end for*] } #let while_loop( condition: "x", comment: none, content: [], ) = { code_block(identifier: [*while* #condition *do*], comment: comment, content: content) [*end while*] } #let if_block( condition: "x", comment: none, content: [], else_comment: none, else_content: none, ) = { code_block(identifier: [*if* #condition *then*], comment: comment, content: content) if else_content != none { code_block(identifier: [*else*], comment: else_comment, content: else_content) } [*end if*] } #let comment( content ) = { [#box(width: 1fr, repeat(" ")) #text(fill: rgb("#6c6c6c"), style: "italic", content)] } #let keyword( keyword, fill: black, weight: "regular", style: none ) = { if style == none { text(fill: fill, weight: weight, keyword) } else { style(keyword) } } #let Return = keyword([return], weight: "bold") #let Break = keyword([break], weight: "bold") #let Continue = keyword([continue], weight: "bold") #let algorithm( name: none, input: none, output: none, content: none ) = { set text(font: "New Computer Modern") align(center, block(width: auto, { align(left, { counter("algorithm").step() //show line: set block(above: 0.4em, below: 0.4em) set par(first-line-indent: 0em) box(width: 1fr, line(length: 100%, stroke: {1.5pt + black})) + [ \ ] [*Algorithm #counter("algorithm").display():* #smallcaps(name) \ ] box(width: 1fr, line(length: 100%, stroke: {1pt + black})) + [ \ ] if input != none { [*Input:*] align(center, block(width: 95%, above: 0.5em, below: 0.5em, align(left, input))) } if output != none { [*Output:*] align(center, block(width: 95%, above: 0.5em, below: 0.5em, align(left, output))) } if output != none or input != none { box(width: 1fr, line(length: 100%, stroke: {1pt + black})) + [ \ ] } [#content \ ] box(width: 1fr, line(length: 100%, stroke: {1pt + black})) }) }) ) } /*********************************LANGUAGE ENVIRONMENT*******************************************/ /*************************************************************************************************/ /***LEAN***/ // #let lean_font(cont) = text(font: "FiraCode Nerd Font", size: 12pt, cont) #let lean_block(it) = { /* set par(first-line-indent: 0em) show par: set block(spacing: 0em) set text(font: "FiraCode Nerd Font", size: 12pt) let reg_comment = regex(`(\/-[^-/]*-\/)|(--.*)`.text) let comment_matches = cont.matches(reg_comment) let cont_without_comments = cont.split(reg_comment) let print_comment(comment) = { set par(first-line-indent: 0em) show regex("[^\*]\*[^\*]+\*(\n | [^\*])"): set text(style: "italic", fill: black) show regex("`.+`"): set text(fill: rgb("#ad7fa8")) show regex("\*\*[^\*]+\*\*"): set text(weight: "bold", fill: black) text(fill: rgb("#6a737d"), comment) } let print_code(code) = { set par(first-line-indent: 0em) show regex("(lemma|theorem|by|sorry|have|def|let|noncomputable|variable|with|example|fun|at|show|class|instance|where)(\s|$)"): set text(fill: rgb("#8b3fef")) show regex("Type"): set text(fill: rgb("#8b3fef")) show regex("(lemma|theorem|def|class)\s\w+"): set text(fill: rgb("#3475f5")) show regex("\(|\[|\{|\}|\]|\)"): set text(fill: rgb("#d4244a")) code } let n_comment = 0 let n_char = 0 let final_content = [] for i in range(cont_without_comments.len()) { while (comment_matches.len() > n_comment and (comment_matches.at(n_comment).start == n_char or comment_matches.at(n_comment).start == 1)) { final_content += print_comment(comment_matches.at(n_comment).text) n_char += comment_matches.at(n_comment).text.len() n_comment += 1 } final_content += print_code(cont_without_comments.at(i)) n_char += cont_without_comments.at(i).len() } if (comment_matches.len() > n_comment) { final_content += print_comment(comment_matches.at(n_comment).text) } */ block( width:100%, stroke: ("left": 1pt+rgb("#d73a4a"), "rest": none), fill: rgb("#f8f6fb"), inset: (bottom: 0.7em, rest: 0.5em), align(left, raw(lang: "lean4", it)) ) } #let gray(it) = text(fill: rgb("#888888"), it) #let grad_color = gradient.linear(rgb("#665bad"), rgb("#b6a4da"), relative: "parent") #let footer(loc, running_author) = { let page_nb = counter("page").at(loc).at(0) let h = query(selector(heading).after(loc), loc).map(h => {h.body}).at(0, default: []) if page_nb == 0 or h == outline_wording.at(s_lang.at(loc)) { return [] } let last_page = get_last_page_before_bib(loc) let max_size_bar = 50pt let current_size_bar = ((page_nb - 1)/(last_page - 1)) * max_size_bar let box = { if past_bib(loc) { [] } else { align(left, box( width: max_size_bar, height: 6pt, fill: rgb("#eeeeee"), radius: 3pt, align(left, rect( width: current_size_bar, height: 6pt, fill: grad_color, radius: 3pt )) )) } } grid( columns: (33%, 33%, 33%), box, align(center, text(size: 9pt, running_author)), align(right, text(size: 9pt, [#page_nb])) ) } #let config( background: none, title_background: none, title_color: title_color, subtitle_color: subtitle_color, text_color: rgb("#000000"), lang: "en", footer: context footer(here(), [<NAME> --- Centre Borelli]), doc ) = { set page( paper: "presentation-16-9", numbering: "1", footer: footer, background: context { let page_nb = counter("page").at(here()).at(0) let h = query(selector(heading).before(here()), here()).map(h => {h.body}).at(0, default: []) if page_nb == 0 and h != outline_wording.at(s_lang.at(here())) { title_background } else { background } } ) // Set rules set par(justify: true) set text(font: "Noto Sans", size: 15pt, fill: text_color, lang: lang) set heading(numbering: none) set cite(style: "chicago-author-date") set math.equation(numbering: "(1)") set list(marker: ($gt.tri$, $arrow.r.curve$)) set enum(indent: 1em) // Reference style set ref(supplement: it => { let fig = it.func() if fig == math.equation { text(fill: black, "Eq.") } else if fig == figure { gray(it.supplement) } }) set raw(theme: "catppuccin_latte.thTheme", syntaxes: "lean4.sublime-syntax") set footnote.entry(separator: align(right, line(length: 20%, stroke: 1pt + title_color))) // Show rules show ref: set text(fill: rgb("#ff0000")) show link: set text(fill: subtitle_color) show cite: set text(fill: rgb("#4361ee")) show math.equation: set text(font: "New Computer Modern Math") show raw: set text(font: "FiraCode Nerd Font") show footnote: set text(fill: subtitle_color) show footnote.entry: it => { set text(fill: subtitle_color, size: 10pt) align(right, it) } // Algorithm & Lean figure show figure: fig => { if fig.kind == "algorithm" { fig.body } else if fig.kind == "leancode" { counter(fig.kind).step() fig.body + align(center, [#fig.supplement #counter(fig.kind).display(): #fig.caption]) } else { show figure.caption: set text(12pt, fill: rgb("#888888")) fig } } show heading: it => { set align(left) if it.level == 1 { set text(25pt, weight: "regular", fill: s_title_color.final()) v(-0.5em) if it.body == bib_wording.at(s_lang.at(here())) { it.body v(1.5em) } else { it.body } } else if it.level == 2 { set text(15pt, style: "italic", weight: "regular", fill: s_subtitle_color.final()) v(-0.5em) it.body } else { it.body } } s_title_color.update(title_color) s_subtitle_color.update(subtitle_color) s_lang.update(lang) doc }
https://github.com/howardlau1999/sysu-thesis-typst
https://raw.githubusercontent.com/howardlau1999/sysu-thesis-typst/master/functions/style.typ
typst
MIT License
#import "../custom.typ": * #let 字号 = ( 初号: 42pt, 小初: 36pt, 一号: 26pt, 小一: 24pt, 二号: 22pt, 小二: 18pt, 三号: 16pt, 小三: 15pt, 四号: 14pt, 中四: 13pt, 小四: 12pt, 五号: 10.5pt, 小五: 9pt, 六号: 7.5pt, 小六: 6.5pt, 七号: 5.5pt, 小七: 5pt, ) #let lengthceil(len, unit: 字号.小四) = calc.ceil(len / unit) * unit
https://github.com/FkHiroki/ex-E5
https://raw.githubusercontent.com/FkHiroki/ex-E5/main/sections/section2.typ
typst
MIT No Attribution
#import "@preview/codelst:2.0.0": sourcecode = 2. 実験結果 = 課題(1) 課題(1)では一様乱数を発生させて、その平均と分散、度数分布を求めた。まず、実行したプログラムの実行結果を@fig:result に示す。ここで、このプログラムでは、乱数を発生させる回数を$30,000$回としている。 #figure( caption: [課題(1): 実行結果], sourcecode( frame: block.with( stroke: 1pt + gray, inset: (x: 10pt, y: 5pt), radius: 5pt, fill: luma(96%) ) )[ #raw(read("../figs/result.txt")) ] ) <fig:result> これをグラフにプロットし、度数分布を求めた結果を@fig:distrb に示す。@fig:result、@fig:distrb から、それぞれの区間での度数が、理論値($6000$)との誤差が$80$以下になっており、発生させた乱数が一様乱数になっていることが確認できる。 #figure( image("../figs/hist.png", width: 90%), caption: [課題(1): 度数分布のグラフ], ) <fig:distrb> 次に、同じプログラム乱数生成法のプログラムを用いて、乱数の発生回数を$1,000$回から$100$万回まで、$1,000$回ずつ増やして、それぞれの平均と分散を求め、その時の平均と分散の値をグラフにプロットした。その結果を@fig:distrb-ave と@fig:distrb-var に示す。 #figure( image("../figs/distrb-ave.png", width: 60%), caption: [課題(1): 平均のグラフ], ) <fig:distrb-ave> #figure( image("../figs/distrb-var.png", width: 60%), caption: [課題(1): 分散のグラフ], ) <fig:distrb-var> @fig:distrb-ave から、乱数の発生回数が増えるにつれて、平均の値が$0.5$に収束していることがわかる。また、@fig:distrb-var から、乱数の発生回数が増えるにつれて、分散の値が$0.083$付近に収束していることがわかる。 = 課題(2) 課題(2)では、buffonの針問題をシミュレーションするプログラムを実行した。このプログラムでは乱数を$3$万回発生させ、buffonの針問題の理論を用いて、円周率$pi$の値を計算した。その結果を@fig:buffon_result に示す。 #figure( caption: [課題(2) $pi$ の計算結果], sourcecode( frame: block.with( stroke: 1pt + gray, inset: (x: 10pt, y: 5pt), radius: 5pt, fill: luma(96%) ) )[ #raw(read("../figs/result2.txt")) ] ) <fig:buffon_result> また、このプログラムを用いて、乱数の発生回数を$1,000$回から$100$万回まで、$1,000$回ずつ増やして、それぞれの$pi$の値を計算し、その時の$pi$の値をグラフにプロットした。その結果を@fig:buffon に示す。 @fig:buffon_result から、乱数の発生回数が増えるにつれて、$pi$の値がある一定の値に収束していることがわかる。 #figure( image("../figs/buffon.png", width: 60%), caption: [課題(2): $pi$ への収束の様子], ) <fig:buffon> = 課題(3) 求積問題によるπの値 == (3)-1: ⼊⾨的モンテカルロ法によりπの値を求める 入門的モンテカルロ法を用いたプログラムを実行して、πの値を計算した。この時、乱数発生の試行回数を$30,000$、$100,000$、$1,000,000$、$10,000,000$、$100,000,000$、$300,000,000$回で実行した。その結果を@fig:monte_result に示す。 #figure( caption: [課題(3)-1: πの値の計算結果], sourcecode( frame: block.with( stroke: 1pt + gray, inset: (x: 10pt, y: 5pt), radius: 5pt, fill: luma(96%) ) )[ #raw(read("../figs/crudedata.txt")) ] ) <fig:monte_result> == (3)-2: 当たり外れのモンテカルロ法によりπの値を求める 次に、当たり外れのモンテカルロ法を用いたプログラムを実行して、πの値を計算した。この時も乱数発生の試行回数を$30,000$、$100,000$、$1,000,000$、$10,000,000$、$100,000,000$、$300,000,000$回で実行した。その結果を@fig:hit_result に示す。 #figure( caption: [課題(3)-2: πの値の計算結果], sourcecode( frame: block.with( stroke: 1pt + gray, inset: (x: 10pt, y: 5pt), radius: 5pt, fill: luma(96%) ) )[ #raw(read("../figs/hitdata.txt")) ] ) <fig:hit_result> そして、@fig:monte_result と@fig:hit_result の結果からそれぞれの絶対誤差を計算し、グラフにプロットすることで、それぞれのモンテカルロ法の精度を比較した。その結果を@fig:monte_hit_comp に示す。 #figure( image("../figs/pi_comp.png", width: 90%), caption: [課題(3): モンテカルロ法の比較], ) <fig:monte_hit_comp> @fig:monte_hit_comp から、どちらの手法も初めは回数が増えるにつれて精度が向上しているが、試行回数が$10^5$を超えてからは、精度の向上がほとんど見られず、誤差が一定になっている。また、$10^9$の時以外は、入門的モンテカルロ法の方が当たり外れのモンテカルロ法よりも精度が高いことがわかる。 = 課題(4) モンテカルロシミュレーション == (4)-1: ランダムウォーク ここでは、ランダムウォークをシミュレーションするプログラムを実行した。まず、今回のランダムウォークでは、$1$ステップの移動距離を$1$とし、$1$回のシミュレーションで$10$回の移動を行った。初めに、表計算ソフトを用いて、今回の状況の確率分布の理論式から位置の確率分布を求めた。その結果を@fig:randomwalk_theory に示す。 #figure( image("../figs/randwalk_theo.png", width: 90%), caption: [課題(4)-1: ランダムウォークの理論値], ) <fig:randomwalk_theory> 次に、ランダムウォークのシミュレーションをするプログラムを試行回数$100$万回で実行し、その時の位置の確率分布をグラフとして可視化した。その結果を@fig:randomwalk に示す。そして、理論値と実験値の比較を@fig:randomwalk_comp に示す。@fig:randomwalk_comp から、理論値と実験値のプロットがほとんど重なっており、プログラムの精度の良さが確認できる。 #figure( image("../figs/randwalk_exp.png", width: 90%), caption: [課題(4)-1: ランダムウォークの実験値], ) <fig:randomwalk> #figure( image("../figs/randwalk_comp.png", width: 90%), caption: [課題(4)-1: ランダムウォークの理論値と実験値の比較], ) <fig:randomwalk_comp> \ == (4)-2: 二項分布に従う確率分布 ここでは、「全住⺠の5%がある感染症に罹患しており、その中から無作為に500⼈を抽出する。ただし住⺠は500⼈よりずっと多いとする。このとき、抽出された集団の中に罹患者が 30⼈以上いる確率はどれくらいか。」という問題を考え、その確率を求めるプログラムを実行した。まず、(4)-1と同様に、表計算ソフトを用いて、この問題の確率分布の理論式から位置の確率分布を求めた。ここで、求めた値は患者数が$0~29$人の時までである。その結果を@fig:binomial_theory に示す。 #figure( image("../figs/patients_theo.png", width: 90%), caption: [課題(4)-2: 二項分布の理論値], ) <fig:binomial_theory> 次に、試行回数を$100$、$1,000$、$1$万、$10$万、$100$万、$1,000$万、$1$億回としてプログラムを実行し、その時の確率を計算し、その確率の値をグラフにプロットした。ここでも求めた値は患者数が$0~29$人の時までである。また、プログラム上で、患者数の期待値を計算させた。まず、期待値の計算結果を@tab:binomial_expectation に示す。この表から、試行回数が増えるにつれて、期待値が理論値である$25 (500 times 0.05)$に収束していることがわかる。 次に、確率の値をグラフにプロットした結果を@fig:binomial に示す。この時、試行回数が$1$億回の時の確率の値を用いた。そして、理論値と実験値の比較を@fig:binomial_comp に示す。@fig:binomial_comp から、理論値と実験値のプロットが、確率が小さいところ(患者数が$15$以下)ではほぼ完全に重なっており、確率が大きいところでは、理論値と実験値のプロットが少しのズレがあるが、ほぼ一致していることがわかる。 #figure( caption: [課題(4)-2: 二項分布の期待値の計算結果], table( columns: 3, stroke: (none), table.header( [試行回数],[期待値],[期待値の絶対誤差] ), table.hline(), [100], [24.400], [0.600], [1,000], [24.880], [0.120], [$1$万], [24.989], [0.011], [$10$万], [24.979], [0.021], [$100$万], [24.993], [0.007], [$1,000$万], [24.998], [0.002], [$1$億], [25.000], [0.000], table.hline(), ) ) <tab:binomial_expectation> #figure( image("../figs/patients_exp.png", width: 90%), caption: [課題(4)-2: 二項分布の実験値], ) <fig:binomial> #figure( image("../figs/patients_comp.png", width: 90%), caption: [課題(4)-2: 二項分布の理論値と実験値の比較], ) <fig:binomial_comp>
https://github.com/MyPedagogicalRessources/Demo-git-typst
https://raw.githubusercontent.com/MyPedagogicalRessources/Demo-git-typst/main/TP1-Gh-Classroom.typ
typst
#import "TP_Commons.typ": * = Github Classroom Prenez des notes ! Github Classroom est un outil qui permet aux enseignants de créer des devoirs et des exercices pratiques pour les étudiants. Les étudiants peuvent ensuite cloner le dépôt de l'enseignant, travailler sur les exercices et les devoirs, et les soumettre pour évaluation. https://classroom.github.com == Créer un devoir Pour créer un devoir, l'enseignant doit se connecter à Github Classroom et suivre les étapes suivantes : 1. Créer une organisation sur Github. 2. Créer un dépôt pour le devoir. 3. Créer un lien d'invitation pour les étudiants. 4. Partager le lien d'invitation avec les étudiants. #remarque(title: "Attention", fill: orange)[Le contenu de ce chapitre a été généré principalement par Copilot !] == Superviser avec Git4School (made in IRIT!) https://git4school.firebaseapp.com/home
https://github.com/xsro/xsro.github.io
https://raw.githubusercontent.com/xsro/xsro.github.io/zola/typst/nlct/solution/3.24.typ
typst
#import "common.typ":exercise,solve #exercise(code:" 3.24 ")[ Let $V: RR times RR^n arrow RR$ be continuously differentiable. Suppose that $V(t,0)=0$ for all $t >= 0$ and $ V(t,x) >= c_1||x||^2; norm((diff V)/(diff x)(t,x)) <= c_4 norm(x), forall (t,x) in [0,infinity) times D $ where $c_1$ and $c_4$ are positive constants and $D subset RR^n$ is a convex domain that contains the origin $x=0$ + Show that $V(t,x) <= 1/2 c_4 norm(x)^2$ for all $x in D$. \ Hint: Use the representation $V(t,x)=integral_0^1 (diff V)/(diff x) (t,sigma x) d sigma x $ + Show that the constants $c_1$ and $x_4$ must satisfy $2 c_1 <= c_4$ + Show that $W(t,x)=sqrt(V(t,x))$ satisfies the Lipschitz condition $ |W(t,x_2)-W(t,x_1)| <= c_4 /(2 sqrt(c_1)) norm(x_2-x_1), forall t >= 0, forall x_1,x_2 in D $ ] #solve(1) $ V(t,x)=integral_0^1 (diff V)/(diff V)(t,sigma x) d x <= integral_0^1 norm((diff V)/(diff x)(t,sigma x)) norm(x) d sigma <= integral_0^1 c_4 sigma d sigma norm(x)^2 <= 1/2 c_4 norm(x)^2 $ #solve(2) Since $ c_1 norm(x)^2 <= V(t,x) <= 1/2 c_4 norm(x)^2, forall x in D $<Vbound> we must have $c_1<=1/2 c_4$ #solve(3) Consider two ponts $x_1$ and $x_2$ such that $alpha x_1 + (1-alpha)x_2 != 0$ for all $0<=alpha<=1$; that is, the orgin does not lie on the line connecting $x_1$ and $x_2$. The Jacobian $[diff W \/ diff x]$ is defined for every $x=alpha x_1 + (1-alpha )x_2$ and given by $ (diff W)/(diff x)(t,x)=1/(2 sqrt(V(t,x))) (diff V)/(diff x)(t,x) $ By the mean value theorem, there is $alpha^* in (0,1)$ such that, with $z=alpha^* x_1+(1-alpha^*)x_2$ $ W(t,x_2)-W(t,x_1) =(diff W)/(diff x)(t,z) (x_2-x_1) = 1/(2 sqrt(V(t,z))) (diff V)/(diff x)(t,z)(x_2-x_1) $ Hence $ |W(t,x_2)-W(t,x_1)| <= 1/(2 sqrt(c_1) norm(z)) $ Consider now the case when the origin lies on the line connecting $x_1$ and $x_2$; that is , $0=alpha_0 x_1+(1-alpha_0)x_2$ for some $alpha_0 in [0,1]$. We have $ abs(W(t,x_2)-W(t,0)) = abs(W(t,x_2))=sqrt(V(t,x_2)) <=sqrt(c_4/2)norm(x_2)\ abs(W(t,x_1)-W(t,0)) = abs(W(t,x_1))=sqrt(V(t,x_1)) <=sqrt(c_4/2)norm(x_1)\ abs(W(t,x_2)-W(t,x_1)) =abs(W(t,x_2)-W(t,0)+W(t,0)-W(t,x_1)) <=sqrt(c_4/2)(norm(x_1)+norm(x_2)) $ Since the origin lies on the line connecting $x_1$ and $x_2$, we have $norm(x_2)+norm(x_1)=norm(x_2-x_1)$. We also have $1<=sqrt(c_4 \/ 2 c_1)$. Therefore, $ abs(W(t,x_2)-W(t,x_1))<=c_4/(2sqrt(c_1))norm(x_2-x_1) $
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/completion/item_shadow.typ
typst
Apache License 2.0
// contains: aa,aac #let aa = 1; #let aa() = 1; #let aac() = 1; #aac(/* range -2..0 */);
https://github.com/Shambuwu/stage-docs
https://raw.githubusercontent.com/Shambuwu/stage-docs/main/documenten/analyserapport.typ
typst
#align( center, text( size: 1.2em, [ *Competentie: Analyseren* \ Analyse en inzichten \ ], ) ) #align( center, figure( image("../bijlagen/analyserapport/OIG.jpg", width: 400pt ) ) ) #let date = datetime( year: 2023, month: 6, day: 30 ) #place( bottom + left, text[ *Student:* <NAME> \ *Studentnummer:* 405538 \ *Datum:* #date.display() \ *Onderwerp:* Competentie: Analyseren \ *Opleiding:* HBO-ICT \ *Studiejaar:* 3 \ ] ) #place( bottom + right, image("../bijlagen/logo.png", width: 175pt) ) #pagebreak() #set heading(numbering: "1.1") #show heading: it => { set block(below: 10pt) set text(weight: "bold") align(left, it) } #outline( title: [ *Inhoudsopgave* ], ) #set page( numbering: "1 / 1", number-align: right, ) #pagebreak() = Inleiding Volgens de stichting HBO-i is de competentie analyseren gedefinieerd als: "Het analyseren van processen, producten en informatiestromen in hun onderlinge samenhang en de context van de omgeving." #cite("hbo-i") Dit is een brede definitie van de competentie analyseren. In dit document wordt de competentie analyseren toegelicht aan de hand van de stageopdracht en de bijbehorende verrichte analyses. == Doel van het systeem Het doel van het systeem is om een gebruiksvriendelijke webapplicatie te ontwerpen en ontwikkelen voor de voedingsindustrie. Deze applicatie stelt gebruikers in staat om recepten en ingrediënten te zoeken, filteren, visualiseren en alternatieve ingrediënten te identificeren. De focus ligt op het bieden van waardevolle inzichten, het verduurzamen van recepten en het versnellen van productinnovatie voor bedrijven in de voedingsindustrie. == Omvang van het systeem De omvang van het systeem omvat de ontwikkeling en implementatie van een datavisualisatietool voor de voedingsindustrie. De tool omvat een gebruiksvriendelijke en intuïtieve webapplicatie die gebruikers in staat stelt om recepten en ingrediënten te zoeken, filteren, visualiseren en alternatieve ingrediënten te identificeren. De tool biedt functionaliteiten zoals zoek- en filterfunctionaliteiten, gegevensvisualisatie en het vergelijken van alternatieve ingrediënten op basis van voedingswaarde, smaak en vergelijkbare recepten. == Doelstellingen en succescriteria van het project De volgende doelstelligen en succescriteria zijn opgesteld voor het project: - *Doelstellingen:* - Het ontwerpen en ontwikkelen van een datavisualisatietool voor de voedingsindustrie. - Het creëren van een gebruiksvriendelijke en intuïtieve webapplicatie die gebruikers in staat stelt om recepten en ingrediënten te zoeken, filteren, visualiseren en alternatieve ingrediënten te identificeren. - Het bieden van waardevolle inzichten aan gebruikers om recepten te verduurzamen, alternatieven te identificeren en productinnovatie te versnellen. - *Succescriteria:* - De webapplicatie is ontworpen en ontwikkeld. - Gebruikers kunnen recepten en ingrediënten zoeken, filteren en visualiseren, - Gebruikers kunnen alternatieve ingrediënten identificeren op basis van voedingswaarde, smaak en vergelijkbare recepten. - Het project wordt binnen de stageperiode afgerond. == Overzicht De volgende structuur wordt gehanteerd voor het document: #box(height: 125pt, columns(2)[ #set par(justify: true) + *Inleiding:* In de inleiding wordt de context en achtergrond van de stage beschreven. Daarnaast wordt de probleemstelling van het stageproject toegelicht. + *Voorgesteld systeem:* In dit hoofdstuk wordt het voorgestelde systeem beschreven. De functionele en nonfunctionele eisen worden beschreven en toegelicht. + *Systeemmodellen:* In dit hoofdstuk worden de systeemmodellen beschreven. De scenario's en het use case model worden beschreven en toegelicht. + *Reflectie:* In dit hoofdstuk wordt de reflectie beschreven. De reflectie bevat een terugblik op de stageperiode en de stageopdracht. ] ) #pagebreak() = Huidig systeem == Overzicht Het huidige systeem voor het verkennen van de data vereist dat gebruikers handmatig Cypher queries uitvoeren om de gewenste informatie te verkrijgen. Dit kan een uitdaging zijn voor gebruikers zonder ervaring met de querytaal, omdat ze mogelijk niet bekend zijn met de juiste syntax en zoektermen. Bovendien kan het opstellen van complexe queries tijdrovend zijn en de kans op fouten vergroten. Dit gebrek aan een intuïtieve en gebruiksvriendelijke interface voor het verkennen van de data kan leiden tot beperkte mogelijkheden voor gebruikers om gerichte zoekopdrachten uit te voeren en relevante informatie te vinden. Het kan ook leiden tot een gebrek aan overzichtelijke informatie en contextuele inzichten, waardoor gebruikers moeite kunnen hebben om de juiste conclusies te trekken en weloverwogen beslissingen te nemen. == Risico's De volgende risico's kunnen zich voordoen bij het huidige systeem. De ernst van de risico's is op een schaal van 1 tot 5, waarbij 1 staat voor een laag risico en 5 voor een hoog risico. De volgende risico's zijn geïdentificeerd: #table( columns: (auto, 1fr, auto), [*Risico*], [*Beschrijving*], [*Ernst*], [Tijdrovende queries], [Het handmatig schrijven van complexe queries kan veel tijd in beslag nemen en de efficiëntie van het werk belemmeren. Bovendien is er een hoger risico op typfouten en andere fouten bij het formuleren van de queries.], [4], [Beperkte flexibiliteit], [Het huidige systeem biedt beperkte flexibiliteit bij het verkennen van de data. Gebruikers zijn beperkt tot het handmatig uitvoeren van cypher queries.], [3], [Technische afhankelijkheid], [ Het huidige systeem is afhankelijk van de technische vaardigheden van gebruikers om queries correct uit te voeren. Dit kan leiden tot een gebrek aan consistentie en betrouwbaarheid in de verkregen resultaten.], [3], [Gebrek aan gebruiksvriendelijkheid], [Het ontbreken van een intuïtieve en gebruiksvriendelijke interface maakt het moeilijk voor gebruikers om efficiënt met het systeem te werken en de gewenste informatie te verkrijgen.], [2] ) #pagebreak() = Voorgesteld systeem == Overzicht Op basis van de requirements die zijn vastgesteld tijdens vergaderingen met de opdrachtgever is het volgende voorgestelde systeem ontworpen en ontwikkeld. Het voorgestelde systeem is een webapplicatie die gebruikers in staat stelt om recepten en ingrediënten te zoeken, filteren, visualiseren en alternatieve ingrediënten te identificeren. De webapplicatie bestaat uit drie componenten: de frontend, backend en database. De frontend is de gebruikersinterface van de webapplicatie. De backend is de server die de frontend bedient en de database is de opslagplaats van de gegevens. De frontend en backend communiceren met elkaar via een API. De frontend en backend communiceren met de database via een database driver. Enkele voordelen van dit ontwerp zijn: - *Verbeterde efficiëntie:* Het voorgestelde systeem stelt gebruikers in staat om snel en gemakkelijk recepten en ingrediënten te zoeken en filteren. Dit bespaart tijd en moeite in vergelijking met handmatig queries uitvoeren in een grafendatabase. - *Gebruiksvriendelijkheid:* De webapplicatie is ontworpen met een intuïtieve en gebruiksvriendelijke interface, waardoor gebruikers zonder technische kennis er gemakkelijk mee kunnen werken. - *Gegevensgestuurde inzichten:* De webapplicatie verzamelt gegevens over recepten en ingrediënten. Deze gegevens kunnen geanalyseerd worden om waardevolle inzichten te bieden aan gebruikers. Dit stelt gebruikers in staat om geïnformeerde beslissingen te nemen en hun recepten te verduurzamen. == Functionele eisen De volgende functionele eisen zijn vastgesteld tijdens vergaderingen met de opdrachtgever: + Gebruikers moeten via een webapplicatie gebruik kunnen maken van de functionaliteiten van het systeem. - Dit betekent dat het systeem toegankelijk moet zijn via een webbrowser en dat gebruikers alle beschikbare functionaliteiten kunnen gebruiken zonder de noodzaak van andere software of platformen. + Gebruikers moeten recepten en ingrediënten kunnen zoeken. - Het systeem moet voorzien in een zoekfunctionaliteit waarmee gebruikers naar specifieke recepten en ingrediënten kunnen zoeke op basis van bijvoorbeeld naam, ingrediënten, voedingswaarde, allergenen, etc. + Gebruikers moeten recepten en ingrediënten kunnen filteren. - Het systeem moet de mogelijkheid bieden om recepten en ingrediënten te filteren op basis van verschillende parameters, zoals voedingswaarde, allergenen, etc. + Gebruikers moeten recepten en ingrediënten kunnen visualiseren. - Het systeem moet visuele weergaven en presentaties van een recepten- en ingrediëntennetwerk kunnen genereren op basis van gebruikersvoorkeuren. + Gebruikers moeten alternatieve ingrediënten kunnen identificeren op basis van voedingswaarde, smaak en vergelijkbare recepten. - Het systeem moet een functie hebben waarmee gebruikers alternatieve ingrediënten kunnen vinden die voldoen aan specifieke criteria, zoals vergelijkbare voedingswaarde, smaakprofiel of geschiktheid voor vergelijkbare recepten. == Niet-functionele eisen De volgende niet-functionele eisen zijn vastgesteld tijdens vergaderingen met de opdrachtgever: + De webapplicatie moet gebruiksvriendelijk en intuïtief zijn. - De webapplicatie moet eenvoudig en intuïtief te gebruiken zijn voor verschillende gebruikers, ongeacht hun technische achtergrond of ervaring met gelijkaardige systemen, Gebruikers moeten gemakkelijk navigeren, de gewenste functionaliteiten vinden en de gewenste resultaten verkrijgen. + De webapplicatie moet snel reageren. - De webapplicatie moet snel reageren op gebruikersinteracties, zoals het invoeren van zoekopdrachten, het selecteren van filters en het genereren van visualisaties. Vertragingen moeten tot een minimum worden beperkt om een vlotte en responsieve gebruikerservaring te garanderen. + Het systeem moet schaalbaar zijn. - Het systeem moet schaalbaar zijn om te voldoen aan de behoeften toenemende datahoeveelheden. + Het systeem moet een beschikbaarheid van 99% hebben, met maximaal 1 uur downtime per maand. - Het systeem moet een hoge beschikbaarheid hebben om te garanderen dat gebruikers ten alle tijde toegang hebben tot de applicatie. #pagebreak() = Systeemmodellen == Scenario's De volgende gebruiksscenario's beschrijven het gedrag en de interactie van het systeem met de gebruikers en andere systemen. De scenario's helpen met het begrijpen van functionele en niet-functionele requirements van het systeem. Enkele scenario's zijn geïdentificeerd tijdens vergaderingen met de opdrachtgever en het ontwerpproces: + *Scenario 1:* Visualiseren van receptrelaties - De gebruiker bevindt zich op de startpagina van de webapplicatie. - De gebruiker voert specifieke zoektermen in, zoals "pasta" en "pesto". - Het systeem kan de zoekresultaten verfijnen door filteropties toe te passen, als "vegetarisch" en "glutenvrij". - Het systeem genereert een visuele weergave van de recepten en ingrediënten die voldoen aan de zoekcriteria. - De gebruiker klikt op een specifiek recept om gedetailleerde informatie te bekijken. - De gebruiker kan doorklikken naar de ingrediënten van het recept. + *Scenario 2:* Identificeren van alternatieve ingrediënten - De gebruiker bevindt zich op de startpagina van de webapplicatie. - De gebruiker voert specifieke zoektermen in, zoals "pasta" en "pesto". - Het systeem kan de zoekresultaten verfijnen door filteropties toe te passen, als "vegetarisch" en "glutenvrij". - Het systeem genereert een visuele weergave van de recepten en ingrediënten die voldoen aan de zoekcriteria. - De gebruiker klikt op een specifiek recept om gedetailleerde informatie te bekijken. - De gebruiker klikt op een specifiek ingrediënt om gedetailleerde informatie te bekijken. - Het systeem genereert een lijst met alternatieve ingrediënten op basis van voedingswaarde, smaak en vergelijkbare recepten. == Use case model en dynamisch model De volgende use cases beschrijven de functionaliteiten van het systeem. De use cases zijn geïdentificeerd tijdens vergaderingen met de opdrachtgever en het ontwerpproces. De use cases zijn voorzien van een sequentiediagram om de interactie tussen de actoren en het systeem te visualiseren. De volgende use cases zijn geïdentificeerd: *Use case 1:* Zoeken naar recepten - Doel: Gebruikers kunnen recepten zoeken op basis van specifieke zoektermen. - Hoofdactoren: Gebruiker - Voorwaarden: De gebruiker bevindt zich op de startpagina van de webapplicatie. - Beschrijving: + De gebruiker bevindt zich op de startpagina van de webapplicatie. + De gebruiker voert specifieke zoektermen in, zoals "pasta" en "pesto". + De gebruiker klikt op de zoekknop. + Het systeem genereert een visuele weergave van de recepten en ingrediënten die voldoen aan de zoekcriteria. + De gebruiker kan doorklikken naar de ingrediënten van het recept. #figure( image("../bijlagen/analyserapport/use_case_1.png", width: 325pt ), caption: [Zoeken naar recepten], kind: "diagram", supplement: [*Use case*] ) *Use case 2:* Identificeren van alternatieve ingrediënten - Doel: Gebruikers kunnen alternatieve ingrediënten identificeren op basis van voedingswaarde, smaak en vergelijkbare recepten. - Hoofdactoren: Gebruiker, Systeem - Voorwaarden: De gebruiker bevindt zich op de startpagina van de webapplicatie. - Beschrijving: + De gebruiker bevindt zich op de startpagina van de webapplicatie. + De gebruiker voert specifieke zoektermen in, zoals "pasta" en "pesto". + De gebruiker klikt op de zoekknop. + Het systeem genereert een visuele weergave van de recepten en ingrediënten die voldoen aan de zoekcriteria. + De gebruiker klikt op een specifiek recept om gedetailleerde informatie te bekijken. + De gebruiker klikt op een specifiek ingrediënt om gedetailleerde informatie te bekijken. + Het systeem genereert een lijst met alternatieve ingrediënten op basis van voedingswaarde, smaak en vergelijkbare recepten. #figure( image("../bijlagen/analyserapport/use_case_2.png", width: 325pt ), caption: [Vinden van alternatieve ingrediënten], kind: "diagram", supplement: [*Use case*] ) *Use case 3:* Filteren van recepten - Doel: Gebruikers kunnen recepten filteren op basis van specifieke criteria. - Hoofdactoren: Gebruiker, Systeem - Voorwaarden: De gebruiker bevindt zich op de startpagina van de webapplicatie. - Beschrijving: + De gebruiker bevindt zich op de startpagina van de webapplicatie. + De gebruiker kan filteropties toepassen, zoals "vegetarisch" en "glutenvrij". + De gebruiker klikt op de zoekknop. + Het systeem genereert een visuele weergave van de recepten en ingrediënten die voldoen aan de filtercriteria. #figure( image("../bijlagen/analyserapport/use_case_3.png", width: 325pt ), caption: [Filteren van recepten], kind: "diagram", supplement: [*Use case*] ) #pagebreak() = Conclusie De huidige systeemvereisten voor het verkennen van de data, waarbij gebruikers handmatig Cypher queries moeten uitvoeren, brengen uitdagingen met zich mee. Het gebrek aan een intuïtieve en gebruiksvriendelijke interface beperkt de mogelijkheden van gebruikers om gerichte zoekopdrachten uit te voeren en relevante informatie te verkrijgen. Dit kan leiden tot inefficiëntie, fouten en een gebrek aan overzichtelijke informatie. Om deze beperkingen aan te pakken, is het essentieel om een nieuwe datavisualisatietool te ontwikkelen die gebruikers in staat stelt om op een intuïtieve en gebruiksvriendelijke manier toegang te krijgen tot de benodigde informatie. Het voorgestelde systeem biedt een verbeterde efficiëntie, gebruiksvriendelijkheid en gegevensgestuurde inzichten, waardoor gebruikers in staat worden gesteld om geïnformeerde beslissingen te nemen en recepten te verduurzamen. #pagebreak() = Literatuurlijst #bibliography( title: "", "../bibliografie/hayagriva.yml" ) #pagebreak() = Bronnen #align(left, table( columns: (auto, auto, auto), rows: (auto, auto, auto), align: left, inset: 10pt, stroke: none, [*Bijlagen*], [], [], [Hanzehogeschool Groningen logo], [Hanzehogeschool Groningen], [https://freebiesupply.com/logos/hanzehogeschool-groningen-logo/], [Titelpagina figuur], [DALL-E-2, OpenAI], [bijlagen -> analyserapport -> OIG.jpg], [Sequentiediagram 1], [<NAME>], [bijlagen -> analyserapport -> use_case_1.png], [Sequentiediagram 2], [<NAME>], [bijlagen -> analyserapport -> use_case_2.png], [Sequentiediagram 3], [<NAME>], [bijlagen -> analyserapport -> use_case_3.png], ) )
https://github.com/indicatelovelace/typstTemplates
https://raw.githubusercontent.com/indicatelovelace/typstTemplates/main/themes/dhbw-thesis/template/main.typ
typst
MIT License
// #import "@local/dhbw-thesis:0.1.0": conf #import "@local/dhbw-thesis:0.1.0": conf #show: doc => conf( title: "Mustertitel", /* author is an array of dicts. The only key that is necessary is "name". Any other property supplied is printed at the bottom end of the page, as per the guidelines, in the format "#key: #value", in the given order. For multiple authors, this data is collected, deduplicated, and either displayed as per usual or, if possible, listed as line seperated values. */ authors: ( ( name: "<NAME>", "<NAME>": "Musterkurs, Mustermatrikelnummer", ), ( name: "<NAME>", "<NAME>nummer": "Musterkurs, Mustermatrikelnummer", "Gutachter der DHBW:": "Prof. Max Musterprofessor" ), ), courseName: "Musterkurs", submissionDate: datetime.today().display(), // expects content, not a datetime, so use .display() submissionPlace: "Musterort", thesisType: "Musterarbeit", // e.g Bachelor Thesis companyLogo: [], // expects any content, e.g. an image universityLogo: image("pics/dhbwLogo.svg"), university: "DHBW Ravensburg", // e.g. DHBW Ravensburg abstractTitle: none, // No abstract if none abstract: none, appendix: none, // no appendix if none glossary: none, // the user is expected to create their own glossarium, with a package of their choice, or by hand. This can of course also include an list of symbols etc. No glossarium is printed if none bibliographyTitle: none, // no bibliography if none bibliographyFiles: (), bibliographyStyle: "ieee", // no specific requirements here, I recommend you use IEEE declarationOnHonour: true, draft: true, language: "de", // enable language-specific quotes with ISO 639-1/2/3 language code font: "IBM Plex Serif", fontSize: 12pt, smallcapsFont: "Linux Libertine", mathFont: "IBM Plex Serif", outlines: ((none, none),), // e.g. (table, "List of Tables") in the submitted order equationTitle: none, // no equation table if none, equations are not a regular figure, only block equations are listed equationSupplement: none, // no eqution supplement if none doc, ) /* Write your thesis here */
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/045_Kamigawa%3A%20Neon%20Dynasty.typ
typst
#import "@local/mtgset:0.1.0": conf #show: doc => conf("Kamigawa: Neon Dynasty", doc) #include "./045 - Kamigawa: Neon Dynasty/001_Kaito Origin Stories: A Test of Loyalty & The Path Forward.typ" #include "./045 - Kamigawa: Neon Dynasty/002_Episode 1: A Stranger in Eiganjo.typ" #include "./045 - Kamigawa: Neon Dynasty/003_Episode 2: Lies, Promises, and Neon Flames.typ" #include "./045 - Kamigawa: Neon Dynasty/004_Episode 3: An Unexpected Alliance.typ" #include "./045 - Kamigawa: Neon Dynasty/005_Episode 4: The Break-In.typ" #include "./045 - Kamigawa: Neon Dynasty/006_Episode 5: Threads of War.typ" #include "./045 - Kamigawa: Neon Dynasty/007_The Blade Reflected and Reborn.typ" #include "./045 - Kamigawa: Neon Dynasty/008_The Epoch Engine.typ" #include "./045 - Kamigawa: Neon Dynasty/009_The Foes Who Make Us.typ"
https://github.com/Gowee/typst-clatter
https://raw.githubusercontent.com/Gowee/typst-clatter/main/clatter.typ
typst
MIT License
#let clatter-wasm = plugin("./clatter.wasm") #let pdf417(text, width: auto, height: auto, direction: auto) = { let args = arguments(bytes("0"), bytes("0")) // horizontal by default if direction != auto or (width != auto and height != auto) { if direction == "vertical" or (direction != "horizontal" and width < height) { args = arguments(bytes("0"), bytes("1")) // vertical: w < h } else { args = arguments(bytes("1"), bytes("0")) // horizontal: w > h } } image.decode(clatter-wasm.pdf417(bytes(text), ..args), format: "svg", width: width, height: height, fit: "contain") }
https://github.com/abaisero/abaisero-typst
https://raw.githubusercontent.com/abaisero/abaisero-typst/main/abaisero.typ
typst
/* math */ #let naturalset = $bb(N)$ #let integerset = $bb(Z)$ #let realset = $bb(R)$ #let kstar = $\ ^*$ #let kplus = $\ ^+$ #let softmax = $op("softmax")$ #let softmin = $op("softmin")$ #let sign = $op("sign")$ /* linalg */ #let diag = $op("diag")$ #let rank = $op("rank")$ #let trace = $op("tr")$ #let colspace = $op("col")$ #let nullspace = $op("ker")$ #let spanspace = $op("span")$ #let tr = $\ ^top$ #let inv = $\ ^(-1)$ #let pinv = $\ ^+$ #let it = $\ ^(-top)$ #let pit = $\ ^(+top)$ /* optim */ #let argmax = $op("argmax")$ #let argmin = $op("argmin")$ #let opt = $\ ^*$ /* stats */ #let Cov = $bb(C)$ #let Ent = $bb(H)$ #let Exp = $bb(E)$ #let Ind = $bb(I)$ #let KL = $op("KL")$ #let DKL = $D_(KL)$ #let MI = $bb(I)$ #let Var = $bb(V)$ /* dists */ #let Categorical = $op("Categorical")$ #let Dirichlet = $op("Dirichlet")$ #let Normal = $op("Normal")$ #let Uniform = $op("Uniform")$ /* ml */ #let data = $cal(D)$ #let loss = $cal(L)$ #let nll = $op("nll")$ #let mse = $op("MSE")$ /* rl */ #let aset = $cal(A)$ #let bset = $cal(B)$ #let hset = $cal(H)$ #let oset = $cal(O)$ #let rset = $cal(R)$ #let sset = $cal(S)$ #let nohistory = $epsilon$ #let policy = $pi$ #let qpolicy = $Q^pi$ #let qmodel = $hat(Q)$ #let vpolicy = $V^pi$ #let vmodel = $hat(V)$ #let upolicy = $U^pi$ #let umodel = $hat(U)$ #let apolicy = $A^pi$ #let amodel = $hat(A)$ /* misc */ #let iter(i) = $\ ^((#i))$ #let sim = $tilde.op$
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_155%20-%20Differential%20Analysis%201/Course%20Notes.typ
typst
#import "/Templates/generic.typ": latex #import "/Templates/notes.typ": chapter_heading #import "@preview/ctheorems:1.1.0": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #import "/Templates/math.typ": * #import "/Templates/monograph.typ": frontpage #import "@preview/cetz:0.2.2": canvas, draw, tree #show: latex #show: chapter_heading #show: thmrules #show: symbol_replacing #show: equation_references #set pagebreak(weak: true) #show: doc => frontpage( toptitle: [Differential Analysis], name: [<NAME>], middletitle: [My course notes for the Fall 2024 Differential Analysis course by #link("https://math.mit.edu/directory/profile.html?pid=2579")[<NAME>] at MIT], doc, ) #set page(margin: (x: 2cm, top: 2cm, bottom: 2cm), numbering: "1") #set enum(numbering: "(1)", indent: 1em) #outline() #pagebreak(weak: true) = Introduction The first ideas resembling distribution theory was developed by <NAME> in 1945, although he called it 'Generalized functions' and was motivated by Physics. Some earlier attempts include those by <NAME> in 1926 and H. Poincare in 1890, who were mainly motivated by generalized solutions to PDEs. // TODO: Fill in full name. To see the need for such a theory let us start with an example. #example("Vibrating string")[ Imagine that you have a string attached on both ends to an immovable surface. The string, for small perturbations, is well modeled by the differential equation $u_(x x) - u_(t t) = 0$. D'Alambert solved this equation and showed that solutions are of the form $u(x,t) = f(x+t) - g(x-t)$ where $f,g in C^2(RR)$. Euler then asked the question, what if we replace $f,g$ with continuous functions, is there still a sense in which $u$ solves the equation. ] #example("Poisson's problem")[ Consider the equation $Delta u = f$ where $f$ is a fixed function. It was well known even by Newton that if one defines $u$ as a potential, in the form $ u(x) = - integral 1 / (4 pi abs(x - y)) f(y) d y $ then $u$ satisfies the desired equation as long as $f in C^infinity_c (RR)$. Laplace then considered the function $ G_y (x) = 1 / abs(x-y) $ and calculated that it is harmonic outside of its singularity. The Laplacian argument was then that since $ Delta integral 1 / abs(x - y) f(y) d y = integral (Delta 1 / abs(x-y)) f( y ) d y $ then since the left term here is zero outside of a set of measure zero, this entire integral must also be zero and thus the solution makes no sense. The mistake Laplace makes here is the illegal swapping of the Laplacian and the integral, and it is this mistake that we will attempt to fix in first section of this course. ] We will go about this by extending the idea of differentiation through integration by parts. We recall that for all functions $f in C^1_c (RR)$ and $g in C^1 (RR)$ we have $ integral f g' = - integral f' g. $ #definition[ A function $h in L^1_("loc")$ is called a weak derivative of a function $f in L^1_("loc")$ if $ integral f g' = - integral h g $ for all $g in C_c^infinity (RR)$. ] #example[ Let $f = |x|$ and $ h = cases(1 : x >= 0, -1 : x < 0) $ We now claim that $h$ is the weak derivative of $f$, to see this we compute $ - integral h g = integral_(-infinity)^0 g - integral_0^infinity g = - integral_(-infinity)^0 x g' + integral_0^infinity x g' = integral_RR |x| g' $ ] #example[ We will say that $u$ is a weak solution to the wave equation if $ integral u (diff_(x x) phi - diff_(t t) phi) = 0 $ for any $phi in C_c^infinity (RR^2)$. Assume that $u(x,t) = f(x+t)$ is a continuous function on $RR$ as we wanted to check before, we want to show that it is indeed a weak solution to the wave equation. To check this we want to show that $ 0 = integral u (diff_(x x) - diff_(t t)) phi. $ To show this we will need to use a small lemma, #lemma("Approximation by smooth functions")[ If $f in C(RR^n)$ and $K$ is a compact set in $RR^n$, then there is a sequence of $C^infinity$-smooth functions $f_n in C^infinity$ such that $f_n -> f$ pointwise on $K$. ] Applying this lemma to $f$ we get such a sequence $f_n$, and thus define $u_n(x,t) = f_n(x + t)$. We now compute $ integral u (diff_(x x) - diff_(t t)) phi = integral (u - u_n) (diff_(x x) - diff_(t t)) phi + integral u_n (diff_(x x) - diff_(t t)) phi. $ The right term here is zero by the standard argument for smooth solutions. The left term is dominated by $|K| sup_K abs(u - u_n)$ which vanishes in the limit. ] Now this process we just went through is the template for the study of distributions, so we shall part by part formalize every part of this example. #definition("Test Functions")[ The space $C_c^infinity (Omega)$ for any open set $Omega$ is called the space of 'Test Functions'. Let $f$ be any test function and $f_n$ be any sequence. We say that $f_n$ converges to $f$ if there is some compact set $K$ containing the support of $f$ and the entire sequence $f_n$, such that for any $N$ $ max_(abs(alpha) <= N) sup_(x in K) abs(f^alpha (x) - f_n^alpha (x)) ->_(n -> infinity) 0. $ For brevity we will refer to the left side here as $norm(f - f_n)_(C^N (K))$ ]<def-test_function> Let us now define the main object of study for the next few lectures. #definition("Distribution")[ A *Distribution* is a linear functional $ell : C_c^infinity (Omega) -> RR$ which is 'bounded', in the sense that for any compact set $K$ there are some constants $C,N$ such that $ abs(ell(phi)) <= C dot norm(phi)_(C^N (K)) $ for any test function $phi$. ]<def-distribution> To distinguish a distribution from the function it is acting on, we will write $ell(phi)$ as $pair(ell,phi)$. #example[ The most important examples of a distributions are regular locally integrable functions. For any function $g in L^1_("loc")(Omega)$, $g$ acts a linear functional by $ pair(g, f) = integral_Omega g f. $ One can easily check that this is indeed a bounded linear functional in $f$. ] #example[ The Dirac Delta functional $delta$ is defined by $ delta(f) = f(0). $ One can easily check that it is indeed a distribution and also that it is not given by a locally integrable function. ] #definition[ The *derivative* of a distribution $ell$ is the distribution $rho$ defined by $ pair(ell, f') = - pair(rho, f) $ for all $f$. ] #example[ The derivative of $delta$ is the distribution $delta'$ which gives $-f'(0)$ for any test function $f$. ] = Appendix #definition[ We denote $L^1_("loc")$ the set of "locally integrable functions" that is measurable functions $f$ with $integral_K |f| < infinity$ for all compact sets $K$. ]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/math/multiline-01.typ
typst
Other
// Test text before first alignment point. $ x + 1 &= a^2 + b^2 \ y &= a + b^2 \ z &= alpha dot beta $
https://github.com/maxgraw/bachelor
https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/7-conclusion/0-index.typ
typst
Im folgenden Kapitel wird zunächst eine Zusammenfassung dieser Arbeit formuliert. Anschließend wird ein Ausblick auf mögliche zukünftige Entwicklungen gegeben. == Zusammenfassung Das Ziel dieser Arbeit lag in der Konzeption und Implementierung einer Augmented-Reality-Konstruktionsumgebung für Möbelsysteme auf Basis von WebXR. Auf Grundlage einer Analyse des Standes der Technik sowie der theoretischen Grundlagen wurde ein Konzept für die Anwendung entwickelt und anschließend implementiert. Darüber hinaus wurde die Anwendung im Rahmen der Arbeit von <NAME> in ein bestehendes System integriert. Hierbei konnte das Konzept in Bezug auf die technische Umsetzung erfolgreich umgesetzt werden und durch die Integration in das Shop-System von <NAME> konnte die Anwendung in einem breiteren Kontext getestet werden. Um die Usability und User Experience der Anwendung zu evaluieren, wurde eine Studie entwickelt und durchgeführt. Die Studie lässt die Schlussfolgerung zu, dass die Anwendung eine positive Usability sowie User Experience bietet. Darüber hinaus konnte durch die Einbindung der Evaluation von <NAME> hervorgehoben werden, dass die Anwendung auch in ein externes System integriert werden kann und hierbei beim Entscheidungsprozess unterstützt. Es lässt sich somit feststellen, dass sich mithilfe von WebXR eine komplexe AR-Anwendung entwickeln lässt, die sowohl auf technischer als auch in der Usability und User Experience funktional und positiv bewertet wird. WebXR erweist sich daher als eine valide Alternative im Bereich der Augmented-Reality-Technologien. == Ausblick Augmented Reality hat sich in den letzten Jahren zu einer bedeutenden Technologie entwickelt. Im Rahmen dieser Arbeit wurde der aktuelle Stand der Technik analysiert und verschiedene Beispielanwendungen vorgestellt, die Augmented Reality bereits in der Möbelbranche einsetzen. Diese Untersuchung zeigt, dass Augmented Reality in einer Vielzahl von Anwendungen im Bereich der Möbelbranche verwendet wird. Die meisten dieser Anwendungen werden als native Anwendungen entwickelt und beschränken sich hauptsächlich auf die Visualisierung von Möbelstücken. Diese Arbeit demonstriert, dass WebXR eine valide Alternative für die Entwicklung von Augmented Reality Anwendungen in der Möbelbranche darstellt. Die Ergebnisse der durchgeführten Studie stimmen mit weiteren Forschungen in diesem Bereich überein und zeigen, dass die Usability und User Experience der Anwendung positiv bewertet wird. Allerdings müssen die Ergebnisse der Studie aufgrund der hohen Streuung kritisch betrachtet werden. Daher sollte diese Arbeit als Grundlage für weiterführende Forschungen und Entwicklungen dienen. Die Interaktion der Anwendung stellt ihr Alleinstellungsmerkmal im Vergleich mit anderen Anwendungen dar. Gerade diese Interaktion erfordert weitere Untersuchungen. Im Rahmen dieser Arbeit wurde nur eine einzige Form der Interaktion implementiert. Es ist jedoch denkbar, dass zusätzliche Interaktionsformen die Usability und User Experience der Anwendung weiter verbessern könnten. Zukünftige Forschungen könnten verschiedene Interaktionsmethoden miteinander vergleichen, um die optimale Lösung zu identifizieren. Darüber hinaus kann die Funktionalität der Anwendung auf weitere Möbelsysteme erweitert werden. Dies könnte die Anwendbarkeit und den Nutzen der Anwendung erheblich steigern. Außerdem besteht die Möglichkeit, die entwickelte Anwendung als Grundlage für neue, innovative Anwendungen zu nutzen, die über die ursprünglichen Anwendungsfälle hinausgehen. Die Integration der Anwendung in andere Systeme ist ebenfalls ein vielversprechender Forschungsansatz. Durch die Einbindung in bestehende Systeme könnte die Anwendung nahtlos in verschiedene Arbeitsabläufe integriert werden, was die Effizienz und Benutzerfreundlichkeit weiter erhöhen würde. Zukünftige Arbeiten sollten diese Integrationsmöglichkeiten genauer untersuchen und mögliche Synergien mit anderen Technologien und Systemen evaluieren. Zusammenfassend lässt sich sagen, dass Augmented Reality in der Möbelbranche ein enormes Potenzial hat. Diese Arbeit liefert eine Grundlage für weitere Forschungen und Entwicklungen in diesem Bereich, mit dem Ziel, die Interaktion, Usability und Funktionalität von Augmented Reality Anwendungen kontinuierlich zu verbessern und zu erweitern.
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-111E0.typ
typst
Apache License 2.0
#let data = ( (), ("SINHALA ARCHAIC DIGIT ONE", "No", 0), ("SINHALA ARCHAIC DIGIT TWO", "No", 0), ("SINHALA ARCHAIC DIGIT THREE", "No", 0), ("SINHALA ARCHAIC DIGIT FOUR", "No", 0), ("SINHALA ARCHAIC DIGIT FIVE", "No", 0), ("SINHALA ARCHAIC DIGIT SIX", "No", 0), ("SINHALA ARCHAIC DIGIT SEVEN", "No", 0), ("SINHALA ARCHAIC DIGIT EIGHT", "No", 0), ("SINHALA ARCHAIC DIGIT NINE", "No", 0), ("SINHALA ARCHAIC NUMBER TEN", "No", 0), ("SINHALA ARCHAIC NUMBER TWENTY", "No", 0), ("SINHALA ARCHAIC NUMBER THIRTY", "No", 0), ("SINHALA ARCHAIC NUMBER FORTY", "No", 0), ("SINHALA ARCHAIC NUMBER FIFTY", "No", 0), ("SINHALA ARCHAIC NUMBER SIXTY", "No", 0), ("SINHALA ARCHAIC NUMBER SEVENTY", "No", 0), ("SINHALA ARCHAIC NUMBER EIGHTY", "No", 0), ("SINHALA ARCHAIC NUMBER NINETY", "No", 0), ("SINHALA ARCHAIC NUMBER ONE HUNDRED", "No", 0), ("SINHALA ARCHAIC NUMBER ONE THOUSAND", "No", 0), )
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/contrib/typlite/README.md
markdown
Apache License 2.0
# Typlite Converts a subset of typst to markdown. ## Usage ```shell # default output is main.md typlite main.typ # specify output typlite main.typ output.md ```
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/op_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // With non-text content $ op(#underline[ul]) a $
https://github.com/VisualFP/docs
https://raw.githubusercontent.com/VisualFP/docs/main/SA/design_concept/content/poc/scope.typ
typst
#import "../../../acronyms.typ": * = Scope The goal of the #ac("PoC") application is to show that the visual concept described in @design-iteration-2 works. To show that, the #ac("PoC") needs to implement - UC1 - Simple function composition - UC3 - Function composition using lists - UC4 - Function composition using higher-order functions - UC5 - Curried Functions - UC6 - Recursive function composition as described in @use-cases. Although all other described use cases are integral to a fully functioning visual editor for functional programming as well, they are not included in the #ac("PoC") due to time constraints.
https://github.com/angelacorte/presentation-2024-acsos-multiplatform-self-organization
https://raw.githubusercontent.com/angelacorte/presentation-2024-acsos-multiplatform-self-organization/master/README.md
markdown
Apache License 2.0
# Typst slides template This is a template for creating slides using [Typst](https://typst.app/) and [Polylux](https://github.com/andreasKroepelin/polylux). This template uses the [metropolis](https://github.com/andreasKroepelin/polylux/blob/main/themes/themes.typ) theme with some customizations for code snippets. ## Usage 1. Rename the `slides-template.typ` file to your desired name. 2. Edit the file by adding your content. 3. Push the file to the repository 4. Access to the released slides in the `Releases` section of the repository.
https://github.com/Mufanc/hnuthss-template
https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/pages/abstract.typ
typst
#import "/configs.typ": font, fontsize #import "/components.typ": paragraph, fp, anchor #let weight-calc(bold) = if bold { "bold" } else { "regular" } #let keyword(lang, words) = [ #set text(font: font.sans, weight: weight-calc(lang == "en")) #set par(first-line-indent: 0em) #let prefix = if lang == "zh" { "关键词:" } else { "Key Words: " } #let suffix = words.join(if lang == "zh" { ";" } else { "; " }) #text(size: fontsize.L4, prefix) #text(size: fontsize.L4s, suffix) ] #let title(content, bold: false) = [ #align(center, text(size: fontsize.L3, font: font.sans, weight: weight-calc(bold), content)) ] #let titlesmall(content, bold: false) = [ #align(center, text(size: fontsize.L3s, font: font.sans, weight: weight-calc(bold), content)) ] #let abstract(content) = [ #content ] #let zh = abstract[ #titlesmall[一些约束体系量子哈密顿中算符次序问题] #v(2em) #title[摘#h(2em)要] #anchor[摘 要] #v(2em) #paragraph[ 根据微分几何中的曲面论,用两个变量就可以完全参数化一个二维曲面。也就是,当一个粒子约束在曲面上运动时,只需要两个独立的变量就可以完全刻画粒子的运动。由于粒子的运动可以在笛卡儿坐标下分解为三个互相正交的方向,动能算符 $T$ 和三个笛卡儿动量 $P_i (i = 1,2,3)$ 的关系似乎为: $ T = 1/(2 mu) sum_(i = 1)^3 P_i^2 $ 其中 $P_i (i = 1,2,3)$ 为厄密算符。事实上,在量子力学中,除非粒子是在自由空间中运动或在经典极限下,此式是不正确的。在存在约束时,上式应代之以 $ T = 1/(2 mu) sum_(i=1)^3 1/(f_i (x, y, z)) P_i f_i (x, y, z) P_i $ 其中 $f_i (i = 1,2,3)$ 是非平凡的函数。本文用圆环面,旋转抛物面,旋转单叶双曲面,磁场中的荷电平面转子,球面转子等体系中的量子运动说明函数 $f_i (i = 1,2,3)$ 是存在的。 在不同的矢势下,荷电粒子的力学动量从而动能的表达式是不同的。本文研究了它们之间和量子规范相因子的关系,发现规范相因子会自然出现在动能算符中。 ] #v(2em) #keyword("zh", ("量子力学", "算符次序", "厄密算符", "正则量子化", "规范变换")) ] #let en = abstract[ #titlesmall(bold: true)[The operator ordering problem in quantum Hamiltonian for some constraint systems] #v(2em) #title(bold: true)[Abstract] #anchor[Abstract] #v(2em) #paragraph[ According to surface theory in differential geometry, the two-dimensional surface is parameterized by two variables. This is, when a particle moves on the surface, only two variables suffice to describe the motion of the particle. However, when examining the same problem in the physical point of view, the motion of the particle can also be described in the three-dimensional Cartesian coordinates. Explicitly, the relation between kinetic energy $T$ and Hermitian Cartesian momentum $P_i (i = 1,2,3)$ is speciously $ T = 1/(2 mu) sum_(i = 1)^3 P_i^2 $ which holds either for the system being free of constraint or for the system in classical limit. Moreover, under constraint, above expression should be replaced by, $ T = 1/(2 mu) sum_(i=1)^3 1/(f_i (x, y, z)) P_i f_i (x, y, z) P_i $ where $f_i (i = 1,2,3)$ are the non-trivial functions. This paper utilizes quantum motions on the torus surface, paraboloid of revolution, hyperboloid of revolution of one sheet, charged planar and spherical rotator etc., to demonstrate the existence of the function $f_i$. Since different vector potentials lead to different kinetic energies, the relationship between these kinetic energies and the gauge phase factors, are studied. Results show that the gauge phase factor can appear in the kinetic operator naturally. ] #v(1em) #keyword("en", ("quantum mechanics", "operator ordering", "Hermitian operator", "canonical quantization", "gauge transformation")) ]
https://github.com/GYPpro/Java-coures-report
https://raw.githubusercontent.com/GYPpro/Java-coures-report/main/Report/Java语言 实验报告模板 2023-10-8-20231214155905.typ
typst
// Some definitions presupposed by pandoc's typst output. #let blockquote(body) = [ #set text( size: 0.92em ) #block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body] ] #let horizontalrule = [ #line(start: (25%,0%), end: (75%,0%)) ] #let endnote(num, contents) = [ #stack(dir: ltr, spacing: 3pt, super[#num], contents) ] #show terms: it => { it.children .map(child => [ #strong[#child.term] #block(inset: (left: 1.5em, top: -0.4em))[#child.description] ]) .join() } #let conf( title: none, authors: none, date: none, abstract: none, cols: 1, margin: (x: 1.25in, y: 1.25in), paper: "us-letter", lang: "en", region: "US", font: (), fontsize: 11pt, sectionnumbering: none, doc, ) = { set page( paper: paper, margin: margin, numbering: "1", ) set par(justify: true) set text(lang: lang, region: region, font: font, size: fontsize) set heading(numbering: sectionnumbering) if title != none { align(center)[#block(inset: 2em)[ #text(weight: "bold", size: 1.5em)[#title] ]] } if authors != none { let count = authors.len() let ncols = calc.min(count, 3) grid( columns: (1fr,) * ncols, row-gutter: 1.5em, ..authors.map(author => align(center)[ #author.name \ #author.affiliation \ #author.email ] ) ) } if date != none { align(center)[#block(inset: 1em)[ #date ]] } if abstract != none { block(inset: 2em)[ #text(weight: "semibold")[Abstract] #h(1em) #abstract ] } if cols == 1 { doc } else { columns(cols, doc) } } #show: doc => conf( cols: 1, doc, ) #underline[#strong[面向对象程序设计/Java语言]] #strong[课程实验项目目录] 学生姓名:xx 学号:yy 专业:zz #align(center)[#table( columns: 6, align: (col, row) => (auto,auto,auto,auto,auto,auto,).at(col), inset: 6pt, [序号], [实验项目编号], [实验项目名称], [\*实验项目类型], [成绩], [指导教师], [], [], [命令行编译运行], [设计性], [], [干晓聪], [], [], [IDE], [设计性], [], [干晓聪], [], [], [sis01学校信息系统C版], [设计性], [], [干晓聪], [], [], [sis01学校信息系统Java版], [设计性], [], [干晓聪], [], [], [sis02封装数据C版], [设计性], [], [干晓聪], [], [], [sis02封装数据Java版], [设计性], [], [干晓聪], [], [], [sis03a用文件封装函数C版], [设计性], [], [干晓聪], [], [], [sis03封装函数Java版], [设计性], [], [干晓聪], [], [], [sis03b用结构体封装函数C版], [设计性], [], [干晓聪], [], [], [sis04封装成员方法], [设计性], [], [干晓聪], [], [], [sis05构造函数], [设计性], [], [干晓聪], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], ) ] = 命令行编译运行 <命令行编译运行> \*实验项目类型:演示性、验证性、综合性、设计性实验。 \*此表由学生按顺序填写。 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 命令行编译运行 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 学习安装、手工使用编译器 #strong[二、实验环境] 计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 下载安装OpenJDK的Oracle版本,最好把JDK\\bin目录加入系统PATH。通过命令javac p/A.java && java p.A来编译运行 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码如下] package p; class A{ public static void main\( String\[\] args ) throws Exception { System.out.printf\( \"Hello World!\\n\" ); } } #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = IDE <ide> \*实验项目类型:演示性、验证性、综合性、设计性实验。 \*此表由学生按顺序填写。 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 IDE 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 学习使用IDE #strong[二、实验环境] 计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 可下载自动安装工具,或手工选择download package的java版本。目前的Eclipse自带自家的Open JDK。调整好自己习惯的Perspective。新建Java Project,新建一个类,菜单方式运行 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码如下] package p; class A{ public static void main\( String\[\] args ) throws Exception { System.out.printf\( \"Hello World!\\n\" ); } } #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis01学校信息系统C版 <sis01学校信息系统c版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis01学校信息系统C版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 复习面向过程编程,实现一个简单的SIS学校信息系统 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 记录一张表,含ID、姓名 输入add xxx yyy添加一条记录,ID为xxx,姓名为yyy 输入show显示所有记录 输入exit退出 用字符数组实现,不用字符串 只用给出的输入、输出单个字符的函数getchar\()和putchar\() 假设输入很规范,英文全小写,每行最多100字符,首尾无空格,词语间用1个空格隔开,命令不会输错,学号最多10字符,姓名最多10字符,最多100条记录 用一个长度101的字符数组接收输入的每一行命令。根据命令开头若干个字符分情况处理,信息记录在两个长度为100的数组中,数组的每个元素是长11的字符数组 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis01,C版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis01学校信息系统Java版 <sis01学校信息系统java版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis01学校信息系统Java版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 复习面向过程编程,实现一个简单的SIS学校信息系统 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 记录一张表,含ID、姓名 输入add xxx yyy添加一条记录,ID为xxx,姓名为yyy 输入show显示所有记录 输入exit退出 用字符数组实现,不用字符串 只用给出的输入、输出单个字符的函数getchar\()和putchar\() 假设输入很规范,英文全小写,每行最多100字符,首尾无空格,词语间用1个空格隔开,命令不会输错,学号最多10字符,姓名最多10字符,最多100条记录 用一个长度101的字符数组接收输入的每一行命令。根据命令开头若干个字符分情况处理,信息记录在两个长度为100的数组中,数组的每个元素是长11的字符数组 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis01,Java版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis02封装数据C版 <sis02封装数据c版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis02封装数据C版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 将数据封装到结构体里面 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 建立一个Person结构体,含两个成员:ID、姓名。数据存放在指向Person结构体的指针数组中,注意内存的分配、释放 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis02,C版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis02封装数据Java版 <sis02封装数据java版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis02封装数据Java版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 将数据封装到类里面 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 建立一个Person类,含两个成员:ID、姓名。数据存放在Person对象数组中 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis02,Java版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis03a用文件封装函数C版 <sis03a用文件封装函数c版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis03a用文件封装函数C版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 将函数封装到文件里面 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 把Person相关的处理函数create, destroy, setIdName, show放入Person文件里面 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis03a] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis03封装函数Java版 <sis03封装函数java版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis03封装函数Java版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 将函数封装到类里面 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 把Person相关的处理函数create, setIdName, show以static的形式放入Person类里面 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis03,Java版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis03b用结构体封装函数C版 <sis03b用结构体封装函数c版> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis03b用结构体封装函数C版 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 将函数封装到结构体里面 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 把Person相关的处理函数destroy, setIdName, show,通过函数指针,放入Person结构体里面 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis03b,C版] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis04封装成员方法 <sis04封装成员方法> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis04封装成员方法 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 学习成员方法 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 将类Person的两个static函数setIdName, show改为成员方法 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis04] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果] = sis05构造函数 <sis05构造函数> 课程名称 面向对象程序设计/Java语言 成绩评定 实验项目名称 sis05构造函数 指导教师 #underline[干晓聪] 实验项目编号 实验项目类型 #underline[设计性] 实验地点 #underline[数学系机房] 学生姓名 #underline[xx] 学号 #underline[yy] 学院 #underline[信息学院] 系 #underline[数学系] 专业 zz 实验时间 年 月 日 午~ 月 日 午 温度 ℃湿度 #strong[一、实验目的] 学习构造函数 #strong[二、实验环境] 计算机:计算机:PC X64 / PC X86 操作系统:Windows / Linux / MacOS 编程语言:Java / Python / C++ IDE:Eclipse / Visual Studio Code / IntelliJ IDEA #strong[三、程序原理] 将类Person的第一个static的create函数改为构造函数。充分利用创建对象时的流程,甚至可省略构造函数 #emph[可在此补充详细原理与代码结构的简要说明] #strong[四、程序代码] #emph[\/\/ 参考代码sis05] #strong[五、出现的问题、原因与解决方法] #strong[六、测试数据与运行结果]
https://github.com/Tran-Thu-Le/tybank
https://raw.githubusercontent.com/Tran-Thu-Le/tybank/main/bank.typ
typst
// #import "macros.typ": * #import "utils.typ": variation_table #import "@preview/cetz:0.2.2": canvas, plot //the variable will contain all the following questions // please do not delete it #let questions = () // ---------------------------------------- // Macros // ---------------------------------------- #let dxdydz = $d x d y d z$ #let dxdy = $d x d y$ #let dx = $d x$ #let dy = $d y$ #let vara = 3 // #let vara = 5 // #let vara = 7 // #let vara = 9 #let pttq = [phương trình tổng quát] #let Pttq = [Phương trình tổng quát] #let ptts = [phương trình tham số] #let Ptts = [Phương trình tham số] #let vector(x)=$arrow(#x)$ #let square(x) = calc.pow(x, 2) // -------------------------- // Cau 1 // -------------------------- #let stem = [#Ptts của đường thẳng $Delta: x+y-1=0$ có phương trình: #let row0 = "x -oo ... -1 ... 2 ... +oo" #let row1 = "y' ... - 0 + | - ..." #let row2 = "y +oo down 2 up +oo down -oo" #variation_table(row0, row1, row2) ] #let choice0 = [$display(cases(x= t, y= 1-t))$] // #let choice0 = [#lorem(5)] #let choice1 = [$display(cases(x= 2t, y= 1-t))$] #let choice2 = [$display(cases(x= t, y= 1+t))$] #let choice3 = [$display(cases(x= 2t, y= 1+t))$] #let correct_choice = 0 #let solution = [Ta có xét điểm $M_0(0, 1)$ thuộc $Delta$. Vì $Delta$ có vector pháp tuyến $vector(n)=(1,1)$, suy ra vector chỉ phương $vector(u)=(1, -1)$. Từ đó áp dụng công thức #ptts.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 2 // -------------------------- #let stem = [#Pttq của đường thẳng $Delta: display(cases(x=1+2t, y=1-3t))$ là: #align(center, canvas(length: 1cm, { plot.plot(size: (7, 4), // align: center, x-tick-step: none, x-ticks: ((-calc.pi, $-pi$), (0, $0$), (1, $x$), (calc.pi, $pi$)), y-tick-step: 0.5, { plot.add-fill-between(domain: (-calc.pi, calc.pi), calc.sin, // First function/data calc.cos, label: "diff" ) } ) } ) ) ] #let choice0 = [$3x+2y-5=0$] #let choice1 = [$-3x+2y +1=0$] #let choice2 = [$3x-2y-1=0$] #let choice3 = [$2x+3y-5=0$] #let correct_choice = 0 #let solution = [Rút $t$ ta được $display(t = (x-1)/2=(y-1)/(-3))$. Nên #pttq là: $-3(x-1) = 2(y-1) <=> 3x+2y -5=0$] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 3 // -------------------------- #let stem = [#Pttq đi qua hai điểm $A(0, 1)$ và $B(2, 2)$ là:] #let choice0 = [$x-2y+2=0$ ] #let choice1 = [$2x+y-6=0$] #let choice2 = [$-2x-y +6=0$ ] #let choice3 = [$2x+y-1=0$] #let correct_choice = 0 #let solution = [Chọn $vector(u)= vector(A B) = (2, 1)$, suy ra $vector(n) = (-1, 2)$. Ta chọn điểm $A(0, 1)$ thuộc đường thẳng (ta cũng có thể chọn $B$). #Pttq có dạng $-(x-0)+2(y-1)=0 <=> -x+2y -2=0$.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "liên tục") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 4 // -------------------------- #let stem = [#Pttq của đường thẳng $Delta'$ đi qua $A(0, 1)$ vuông góc với đường thẳng $Delta: 2x+y-1=0$ là:] #let choice0 = [$x-2y+2=0$] #let choice1 = [$x-2y+1=0$] #let choice2 = [$2x-y +1=0$] #let choice3 = [$2x-y-1=0$] #let correct_choice = 0 #let solution = [Vì vector pháp tuyến của $Delta$, đặt là $vector(n)=(2, 1)$, là chỉ phương của $Delta'$ (hãy vẽ hình để kiểm tra). Nên vector pháp tuyến của $Delta'$ là $vector(n')=(-1, 2)$. Vậy #pttq của $Delta'$ là $-(x-0)+2(y-1) <=> -x+2y-2=0$.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "đạo hàm cấp 1") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 5 // -------------------------- #let stem = [Khoảng cách giữa hai đường thẳng song song $Delta_1: y=2x+1$ và $Delta_2: y=2x+6$ là:] #let choice0 = [$sqrt(2)$] #let choice1 = [$sqrt(3)$] #let choice2 = [$sqrt(5)$] #let choice3 = [$sqrt(7)$] #let correct_choice = 2 #let solution = [ - _Cách 1._ Áp dụng công thức khoảng cách giữa hai đường thẳng song song được $ d(Delta_1, Delta_2)= (|6-1|)/sqrt(1+(-2)^2)=sqrt(5) $. - _Cách 2._ Lấy một điểm thuộc đường này tính khoảng cách đến đường kia.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 6 // -------------------------- #let stem = [Góc giữa hai đường thẳng $Delta_1: y=-0.5x +1$ và $Delta_2: y=2x+1$ bằng:] #let choice0 = [$0^o$] #let choice1 = [$30^o$] #let choice2 = [$90^o$] #let choice3 = [$120^o$] #let correct_choice = 2 #let solution = [ - _Cách 1._ Tích hai hệ số góc bằng $-1$ nên hai đường thẳng vuông góc với nhau. - _Cách 2._ Tính góc giữa hai đường thẳng theo công thức. Ta có $vector(n_1) = (0.5, 1)$ và $vector(n_2) = (-2, 1)$, nên (chú ý cẩn thận quên dấu trị tuyệt đối) $ cos(Delta_1, Delta_2) = |cos(vector(n_1), vector(n_2))| =(|0.5 times (-2) + 1 times 1|)/(sqrt(0.5^2+1^2) dot sqrt((-2)^2+1)) =0. $ Bấm máy $cos^(-1)(0)=90^o $. ] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 7 // -------------------------- #let stem = [Vị trí tương đối của hai đường thẳng $Delta_1: y=2x+1$ và $Delta_2: 3x+y-7=0$ là:] #let choice0 = [song song] #let choice1 = [cắt nhau] #let choice2 = [trùng nhau] #let choice3 = [không xác định] #let correct_choice = 1 #let solution = [Đưa hai đường thẳng đã cho về #pttq $ Delta_1: y=2x-y+1=0 quad quad Delta_2: 3x+y-7=0 $ - _Cách 1._ Chú ý $vector(n_1)=(2,-1)$ và $vector(n_2)=(3, 1)$ khác tỷ lệ, nên hai đường đã cho cắt nhau. - _Cách 2._ Bấm máy hệ phương trình, ta thấy có nghiệm, nên hai đường đã cho cắt nhau. ] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 8 // -------------------------- #let stem = [Viết #pttq của đường trung trực của cạnh $B C$ trong tam giác $Delta A B C$ với $A(0, 0), B(1, 2), C(3, 0)$.] #let choice0 = [$y=x+1$] #let choice1 = [$y=x-1$] #let choice2 = [$x+y=1$] #let choice3 = [$x+y=-1$] #let correct_choice = 1 #let solution = [Gọi $Delta$ là đường trung trực của $B C$. Ta có $Delta$ đi qua trung điểm $M$ của $B C$ và nhận $vector(B C)$ làm vector pháp tuyến. Ta tính được $M(2, 1)$ (trung bình tọa độ của $B$ và $C$) và $vector(n)= vector(B C)=(2, -2)$ (tọa độ $C$ trừ tọa độ $B$). #Pttq $Delta: 2(x-2)-2(y-1)=0 <=> 2x-2y-2=0$. Ta có thể viết lại $Delta: y=x-1$.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 9 // -------------------------- #let stem = [Cho tam giác $Delta A B C$ với $A(0, 0), B(1, 2), C(3, 0)$. Viết #pttq của đường thẳng đi qua $B$ và song song với cạnh $A C$.] #let choice0 = [$x=-1$] #let choice1 = [$x=1$] #let choice2 = [$y=0$] #let choice3 = [$y=2$] #let correct_choice = 3 #let solution = [Ta có $B(1, 2)$ và $vector(u)=vector(A C)=(3, 0)$, suy ra $vector(n)=(0, 3)$. Nên có $0(x-1)+3(y-2)=0 <=> y=2$.] #let tags = ("chapter": 1, "difficulty": 1, "topic": "giới hạn") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion) // -------------------------- // Cau 10 // -------------------------- #let stem = [Trong tam giác $Delta A B C$, biết //$A(1, 3), B(0, 0)$, $C(4,0)$. Biết phương trình đường cao $A H: y=x$ và đường cao $B K: x=1$. Tìm #pttq đường cao $C P$.] #let choice0 = [#Pttq $C P: x+3y-8=0$] #let choice1 = [#Pttq $C P: x+3y-4=0$] #let choice2 = [#Pttq $C P: x+2y-4=0$] #let choice3 = [#Pttq $C P: x+2y-8=0$] #let correct_choice = 1 #let solution = [Gọi $X$ là trực tâm là giao của $A H$ và $B K$. ta có $X=(1,1)$. Đường cao $C P$ cũng chính là $C X$. Ta có điểm $C(4, 0)$ và $vector(u)= vector(C X)=(-3, 1)$ hay $vector(n)=(1,3)$. Nên $1(x-4)+3(y-0)=0 <=> x+3y -4=0.$] #let tags = ("chapter": 1, "difficulty": 3, "topic": "cực trị không điều kiện") // template #let aquestion = ( "stem": stem, "choice0": choice0, "choice1": choice1, "choice2": choice2, "choice3": choice3, "correct_choice": correct_choice, "solution": solution, "tags": tags ) #questions.push(aquestion)
https://github.com/wyatt-feng/sustech-ug-thesis-typst
https://raw.githubusercontent.com/wyatt-feng/sustech-ug-thesis-typst/main/metadata.typ
typst
Other
// Import `template_zh.typ` if using Chinese // or else import `template_en.typ` if using English // 如果是中文论文,则导入 `template_zh.typ` #import "resources/template_en.typ": * #let meta = conf.with( // CLC 分类号 class: "", // Number 编号 serialnumber: "", // UDC udc: "", // 密级 only for the Chinese template confidence: "", // Available for reference, only for the English template // 中文版不用管 available_for_reference: true, author: "<NAME>", studentid: "12010000", title: "Undergraduate Thesis Template", subtitle: "A Typst One", department: "Computer Science and Engineering", major: "Some Major", supervisor: "Prof. <NAME>", date: "June 30, 2024", cabstract: "本文介绍了 sustech-ug-thesis-typst 文档模板所提供的功能。", ckeywords: ("Typst", "模板"), eabstract: "This document introduces the features of the sustech-ug-thesis-typst template.", ekeywords: ("Typst", "Template"), acknowledgements: [感谢 Typst 开发者的辛勤付出。], linespacing: 1.5em, parspacing: 1.5em, outlinedepth: 3, blind: false, )
https://github.com/typst/templates
https://raw.githubusercontent.com/typst/templates/main/test.typ
typst
MIT No Attribution
#import "./charged-ieee/lib.typ": * #show: ieee.with( title: [A typesetting system to untangle the scientific writing process], abstract: [ The process of scientific writing is often tangled up with the intricacies of typesetting, leading to frustration and wasted time for researchers. In this paper, we introduce Typst, a new typesetting system designed specifically for scientific writing. Typst untangles the typesetting process, allowing researchers to compose papers faster. In a series of experiments we demonstrate that Typst offers several advantages, including faster document creation, simplified syntax, and increased ease-of-use. ], authors: ( ( name: "<NAME>", department: [Co-Founder], organization: [Typst GmbH], location: [Berlin, Germany], email: "<EMAIL>" ), ( name: "<NAME>", department: [Co-Founder], organization: [Typst GmbH], location: [Berlin, Germany], email: "<EMAIL>" ), ), index-terms: ("Scientific writing", "Typesetting", "Document creation", "Syntax"), ) = Introduction Scientific writing is a crucial part of the research process, allowing researchers to share their findings with the wider scientific community. However, the process of typesetting scientific documents can often be a frustrating and time-consuming affair, particularly when using outdated tools such as LaTeX. Despite being over 30 years old, it remains a popular choice for scientific writing due to its power and flexibility. However, it also comes with a steep learning curve, complex syntax, and long compile times, leading to frustration and despair for many researchers. ```rs fn main() { println!("Hello world"); } ``` #figure( caption: [The famous `hello world` program, in Rust.], ```rs fn main() { println!("Hello world!"); } ``` )
https://github.com/JosephBoom02/Appunti
https://raw.githubusercontent.com/JosephBoom02/Appunti/main/Anno_3_Semestre_2/Ingegneria_del_Software/ingegneria-del-software.typ
typst
#import "@preview/physica:0.9.0": * #import "@preview/i-figured:0.2.3" #import "@preview/cetz:0.1.2" #import "@preview/xarrow:0.2.0": xarrow #let title = "Ingegneria del Software" #let author = "<NAME>" #set document(title: title, author: author) #cetz.canvas({ import cetz.draw: * // Your drawing code goes here }) #show math.equation: i-figured.show-equation.with(level: 2, only-labeled: true) #show link: set text(rgb("#cc0052")) #show ref: set text(green) #set page(margin: (y: 0.5cm)) #set text(13pt) #set heading(numbering: "1.1.1.1.1.1") //#set math.equation(numbering: "(1)") #set math.mat(gap: 1em) //Code to have bigger fraction in inline math #let dfrac(x,y) = math.display(math.frac(x,y)) //Equation without numbering (obsolete) #let nonum(eq) = math.equation(block: true, numbering: none, eq) //Usage: #nonum($a^2 + b^2 = c^2$) #let space = h(5em) //Color #let myblue = rgb(155, 165, 255) #let myred = rgb(248, 136, 136) //Shortcut for centered figure with image #let cfigure(img, wth) = figure(image(img, width: wth)) //Usage: #cfigure("Images/Es_Rettilineo.png", 70%) #let nfigure(img, wth) = figure(image("images/"+img, width: wth)) #set highlight(extent: 2pt) //Code to have sublevel equation numbering /*#set math.equation(numbering: (..nums) => { locate(loc => { "(" + str(counter(heading).at(loc).at(0)) + "." + str(nums.pos().first()) + ")" }) },) #show heading: it => { if it.level == 1 { counter(math.equation).update(0) } }*/ // //Shortcut to write equation with tag aligned to right #let tageq(eq,tag) = grid(columns: (1fr, 1fr, 1fr), column-gutter: 1fr, [], math.equation(block: true ,numbering: none)[$eq$], align(horizon)[$tag$]) // Usage: #tageq($x=y$, $j=1,...,n$) // Show title and author #v(3pt, weak: true) #align(center, text(18pt, title)) #v(8.35mm, weak: true) #align(center, text(15pt, author)) #v(8.35mm, weak: true) #outline() //Justify text = Diagrammi UML == Premessa - In questo blocco vedremo i principali Diagrammi UML per la fasi di Analisi del Problema e del Progetto - per ora non vedremo i diagrammi di deployment e dei componenti - In particolare: - Diagramma dei Package e Diagramma delle Classi → parte “*statica*” dell'Architettura Logica e dell'Architettura del Sistema - definiscono le entità di sistema senza analizzare come possano interagire tra loro - Diagramma di Sequenza → parte “*interazione*” dell'Architettura Logica e dell'Architettura del Sistema - definiscono come le entità, definite nella parte precedente, interagiscono tra loro - Diagramma di Stato e Diagramma delle Attività → parte “*comportamentale*” dell'Architettura Logica e dell'Architettura del Sistema - definiscono il comportamento delle entità del sistema - Per ogni Diagramma vedremo solo i concetti fondamentali - In caso di dubbi fare riferimento alla specifica UML 2.5.1 == Unified Modeling Language - È un *linguaggio* che serve per visualizzare, specificare, costruire, documentare un sistema e gli elaborati prodotti durante il suo sviluppo - Ha una semantica e una notazione standard, basate su un metamodello integrato, che definisce i costrutti forniti dal linguaggio - La notazione (e la semantica) è estensibile e personalizzabile - È utilizzabile per la modellazione durante tutto il ciclo di vita del software (dai requisiti al testing) e per piattaforme e domini diversi - Combina approcci di: - modellazione dati (Entity/Relationship) - business Modeling (workflow) - modellazione a oggetti - modellazione di componenti - Prevede una serie di diagrammi standard, che mostrano differenti viste architetturali del modello di un sistema - UML è un linguaggio e non un processo di sviluppo - UML propone un ricco insieme di elementi a livello utente; tuttavia è alquanto informale sul modo di utilizzare al meglio i vari elementi - ciò implica che per comprendere un diagramma un lettore deve conoscere il contesto in cui esso è collocato == Diagrammi di UML 2.5.1 - Diagrammi di struttura: - diagramma delle classi (class) - diagramma delle strutture composite (composite structure) - diagramma dei componenti (component) - diagramma di deployment (deployment) - diagramma dei package (package) - diagramma dei profili (profile) - Diagrammi di comportamento: - diagramma dei casi d'uso (use case) - diagramma di stato (state machine) - diagramma delle attività (activity) - diagrammi di interazione: - diagramma di comunicazione (communication) - diagramma dei tempi (timing) - diagramma di sintesi delle interazioni (interaction overview) - diagramma di sequenza (sequence) #cfigure("images/image-1710162664687-0.png", 90%) == UML 2.5.1 e Visio - Visio 2016 gestisce nativamente solo alcuni dei Diagrammi di UML 2.5.1 - classi - attività - sequenza - stato - casi d'uso - È possibile però scaricare uno stencil per poter gestire anche gli altri diagrammi: http://softwarestencils.com/uml/index.html == Diagramma dei Package ==== Package - Un package, in programmazione, è un contenitore di classi - Un package, in generale, è utilizzato per raggruppare elementi e fornire loro un namespace - Un package può essere innestato in altri package - NAMESPACE: è una porzione del modello nella quale possono essere definiti e usati dei nomi - In un namespace ogni nome ha un significato univoco #cfigure("images/image-1710162829556-0.png", 90%) ==== Diagramma dei Package - Un diagramma dei package è un diagramma che illustra come gli elementi di modellazione sono organizzati in package e le relazioni (dipendenze) tra i package #cfigure("images/image-1710162883736-0.png", 90%) - Un diagramma può rappresentare package con diversi livelli di astrazione ==== Dipendenze - UML permette di rappresentare relazioni che NON sussistono fra istanze nel dominio rappresentato, ma sussistono fra gli elementi del modello UML stesso o fra le astrazioni che tali elementi rappresentano - Dipendenza: è rappresentata da una linea tratteggiata orientata che va da un elemento dipendente (Source) ad uno indipendente(Target) #cfigure("images/image-1710163145240-0.png", 80%) - Una dipendenza indica che cambiamenti dell'elemento *indipendente* influenzano l'elemento *dipendente* - modificano il significato dell'elemento dipendente - causano la necessità di modificare anche l'elemento dipendente perché i significati sono dipendenti - UML mette a disposizione nove diversi tipi di dipendenza, ma per i nostri fini consideriamo quasi sempre <<use>> #cfigure("images/image-1710163162642-0.png", 50%) ==== Diagramma dei Package - Tutti i diagrammi che utilizzeremo nella fase di analisi saranno trasformati per venir utilizzati nella fase di progettazione (in analisi definisco il "cosa" e in progettazione definisco il "come") - Quando si usa il diagramma dei package per definire la parte strutturale dell'architettura logica ricordare sempre che si stanno esprimendo *dipendenze logiche* che sussistono tra le entità del problema - Non è detto che tali dipendenze rimangano tali anche nella fase di progettazione - Esempio: in sistema per l'interpretazione di una grammatica si hanno due parti fondamentali - Lexer→strumento che legge e spezza una sequenza di caratteri in sotto-sequenze dette “token” - Parser prende in ingresso i token generati, li analizza e li elabora in base ai costrutti specificati nella grammatica stessa ==== Esempio #cfigure("images/image-1710163246985-0.png", 90%) È ovvio che è il Parser a usare il Lexer, quindi il diagramma prodotto nella fase di analisi sarà così #cfigure("images/image-1710163288049-0.png", 90%) Ma nel diagramma del progetto è il Lexer a fare il Parser #cfigure("images/image-1710174515137-0.png", 90%) == Interfaccia - Le interfacce forniscono un modo per partizionare e caratterizzare gruppi di proprietà - Un'interfaccia non deve specificare come possa essere implementata, ma semplicemente quello che è necessario per poterla realizzare - Le entità che realizzano l'interfaccia dovranno fornire una “*^^vista pubblica^^*”(attributi, operazioni, comportamento osservabile all'esterno) conforme all'interfaccia stessa - Se un'interfaccia dichiara un attributo, non significa necessariamente che l'elemento che realizza l'interfaccia debba avere quell'attributo nella sua implementazione, ma solamente che esso apparirà così a un osservatore esterno ==== Notazione #cfigure("images/image-1710163566742-0.png", 90%) Il diagramma sopra e il diagramma sotto hanno lo stesso significato == Diagramma delle Classi - Un diagramma delle classi descrive il tipo degli oggetti facenti parte di un sistema e le varie tipologie di relazioni statiche tra di essi - I diagrammi delle classi mostrano anche le proprietà e le operazioni di una classe e i vincoli che si applicano alla classe e alle relazioni tra classi - Le proprietà rappresentano le caratteristiche strutturali di una classe: - sono un unico concetto, rappresentato però con due notazioni molto diverse: attributi e associazioni - benché il loro aspetto grafico sia molto differente, concettualmente sono la stessa cosa ==== Esempio #cfigure("images/image-1710163858337-0.png", 100%) - La molteplicità da OrdinePizza a Cliente è *uno a molti*: un cliente può avere da $1$ a $n$ ordini - La molteplicità da Cliente a OrdinePizza è *univoca*: un ordine è relativo a uno e un solo cliente - Associazione di *composizione* tra Pizza e OrdinePizza - Associazione *navigabile* da Pizza e PizzaStandard: da Pizza ci interessa capire qual è la PizzaStandard, ma da PizzaStandard non ci interessa andare a Pizza, cioè ci interessa sapere ogni Pizza da quale PizzaStandard deriva - Associazione di *aggregazione* tra PizzaStandard e Ingredienti - Ogni Pizza può avere delle modifiche di ingredienti - *Classe di associazione* Modifica, che aggiunge attributi e/o comportamenti a quell'associazione - Per ogni Pizza, ogni Ingrediente è presente in una certa quantità, che può essere modificata ==== Classe - Una *classe* modella un insieme di entità (le istanze della classe) aventi tutti lo stesso tipo di caratteristiche (attributi, associazioni, operazioni...) - Ogni classe è descritta da: - un nome - un insieme di caratteristiche (feature): attributi, operazioni, ... #cfigure("images/image-1710163911503-0.png", 90%) === Attributi - La notazione degli attributi descrive una proprietà con una riga di testo all'interno del box della classe - La forma completa è: - `visibilità nome:tipo molteplicità==default {stringa di proprietà}` - Un esempio di attributo è: - `stringa: String[10] == “Pippo”{readOnly}` - L'unico elemento necessario è il nome - Visibilità: attributo pubblico (+), privato (-) o protected( == ) - Nome: corrisponde al nome dell'attributo - Tipo: vincolo sugli oggetti che possono rappresentare l'attributo - Default: valore dell'attributo in un oggetto appena creato - Stringa di proprietà: caratteristiche aggiuntive (readOnly) - Molteplicità: ... ==== Molteplicità - È l'indicazione di quanti oggetti possono entrare a far parte di una proprietà - Le molteplicità più comuni sono: - `1, 0..1, *` - In modo più generale, le molteplicità si possono definire indicando gli estremi inferiore e superiore di un intervallo (per esempio `2..4`). - Molti termini si riferiscono alla molteplicità degli attributi: - Opzionale: indica un limite inferiore di 0 - Obbligatorio: implica un limite inferiore di 1 o più - A un solo valore: implica un limite superiore di 1 - A più valori: implica che il limite superiore sia maggiore di 1, solitamente ==== Visibilità - È possibile etichettare ogni operazione o attributo con un identificatore di visibilità - UML fornisce comunque quattro abbreviazioni per indicare la visibilità: - + (public) - \- (private) - \~ (package) - \# (protected) ==== Attributi: Molteplicità - Nelle istanze, il valore di un attributo multi-valore si indica mediante un insieme #cfigure("images/image-1710168708671-0.png", 90%) ==== Operazioni - Le operazioni sono le azioni che la classe sa eseguire, e in genere si fanno corrispondere direttamente ai metodi della corrispondente classe a livello implementativo - Le operazioni che manipolano le proprietà della classe di solito si possono dedurre, per cui non sono incluse nel diagramma - La sintassi UML completa delle operazioni è `visibilità nome (lista parametri) : tipo ritorno {stringa di propr}` - Visibilità: operazione pubblica (+) o privata (-) - Nome: stringa - Lista parametri: lista parametri dell'operazione - Tipo di ritorno: tipo di valore restituito dall'operazione, se esiste - Stringa di proprietà: caratteristiche aggiuntive che si applicano all'operazione ==== Operazioni e Attributi Statici - UML chiama *static* un'operazione o un attributo che si applicano a una classe anziché alle sue istanze - Questa definizione equivale a quella dei membri statici nei linguaggi come per esempio java e C - Le caratteristiche statiche vanno sottolineate sul diagramma #cfigure("images/image-1710169509255-0.png", 60%) ==== Associazioni - Le associazioni sono un altro modo di rappresentare le proprietà - Gran parte dell'informazione che può essere associata a un attributo si applica anche alle associazioni - Un'associazione è una linea continua che collega due classi, orientata dalla classe sorgente a quella destinazione - Il nome e la molteplicità vanno indicati vicino all'estremità finale dell'associazione: - la classe destinazione corrisponde al tipo della proprietà #cfigure("images/image-1710169568202-0.png", 70%) - È possibile assegnare un nome all'associazione e anche assegnare dei nomi ai “*ruoli*” svolti da ciascun elemento di un associazione - Gran parte delle cose ce valgono per gli attributi valgono anche per le associazioni - Anche nei casi in cui non è strettamente necessario, il ruolo può essere utile per aumentare la leggibilità del diagramma - Ovviamente quando abbiamo un associazione il tipo della proprietà corrisponde alle classi che sono dall'altra parte della associazione, cioè se guardiamo a la proprietà nella classe A sarà di tipo classe B, e viceversa se guardiamo a classe B la proprietà sarà di tipo classe A #cfigure("images/image-1710169694503-0.png", 95%) ==== Associazioni Bidirezionali - Una tipologia di associazione è quella *#text(blue)[bidirezionale (o binaria)]*, costituita da una coppia di proprietà collegate, delle quali una è l'inversa dell'altra - Il collegamento inverso implica che, se seguite il valore di una proprietà e poi il valore della proprietà collegata, dovreste ritornare all'interno di un insieme che contiene il vostro punto di partenza #cfigure("images/image-1710169720862-0.png", 75%) la natura bidirezionale dell'associazione è palesata dalle *frecce di navigabilità* aggiunte a entrambi i capi della linea - Con questa specifica stiamo dicendo all'implementatore che nel progetto deve essere garantita la navigabilità in entrambi i sensi; nel caso non ci sia una specifica di navigabilità la realizzazione è deliberata all'implementatore ==== Associazioni Ternarie Quando si hanno associazioni ternarie (o che coinvolgono più classi) si introduce il simbolo “#text(blue)[diamante]” #cfigure("images/image-1710169756579-0.png", 80%) ==== Associazioni: molteplicità - La specifica UML (vista fino a ora) dichiara che la molteplicità di un'associazione è #align(center)[#text(blue)[_the multiplicity of instances of that entity is the range of number of objects that participate in the association from the perspective of the other end (the other class)_]] in italiano #align(center)[#text(blue)[_la molteplicità delle istanze di quell'entità è l'intervallo del numero di oggetti che partecipano all'associazione dal punto di vista dell'altro estremo (l'altra classe)_]] - Tale definizione (derivata dalla specifica E/R originale) non può però applicarsi alle associazioni multiple - Pertanto, come già visto nel corso SIT, la notazione usata in questo corso (e in altri) prevede che #align(center)[#text(blue)[_la molteplicità di un'associazione rappresenti il numero (minimo e massimo) di istanze dell'associazione a cui un'istanza dell'entità può partecipare_]] === Classi di Associazione - In UML non si possono aggiungere attributi come in ER, ma si creano delle classi di associazione, che permettono di aggiungere attributi, operazioni e altre caratteristiche a una classe, che sono proprie dell'associazione - In UML si indicano le classi di associazione con una linea tratteggiata, o utilizzando un rombo, come in figura #cfigure("images/image-1710169956471-0.png", 100%) - In generale le classi di associazione sono delle classi che sono venute fuori più avanti nel progetto, perché, ad esempio, l'associazione in figura si può realizzare anche con una classe normale - La classe di associazione aggiunge implicitamente un vincolo extra: ci può essere #underline[solo un'istanza della classe di associazione] tra ogni coppia di oggetti associati === Aggregazione e Composizione - #highlight(fill: myblue)[Aggregazione:] - è un associazione che corrisponde a una relazione intuitiva Intero-Parte (“*part-of*”) - è rappresentata da un *#text(blue)[diamante vuoto]* sull'associazione, posto vicino alla classe le cui istanze sono gli “interi” #cfigure("images/image-1710170826307-0.png", 40%) - è una relazione *binaria* - può essere *ricorsiva* - #highlight(fill: myblue)[Composizione:] - è un aggregazione che rispetta due vincoli ulteriori: - una parte può essere inclusa in al massimo un intero in ogni istante - solo l'oggetto intero può creare e distruggere le sue parti, cioè, le parti non esistono al di fuori dell'intero; questo implica, nell'implementazione, che non esiste un costruttore per le parti - è rappresentata da un *#text(blue)[diamante pieno]* vicino alla classe che rappresenta gli “interi” #cfigure("images/image-1710170843379-0.png", 40%) - se l'oggetto che compone viene distrutto,anche i figli vengono distrutti, anche se i figli possono essere creati/distrutti in momenti diversi dalla creazione/distruzione dell'oggetto che compone - può essere *ricorsiva* === Generalizzazione - La generalizzazione è indicata con una *freccia vuota* fra due classi dette *#text(blue)[sottoclasse]* e *#text(blue)[superclasse]* - Il significato della generalizzazione è il seguente: ogni istanza della sottoclasse è anche istanza della superclasse #cfigure("images/image-1710171110210-0.png", 40%) - La stessa superclasse può partecipare a diverse generalizzazioni - Una generalizzazione può essere *disgiunta*, cioè le sottoclassi sono disgiunte (non hanno istanze in comune), o meno #cfigure("images/image-1710171249961-0.png", 70%) - Una generalizzazione può essere *#text(blue)[completa]* (l'unione delle istanze delle sottoclassi è uguale all'insieme delle istanze della superclasse), o meno - *Attenzione*: i valori di default sono `{incomplete, disjoint}` #cfigure("images/image-1710171327443-0.png", 75%) - In una generalizzazione la sottoclasse non solo può avere caratteristiche aggiuntive rispetto alla superclasse, ma può anche *#text(blue)[sovrascrivere]* (*#text(blue)[overriding]*) le proprietà ereditate dalla superclasse #cfigure("images/image-1710171353810-0.png", 70%) === Generalizzazione Multipla - Con la *#text(blue)[generalizzazione singola]* un oggetto appartiene a un solo tipo, che può eventualmente ereditare dai suoi tipi padre - Con la *#text(blue)[generalizzazione multipla]* un oggetto può essere descritto da più tipi, non necessariamente collegati dall'ereditarietà - Si noti che la generalizzazione multipla è una cosa ben diversa dall'ereditarietà multipla - #highlight(fill: myred)[Ereditarietà multipla:] un tipo può avere più supertipi, ma ogni oggetto deve sempre appartenere a un suo tipo ben definito - #highlight(fill: myred)[Generalizzazione multipla:] un oggetto viene associato a più tipi senza che per questo debba esserne appositamente definito un altro; ad esempio, ogni istanza di persona può essere sia uomo sia studente - Se si usa la generalizzazione multipla, ci si deve assicurare di rendere chiare le combinazioni “legali” - Per questo fatto, UML pone ogni relazione di generalizzazione in un *insieme di generalizzazione* - Sul diagramma delle classi, la freccia che indica una generalizzazione va etichettata con il nome del rispettivo insieme - La generalizzazione singola corrisponde all'uso di un singolo anonimoinsieme di generalizzazione - Gli insiemi di generalizzazione sono disgiunti per definizione - Ogni istanza del supertipo può essere istanza di uno dei sottotipi all'interno di quel sottoinsieme #cfigure("images/image-1710419146192-0.png", 80%) - Questa figura ci dice che ci sono tre modi diversi di vedere una persona: - dal punto di vista del sesso - dal punto di vista dell'essere paziente o meno - dal punto di vista del ruolo ==== Relazione tra classi: sintassi - Attenzione all'uso corretto delle frecce: UML è un linguaggio (anche se grafico) e scambiare una freccia per un'altra è un errore non da poco #cfigure("images/image-1710419179129-0.png", 80%) === Classi Astratte - Una *#text(blue)[classe astratta]* è una classe che non può essere direttamente istanziata: per farlo bisogna prima crearne una sottoclasse concreta - Tipicamente, una classe astratta ha una o più operazioni astratte - Un'operazione astratta non ha implementazione - è costituita dalla sola dichiarazione, resa pubblica affinché le classi client possano usufruirne - Il modo più diffuso di indicare una classe o un'operazione astratta in UML è #text(blue)[scriverne il nome in _corsivo_] - Si possono anche rendere astratte le proprietà indicandole direttamente come tali o rendendo astratti i metodi d'accesso - A cosa servono? - servono come superclassi comuni per un insieme di sottoclassi concrete - queste sottoclassi, in virtù del subtyping, sono in qualche misura compatibili e intercambiabili fra di loro - infatti sono tutte sostituibili con la superclasse - per il principio di sostituzione di Liskov, tutte le istanze delle sottoclassi sono anche istanze delle superclasse, quindi possono attuare qualsiasi comportamento descritto dalla superclasse, inclusi i comportamenti astratti === Enumerazioni - Le enumerazioni sono usate per mostrare un insieme di valori prefissati (quelli scritti all'interno) che non hanno altre proprietà oltre al loro valore simbolico - Sono rappresentate con una classe marcata dalla parola chiave «enumeration» #cfigure("images/image-1710419317953-0.png", 23%) == Diagramma di sequenza - Diagramma che illustra le interazioni tra le classi / entità disponendole lungo una sequenza temporale - In particolare mostra i soggetti (chiamati tecnicamente *#text(blue)[Lifeline]*) che partecipano all'interazione e la sequenza dei messaggi scambiati - In ascissa troviamo i diversi soggetti (non necessariamente in ordine di esecuzione), mentre in ordinata abbiamo la scala dei tempi sviluppata verso il basso #cfigure("images/image-1710419751978-0.png", 100%) - Le linee della _Lifeline_ partono da un quadrato, un'entità definita con sintassi UML. In questo caso i ":" indicano un'istanza della classe - Tra la classe `User` e la classe `ACSystem` ci sarà sicuramente un'associazione - La figura ci die inoltre che i due messaggi che vengono inviati dopo la ricezione di `PIN` possono venire inviati in momenti diversi === Esempio #cfigure("images/image-1710419777733-0.png", 80%) - La freccia con linea continua e piena indica un messaggio sincrono, il chiamante rimane in attesa della risposta del chiamato - La freccia con linea tratteggiata e vuota è il messaggio che il chiamato invia al chiamante === Lifeline - In un diagramma di sequenza, i partecipanti solitamente sono istanze di classi UML caratterizzate da un nome - La loro vita è rappresentata da una _#text(blue)[Lifeline]_, cioè una linea #text(blue)[tratteggiata verticale ed etichettata], in modo che sia possibile comprendere a quale componente del sistema si riferisce - In alcuni casi il partecipante non è un'entità semplice, ma composta - è possibile modellare la comunicazione fra più sottosistemi, assegnando una Lifelinead ognuno di essi - L'ordine in cui le OccurrenceSpecification (cioè l'invio e la ricezione di eventi) avvengono lungo la Lifeline #text(blue)[rappresenta esattamente l'ordine in cui tali eventi si devono verificare] - La distanza (in termini grafici) tra due eventi non ha rilevanza dal punto di vista semantico - Dal punto di vista notazionale, una Lifeline è rappresentata da un rettangolo che costituisce la “testa” seguito da una linea verticale che rappresenta il tempo di vita del partecipante - È interessante notare che nella sezione della notazione, viene indicato espressamente che il “rettangolino” che viene apposto sulla Lifeline rappresenta l'attivazione di un metodo alla ricezione di un messaggio ==== Vincoli Temporali - Per modellare sistemi real-time, o comunque qualsiasi altra tipologia di sistema in cui la temporizzazione è critica, è necessario specificare un istante in cui un messaggio deve essere inviato, oppure quanto tempo deve intercorrere fra un'interazione e un'altra - Grazie, rispettivamente, a Time Constraint e Duration Constraint è possibile definire questo genere di vincoli #cfigure("images/image-1710420323320-0.png", 90%) *N.B.* Noi non utilizzeremo mai vincoli temporali #cfigure("images/image-1710420355654-0.png", 100%) === Riferimento ad altri Diagrammi - Spesso i diagrammi di sequenza possono assumereu una certa complessità - necessità di poter definire comportamenti più articolati come composizione di nuclei di interazione più semplici - Oppure, se una sequenza di eventi ricorre spesso, potrebbe essere utile definirla una volta e richiamarla dove necessario - Per questa ragione, UML permette di inserire #text(blue)[*riferimenti ad altri diagrammi*] e passare loro degli argomenti - Ovviamente ha senso sfruttare quest'ultima opzione solo se il diagramma accetta dei parametri sui quali calibrare l'evoluzione del sistema - Questi riferimenti prendono il nome di #text(blue)[InteractionUse] - I punti di connessione tra i due diagrammi prendono il nome di #text(blue)[Gate] - Un Gate rappresenta un #text(blue)[punto di interconnessione] che mette in relazione un messaggio al di fuori del frammento di interazione con uno all'interno del frammento #cfigure("images/image-1710420483529-0.png", 100%) ==== Messaggio - Un messaggio rappresenta un'interazione realizzata come comunicazione fra Lifeline - Questa interazione può consistere nella creazione o distruzione di un'istanza, nell'invocazione di un'operazione, o nella emissione di un segnale - UML permette di rappresentare tipi differenti di messaggi ====== Tipi di Messaggio - Se sono specificati mittente e destinatario è un *#text(blue)[complete message]* - la semantica è rappresentata quindi dall'occorrenza della coppia di eventi `<sendEvent, receiveEvent>` - Se il destinatario non è stato specificato è un *#text(blue)[lost message]* - in questo caso è noto solo l'evento di invio del messaggio - Se il mittente non è stato specificato è un *#text(blue)[found message]* - in questo caso è noto solo l'evento di ricezione del messaggio - Nel caso non sia noto né il destinatario né il mittente è un *#text(blue)[unknown message]* #cfigure("images/image-1710420606015-0.png", 90%) - Attenzione alle frecce che usate nei messaggi, hanno significati diversi: - #highlight(fill: myblue)[riga continua freccia piena:] indica un messaggio (*call*) *sincrono* in cui il mittente *aspetta* il completamento dell'esecuzione del destinatario prima di continuare la sua esecuzione #cfigure("images/image-1710420774542-0.png", 25%) - Necessita di un messaggio di ritorno per sbloccare l'esecuzione del mittente - #highlight(fill: myblue)[riga continua freccia vuota:] indica un messaggio *asincrono* in cui il mittente *non aspetta* il completamento dell'esecuzione del destinatario ma continua la sua esecuzione #cfigure("images/image-1710420774542-1-1710421153612-0.png", 27%) - Il valore di ritorno potrebbe o meno essere necessario, dipende dalla semantica - #highlight(fill: myblue)[riga tratteggiata freccia vuota:] indica il ritorno di un messaggio #cfigure("images/image-1710421186142-0.png", 27%) #cfigure("images/image-1710421256766-0.png", 100%) - Non specifichiamo chi è che ha inviato il messaggio, in questo diagramma non ci interessa - Register manda il messaggio `doA` all'oggetto `Sale` e aspetta la sua terminazione - Poi manda il messaggio `doB` all'oggetto `Sale` e aspetta la sua terminazione - Infine invia il messaggio `doC`, e come conseguenza `Sale` invia `doD` alla classe `Register` #cfigure("images/image-1710421277921-0.png", 100%) - `authorize` - Per realizzare `makePayament(cashTandered)` la classe `Sale` delega la classe `Payment` (creando un istanza della classe stessa), che invoca il metodo `create(casheTandered)`; dopodiché invia il messaggio sincrono `authorize`, e restituisce il controllo a `Sale` - A questo punto `Sale` può notificare l'avvenuto pagamento - `destroy` - con il messaggio `destroy` vine distrutta l'istanza di quella classe - siccome siamo in _modellazione_, non dobbiamo soffermarci sul fatto che il nostro linguaggio di programmazione possa o meno poter distruggere un istanza di una classe === Combined Fragment - La specifica di UML permette di esprimere comportamenti più complessi rispetto al singolo scambio di messaggi - È possibile rappresentare l'esecuzione atomica di una serie di interazioni, oppure che un messaggio debba essere inviato solo in determinate condizioni - A tale scopo UML mette a disposizione i #text(blue)[_Combined Fragment_], cioè contenitori atti a delimitare un'area d'interesse nel diagramma - Servono per spiegare che una certa catena di eventi, racchiusa in uno o più operandi, si verificherà in base alla semantica dell'operatore associato - Ogni fragment ha un operatore e una (eventuale) guardia ==== Tipi - #highlight(fill: myblue)[Loop:] specifica che quello che è racchiuso nell'operando sarà eseguito ciclicamente finché la guardia sarà verificata - #highlight(fill: myblue)[Alternatives] (alt): indica che sarà eseguito il contenuto di uno solo degli operandi, quello la cui guardia risulta verificata - #highlight(fill: myblue)[Optional] (opt): indica che l'esecuzione del contenuto dell'operando sarà eseguita solo se la guardia è verificata - #highlight(fill: myblue)[Break] (break): ha la stessa semantica di opt, con la differenza che in seguito l'interazione sarà terminata - #highlight(fill: myblue)[Critical]: specifica un blocco di esecuzione atomico (non interrompibile) - #highlight(fill: myblue)[Parallel] (par): specifica che il contenuto del primo operando può essere eseguito in parallelo a quello del secondo - #highlight(fill: myblue)[Weak Sequencing] (seq): specifica che il risultato complessivo può essere una qualsiasi combinazione delle interazioni contenute negli operandi, purché: - l'ordinamento stabilito in ciascun operando sia mantenuto nel complesso - eventi che riguardano gli stessi destinatari devono rispettare anche l'ordine degli operandi, cioè i messaggi del primo operando hanno precedenza su quelli del secondo - eventi che riguardano destinatari differenti non hanno vincoli di precedenza vicendevole - #highlight(fill: myblue)[StrictSequencing] (strict): indica che il contenuto deve essere eseguito nell'ordine in cui è specificato, anche rispetto agli operandi - #highlight(fill: myblue)[Ignore:] indica che alcuni messaggi, importanti ai fini del funzionamento del sistema, non sono stati rappresentati, perché non utili ai fini della comprensione dell'interazione - #highlight(fill: myblue)[Consider:] è complementare ad ignore - #highlight(fill: myblue)[Negative] (neg): racchiude una sequenza di eventi che non deve mai verificarsi - #highlight(fill: myblue)[Assertion] (assert): racchiude quella che è considerata l'unica sequenza di eventi valida - di solito è associata all'utilizzo di uno State Invariant come rinforzo #cfigure("images/image-1710421496294-0.png", 100%) #cfigure("images/image-1710421508172-0.png", 100%) Fintanto che ci sono degli `item`, io faccio `enter item` e quello mi restituisce `description total`. Quando non esistono più `item` invio il messaggio `endSale`. #cfigure("images/image-1710421519605-0.png", 90%) Fintanto che il chiamante invoca certi numeri, ridireziona quei numeri al chiamato, se viene chiamato il 991 quella è una chiamata critica che non può essere interrotta. == Diagrammi di Stato - I #text(blue)[*diagrammi di stato*] modellano la dipendenza che esiste tra lo stato di una classe / entità (cioè il valore corrente delle sue proprietà) e i messaggi e/o eventi che questo riceve in ingresso - Specifica il ciclo di vita di una classe / entità, definendo le regole che lo governano - Quando una classe / entità si trova in un certo stato può essere interessata a determinati eventi (e non ad altri) - Come risultato di un evento una classe / entità può passare a un nuovo stato (transizione) - Uno #text(blue)[stato] è una condizione o situazione nella vita di un oggetto in cui esso soddisfa una condizione, esegue un'attività o aspetta un evento - Un #text(blue)[evento] è la specifica di un'occorrenza che ha una collocazione nel tempo e nello spazio - Una #text(blue)[transizione] è il passaggio da uno stato a un altro in risposta ad un evento ==== Esempio #cfigure("images/image-1710421992238-0.png", 100%) - Quando la porta è creata, la porta è aperta. - Fintanto che la porta è aperta, è interessata a un unico messaggio: `close`; tutti gli altri messaggi vengono ignorati - Quando riceve il messaggio `close`, e, parentesi quadra che indica la #underline[guardia], `doorway -> isEmpty()`, cioè non c'è nessuno sulla soglia, la porta transita dallo stato `open` allo stato `close` - Dunque la porta si potrebbe trovare in un stato close, ed è interessata a due messaggi: - il messaggio open, che la riporta nello stato `open` - il messaggio lock, che la porta nello stato `lock` - Quando si trova nello stato lock, la porta può essere interessata solo all'evento `unlock`, che la riporta nello stato `closed` ==== Concetti - I concetti più importanti di un diagramma di stato sono: - gli #highlight(fill: myblue)[stati], indicati con rettangoli con angoli arrotondati - le #highlight(fill: myblue)[transizioni] tra stati, indicate attraverso frecce - gli #highlight(fill: myblue)[eventi] che causano transizioni, la tipologia più comune è rappresentata dalla ricezione di un messaggio, che si indica semplicemente scrivendo il nome del messaggio con relativi argomenti vicino alla freccia; quindi l'oggetto, l'istanza, riceve un messaggio, e ricevendo quel messaggio effetto la transizione - i #highlight(fill: myblue)[marker] di #underline[inizio] e #underline[fine] rappresentati rispettivamente da un cerchio nero con una freccia che punto allo stato iniziale e come un cerchio nero racchiuso da un anello sottile - le #highlight(fill: myblue)[azioni] che una entità è in grado di eseguire in risposta alla ricezione di un evento; cioè, se ricevo quel evento, oltre a fare la transizione, posso fare anche altre cose - il #highlight(fill: myblue)[vertice] che rappresenta l'astrazione di nodo nel diagramma e può essere la sorgente o la destinazione di una o più transizioni; rappresento un sotto-diagramma ==== Esempio #cfigure("images/image-1710422071247-0.png", 100%) - Marker iniziale, stato iniziale, a seguito di un messaggio ricevuto, effetto quest'azione e vado in transizione verso un nuovo stato - Da quello stato, quando posso, quando ricevo la distruzione, vado al marker finale ==== Stato - Uno stato modella una situazione durante la quale vale una condizione invariante (solitamente implicita) - L'invariante può rappresentare una situazione statica, come un oggetto in attesa che si verifichi un evento esterno - Tuttavia, può anche modellare condizioni dinamiche, come il processo di esecuzione di un comportamento (cioè, l'elemento del modello in esame entra nello stato quando il comportamento inizia e lo lascia non appena il comportamento è completato) - Stati possibili: - #text(blue)[Simple state] - #text(blue)[Composite state] - #text(blue)[Submachine state] - Composite state: - può contenere una regione oppure è decomposto in due o più regioni ortogonali - ogni regione ha il suo insieme di sotto-vertici mutuamente esclusivi e disgiunti e il proprio insieme di transizioni - ogni stato appartenente ad una regione è chiamato substato - la transizione verso il marker finale all'interno di una regione rappresenta il completamento del comportamento di quella regione - quando tutte le regioni ortogonali hanno completato il loro comportamento questo rappresenta il completamento del comportamento dell'intero stato e fa scattare il trigger dell'evento di completamento - Simple state: - è uno stato che non ha sottostati - Submachine state: - specifica l'inserimento di un diagramma di una sotto-parte del sistema e permette la fattorizzazione di comportamenti comuni e il riuso dei medesimi - è semanticamente equivalente a un composite state, quindi le regioni del submachinestate sono come le regioni del composite state - le azioni sono definite come parte dello stato - Uno stato può essere ridefinito: - uno stato semplice può essere ridefinito diventando uno stato composito - uno stato composito può essere ridefinito aggiungendo regioni, vertici, stati, transizioni e azioni ==== Esempio #cfigure("images/image-1710422303917-0.png", 96%) Questo è uno stato composito, nel senso che quello stato composito può essere inserito all'interno di un altro diagramma di stato. E quindi rappresenta la fattorizzazione che abbiamo visto, è analoga a quello che abbiamo visto nel diagramma dell'attività. ==== Esempio #cfigure("images/image-1710422325220-0.png", 96%) - Una Regione è una parte ortogonale di uno stato composto o di un state machine - Questo è uno stato composito con regioni ortogonali che rappresenta il diagramma di stato per il superamento di un esame da parte dello studente - In questo stato di piano ci sono le tre regioni che sono eseguite "concorrentemente", possono essere eseguite in paralleli, non sto indicando una sequenzialità - Possono iniziare contemporaneamente ma non finiscono per forza nello stesso istante - Il diagramma dice che il design prevede lo svolgimento della Lab1, dal quale si esce quando `lab done` - A quel punto posso fare Lab2, quando ho fatto Lab2, `lab done`, ho terminato quella regione - Quindi si termina quella regione quando ho terminato Lab1 e Lab2 - Nella seconda regione si esce quando il progetto è terminato - In fine c'è il final test; dal final test si può uscire con due messaggi - `fail` che provoca automaticamente la segnalazione dell'esame come fallito, `Failed` - `pass`, allora termino quella regione, e l'esame viene segnato come passato, `Passed` ==== Esempio #cfigure("images/image-1710422403624-0.png", 100%) ==== Pseudostato - Gli pseudostati vengono generalmente utilizzati per collegare più transizioni in percorsi di transizioni di stato più complessi - Ad esempio, combinando una transizione che entra in uno pseudostato fork con un insieme di transizioni che escono dallo pseudostato fork, otteniamo una transizione composta che porta a un insieme di stati ortogonali ==== Tipi di Pseudostati - #highlight(fill: myblue)[Initial:] vertice di default che è la sorgente della singola transizione verso lo stato di default di un composite state - Ci può essere al massimo un vertice initial e la transizione uscente da questo vertice non può avere trigger o guardie - #highlight(fill: myblue)[deepHistory]: la più recente configurazione attiva del composite state che contiene direttamente questo pseudostato - #highlight(fill: myblue)[shallowHistory:] il più recente substate attivo di un composite state initial deepHistory shallowHistory #cfigure("images/image-1710422587280-0.png", 65%) - #highlight(fill: myblue)[Join:] permette di eseguire il merge di diverse transizioni provenienti da diverse sorgenti appartenenti a differenti regioni ortogonali - Le transizioni entranti in questo vertice non possono avere guardie e trigger - #highlight(fill: myblue)[Fork:] permette di separare una transizione entrante in due o più transizioni che terminano in vertici di regioni ortogonali - Le transizioni uscenti da questo vertice non possono avere guardie #cfigure("images/image-1710426556871-0.png", 75%) - #highlight(fill: myblue)[Junction:] è un vertice privo di semantica che viene usato per “incatenare” insieme transizioni multiple - È usato per costruire percorsi di transizione composti tra stati - Una junction può essere usata per far convergere transizioni multiple entranti in una singola transizione uscente che rappresenta un percorso condiviso di transizione - Allo stesso modo una junction può essere usata anche per suddividere una transizione entrante in più transizioni uscenti con differenti guardie - Permette di realizzare un #underline[branch condizionale statico], , quindi quando esco da un certo stato, so già in quale delle biforcazioni finirò - Esiste una guardia predefinita chiamata “else”che viene attivata quando tutte le guardie sono false #cfigure("images/image-1710426578024-0.png", 70%) - #highlight(fill: myblue)[Choice:] è un tipo di vertice che quando viene raggiunto causa la valutazione dinamica delle guardie dei trigger delle transizioni uscenti - Le guardie sono quindi tipicamente scritte sotto forma di “funzione”che viene valutata al momento del raggiungimento del vertice choice - Permette di realizzare un #underline[branch condizionale dinamico] separando le transizioni uscenti e creando diversi percorsi di uscita - Se più di una guardia è verificata viene scelto il percorso in modo arbitrario - Se nessuna è verificata il modello viene considerato “ill-formed” - È quindi caldamente consigliato definire sempre un percorso di uscita di tipo “else” #cfigure("images/image-1710426645434-0.png", 70%) - La differenza tra _Junciton_ e _Choise_ è che, siccome nelle transizioni io posso eseguire delle azioni, la biforcazione di junction non può dipendere dalle azioni, mentre la biforcazione di choice può dipendere dall'esito di quelle azioni. - #highlight(fill: myblue)[Entry point:] è l'ingresso di uno state machine o di un composite state - #highlight(fill: myblue)[Exit point:] è l'uscita da uno state machine o da uno stato composito - Entrare in questo vertice significa attivare la transizione che ha questo vertice come sorgente - #highlight(fill: myblue)[Terminate:] entrare in questo vertice implica che l'esecuzione di questo state machine è terminata - Lo state machine non uscirà da nessuno stato né verranno invocate altre azioni a parte quelle associate con la transizione che porta allo stato terminate #cfigure("images/image-1710426724993-0.png", 75%) ==== Transizione - Una transizione è una relazione diretta tra un vertice di origine e un vertice di destinazione, un arco direzionato - Può essere parte di una transizione composta, che porta la macchina a stati da una configurazione di stato a un'altra, rappresentando la risposta completa della macchina a stati al verificarsi di un evento di un tipo particolare; cioè, c'è un evento, definisco qual è la risposta della macchina a quell'evento, la risposta dell'istanza a quell'evento - Analizzando la specifica UML è possibile vedere che tra le proprietà di una transizione compaiono diversi concetti molto rilevanti tra cui: - #highlight(fill: myblue)[trigger:] cioè i tipi di evento che possono innescare la transizione - #highlight(fill: myblue)[guardia:] cioè un vincolo che fornisce un controllo fine sull'innesco della transizione - La guardia è valutata quando una occorrenza dell'evento è consegnata allo stato - Se la guardia risulta verificata allora la transizione può essere abilitata altrimenti questa viene disabilitata - Il problema delle guardie è che, in teoria, la guardia potrebbe essere rappresentata dalla esecuzione di operazione; se la guardia (l'operazione) ha degli effetti collaterali (_side effect_), potrebbe succedere il caso in cui la prima ricezione di un messaggio non blocca la transizione, mentre la seconda ricezione dello stesso messaggio blocca la transizione - Quindi le guardie dovrebbero essere pure espressioni senza _side effect_, i quali sono assolutamente sconsigliati nella specifica - #highlight(fill: myblue)[effetto:] specifica un comportamento opzionale (cioè un'azione) che deve essere eseguito quando la transizione scatta trigger guardia effetto (l'effetto viene considerato da choise e non da junction) #cfigure("images/image-1710426803459-0.png", 86%) - Sono in stato Selling, ricevo `bid`, scatta la guardia; se il valore è minore di 100 eseguo l'operazione `reject`, e rimango nello stato selling - Se il valore è maggiore o uguale a 100 e minore di 200 alla ricezione del messaggio `bid`, eseguo l'operazione `sell` e passo in un stato Unhappy - Se il valore è maggiore o uguale a 200 all'atto della ricezione del messaggio `bid`, eseguo l'operazione `sell` e passo nello stato Happy ==== Tipi di Eventi - #highlight(fill: myblue)[Evento di chiamata:] ricezione di un messaggio che richiede l'esecuzione di una operazione - #highlight(fill: myblue)[Evento di cambiamento:] si verifica quando una condizione passa da “falsa” a “vera” - Tale evento si specifica scrivendo \<\<when\>\> seguito da un'espressione, racchiusa tra parentesi tonde, che descrive la condizione - Utile per descrivere la situazione in cui un oggetto cambia stato perché il valore dei suoi attributi è modificato dalla risposta a un messaggio inviato - Evento segnale: consiste nella ricezione di un segnale - Evento temporale: espressione che denota un lasso di tempo che deve trascorrere dopo un evento dotato di nome - Con <<after>> si può far riferimento all'istante in cui l'oggetto è entrato nello stato corrente - Con <<at>> si esprime qualcosa che deve accadere in un particolare momento ==== Azione - Un'azione è un elemento avente un nome che è l'unità fondamentale della funzionalità eseguibile - L'esecuzione di un'azione rappresenta una trasformazione o elaborazione nel sistema modellato, sia esso un sistema informatico o altro - #highlight(fill: myblue)[Entry:] tutte le volte che si entra in uno stato viene generato un evento di entrata a cui può essere associato uno o più specifici comportamenti che vengono eseguiti prima che qualsiasi altra azione possa essere eseguita - #highlight(fill: myblue)[Exit:] tutte le volte che si esce da uno stato viene generato un evento di uscita a cui può essere associato uno o più specifici comportamenti che vengono eseguiti come ultimo passo prima che lo stato venga lasciato - #highlight(fill: myblue)[Do:] rappresenta il comportamento che viene eseguito all'interno dello stato - il comportamento parte subito dopo l'ingresso nello stato (dopo che è stato eseguito l'entry) - se questo comportamento termina mentre lo stato è ancora attivo viene generato un evento di completamento e nel caso sia stata specificata una transizione per il completamento allora viene eseguito l'exit e successivamente la transizione d'uscita - se invece viene innescata una transizione di uscita prima che il do termini, allora l'esecuzione del do è abortita, viene eseguito l'exit e poi la transizione - Il comportamento di entry è stato definito per #text(blue)[permettere di fattorizzare comportamenti comuni] all'ingresso di uno stato, sui quali non possiamo mettere la guardia - Senza la possibilità di poter specificare un comportamento di entry, il progettista avrebbe dovuto specificare su ogni transizione verso lo stato una azione effetto legata alle transizioni - Il medesimo discorso vale per le exit, nella quale sono fattorizzati tutti quei comportamenti che devono essere eseguiti prima di uscire dallo stato - È importante però ricordare che non vi è la possibilità di esprimere condizioni di guardia su questi comportamenti ==== Diagramma di Stato - Transizione interna che esclude azioni di entrata e di uscita #cfigure("images/image-1710427558944-0.png", 25%) - Attività interna: generazione di un thread concorrente che resta in esecuzione finché: - il thread (eventualmente) termina - si esce dallo stato attraverso una transizione esterna #cfigure("images/image-1710427643942-0.png", 25%) - Il diagramma di stato relativo a una singola classe / entità dovrebbe essere il più semplice possibile - Le classi / entità con diagrammi di stato complicati hanno diversi problemi: - il codice risulta più difficile da scrivere perché le implementazioni dei metodi contengono molti blocchi condizionali - il testing è più arduo - è molto difficile utilizzare una classe dall'esterno se il comportamento dipende dallo stato in modo complesso - Se una classe ha un numero troppo elevato di stati è bene considerare se esistano progetti alternativi, come per esempio scomporre la classe in due diverse classi - Questa però non va presa come regola universale - La scomposizione di una classe è sempre un'operazione molto delicata e va ponderata molto bene in quanto potrebbe portare a progetti fuorvianti o instabili - A volte il male minore è proprio avere diagrammi di stato complessi == Diagramma delle attività - I diagrammi delle attività descrivono il modo in cui diverse attività sono coordinate e possono essere usati per mostrare l'implementazione di una operazione - Un diagramma delle attività mostra le attività di un sistema in generale e delle sotto-parti, specialmente quando un sistema ha diversi obiettivi e si desidera modellare le dipendenze tra essi prima di decidere l'ordine in cui svolgere le azioni - I diagrammi delle attività sono utili anche per descrivere lo svolgimento dei singoli casi d'uso e la loro eventuale dipendenza da altri casi - Sostanzialmente, modellano un processo - Organizzano più entità in un insieme di azioni secondo un determinato flusso - Si usano ad esempio per: - modellare il flusso di un caso d'uso (analisi) - modellare il funzionamento di un'operazione (progettazione) - modellare un algoritmo (progettazione) #cfigure("images/image-1710427924392-0.png", 100%) - #highlight(fill: myblue)[Attività:] indica un lavoro che deve essere svolto - Specifica un'unità atomica, non interrompibile e istantanea di comportamento - Da ogni attività possono uscire uno o più archi, che indicano il percorso da una attività ad un'altra - #highlight(fill: myblue)[Arco:] è rappresentato come una freccia proprio come una transizione - A differenza di una transizione, un arco non può essere etichettato con eventi o azioni - Un arco può essere etichettato con una condizione di guardia, se l'attività successiva la richiede - #highlight(fill: myblue)[Oggetto:] rappresenta un oggetto “importante” usato come input/output di azioni - #highlight(fill: myblue)[Sottoattività:] “nasconde” un diagramma delle attività interno a un'attività - #highlight(fill: myblue)[Start e End Point:] punti di inizio e fine del diagramma - Gli End Point possono anche non essere presenti, oppure essere più di uno - #highlight(fill: myblue)[Controllo:] nodi che descrivono il flusso delle attività #v(2em) - Per capire la semantica dei diagrammi di attività, bisogna immaginare delle entità, dette #text(blue)[token], che viaggiano lungo il diagramma - Il flusso dei tokendefinisce il flusso dell'attività - I token possono rimanere fermi in un nodo azione/oggetto in attesa che si avveri - una condizione su un arco - oppure una precondizione o postcondizionesu un nodo - Il movimento di un token è atomico - Un nodo azione viene eseguito quando sono presenti token su tutti gli archi in entrata, e tutte le precondizioni sono soddisfatte - Al termine di un'azione, sono generati token su tutti gli archi in uscita ==== Notazione #cfigure("images/image-1710428025939-0.png", 100%) - #highlight(fill: myblue)[Decision e Merge]: determinano il comportamento condizionale - #highlight(fill: myblue)[Decision] ha una singola transizione entrante e più transizioni uscenti in cui solo una di queste sarà prescelta - #highlight(fill: myblue)[Merge] ha più transizioni entranti e una sola uscente e serve a terminare il blocco condizionale cominciato con un decision - #highlight(fill: myblue)[Fork e join:] determinano il comportamento parallelo: - quando scatta la transazione entrante, si eseguono in parallelo tutte le transazioni che escono dal fork - Con il parallelismo non è specificata la sequenza - Le fork possono avere delle guardie - Per la sincronizzazione delle attività è presente il costrutto di join che ha più transazioni entranti e una sola transazione uscente #cfigure("images/image-1710428137459-0.png", 40%){:height 343, :width 434} === Object Flow - È un arco che ha oggetti o dati che fluiscono su di esso #cfigure("images/image-1710428157989-0.png", 100%) === Segnali ed Eventi #cfigure("images/image-1710428183146-0.png", 100%) === Exception Handler #cfigure("images/image-1710428204930-0.png", 100%) #pagebreak() === InterruptibleActivityRegion #cfigure("images/image-1710428254604-0.png", 100%) = Progetto == Analisi dei requisiti === Requisiti - I requisiti di un sistema rappresentano la descrizione - dei servizi forniti (le funzionalità) - dei vincoli operativi - Il processo di ricerca, analisi, documentazione e verifica di questi servizi e vincoli è chiamato *Ingegneria dei Requisiti* (RE - Requirements Engineering) - I requisiti di solito vengono forniti a livelli diversi di descrizione e questo porta a una prima classificazione... - I Requisiti utente dichiarano: - Quali servizi il sistema dovrebbe fornire - I vincoli sotto cui deve operare - Sono requisiti molto astratti e di alto livello che vengono specificati nella prima fase interlocutoria con il committente - Tipicamente sono espressi in linguaggio naturale e corredati da qualche diagramma - Requisiti di sistema definiscono: - Le funzioni, i servizi e i vincoli operativi del sistema in modo dettagliato - È una descrizione dettagliata di quello che il sistema dovrebbe fare - Il Documento dei Requisiti del Sistema deve essere preciso e definire esattamente cosa deve essere sviluppato - Tale documento fa spesso parte del contratto tra committente e azienda sviluppatrice - ![image.png](images/image-1710063362882-0.png) ==== Requisiti di Sistema - I requisiti di sistema tipicamente vengono divisi in tre diverse tipologie: - Requisiti funzionali - Requisiti non funzionali - Requisiti di dominio ==== Requisiti Funzionali - Descrivono quello che il sistema dovrebbe fare - Sono elenchi di servizi che il sistema dovrebbe fornire - Per ogni servizio dovrebbe essere indicato: - come reagire a particolari input - come comportarsi in particolari situazioni - in alcuni casi specificare cosa il sistema NON dovrebbe fare - Le specifiche dei requisiti funzionali dovrebbero essere: - complete: tutti i servizi definiti - coerenti: i requisiti non devono avere definizioni contraddittorie ==== Requisiti Non Funzionali - Non riguardano direttamente le specifiche funzionali - Non devono essere necessariamente coerenti - I principali tipi di requisiti non funzionali: - Requisiti del prodotto: specificano o limitano le proprietà complessive del sistema - affidabilità, prestazioni, protezione dei dati, disponibilità dei servizi, tempi di risposta, occupazione di spazio, capacità dei dispositivi di I/O, rappresentazione dei dati nelle interfacce, etc. - Requisiti Organizzativi: possono vincolare anche il processo di sviluppo adottato - politiche e procedure dell'organizzazione cliente e sviluppatrice, specifiche degli standard di qualità da adottare, uso di un particolare CASE toole linguaggi di implementazione, limiti di budget, requisiti di consegna e milestone, etc. - Requisiti esterni: si identificano tutti i requisiti che derivano da fattori non provenienti dal sistema e dal suo processo di sviluppo - necessità di interoperabilità con altri sistemi software o hardware prodotti da altre organizzazioni - requisiti legislativi che devono essere rispettati affinché il sistema operi nella legalità →legislazioni sulla privacy dei dati - requisiti etici perché il sistema possa essere accettato dagli utenti e dal grande pubblico - ![image.png](images/image-1710063695471-0.png) - Uno dei maggiori problemi di questi requisiti è che possono essere difficili da verificare perché spesso sono espressi in modo vago e sono mescolati ai requisiti funzionali - Esempi: facilità d'uso, capacità di ripristino dopo un malfunzionamento - Spesso contrastano o interagiscono con i requisiti funzionali - La protezione e la privacy dei dati contrastano con la facilità d'uso perché richiedono procedure spesso macchinose per l'utente... - ...occorre trovare un compromesso tra i requisiti o chiedere al committente quale sia più prioritario - Vanno studiati ed analizzati con molta cura e precisione e indicati quanto più chiaramente possibile nel documento dei requisiti ==== Requisiti di Dominio - I requisiti di dominio descrivono i vincoli che esistono nel dominio e che potrebbero non essere condivisi tra tutti coloro che saranno impegnati nello sviluppo del software - Derivano dal dominio di applicazione del sistema - Solitamente includono una terminologia propria del dominio del sistema o si riferiscono ai suoi concetti - Poiché sono requisiti “specialistici” spesso gli ingeneri del software trovano difficile capire come questo tipo di requisiti si rapportino agli altri requisiti del sistema - Sono requisiti che vanno comunque analizzati con molta cura perché riflettono i fondamenti del dominio dell'applicazione - l'analisi deve coinvolgere gli esperti del dominio per chiarire ogni dubbio sulla terminologia === Analisi - Obiettivo - Specificare (cioè definire) le proprietà che il sistema dovrà avere senza descrivere una loro possibile realizzazione - Risultato: una serie di documenti - contenenti la descrizione dettagliata dei requisiti - base di partenza per lanalisi del problema - Per determinare in dettaglio i requisiti del sistema, è necessario - interagire il più possibile con lutente, o con il potenziale utente - conoscere il più possibile larea applicativa + #highlight(fill: myblue)[Raccolta dei requisiti] \ Obiettivo: raccogliere tutte le informazioni su cosa il sistema deve fare secondo le intenzioni del cliente + #highlight(fill: myblue)[Analisi dei requisiti] \ Obiettivo: definire il comportamento del sistema + #highlight(fill: myblue)[Analisi del dominio] \ Obiettivo: definire la porzione del mondo reale, rilevante per il sistema + #highlight(fill: myblue)[Analisi e gestione dei rischi] \ Obiettivo: identificare e gestire i possibili rischi che possono fare fallire o intralciare la realizzazione del sistema ![image.png](images/image-1710064987414-0.png) ==== Raccolta dei Requisiti - Obiettivo: raccogliere tutte le informazioni su cosa il sistema deve fare secondo le intenzioni del cliente (si chiede al cliente cosa voglia che faccia l'applicazione) - Non prevede passi formali, né ha una notazione specifica, perché dipende moltissimo dal particolare tipo di problema - Risultato - un documento (testuale) - scritto dallanalista - discusso e approvato dal cliente - una versione iniziale del vocabolario o glossario contenente la definizione precisa e non ambigua di tutti i termini e i concetti utilizzati - Tipologie di persone coinvolte - Analista - Utente - Esperto del dominio (non sempre indispensabile) - Metodi utilizzati - Interviste, questionari - Studio di documenti che esprimono i requisiti in forma testuale - Osservazione passiva o attiva del processo da modellare - Studio di sistemi software esistenti - Prototipi - La gestione delle interviste è molto complessa - I clienti potrebbero - Avere solo una vaga idea dei requisiti - Non essere in grado di esprimere i requisiti in termini comprensibili - Chiedere requisiti non realizzabili o troppo costosi - Fornire requisiti in conflitto - Essere poco disponibili a collaborare ==== Validazione dei Requisiti - Ogni requisito deve essere validato e negoziato con i clienti prima di essere riportato nel Documento dei Requisiti (se non è completamente validato si rifà l'intervista) - Attività svolta in parallelo alla raccolta - #highlight(fill: myblue)[Validità] - il nuovo requisito è inerente il problema da risolvere? - #highlight(fill: myblue)[Consistenza] - il nuovo requisito è in sovrapposizione e/o in conflitto con altri requisiti? - #highlight(fill: myblue)[Realizzabilità] - il nuovo requisito è realizzabile con le risorse disponibili (hardware, finanziamenti, ...)? - #highlight(fill: myblue)[Completezza] - esiste la possibilità che ci siano requisiti rimasti ignorati? ==== Documento dei Requisiti - Il Documento dei Requisiti deve specificare in modo chiaro e univoco cosa il sistema dovrà fare - I requisiti dovrebbero essere: - Chiari - Corretti - Completi - Concisi - Non ambigui - Precisi - Consistenti - Tracciabili - Modificabili - Verificabili - Il Documento dei Requisiti deve contenere la versione iniziale del dizionario dei termini - Un buon modo per organizzare i requisiti e facilitare la tracciabilità è quello di elencare i requisiti in una tabella - ![image.png](images/image-1710065295316-0.png) - Se durante il processo di sviluppo ci si riferisce sempre allid del requisito diventa facile collegare le diverse fasi e garantire una tracciabilità requisito-codice ==== Cambiamento dei Requisiti - È normale che i requisiti subiscano modificazioni ed evolvano nel tempo - Requisiti esistenti possono essere rimossi o modificati - Nuovi requisiti possono essere aggiunti in una fase qualsiasi del ciclo di sviluppo - Tali cambiamenti - Sono la norma, non l'eccezione; i sistemi vanno progettati avendo in mente il cambiamento - Possono diventare un grosso problema se non opportunamente gestiti - Più lo sviluppo è avanzato, più il cambiamento è costoso - Modificare un requisito appena definito è facile - Modificare lo stesso requisito dopo che è stato implementato nel software potrebbe essere molto costoso - Ogni cambiamento deve essere accuratamente analizzato per valutare - La fattibilità tecnica, cioè, lo si può implementare, indipendentemente dal costo? - Limpatto sul resto del sistema - Il costo - Consiglio - sviluppare sistemi che - Siano il più possibile resistenti ai cambiamenti dei requisiti - Inizialmente, eseguano esclusivamente e nel modo migliore i soli compiti richiesti - In seguito, siano in grado di sostenere laggiunta di nuove funzionalità senza causare “disastri” strutturali e/o comportamentali - Tenete traccia dei cambiamenti anche nella tabella dei requisiti ==== Analisi del Dominio - Obiettivo: definire la porzione del mondo reale rilevante per il sistema, quindi una visione astratta del mondo reale - Principio fondamentale: Astrazione Permette di gestire la complessità intrinseca del mondo reale - ignorare gli aspetti che non sono importanti per lo scopo attuale - concentrarsi maggiormente su quelli che lo sono - Risultato: prima versione del vocabolario partendo dai “sostantivi” che si trovano nei requisiti - L'analisi del dominio può essere effettuata anche considerando un gruppo di sistemi afferenti alla stessa area applicativa - Esempi di aree applicative: - il controllo del traffico aereo - la gestione aziendale - le operazioni bancarie - ... - In tal caso, è possibile - identificare entità e comportamenti comuni a tutti i sistemi - realizzare schemi di progettazione e componenti software riutilizzabili nei diversi sistemi ==== Analisi dei Requisiti - Obiettivo: definire il comportamento del sistema da realizzare - Risultato: un modello comportamentale (o modello dinamico) che descrive in modo chiaro e conciso le funzionalità del sistema - L'analisi dei requisiti deve partire dalla raccolta, che è un elenco di requisiti, e definire per bene qual è il comportamento del sistema - Strategia: - Scomposizione funzionale (mediante analisi top-down) ► identificare le singole funzionalità previste dal sistema - Astrazione procedurale ► considerare ogni operazione come una singola entità, nonostante tale operazione sia effettivamente realizzata da un insieme di operazioni di più basso livello - Attenzione: La scomposizione in funzioni è molto volatile a causa del continuo cambiamento dei requisiti funzionali - Come prima cosa vanno analizzati in modo sistematico tutti i requisiti inseriti nella Tabella dei requisiti - Bisogna porre particolare attenzione ai sostantivi e ai verbi che compaiono nel testo di specifica dei requisiti - Dall'analisi dei sostantivi è possibile formalizzare la conoscenza sul dominio applicativo → costruzione di un primo modello del dominio - Dall'analisi dei verbi è possibili individuare linsieme delle azioni che il sistema dovrà compiere → modello dei casi duso - Aggiornare costantemente la Tabella dei Requisiti → dallanalisi nascono sempre nuovi requisiti ==== Vocabolario - Nella modellazione del dominio è di fondamentale importanza usare solo la terminologia di quello specifico dominio - Il vocabolario è una lista dei termini usati nella specifica dei requisiti a cui viene data una definizione precisa e non ambigua - È uno dei fattori chiave per migliorare la comunicazione tra i diversi attori del processo di sviluppo, in particolare tra analisti e progettisti - Ciascuna entità del dominio che si evince dai requisiti può essere espressa come classe UML e messa in relazione logica con le altre entità andando a creare il primo modello del dominio ==== Analisi e gestione dei rischi - Ci si riferisce generalmente ai rischi di tipo legale - Analisi sistematica e completa di tutti i possibili rischi che possono fare fallire o intralciare la realizzazione del sistema in una qualsiasi fase del processo di sviluppo - Ogni rischio presenta due caratteristiche: - Probabilità che avvenga non esistono rischi con una probabilità del 100% (sarebbero vincoli al progetto) - Costo se il rischio si realizza, ne seguono effetti indesiderati e/o perdite - Rischi relativi ai requisiti - I requisiti sono perfettamente noti? - Il rischio maggiore è quello di costruire un sistema che non soddisfa le esigenze del cliente - Rischi relativi alle risorse umane - È possibile contare sulle persone e sullesperienza necessarie per lo sviluppo del progetto? - Rischi relativi alla protezione e privacy dei dati - Di che tipo sono i dati che dobbiamo trattare? - Quali sono i possibili attacchi informatici a cui il sistema può essere soggetto? - Rischi tecnologici - Si sta scegliendo la tecnologia corretta? - Si è in grado di aggregare correttamente i vari componenti del progetto (ad es., GUI, DB, ...)? - Quali saranno i possibili futuri sviluppi della tecnologia? - Rischi politici - Ci sono delle forze politiche (anche in senso lato) in grado di intralciare lo sviluppo del progetto? - Strategia reattiva o “alla Indiana Jones” - “Niente paura, troverò una soluzione” - Strategia preventiva - Si mette in moto molto prima che inizi il lavoro tecnico - Si individuano i rischi potenziali, se ne valutano le probabilità e gli effetti e si stabilisce un ordine di importanza - Si predispone un piano che permetta di reagire in modo controllato ed efficace - Più grande è un rischio, dove per grande possiamo intendere il prodotto di probabilità per costo - Maggiore sarà l'attenzione che bisognerà dedicargli === Sicurezza e Privacy ==== Nuova normativa ===== General Data Protection Regulation - Dal 25/5/2018 sostituisce la Data Protection Directive - Obbligo di aderenza (compliance) di un prodotto software che tratti dati personali ai principi della GDPR - privacy by design & by default(misure tecniche e organizzative) - minimalità, proporzionalità - anonimizzazione, pseudonimizzazione - trasferimento dati fuori dalla EU (occhio al cloud!) - adeguatezza delle misure di sicurezza - Non è qualcosa che si possa “aggiungere dopo”, a sistema già progettato: va considerato fin dall'inizio - ma non è (solo) un vincolo: è un'opportunità per creare valore #highlight(fill: myblue)[Pseudonimizzazione:] processo di trattamento dei dati personali in modo tale che i dati non possano più essere attribuiti a un interessato specifico senza l'utilizzo di informazioni aggiuntive, sempre che tali informazioni aggiuntive siano conservate separatamente e soggette a misure tecniche e organizzative intese a garantire la non attribuzione a una persona identificata o identificabile.\ ===== Principi I dati personali devono essere: - trattati in modo lecito, equo e trasparente nei confronti dell'interessato (“#text(blue)[liceità, equità e trasparenza]”) - raccolti per finalità determinate, esplicite e legittime, e successivamente trattati in modo non incompatibile con tali finalità - adeguati, pertinenti e limitati a quanto necessario rispetto alle finalità per le quali sono trattati (“#text(blue)[minimizzazione dei dati]”) - esatti e, se necessario, aggiornati - devono essere prese tutte le misure ragionevoli per cancellare o rettificare tempestivamente i dati inesatti rispetto alle finalità per le quali sono trattati (“#text(blue)[esattezza]”); quindi bisogna dare all'utente la possibilità di aggiornarli - conservati in una forma che consenta l'identificazione degli interessati per un arco di tempo non superiore al conseguimento delle finalità per le quali sono trattati - i dati personali possono essere conservati per periodi più lunghi a condizione che siano trattati esclusivamente per finalità di archiviazione nel pubblico interesse o per finalità di ricerca scientifica e storica o per finalità statistiche, conformemente all'articolo 83 - trattati in modo da garantire un'adeguata sicurezza dei dati personali, compresa la protezione, mediante misure tecniche e organizzative adeguate, da trattamenti non autorizzati o illeciti e dalla perdita, dalla distruzione o dal danno accidentali (“#text(blue)[integrità e riservatezza]”); quindi bisogna garantire che non ci siano trattamenti illeciti dei dati degli utenti, e che non vengano persi ===== Articolo 25 *Protezione dei dati fin dalla progettazione e protezione di default* + Tenuto conto dello stato dell'arte e dei costi di attuazione, nonché della natura, del campo di applicazione, del contesto e delle finalità del trattamento, come anche dei rischi di varia probabilità e gravità per i diritti e le libertà delle persone fisiche costituiti dal trattamento, #text(blue)[sia al momento di determinare i mezzi del trattamento sia all'atto del trattamento stesso] il responsabile del trattamento mette in atto #text(blue)[misure tecniche e organizzative adeguate], quali la pseudonimizzazione, volte ad attuare i principi di protezione dei dati, quali la minimizzazione, in modo efficace e a integrare nel trattamento le necessarie garanzie al fine di soddisfare i requisiti del presente regolamento e tutelare i diritti degli interessati + Il responsabile del trattamento mette in atto misure tecniche e organizzative adeguate per garantire che siano trattati, #text(blue)[di default], solo i dati personali necessari per ogni specifica finalità del trattamento; ciò vale per la quantità dei dati raccolti, l'estensione del trattamento, il periodo di conservazione e l'accessibilità. #text(blue)[In particolare dette misure garantiscono che, di default, non siano resi accessibili dati personali a un numero indefinito di persone fisiche senza l'intervento della persona fisica] ; cioè, normalmente, nessuno può far vedere quei dati, tranne la persona stessa ===== Articolo 32: *Sicurezza del Trattamento* + Tenuto conto dello stato dell'arte e dei costi di attuazione, nonché della natura, del campo di applicazione, del contesto e delle finalità del trattamento, come anche del rischio di varia probabilità e gravità per i diritti e le libertà delle persone fisiche, il responsabile del trattamento e l'incaricato del trattamento mettono in atto misure tecniche e organizzative adeguate per garantire un #text(blue)[livello di sicurezza adeguato al rischio], che comprendono tra l'altro: - la #text(blue)[pseudonimizzazione] e la #text(blue)[cifratura dei dati personali]; - la capacità di assicurare la #text(blue)[continua riservatezza], integrità, disponibilità e resilienza dei sistemi e dei servizi che trattano i dati personali; - la capacità di #text(blue)[ripristinare tempestivamente la disponibilità] e l'accesso dei dati in caso di incidente fisico o tecnico; - una procedura per provare, verificare e valutare regolarmente l'efficacia delle misure tecniche e organizzative al fine di garantire la sicurezza del trattamento; cioè bisogna non solo mettere in campo queste misure, ma anche testarle regolarmente + Nel valutare l'adeguato livello di sicurezza, si tiene conto in special modo [dei rischi presentati] da trattamenti di dati derivanti in particolare dalla distruzione, dalla perdita, dalla modifica, dalla divulgazione non autorizzata o dall'accesso, in modo accidentale o illegale, a dati personali trasmessi, memorizzati o comunque trattati + L'adesione a un #text(blue)[codice di condotta] approvato di cui all'articolo 40 o a un #text(blue)[meccanismo di certificazione] approvato di cui all'articolo 42 può essere utilizzata come elemento per dimostrare la conformità ai requisiti di cui al paragrafo 1 del presente articolo Quindi per dimostrare di aver seguito tutti i passi descritti nell'articolo ci si avvale di una certificazione o di un codice di condotta. ===== Trasferimento Dati a Paesi Terzi - Articolo 45: - Il trasferimento di dati personali verso un paese terzo o un'organizzazione internazionale è ammesso se la Commissione ha deciso che il paese terzo, o un territorio o uno o più settori specifici all'interno del paese terzo, o l'organizzazione internazionale in questione garantiscano un livello di protezione adeguato. In tal caso il trasferimento non necessita di autorizzazioni specifiche. - Articolo 46: - In mancanza di una decisione ai sensi dell'articolo 45, il responsabile del trattamento o l'incaricato del trattamento può trasferire dati personali verso un paese terzo o un'organizzazione internazionale solo se ha offerto garanzie adeguate e a condizione che siano disponibili diritti azionabili degli interessati e mezzi di ricorso effettivi per gli interessati. ==== Concetti di Base ===== Sicurezza Informatica Salvaguardia dei sistemi informatici da potenziali rischi e/o violazioni dei dati - Obiettivo dell'attacco = contenuto informativo - Sicurezza informatica = preoccuparsi di - impedire l'accesso ad utenti non autorizzati - regolamentare l'accesso ai diversi soggetti... - ... che potrebbero avere autorizzazioni diverse (relative solo a certe operazioni e non altre) - per evitare che i dati appartenenti al sistema informatico vengano copiati, modificati o cancellati Cosa Proteggere: - L'informazione... - Riservatezza: solo determinati utenti possono avere accesso alle informazioni - Integrità ed Autenticità: nessuno deve modificare impropriamente quelle informazioni - Disponibilità: le informazioni sono disponibili nel momento c'è la necessità di accedervi - trattata per mezzo di calcolatori e reti - Accesso controllato - Tre aspetti: #highlight(fill: myblue)[identificazione, autenticazione, autorizzazione] - Funzionamento affidabile; per il concetto di affidabilità riguardare gli argomenti precedenti ===== Violazioni - Le violazioni possono essere molteplici: - tentativi non autorizzati di accesso a zone riservate - furto di identità digitale o di file riservati - utilizzo di risorse che l'utente non dovrebbe potere utilizzare - ecc. - La sicurezza informatica si occupa anche di prevenire eventuali #text(blue)[Denial of Service] (DoS) - sono attacchi sferrati al sistema con l'obiettivo di rendere inutilizzabili alcune risorse onde danneggiare gli utenti ===== Fattori Influenti - Nella scelta delle misure di sicurezza #text(red)[incidono diverse caratteristiche] dell'informazione e del contesto: - Dinamicità - Dimensione e tipo di accesso - Tempo di vita - Costo di generazione - Costo in caso di violazione (di riservatezza, di integrità, di disponibilità) - Valore percepito (dall'utente e dal detentore) e tipologia di attaccante #heading(level: 5, numbering: none)[La Catena degli Anelli] La forza di un sistema è pari alla forza dell'anello più debole che lo compone. Non bisogna tralasciare nulla, nemmeno il più piccolo dettaglio ===== Metodi di Protezione - Legali: ci sono leggi che regolano i casi in cui un sistema informatico viene violato, attraverso sanzioni ad esempio - Organizzativi - Tecnologici: metodi che ci interessano di più - Fisici: un oggetto fisico che viene utilizzato per proteggere l'accesso ai dati, ad esempio un tesserino - Crittografici: cifrare i dati in modo che siano difficilmente interpretabili da un attaccante - Biometrici: caratteristiche fisiche misurabili che identificano univocamente un individuo Attuiamo questi metodi per: - Prevenzione: evitare che un attaccante entri nel sistema - Rilevazione: scopriamo eventuali attacchi o violazioni - Contenimento: se c'è una violazione dei sistemi si cerca di tutti i modi di contenere eventuali danni - Ripristino: ripristino del sistema all'istante precedente al danno ===== Protezione Fisica - Essenziale: la vulnerabilità fisica non sia la più facilmente attaccabile - Efficace per i sistemi - criteri che esistono da ben prima dei problemi di sicurezza informatica - Efficace per i dati - purché si conosca il comportamento dei sistemi che li trattano (percorsi accessibili, copie temporanee in memoria e su disco, ...) - costo di generazione - purché si prevedano metodi aggiuntivi per contenere gli effetti delle violazioni fisiche dei sistemi (es. furto) ===== Autenticazione Forte #cfigure("images/2024-03-18-10-26-42.png", 90%) L'autenticazione forte è garantita esistono le seguenti condizioni - Possesso - Conoscenza - Conformità Ovviamente garantire tutte e tre le condizioni ha un costo. ==== Crittografia - Crittografia simmetrica - garantire riservatezza - non identifica né autentica - *funzionamento*: esiste una sola chiave che viene utilizzata per cifrare; ad esempio prendo un dato, lo cifro, e ottengo un dato che non è immediatamente comprensibile; la stessa chiave è usata per decifrare. - Crittografia asimmetrica - garantisce riservatezza - obiettivo: identificazione e quindi autenticazione e paternità - *funzionamento*: le chiavi sono due; c'è una che è in esclusivo possesso del cifratore e una che invece è pubblica, quindi chiave privata e chiave pubblica - Infrastrutture per la certificazione della chiave pubblica - Terze parti fidate che possano certificare l'autenticità di una chiave pubblica ===== Crittografia Simmetrica #cfigure("images/2024-03-18-10-52-29.png", 90%) - Classica e moderna, implementata con dispositivi segreti, algoritmi segreti o chiavi segrete - Tipicamente tecniche derivanti dalla teoria dell'informazione (confusione e diffusione) - Una singola chiave cifra e decifra ===== Crittografia Asimmetrica - Moderna (ufficialmente 1976) - Basata sulla teoria della complessità computazionale - Due chiavi correlate ma non (facilmente) calcolabili l'una dall'altra - La #text(red)[*chiave privata*] è strettamente personale e quindi _identifica_ il possessore - L'uso di una determinata chiave privata può essere verificato da chiunque per mezzo della corrispondente #text(green)[*chiave pubblica*] #figure(image("images/2024-03-18-10-58-12.png", width: 90%), caption: "Procedimento di cifratura") Se io voglio che il mio documento sia letto solamente da chi deve poterlo leggere, io cifro quel documento con la chiave pubblica, quindi se io cifro con la chiave privata è decifrabile solo dalla chiave pubblica, se io cifro con la chiave pubblica è decifrabile solo dalla chiave privata *Firma Digitale:* #figure(image("images/2024-03-18-11-01-47.png", width: 90%), caption: "Procedimento di firma") Viceversa, firma, autenticità: se io cifro il documento con la mia chiave pubblica genero un documento che è leggibile, ma che di fianco ha la mia firma, a questo punto chiunque sia in possesso della chiave pubblica può cifrare o decifrare la firma, e vedere se i documenti sono uguali, cioè controllo che la chiave che è stata usata per cifrare, per produrre la firma, corrisponde alla chiave pubblica che ho in mano io. ===== Confronto tra i due tipo di crittografia #cfigure("images/2024-03-18-11-07-55.png", 85%) La cifratura asimmetrica purtroppo è poco efficiente perché le procedure di cifratura e decifratura evidentemente sono complicate. Però, per quanto riguarda le chiavi simmetriche, bisogna averne un numero importante, perché se ho una sola chiave che cifra e decifra tutto, se capita in mano a un malintenzionato ha accesso a tutto. ===== Biometria - Componente cardine per la terna di fattori per l'#text(blue)[*autenticazione forte*] - qualcosa che sei, qualcosa che hai, qualcosa che sai - Problemi non ancora risolti: - Ostinatamente usata per l'_identificazione_ - lunghe operazioni di confronto - cattivo bilanciamento tra falsi positivi e falsi negativi - Meglio per l'_autenticazione_ - un solo confronto, minore probabilità di errori - Prestazioni più sfumate rispetto ad altre tecniche - difficile tuning tra falsi positivi e falsi negativi - Impossibilità di sostituzione in caso di compromissione ===== Sicurezza delle Password - Aspetto da sempre fondamentale per: - impedire l'accesso a utenti non autorizzati - nascondere e/o vincolare l'accesso a documenti - Diverse categorie: - Deboli - Semplici - Intelligenti - Strong ==== Analizzare e Progettare la Sicurezza ===== Sistema Sicuro - La definizione di una politica di sicurezza deve tenere conto di vincoli tecnici, logistici, amministrativi, politici ed economici, imposti dalla struttura organizzativa in cui il sistema opera - Per questo serve introdurre la sicurezza sin dalle prime fasi di analisi dei requisiti di un nuovo sistema - le vigenti leggi, le politiche e i vincoli aziendali sono la base di partenza per la definizione di un #text(blue)[*piano per la sicurezza*] - Un'applicazione o un servizio possono consistere di uno o più componenti funzionali allocati localmente o distribuiti sulla rete - La sicurezza viene vista come un #text(blue)[processo complesso], come una catena di caratteristiche - dalla computer system security, network security, application-level security sino alle problematiche di protezione dei dati sensibili - La sfida maggiore lanciata ai progettisti è quella di #text(blue)[progettare applicazioni sicure e di qualità] che tengano conto in modo strutturato di tutti gli aspetti della sicurezza sin dalle prime fasi di analisi del sistema ===== Sistemi Critici - I #text(blue)[sistemi critici] sono sistemi tecnici o socio-tecnici da cui dipendono persone o aziende - Se questi sistemi non forniscono i loro servizi come ci si aspetta possono verificarsi seri problemi e importanti perdite - Ci sono tre tipi principali di sistemi critici: - #highlight(fill: myblue)[Sistemi safety-critical:] i fallimenti possono provocare incidenti, perdita di vite umane o seri danni ambientali - #highlight(fill: myblue)[Sistemi mission-critical:] i malfunzionamenti possono causare il fallimento di alcune attività e obiettivi diretti - #highlight(fill: myblue)[Sistemi business-critical:] i fallimenti possono portare a costi molto alti per le aziende che li usano - La proprietà più importante di un sistema critico è la sua #text(blue)[*fidatezza*] - Sistema fidato = #text(red)[*disponibilità + affidabilità + sicurezza e protezione*] - Ci sono diverse ragioni per le quali la fidatezza è importante: - I sistemi non affidabili, non sicuri e non protetti sono rifiutati dagli utenti - I costi di un fallimento del sistema potrebbero essere enormi - I sistemi inaffidabili possono causare perdita di informazioni - Componenti del sistema che possono causare fallimenti (in ordine dal più affidabile al meno affidabile): - Hardware: può fallire a causa di errori nella progettazione, di un guasto a un componente o perché i componenti hanno terminato la loro vita naturale - Software: può fallire a causa di errori nelle sue specifiche, nella sua progettazione o nella sua implementazione - Operatori umani: possono sbagliare a interagire con il sistema - Con l'aumentare dell'affidabilità di software e hardware gli errori umani sono diventati la più probabile causa di difetto di un sistema. Una persona può non usarlo come dovrebbe, come abbiamo pensato che dovesse utilizzarlo o che volontariamente usa il sistema in maniera inopportuna per evitare la fidatezza del sistema e quindi per distruggere l'affidabilità, distruggere la sicurezza, distruggere la protezione e distruggere la disponibilità. - La sicurezza e la protezione dei sistemi critici sono diventate sempre più importanti con l'aumentare delle connessioni di rete - Da una parte le connessioni di rete espongono il sistema ad attacchi da parte di malintenzionati - Dall'altra parte la rete fa in modo che i dettagli delle vulnerabilità siano facilmente divulgati e facilita la distribuzione di patch - Esempi di attacchi sono: - virus - usi non autorizzati dei servizi - modifiche non autorizzate al sistema e ai suoi dati - #highlight(fill: myblue)[Exploit:] metodo che sfrutta un bug o una vulnerabilità, per l'acquisizione di privilegi - #highlight(fill: myblue)[Buffer Overflow:] fornire al programma più dati di quanto esso si aspetti di ricevere, in modo che una parte di questi vadano scritti in zone di memoria dove sono, o dovrebbero essere, altri dati o lo stack del programma stesso - #highlight(fill: myblue)[Shell code:] sequenza di caratteri che rappresenta un codice binario in grado di lanciare una shell, può essere utilizzato per acquisire un accesso alla linea di comando - #highlight(fill: myblue)[Sniffing:] attività di intercettazione passiva dei dati che transitano in una rete - #highlight(fill: myblue)[Cracking:] modifica di un software per rimuovere la protezione dalla copia, oppure per ottenere accesso a un'area riservata - #highlight(fill: myblue)[Spoofing:] tecnica con la quale si simula un indirizzo IP privato da una rete pubblica facendo credere agli host che l'IP della macchina server da contattare sia il suo - #highlight(fill: myblue)[Trojan:] programma che contiene funzionalità maliziose; la vittima è indotta a eseguire il programma poiché questo viene spesso inserito nei videogiochi pirati - #highlight(fill: myblue)[Denial of Service:] il sistema viene forzatamente messo in uno stato in cui i suoi servizi non sono disponibili, influenzando così la disponibilità del sistema ==== Introduzione alla Security Engineering ===== Security Engineering #cfigure("images/2024-03-18-11-53-45.png", 90%) - L'ingegneria della sicurezza è parte del più vasto campo della sicurezza informatica - Nell'ingegnerizzazione di un sistema software #underline[non si può] prescindere dalla consapevolezza delle #underline[minacce] che il sistema dovrà affrontare e dei modi in cui tali minacce possono essere neutralizzate - Quando si considerano le problematiche di sicurezza nell'ingegnerizzazione di un sistema vanno presi in considerazione due aspetti diversi: - la sicurezza dell'applicazione - la sicurezza dell'infrastruttura su cui il sistema è costruito #cfigure("images/2024-03-18-12-16-43.png", 90%) ===== Applicazione e Infrastruttura - La sicurezza di una applicazione è un problema di ingegnerizzazione del software dove gli ingegneri devono garantire che il #text(blue)[*sistema sia progettato per resistere agli attacchi*] - La sicurezza dell'infrastruttura è invece un problema manageriale nel quale gli amministratori dovrebbero garantire che #text(blue)[*l'infrastruttura sia configurata per resistere agli attacchi*] - Gli amministratori dei sistemi devono: - inizializzare l'infrastruttura in modo tale che tutti i servizi di sicurezza siano disponibili - monitorare e riparare eventuali falle di sicurezza che emergono durante l'uso del software ===== Gestione della Sicurezza - Gestione degli utenti e dei permessi: - inserimento e rimozione di utenti dal sistema - autenticazione degli utenti - creazione di appropriati permessi per gli utenti - Deployment e mantenimento del sistema: - installazione e configurazione dei software e del middleware - aggiornamento periodico del software con tutte le patch disponibili - Controllo degli attacchi, rilevazione e ripristino - controllo del sistema per accessi non autorizzati - identificazione e messa in opera di strategie contro gli attacchi - backup per ripristinare il normale utilizzo dopo un attacco ==== Glossario e Minacce ===== Glossario della Sicurezza - #highlight(fill: myblue)[Bene] (Asset): una risorsa del sistema che deve essere protetta - #highlight(fill: myblue)[Esposizione] (Exposure): possibile perdita o danneggiamento come risultato di un attacco andato a buon fine - Potrebbe essere una perdita o un danneggiamento di dati o una perdita di tempo nel ripristino del sistema dopo l'attacco - #highlight(fill: myblue)[Vulnerabilità] (Vulnerability): una debolezza nel sistema software che potrebbe essere sfruttata per causare una perdita o un danno - #highlight(fill: myblue)[Attacco] (Attack): sfruttamento di una vulnerabilità del sistema allo scopo di esporre un bene - #highlight(fill: myblue)[Minaccia] (Threat): circostanza che ha le potenzialità per causare perdite e danni - #highlight(fill: myblue)[Controllo] (Control): una misura protettiva che riduce una vulnerabilità del sistema ===== Tipi di Minacce - #text(blue)[Minacce alla riservatezza del sistema o dei suoi dati]: le informazioni posso essere svelate a persone o programmi non autorizzati - #text(blue)[Minacce all'integrità del sistema o dei suoi dati]: i dati o il software possono essere danneggiati o corrotti - #text(blue)[Minacce alla disponibilità del sistema o dei suoi dati]: può essere negato l'accesso agli utenti autorizzati al software o ai dati - Queste minacce sono interdipendenti - Se un attacco rende il sistema non disponibile, la modifica sulle informazioni potrebbe non avvenire, rendendo così il sistema non integro ===== Tipi di Controllo - #text(blue)[Controlli per garantire che gli attacchi non abbiano successo]: la strategia è quella di progettare il sistema in modo da evitare i problemi di sicurezza - i sistemi militari sensibili non sono connessi alla rete pubblica - crittografia - #text(blue)[Controlli per identificare e respingere attacchi]: la strategia è quella di monitorare le operazioni del sistema e identificare pattern di attività atipici, nel caso agire di conseguenza (spegnere parti del sistema, restringere l'accesso agli utenti, ..) - #text(blue)[Controlli per il ripristino] - backup, replicazione, polizze assicurative #heading(level: 5, numbering: none)[Esempio] - Un sistema informativo ospedaliero mantiene le informazioni personali sui pazienti e sui loro trattamenti - Il sistema deve essere accessibile da differenti ospedali e cliniche attraverso un'interfaccia web - Lo staff ospedaliero deve utilizzare una specifica coppia \<username, password\> per autenticarsi, dove lo username è il nome del dipendente - Il sistema richiede password che siano lunghe almeno 8 caratteri, ma consente ogni password senza ulteriori verifiche #figure(image("images/2024-03-18-12-28-51.png"), caption: "Schema logico") #cfigure("images/2024-03-18-12-29-51.png", 100%) ==== Analisi del Rischio - L'analisi del rischio si occupa di - valutare le possibili perdite che un attacco può causare ai beni di un sistema - bilanciare queste perdite con i costi richiesti per la protezione dei beni stessi #cfigure("images/2024-03-18-12-31-20.png", 90%) - L'analisi del rischio è una problematica più manageriale che tecnica - Il ruolo degli ingegneri della sicurezza è quindi quello di fornire una #text(blue)[guida tecnica e giuridica] sui problemi di sicurezza del sistema - Sarà poi compito dei manager decidere se accettare i costi della sicurezza o i rischi che derivano dalla mancanza di procedure di sicurezza - L'analisi del rischio inizia dalla valutazione delle politiche di sicurezza di organizzazione che spiegano cosa dovrebbe e cosa non dovrebbe essere consentito fare - Le politiche di sicurezza propongono le condizioni che dovrebbero sempre essere mantenute dal sistema di sicurezza, quindi aiutano ad identificare le minacce che potrebbero sorgere - La valutazione del rischio è un processo in più fasi: - #text(blue)[valutazione preliminare del rischio]: determina i requisiti di sicurezza dell'intero sistema - #text(blue)[ciclo di vita della valutazione del rischio]: avviene contestualmente e segue il ciclo di vita dello sviluppo del software; valutare i rischi ogni volta che viene cambiato qualcosa #figure(image("images/2024-03-18-12-34-44.png"), caption: "Valutazione Preliminare del Rischio") ==== Identificazione del bene ===== Analisi del Sistema Informatico - Durante questa fase si può stabilire la seguente agenda delle attività: - Analisi delle risorse fisiche - Analisi delle risorse logiche - Analisi delle dipendenze fra risorse ===== Analisi delle Risorse Fisiche - In questa attività, il sistema informatico viene visto come insiemi di dispositivi che, per funzionare, hanno bisogno di spazio, alimentazione, condizioni ambientali adeguate, protezioni da furti e danni materiali - In particolare occorre: - individuare sistematicamente tutte le risorse fisiche - ispezionare e valutare tutti i locali che ospiteranno le risorse fisiche - verificare la cablatura dei locali ===== Analisi delle Risorse Logiche - Il sistema viene visto come insieme di informazioni, flussi e processi - In particolare occorre: - #text(red)[Classificare le informazioni] in base al valore che hanno per l'organizzazione, il grado di riservatezza e il contesto di afferenza - #text(red)[Classificare i servizi] offerti dal sistema informatico affinché non presentino effetti collaterali pericolosi per la sicurezza del sistema ===== Analisi delle Dipendenze tra Risorse - Per ciascuna risorsa (fisica o logica) occorre individuare di quali altre risorse essa ha bisogno per funzionare correttamente - Questa analisi tende ad evidenziare le risorse potenzialmente critiche, ovvero quelle da cui dipende il funzionamento di un elevato numero di altre risorse - I risultati di questa analisi sono usati anche nella fase di valutazione del rischio - in particolare, sono di supporto allo studio della propagazione dei malfunzionamenti a seguito dell'occorrenza di eventi indesiderati ==== Identificazione delle minacce - In questa fase si cerca di definire quello che #text(red)[#underline[non deve poter accadere]] nel sistema - Si parte dal considerare come evento indesiderato qualsiasi accesso che non sia esplicitamente permesso - A tal fine è possibile in generale distinguere tra - attacchi intenzionali - eventi accidentali ===== Attacchi Intenzionali - Gli attacchi vengono caratterizzati in funzione della risorsa (sia fisica che logica) che viene attaccata e delle possibili tecniche usate per l'attacco - Le tecniche di attacco possono essere classificate in funzione del livello al quale operano - Si distingue tra #text(red)[tecniche a livello fisico] e #text(red)[a livello logico] - Gli attacchi a livello fisico sono principalmente tesi a sottrarre o danneggiare le risorse critiche - Si tratta di - Furto = un attacco alla disponibilità e alla riservatezza - Danneggiamento = un attacco alla disponibilità e alla integrità ===== Attacchi a Livello Logico - Gli attacchi a livello logico sono principalmente tesi a sottrarre informazione o degradare l'operatività del sistema - Dal punto di vista dei risultati che è indirizzato a conseguire un attacco logico può essere classificato come: - #highlight(fill: myblue)[Intercettazione e deduzione] (attacco alla riservatezza): sniffing, spoofing, emulatori... - #highlight(fill: myblue)[Intrusione] (attacco all'integrità e alla riservatezza): IP-spoofing, backdoor... - #highlight(fill: myblue)[Disturbo] (attacco alla disponibilità): virus, worm, denial of service... ===== Eventi Accidentali - Una possibile casistica degli eventi accidentali che accadono più di frequente: - #text(red)[a livello fisico]: - guasti ai dispositivi che compongono il sistema - guasti di dispositivi di supporto (es. condizionatori) - #text(red)[a livello logico]: - perdita di password o chiave hardware - cancellazione di file - corruzione del software di sistema (ad esempio, a seguito dell'installazione di estensioni incompatibili) ===== Valutazione dell'Esposizione - A ogni minaccia occorre associare un rischio così da indirizzare l'attività di individuazione delle contromisure verso le aree più critiche - Per #text(red)[rischio] s'intende una combinazione della probabilità che un evento accada con il danno che l'evento può arrecare al sistema - Nel valutare il danno si tiene conto - delle dipendenze tra le risorse - dell'eventuale propagazione del malfunzionamento ===== Valutazione delle Probabilità: Attacchi Intenzionali - La probabilità di occorrenza di attacchi intenzionali dipende principalmente dalla #text(red)[facilità] di attuazione e dai #text(red)[vantaggi] che potrebbe trarne l'intruso - Il danno si misura come #text(blue)[grado di perdita] dei tre requisiti fondamentali (riservatezza, integrità, disponibilità) - MA l'attaccante applicherà sempre tutte le tecniche di cui dispone, su tutte le risorse attaccabili → necessità di valutare anche il rischio di un #text(red)[attacco composto] - un insieme di attacchi elementari concepiti con un medesimo obiettivo e condotti in sequenza ===== Individuazione del Controllo - Occorre scegliere il controllo da adottare per neutralizzare gli attacchi individuati: - Valutazione del rapporto costo/efficacia - Analisi di standard e modelli di riferimento - Controllo di carattere organizzativo - Controllo di carattere tecnico ===== Valutazione del Rapporto Costo/Efficacia - Valuta il #text(red)[grado di adeguatezza] di un controllo - Mira ad evitare che i controlli presentino un costo ingiustificato rispetto al rischio dal quale proteggono - #text(red)[Efficacia del controllo] definita come funzione del rischio rispetto agli eventi indesiderati che neutralizza - Il costo di un controllo deve essere calcolato senza dimenticare i #text(blue)[costi nascosti] ===== Costi Nascosti - Occorre tenere presenti le limitazioni che i controlli impongono e le operazioni di controllo che introducono nel flusso di lavoro del sistema informatico e dell'organizzazione - Le principali voci di costo sono le seguenti: - costo di messa in opera del controllo - peggioramento dell'ergonomia dell'interfaccia utente - decadimento delle prestazioni del sistema nell'erogazione dei servizi - aumento della burocrazia ===== Controlli di Carattere Organizzativo - #text(blue)[Condizione essenziale] affinché la tecnologia a protezione del sistema informatico risulti efficace è che venga #text(blue)[utilizzata nel modo corretto] da personale pienamente #text(blue)[consapevole] - Devono quindi essere definiti con precisione #text(red)[ruoli] e #text(red)[responsabilità] nella gestione sicura di tale sistema - Per ciascun ruolo, dall'amministratore al semplice utente, devono essere definite #text(red)[norme comportamentali] e #text(red)[procedure precise] da rispettare ===== Controlli di Carattere Tecnico - Controlli di base - a livello del sistema operativo e dei servizi di rete - Controlli specifichi del particolare sistema - si attestano normalmente a livello applicativo - Controlli tecnici più frequenti - configurazione sicura del sistema operativo di server e postazioni di lavoro (contromisura di base) - confinamento logico delle applicazioni server su server dedicati - Etichettatura delle informazioni, allo scopo di avere un controllo più fine dei diritti di accesso - Moduli software di cifratura integrati con le applicazioni - Apparecchiature di telecomunicazione in grado di cifrare il traffico dati in modo trasparente alle applicazioni - Firewall e server proxy in corrispondenza di eventuali collegamenti con reti TCP/IP - Chiavi hardware e/o dispositivi di riconoscimento degli utenti basati su rilevamenti biofisici Integrazione dei Controlli - Un insieme di controlli non deve presentarsi come una “collezione di espedienti” non correlati tra loro - È importante integrare i vari controlli in una politica di sicurezza organica - Operare una selezione dei controlli adottando un sottoinsieme di costo minimo che rispetti alcuni vincoli: - completezza delle contromisure - omogeneità delle contromisure - ridondanza controllata delle contromisure - effettiva attuabilità delle contromisure Vincoli del Sottoinsieme - Completezza: il sottoinsieme deve fare fronte a tutti gli eventi indesiderati - Omogeneità: le contromisure devono essere compatibili e integrabili tra loro - Ridondanza controllata: la ridondanza delle contromisure ha un costo e deve essere rilevata e vagliata accuratamente - Effettiva attuabilità: l'insieme delle contromisure deve rispettare tutti i vincoli imposti dall'organizzazione nella quale andrà ad operare Esempio - Torniamo all'esempio del sistema per la gestione di dati ospedalieri - Quali sono i beni del sistema? - il sistema informativo - il database dei pazienti - i record di ogni paziente Quali sono le minacce? - furto identità dell'amministratore - furto identità di utente autorizzato - DoS Esempio Valutazione del Bene Bene Valore Esposizione Sistema Informativo Alto. Supporto a tutte le consultazioni cliniche Alta. Perdita finanziaria; costi ripristino sistema; danni a pazienti se cure non date Database pazienti Alto. Supporto a tutte le consultazioni cliniche Critico dal punto di vista della sicurezza Alta. Perdita finanziaria; costi ripristino sistema; danni a pazienti se cure non date Record paziente Normalmente basso. Potrebbe essere alto per pazienti particolari Perdita diretta bassa, ma possibile perdita di reputazione della clinica Esempio Analisi Minacce e Controlli Minaccia Probabilità Controllo Fattibilità Furto identità Amministratore Bassa Accesso solo da postazioni specifiche fisicamente sicure Basso costo implementativo ma attenzione alla distribuzione delle chiavi Furto identità utente Alta Meccanismi biometrici Molto costoso e non accettato Log di tutte le operazioni Semplice, trasparente e supporta il ripristino DoS Media Progettazione adeguata, controllo e limitazione degli accessi Basso costo. Impossibile prevedere e impedire questo tipo di attacco Esempio Requisiti di Sicurezza - Alcuni dei requisiti ricavati dalla valutazione preliminare dei rischi - le informazioni relative ai pazienti devono essere scaricate - all'inizio della sessione clinica dal database e memorizzate - in un'area sicura sul client - le informazioni relative ai pazienti non devono essere mantenute - sul client dopo la chiusura della sessione clinica - deve essere mantenuto un log - su una macchina diversa dal server - che memorizzi tutti i cambiamenti effettuati sul database Bene Valore Esposizione Sistema Informativo Alto. Supporto a tutta la gestione del villaggio turistico Alta. Perdita finaziaria e di immagine Informazioni relative agli Ospiti Medio. Dati generali degli ospiti del villaggio turistico Media. Perdita di immagine se vengono divulgati dati degli Ospiti Informazioni relative alle GuestCard Alto. L'elenco degli acquisti è associato alle GuestCard Molto Alta. Perdita finanziaria nel caso gli Ospiticontestino acquisti ingiustamente addebitati. Perdita di immagine Informazioni relative alle vendite Alto. Sulla basedei movimenti nei PuntidiVendita, la CatenaPuntiVenditagestisce i magazzini e i dati fiscali Alta. Perdita finanziaria se i dati delle vendite e delle forniture non coincidono. Perdita di immagine se il servizio che vuole essere acquistato per qualche motivo non è presente Informazioni relative al personale Alto. Ci sono tutte le informazioni relative al personale, comprese le credenziali di accesso Alta. Perdita finanziaria, se vengono rubate le credenziali del personale si possono perpetuare svariate frodi. Perdita di immagine Villaggio Turistico Valutazione del Bene Villaggio Turistico Analisi Minacce e Controlli Minaccia Probabilità Controllo Fattibilità Furto credenziali Operatore Alta. La username è fissata e facile da identificare Accesso da macchine sicure Basso costo di realizzazione ma attenzione se le macchine vengono lasciate incustodite Log delle Operazioni Basso costo implementativo Furto credenziali personale dei punti di vendita Alta. La username è fissata e facile da identificare Accesso da macchine sicure Basso costo di realizzazione ma attenzione se le macchine vengono lasciate incustodite Log delle Operazioni Basso costo implementativo Intercettazione comunicazioni Alta. Il sistema è distribuito e client/server avvengono tantissime interazioni tra i diversi client e il server. Cifratura delle comunicazioni Il costo dipende dal tipo di cifratura scelto. Se simmetrica basso, se asimmetrica più alto dovuto alla necessità di rilascio di coppie di chiavi da un ente di certificazione Log di tutte le operazioni Basso costo implementativo DoS Bassa Progettazione adeguata, controllo e limitazione degli accessi Basso costo. Impossibile prevenire un DoS Ciclo di vita della valutazione del rischio Ciclo di Vita della Valutazione del Rischio - È necessaria la conoscenza dell'architettura del sistema - e dell'organizzazione dei dati - La piattaforma e il middleware sono già stati scelti, - così come la strategia di sviluppo del sistema - Questo significa che si hanno molti più dettagli - riguardo a che cosa è necessario proteggere - e sulle possibili vulnerabilità del sistema - Le vulnerabilità possono essere “ereditate” - dalle scelte di progettazione ma non solo - La valutazione del rischio dovrebbe essere parte - di tutto il ciclo di vita del software: dall'ingegnerizzazione - dei requisiti al deployment del sistema Ciclo di Vita della Valutazione del Rischio - Il processo seguito è simile a quello della valutazione - preliminare dei rischi, con l'aggiunta di attività riguardanti - l'identificazione e la valutazione delle vulnerabilità - La valutazione delle vulnerabilità identifica i beni - che hanno più probabilità di essere colpiti - da tali vulnerabilità - Vengono messe in relazione le vulnerabilità - con i possibili attacchi al sistema - Il risultato della valutazione del rischio è - un insieme di decisioni ingegneristiche - che influenzano la progettazione o l'implementazione - del sistema o limitano il modo in cui esso è usato Esempio - Si supponga che il provider dei servizi ospedalieri decida di acquistare un prodotto commerciale per la gestione dei dati dei pazienti - Questo sistema deve essere configurato per ogni tipo di clinica in cui è utilizzato - Scelte progettuali del sistema acquistato: - autenticazione solo con username e password - architettura client-server: il client accede attraverso - un'interfaccia web standard - l'informazione è presentata agli utenti - attraverso una web form editabile, - è quindi possibile modificare le informazioni Esempio: Vulnerabilità Autenticazione Login/password Tecnologia Vulnerabilità Password <PASSWORD> Utente rivela password Architettura client-server Denial of Service Informazioni nella cache Uso web form editabili Log dettagliati non possibili Stessi permessi per gli utenti Bachi nel browser Esempio - Valutate le vulnerabilità del sistema adottato si deve decidere quali mosse attuare al fine di limitare i rischi associati - Introduzione di nuovi requisiti di sicurezza - Introduzione di un meccanismo di verifica delle password - l'accesso al sistema deve essere permesso - solo ai client approvati e registrati dall'amministratore - tutti i client devono avere un solo browser installato - e approvato dall'amministratore Villaggio Turistico Vulnerabilità Tecnologia Vulnerabilità Autenticazione username/password - Password banali - Utente rivela volontariamente password - Utente rivela password a seguito di un attacco di - Ingegneria Sociale Cifratura comunicazioni Le vulnerabilità dipendono dal tipo di cifratura. Cifratura Simmetrica: - Tempo di vita della chiave. Più informazioni cifro - con la stessa chiave più materiale offro per l'analisi - del testo ad un attaccante - Lunghezza della chiave - Memorizzazione della chiave - Cifratura Asimmetrica: - Memorizzazione chiave privata Architettura Client/Server DoS - Man in the Middle - Sniffing delle comunicazioni Security Use Case e Misuse Case Security Use Case e Misuse Case - I misuse case si concentrano sulle interazioni tra l'applicazione e gli attaccanti che cercano di violarla - La condizione di successo di un misuse case è l'attacco andato a buon fine - Questo li rende particolarmente adatti per analizzare le minacce, ma non molto utili per la determinazione dei requisiti di sicurezza - È invece compito dei security use case specificare i requisiti tramite i quali l'applicazione dovrebbe essere in grado di proteggersi dalle minacce Security Use Cases -<NAME>. Firesmith-JOT Vol. 2, No. 3, May-June 2003 Security Use Case e Misuse Case MisuseCase Security Use Case Uso Analizzare e specificare le minacce Analizzare e specificare i requisiti di sicurezza Criteri di successo Successo attaccanti Successo applicazione Prodotto da Security Team Security Team Usato da Security Team RequirementsTeam Attori Esterni Attaccanti, Utenti Utenti Guidato da Analisi vulnerabilità dei beni e analisi minacce Misusecase Security Use Case e Misuse Case Esempio INTRODUCTION VOL. 2 , NO. 3 JOURNAL OF OBJECT TECHNOLOGY 55 The following table summarizes the primary differences between misuse cases and security use cases. Misuse Cases Security Use Cases Usage Analyze^ and^ specify^ security^ threats. Analyze and specify security requirements Success Criteria Misuser^ Succeeds^ Application^ Succeeds^ Produced By Security^ Team^ Security^ Team^ Used By Security^ Team^ Requirements^ Team^ External Actors Misuser,^ User^ User^ Driven By Asset^ Vulnerability^ Analysis^ Threat Analysis Misuse Cases To further illustrate the differences between normal use cases, security use cases, and associated misuse cases, consider Figure 3. The traditional use cases for an automated teller machine might include Deposit Funds, Withdraw Funds, Transfer Funds, and Query Balance, all of which are specializations of a general Manage Accounts use case. To securely manage one's accounts, one can specify security use cases to control access (identification, authentication, and authorization), ensure privacy (of data and communications), ensure integrity (of data and communications), and ensure nonrepudiation of transactions. The resulting four security use cases specify requirements that protect the ATM and its users from three security threats involving attacks by either crackers or thiefs. Customer Manage Accounts Deposit Funds Withdraw Funds Transfer Funds Query Balance Control Access (Security) Ensure Privacy (Security) Ensure Integrity (Security) Ensure Nonrepudiation (Security) Spoof User (Misuse) Invade Privacy (Misuse) Perpetrate Fraud (Misuse) Cracker Thief Misuse Case Misuser Security Use Case Fig. 3 : Example Security Use Cases and Misuse Cases Security Use Cases -D<NAME>smith-JOT Vol. 2, No. 3, May-June 2003 Esempio: Scenario Security Use Cases -<NAME>-JOT Vol. 2, No. 3, May-June 2003 Villaggio Turistico Punto Vendita CatenaPuntiVendita ElencoVendite Registrazione NuovoMovimento Login ChiusuraCredito GestioneOspite ElencoAcquisti FineSettimana<<event>> FineVacanza<<event>> Operatore OspitePagante <<include>> <<extend>> <<extend>> AperturaCredito <<extend>> <<include>><<extend>> <<include>> Gestione Villaggio Turistico Garantire Protezione (security) Controllo Accesso (security) (misuse)Frode SniffingInformazioni(misuse) FurtoCredenziali(misuse) Truffatore Hacker Villaggio Turistico Titolo ControlloAccesso Descrizione Gliaccessialsistemadevonoesserecontrollati Misusecase SniffingInformazioni,FurtoCredenziali Relazioni Precondizioni L'AttaccantehaimezziperscoprirealmenolausernamediOperatoriepersonaledeipuntivendita Postcondizioni IlSistemabloccamomentaneamentel'accessoall'utenteenotificauntentativodiaccessofraudolento Scenario principale Sistema Attaccante Dopo aver scoperto qualche username tenta di accedere al sistema inserendo passwordconunattaccocondizionario Controllalecredenzialiimmesseebloccal'accessonelcasotali credenzialirisultinoerratedopouncertonumeroditentativi. Scenario di attacco avvenuto consuccesso Sistema Attaccante Attaccocondizionarioriuscito IlSistemacontrollalecredenzialiimmesseeconsentel'accesso alsistema Naviga tra le maschere del sistema e cercadicarpirepiùinformazionipossibili IlSistemascrivenellogtutteleoperazionieseguitedall'utente Il Sistema controllaperiodicamente il logallaricerca di pattern diaccessoatipicieserilevatinotificaunaccessofraudolento Security Use Case: Linee Guida - I casi d'uso non dovrebbero mai specificare meccanismi di sicurezza - Le decisioni relative ai meccanismi devono essere lasciate - alla progettazione - Requisiti attentamente differenziati dalle informazioni secondarie - interazioni del sistema, azioni del sistema e post-condizioni - sono i soli requisiti - Evitare di specificare vincoli progettuali non necessari - Documentare esplicitamente i percorsi individuali attraverso i casi d'uso al fine di specificare i reali requisiti di sicurezza - Basare i security use case su differenti tipi di requisiti di sicurezza fornisce una naturale organizzazione dei casi d'uso Security Use Case: Linee Guida - Documentare le minacce alla sicurezza che giustificano i percorsi individuali attraverso i casi d'uso - Distinguere chiaramente tra interazioni degli utenti e degli attaccanti - Distinguere chiaramente tra le interazioni che sono visibili esternamente e le azioni nascoste del sistema - Documentare sia le precondizioni che le post-condizioni che catturano l'essenza dei percorsi individuali SPECIFICA DEI REQUISITI DI SICUREZZA Requisiti di Sicurezza - Non è sempre possibile specificare i requisiti associati alla sicurezza in modo quantitativo - Quasi sempre questa tipologia dei requisiti è espressa nella forma “non deve” - definisce comportamenti inaccettabili per il sistema - non definisce funzionalità richieste al sistema - L'approccio convenzionale della specifica dei requisiti è basato sul contesto, sui beni da proteggere e sul loro valore per l'organizzazione Categorie Requisiti di Sicurezza - Requisiti di identificazione - specificano se un sistema deve identificare gli utenti - prima di interagire con loro - Requisiti di autenticazione - specificano come identificare gli utenti - Requisiti di autorizzazione - specificano i privilegi e i permessi di accesso - degli utenti identificati - Requisiti di immunità - specificano come il sistema deve proteggersi da virus, worm - e minacce simili Categorie Requisiti di Sicurezza - Requisiti di integrità - specificano come evitare la corruzione dei dati - Requisiti di scoperta delle intrusioni - specificano quali meccanismi utilizzare per scoprire - gli attacchi al Sistema - Requisiti di non-ripudiazione - specificano che una parte interessata in una transazione - non può negare il proprio coinvolgimento - Requisiti di riservatezza - specificano come deve essere mantenuta la riservatezza - delle informazioni Categorie Requisiti di Sicurezza - Requisiti di controllo della protezione - specificano come può essere controllato e verificato - l'uso del sistema - Requisiti di protezione della manutenzione del sistema - specificano come una applicazione può evitare - modifiche autorizzate da un accidentale annullamento - dei meccanismi di protezione Villaggio Turistico Requisiti di Sicurezza - Creazione di un log per tracciare - tutte le azioni che avvengono sul sistema - i messaggi scambiati tra le parti del sistema - - che vanno protetti in un qualche modo per evitare che un accesso - - fraudolento al sistema di log possa rivelare dati riservati - Adottare meccanismi di analisi del log per - identificare pattern di accesso atipici - identificare discrepanze tra i messaggi spediti e ricevuti - Individuare una corretta politica di controllo degli accessi - I dati memorizzati e scambiati nel sistema devono essere protetti == Analisi del problema === Introduzione - #text(red)[Obiettivo]: esprimere fatti il più possibile “oggettivi” sul #text(blue)[#underline[*problema*]] focalizzando l'attenzione su #text(blue)[sottosistemi], #text(blue)[ruoli] e #text(blue)[responsabilità] insiti negli scenari prospettati durante l'analisi dei requisiti #text(blue)[#underline[senza descrivere la sua possibile soluzione]] - #text(red)[Risultato]: - Architettura Logica - Piano di Lavoro - Piano del Collaudo (in che modo collauderemo il sistema) #cfigure("images/2024-03-22-10-41-17.png", 100%) === Passi dell'Analisi del Problema 1. #text(blue)[Analisi del Documento dei Requisiti]\ Obiettivo: concentrarsi sull'analisi delle funzionalità e dei rischi evidenziati nel documento dei requisiti 2. #text(blue)[Analisi dei Ruoli e delle Responsabilità]\ Obiettivo: analizzare bene i ruoli emersi nei casi d'uso e porre particolare attenzione nell'attribuzione delle responsabilità a tali ruoli tenendo conto dell'analisi del rischio 3. #text(blue)[Scomposizione del problema]\ Obiettivo: se possibile suddividere il problema in sotto-problemi più piccoli 4. #text(blue)[Creazione del Modello del Dominio]\ Obiettivo: partendo dal vocabolario si costruisce il diagramma delle classi del dominio; il modello di dominio è il modello delle entità che sono importanti nel dominio applicativo e definisce le relazioni tra tali entità 5. #text(blue)[Architettura Logica: Struttura]\ Obiettivo: creazione dei diagrammi strutturali (package e classi) dell'Architettura Logica 6. #text(blue)[Architettura Logica: Interazione]\ Obiettivo: creazione dei diagrammi di interazione (diagrammi di sequenza) dell'Architettura Logica; specificano le funzionalità 7. #text(blue)[Architettura Logica: Comportamento]\ Obiettivo: creazione dei diagrammi di comportamento (stato e attività) dell'Architettura Logica, se è opportuno che ci siano 8. #text(blue)[Definizione del Piano di Lavoro]\ Obiettivo: assegnare le responsabilità a ciascun membro del team di progetto, stabilire i vincoli temporali, impostare eventuali milestone, ... 9. #text(blue)[Definizione del Piano del Collaudo]\ Obiettivo: definire i risultati attesi da ogni entità (classe, sottosistema) che compare nell'Architettura Logica; scrivere le classi di test per verificare tali risultati #cfigure("images/2024-03-22-10-43-41.png", 100%) ==== Architettura Logica - L'*#text(blue)[Architettura Logica]* è un insieme di modelli UML costruiti per definire una struttura concettuale del problema robusta e modificabile - Attraverso l'Architettura Logica l'analista descrive - #text(blue)[la struttura] (insieme delle parti) - #text(blue)[il comportamento atteso] (da tutto e da ciascuna parte) - #text(blue)[le interazioni] così come possono essere dedotte dai requisiti, dalle caratteristiche del problema e del dominio applicativo *#text(red)[senza alcun riferimento alle tecnologie realizzative]* ==== Piano di Lavoro - Il #text(blue)[Piano di Lavoro] esprime l'articolazione delle attività in termini di risorse - umane - temporali - di elaborazione - ... necessarie allo sviluppo del prodotto in base ai risultati dell'Analisi del Problema ==== Piano del Collaudo - Il #text(blue)[Piano del Collaudo] definisce l'insieme dei risultati attesi da ogni entità definita nell'Architettura Logica in relazione a specifiche sollecitazioni stimolo-risposta prevista - Un modo per impostare il Piano del Collaudo è quello di fornire i test delle classi definite nell'Architettura Logica, così da pianificare già in questa fase i test di integrazione dei vari sottosistemi - Ciò agevola il lavoro della successiva fase di progetto, riducendo il rischio di brutte sorprese in fase di integrazione delle sotto-parti - Strumenti tipici per scrivere i test-case: - JUnit nel mondo Java - NUnit(http://nunit.org/) nel mondo C\# #pagebreak() === Analisi Documento dei Requisiti #cfigure("images/2024-03-22-10-46-37.png", 100%) - Il Documento dei Requisiti evidenzia - le #text(blue)[funzionalità] e i #text(blue)[servizi] che dovranno essere sviluppati (requisiti funzionali) - i #text(blue)[vincoli] che dobbiamo tenere in considerazione (requisiti non funzionali) - il “#text(blue)[mondo esterno]” con cui si dovrà interagire (attori e sistemi esterni) - i “#text(blue)[rischi]” legati a possibili attacchi alla protezione, integrità e privacy dei dati (requisiti di sicurezza) - Partendo da tale documento occorre applicare un'attenta analisi delle singole funzionalità, vincoli, interazioni e rischi #cfigure("images/2024-03-22-10-48-27.png", 95%) ==== Analisi delle Funzionalità - Per ogni funzionalità espressa nei Casi d'Uso vanno analizzati: - _#text(blue)[il tipo, ovvero l'obiettivo della funzionalità]_ : memorizzazione dei dati, interazione con l'esterno, gestione/manipolazione dei dati - etichettiamo la funzionalità in modo da rendere evidente durante la creazione dell'Architettura Logica dove “posizionarla” - se la funzionalità è molto complessa potrebbe appartenere a più tipi differenti:marcare la funzionalità come “complessa” - #text(blue)[_le informazioni coinvolte_]: analisi sistematica di tutte le informazioni sulle quali deve “operare” la funzionalità - In particolare individuare il tipo di dato (composto/singolo) e il grado di riservatezza richiesto - _#text(blue)[il “flusso delle informazioni”]_ : quali sono le informazioni che - #underline[si ricevono in input]: permette di dare indicazioni sulla validazione dell'input e se sono presenti vincoli sui valori ammessi - #underline[vanno prodotte in output]: permette di valutare dall'esterno se la funzionalità si comporta come ci si aspetta #line(length: 100%) - Si possono predisporre diverse tabelle di analisi #cfigure("images/2024-03-22-10-51-43.png", 100%) Se il grado di complessità è alto (Funzionalità complessa), allora bisognerà scomporla in sotto-funzionalità. - La Tabella delle Funzionalità è una sola tabella per tutte le funzionalità - La Tabella delle Informazioni/Flusso è una tabella per ogni funzionalità; è importante specificare ogni funzionalità, anche se prima si sono tralasciate funzionalità semplici ==== Esempio - Tabella Funzionalità per il Villaggio Turistico #cfigure("images/2024-03-22-10-53-26.png", 100%) - Tabella Informazioni/Flusso per NuovoMovimento #cfigure("images/2024-03-22-10-54-04.png", 100%) ==== Analisi dei Vincoli - Per ogni requisito non funzionale vanno analizzati: - #text(blue)[il tipo, ovvero a quale categoria appartiene]: vincoli sulle performance, sui tempi di risposta, sulla scalabilità, sull'usabilità, sulla protezione dei dati, etc... - etichettiamo il requisito in modo da rendere evidente la categoria - alcuni requisiti potrebbero influenzare diversi aspetti del sistema, nel caso indicarli tutti, insieme anche al tipo di impatto (es: portano ad un peggioramento) - #text(blue)[le funzionalità coinvolte]: indicare le funzionalità che vengono influenzate dal requisito - Si può predisporre una tabella #cfigure("images/2024-03-22-10-55-24.png", 100%) ==== Esempio - Tabella Vincoli per il Villaggio Turistico #cfigure("images/2024-03-22-10-55-56.png", 100%) ==== Analisi delle Interazioni - Vanno distinte le interazioni con gli #text(blue)[umani] da quelle con #text(blue)[sistemi esterni] - Nel caso delle interazioni con gli umani - analizzare le eventuali interfacce identificate con il cliente nella fase di Analisi dei Requisiti, oppure delineare le possibili interfacce - individuare le maschere di inserimento/output dati - individuare le sole informazioni necessarie da mostrare in ogni maschera - creare un legame tra maschere - informazioni - funzionalità - Si può predisporre una tabella #cfigure("images/2024-03-22-10-59-16.png", 100%) ==== Esempio - Tabella Maschere per il Villaggio Turistico #cfigure("images/2024-03-22-11-00-16.png", 100%) - Nel caso delle interazioni con sistemi esterni - analizzare ai morsetti i sistemi esterni con cui si dovrà interagire - individuare i protocolli di interazione con tali sistemi #cfigure("images/2024-03-22-11-04-11.png", 100%) ==== Esempio - Tabella Sistemi Esterni per il Villaggio Turistico #cfigure("images/2024-03-22-11-06-45.png", 100%) === Analisi Ruoli e Responsabilità - Per ogni Attore individuato nei Casi d'Uso specificare - le responsabilità - cosa deve fare in ogni funzionalità - specificare le #text(blue)[informazioni a cui può accedere] relativamente a ciascuna funzionalità in cui è coinvolto con relativa indicazione del #text(blue)[tipo di accesso] - le maschere che può visualizzare - il suo livello di riservatezza - quale livello di riservatezza è necessario avere per poter ricoprire quel ruolo - la numerosità attesa - il numero di persone che possono giocare quel ruolo ==== Analisi dei Ruoli e Responsabilità - Si possono predisporre alcune tabelle #cfigure("images/2024-03-22-11-08-17.png", 100%) Come prima, una sola tabella per tutti i ruoli e una tabella per ogni ruolo. Non ha senso specificare una numerosità potenzialmente infinita, perché il numero delle persone che interagiranno con il sistema è una informazione che influenza come il sistema verrà progettato. Se la numerosità cambia nel tempo, probabilmente servirà riprogettare il sistema. È possibile inserire come specifica di numerosità "si progetti il sistema in modo che possa supportare il maggior numero di utenti". ==== Esempio - Tabella Ruoli per il Villaggio Turistico #cfigure("images/2024-03-22-11-09-38.png", 100%) ==== Esempio - Tabella Operatore-Informazioni per il Villaggio Turistico #cfigure("images/2024-03-22-11-09-58.png", 100%) === Scomposizione del Problema - Il punto di partenza è l'Analisi delle Funzionalità - Per ogni funzionalità marcata come “#text(blue)[complessa]” nella Tabella delle Funzionalità occorre valutare se sia possibile operare una scomposizione - la funzionalità può essere suddivisa in sotto-funzionalità più semplici? - quale “legame” sussiste tra le sotto-funzionalità? - quali informazioni devono “fluire” tra le sotto-funzionalità - Si possono predisporre alcune tabelle #cfigure("images/2024-03-22-15-58-43.png", 100%) La tabella Sotto-Funzionalità elenca le dipendenze tra funzionalità. - Tabella Scomposizione Funzionalità per il Villaggio Turistico #cfigure("images/2024-03-22-15-59-45.png", 65%) - Tabella Sotto-Funzionalità per il Villaggio Turistico #cfigure("images/2024-03-22-16-00-46.png", 100%) === Creazione Modello del Dominio - Il punto di partenza è costituito dall'insieme di: - #text(blue)[glossario] definito nell'Analisi dei Requisiti - tabelle informazioni/flusso - Sulla base di questi si costruisce il diagramma delle classi che rappresenta il Modello del Dominio - Tale modello poi sarà riusato nell'Architettura Logica come modello dei dati - Occorre tenere presente che non tutti i vocaboli elencati nel glossario diventeranno classi, si devono infatti evitare: - ridondanze: classi uguali ma con diverso nome - costruzione di classi a partire da termini ambigui nel glossario - nomi che si riferiscono a eventi o operazioni - nomi appartenenti al meta-linguaggio del processo come, per esempio, requisiti e sistema - nomi al di fuori dell'ambito del sistema - nomi che possono essere attributi - Individuare - #text(blue)[Oggetti] e #text(blue)[classi] rilevanti per il problema che si sta analizzando - Limitarsi esclusivamente a quelle classi che fanno parte del vocabolario del dominio del problema, non dell'applicazione in se, quindi evitare, ad esempio, di pensare a "che tipo di classe Java devo sviluppare" - #text(blue)[Relazioni tra le classi] - Per ogni classe - #text(blue)[Attributi] - #text(blue)[Operazioni fondamentali] cioè servizi forniti all'esterno Pensare sempre al "_cosa_" non al "_come_"; il "come" non è l'oggetto di questa fase. #cfigure("images/2024-03-22-16-02-37.png", 100%) Questo schema non è per forza in successione, nel senso che se, mentre stiamo definendo le operazioni di una classe, mi accorgo che c'è bisogno di un attributo, è possibile aggiungerlo. ==== Individuazione delle Classi - Dal glossario eliminare i nomi che sicuramente - non si riferiscono a classi - indicano attributi (dati di tipo primitivo) - indicano operazioni - Scegliere un solo termine significativo se più parole indicano lo stesso concetto (sinonimi) - Il nome della classe deve essere un nome familiare - all'utente o all'esperto del dominio del problema - non allo sviluppatore! - #text(blue)[Attenzione agli aggettivi e agli attributi], possono - indicare oggetti diversi - indicare usi diversi dello stesso oggetto - essere irrilevanti - Ad esempio: - “Studente bravo” potrebbe essere irrilevante - “Studente fuori corso” potrebbe essere una nuova classe - #text(blue)[Attenzione alle frasi passive, impersonali o con soggetti fuori dal sistema]: - devono essere rese attive ed esplicite, perché potrebbero mascherare entità rilevanti per il sistema in esame - Individuare #text(blue)[Attori] con cui il sistema in esame deve interagire - #text(blue)[Persone]: Docente, Studente, Esaminatore, Esaminando, ... - #text(blue)[Sistemi esterni]: ReteLocale, Internet, DBMS, ... - #text(blue)[Dispositivi]: attuatori, sensori, ... - Individuare #text(blue)[modelli] e #text(blue)[loro elementi specifici]: - Insegnamento - “Ingegneria del Software T” - CorsoDiStudio -“Ingegneria Informatica” - Facoltà - “Ingegneria” - Individuare #text(blue)[cose tangibili], cioè oggetti reali appartenenti al dominio del problema - Banco, LavagnaLuminosa, Schermo, Computer, ... - Individuare #text(blue)[contenitori] (fisici o logici) di altri oggetti - Facoltà, Dipartimento, Aula, SalaTerminali, ... - ListaEsame, CommissioneDiLaurea, OrdineDegliStudi, ... - Individuare #text(blue)[eventi] o #text(blue)[transazioni] che il sistema deve gestire e memorizzare - possono avvenire in un certo istante (es., una vendita) o - possono durare un intervallo di tempo (es., un affitto) - Appello, EsameScritto, Registrazione, AppelloDiLaurea, ... - Per determinare se includere una classe nel modello, porsi le seguenti domande: - il sistema deve interagire in qualche modo con gli oggetti della classe? - #text(blue)[utilizzare informazioni] (attributi) contenute negli oggetti della classe - #text(blue)[utilizzare servizi] (operazioni) offerti dagli oggetti della classe - quali sono le responsabilità della classe nel contesto del sistema? - Attributi e operazioni devono essere applicabili a tutti gli oggetti della classe - Se esistono - attributi con un valore ben definito solo per alcuni oggetti della classe - operazioni applicabili solo ad alcuni oggetti della classe siamo in presenza di #text(blue)[ereditarietà] - Esempio: dopo una prima analisi, la classe Studente potrebbe contenere un attributo booleano inCorso, ma un'analisi più attenta potrebbe portare alla luce la gerarchia: - Studente: StudenteInCorso, StudenteFuoriCorso ==== Individuazione delle Classi: Villaggio Turistico #cfigure("images/2024-03-22-16-06-33.png", 100%) - Villaggio Turistico è in verde perché è una classe che non viene creata, dato che non serve; se, invece, avessimo avuto un progetto che prevedeva molteplici villaggi turistici, allora avrebbe avuto senso definire la classe `VillaggioTuristico` - I nomi in rosso sono delle classi, tra l'altro con una probabile gerarchia (alcune) - Forse `Stanza` e `StanzaCollegata` sono una gerarchia #cfigure("images/2024-03-22-16-07-27.png", 100%) ==== Individuazione delle Relazioni - La maggior parte delle classi (degli oggetti) #text(blue)[interagisce] con altre classi (altri oggetti) in vari modi - In ogni tipo di relazione, esiste un cliente C che dipende da un fornitore di servizi F - C ha bisogno di F per lo svolgimento di alcune funzionalità che C non è in grado di effettuare autonomamente - Conseguenza per il corretto funzionamento di C è indispensabile il corretto funzionamento di F #cfigure("images/2024-03-22-16-08-12.png", 100%) - Nell'associazione il fornitore è il contenuto e il cliente è il contenitore, perché il contenitore contenendo il contenuto può usare i servizi del contenuto ==== Individuazione dell'Ereditarietà - L'ereditarietà deve rispecchiare una tassonomia effettivamente presente nel dominio del problema - Non usare l'ereditarietà dell'implementazione (siamo ancora in fase di analisi!) - Non usare l'ereditarietà solo per riunire caratteristiche comuni - ad es., Studente e Dipartimento hanno entrambi un indirizzo, ma non per questo c'è ereditarietà! ==== Ereditarietà: Villaggio Turistico #cfigure("images/2024-03-22-16-11-00.png", 100%) - Tutte le ereditarietà di questo caso sono complete e disgiunte; cioè non esistono ospiti che non siano paganti e non paganti e un ospite è o pagante o non pagante, non esistono ospiti non paganti che non siano minorenni e maggiorenni e un ospite non pagante è o minorenne o maggiorenne ==== Individuazione delle Associazioni - Un'associazione rappresenta una relazione strutturale tra due istanze di classi diverse o della stessa classe - Un'associazione può - Rappresentare un contenimento logico (#text(blue)[aggregazione]) - Una lista d'esame contiene degli studenti - Rappresentare un contenimento fisico (#text(blue)[composizione]) - Un triangolo contiene tre vertici - Non rappresentare un reale contenimento - Una fattura si riferisce a un cliente - Un evento è legato a un dispositivo === Individuazione delle Associazioni - #text(blue)[Aggregazione]\ Un oggetto x di classe X è associato a (contiene) un oggetto y di classe Y in modo non esclusivo x può condividere y con altri oggetti anche di tipo diverso (che a loro volta possono contenere y) - Una lista d'esame contiene degli studenti - Uno studente può essere contemporaneamente in più liste d'esame - La cancellazione della lista d'esame non comporta l'eliminazione “fisica” degli studenti in lista - #text(blue)[Composizione]\ Un oggetto x di classe X è associato a (contiene) un oggetto y di classe Y #text(blue)[in modo esclusivo] y esiste solo in quanto contenuto in x - Un triangolo contiene tre punti (i suoi vertici) - L'eliminazione del triangolo comporta l'eliminazione dei tre punti - Se la distruzione del contenitore comporta la distruzione degli oggetti contenuti, si tratta di composizione, altrimenti si tratta di aggregazione - Attenzione alle associazioni molti a molti possono nascondere una classe (classe di associazione) del tipo “evento da ricordare” - Ad esempio, - la connessione “matrimonio” tra Persona e Persona può nascondere una classe Matrimonio, che lega due Persone - la connessione “possiede” tra Proprietario e Veicolo può nascondere una classe CompraVendita, che lega un Proprietario a un Veicolo ==== 1 ° Esempio di Associazione #cfigure("images/2024-03-22-16-13-31.png", 100%) #cfigure("images/2024-03-22-16-13-49.png", 100%) Quindi, quando l'associazione ha delle informazioni, o più raramente del comportamento, si introduce la classe d'associazione. ==== 2 ° Esempio di Associazione #cfigure("images/2024-03-22-16-14-47.png", 100%) - Qui c'è un vincolo particolare, che è quello di tenere in conto del caso in cui una persona compra un veicolo da solo e, successivamente, vuole averlo in comproprietà - Da notare che ci può essere solo un'istanza della classe di associazione per ogni coppia di oggetti associati ==== Associazioni: Villaggio Turistico #cfigure("images/2024-03-22-16-15-30.png", 100%) #cfigure("images/2024-03-22-16-15-47.png", 100%) ==== Individuazione Collaborazioni - Una classe A è in relazione USA con una classe B (A USA B) quando A ha bisogno della collaborazione di B per lo svolgimento di alcune funzionalità che A non è in grado di effettuare autonomamente - Un'operazione della classe A ha bisogno come argomento di un'istanza della classe B - `voidfun1(B b) { ... usa b ... }` - Un'operazione della classe A restituisce un valore di tipo B - `B fun2(...) { B b; ... return b; }` - Un'operazione della classe A utilizza un'istanza della classe B (ma non esiste un'associazione tra le due classi) - `void fun3(...) { B b = new B(...); ... usa b ... }` - La relazione non è simmetrica: A dipende da B, ma B non dipende da A - Evitare situazioni in cui una classe, tramite una catena di relazioni USA, alla fine dipende da se stessa #cfigure("images/2024-03-22-16-17-13.png", 100%) ==== Individuazione degli Attributi - Ogni attributo modella una proprietà atomica di una classe - Un valore singolo - Una descrizione, un importo, .. - Un gruppo di valori strettamente collegati tra loro - Un indirizzo, una data, .. - Proprietà non atomiche di una classe devono essere modellate come associazioni - A tempo di esecuzione, in un certo istante, ogni oggetto avrà un valore specifico per ogni attributo della classe di appartenenza: informazione di stato - La base di partenza per la ricerca degli attributi sono le Tabelle di Informazione/Flusso - Il nome dell'attributo - deve essere un nome familiare - all'utente o all'esperto del dominio del problema - non allo sviluppatore! - non deve essere il nome di un valore (“qualifica” sì, “ricercatore” no) - deve iniziare con una lettera minuscola - Esempi - cognome, dataDiNascita, annoDiImmatricolazione - Esprimere tutti i vincoli applicabili all'attributo - Tipo (semplice o enumerativo) - Opzionalità - Valori ammessi - dominio, anti-dominio, univocità - Vincoli di creazione - valore iniziale di default, immodificabilità del valore (readonly), etc. - Vincoli dovuti ai valori di altri attributi - Unità di misura, precisione - Esprimere tutti i vincoli applicabili all'attributo - #text(blue)[Visibilità] (opzionale in fase di analisi) Attenzione: #text(blue)[gli attributi membro devono essere sempre privati!] - Appartenenza alla classe (e non all'istanza) Attributi (e associazioni) possono essere di classe, cioè essere unici nella classe - numIstanze: int = 0 - I vincoli possono essere scritti - Utilizzando direttamente UML - Utilizzando Object Constraint Language (OCL) - Come testo in formato libero in un commento UML #cfigure("images/2024-03-22-16-18-49.png", 85%) - Attenzione: nel caso di attributi con valore booleano “vero o falso”, “sì o no”, il nome dell'attributo potrebbe essere uno dei valori di un'enumerazione - Ad esempio: tassabile (sì o no) potrebbe diventare tipoTassazione{ tassabile, esente, ridotto, ... } - Attenzione: attributi - con valore “non applicabile” o - con valore opzionale o - a valori multipli (enumerazioni) possono nascondere ereditarietà o una nuova classe #cfigure("images/2024-03-22-16-19-21.png", 100%) - Attenzione: nel caso di attributi calcolabili (ad esempio, età), specificare sempre l'operazione di calcolo mai l'attributo - se memorizzare oppure no un attributo calcolabile è una decisione progettuale, un compromesso tra tempo di calcolo e spazio di memoria - Applicare l'ereditarietà: - Posizionare attributi e associazioni più generali più in alto possibile nella gerarchia - Posizionare attributi e associazioni specializzati più in basso ==== Individuazione degli Attributi: Villaggio Turistico #cfigure("images/2024-03-22-16-20-18.png",100%) #cfigure("images/2024-03-22-16-20-58.png",100%) - GuestCard una classe, l'identificativo sarà mappato con una associazione - Saldo nasconde una nuova classe, associata alle funzionalità di Apertura e Chiusura Credito →L'ospite ha un conto aperto presso il Villaggio Turistico - Movimento è relativo all'uso della GuestCard #cfigure("images/2024-03-22-16-24-20.png",100%) ==== Individuazione delle Operazioni - Il nome dell'operazione - deve appartenere al vocabolario standard del dominio del problema - potrebbe essere un verbo - all'imperativo (scrivi, esegui, ...) o - in terza persona (scrive, esegue, ...) - in modo consistente in tutto il sistema - Operazioni standard - Operazioni che tutti gli oggetti hanno per il semplice fatto di esistere e di avere degli attributi e delle relazioni con altri oggetti (costruttore, accessori, ...) - Sono implicite e, di norma, non compaiono nel diagramma delle classi di analisi - Altre operazioni - Devono essere determinate - servizi offerti agli altri oggetti - Compaiono nel diagramma delle classi di analisi - Classi contenitori - Operazioni standard - aggiungi, rimuovi, conta, itera, ... - Altre operazioni - riguardano l'insieme degli oggetti, non il singolo oggetto - Calcoli da effettuare sugli oggetti contenuti Es: calcolaSulleParti(), totalizza() - Selezioni da fare sugli oggetti contenuti Es: trovaPartiSpecifiche() - Operazioni del tipo Es: eseguiUnAzioneSuTutteLeParti() - Distribuire in modo bilanciato le operazioni nel sistema - Mettere ogni operazione “vicino” ai dati a essa necessari - Applicare l'ereditarietà - Posizionare le operazioni più generali più in alto possibile nella gerarchia - Posizionare le operazioni specializzate più in basso - Descrivere tutti i vincoli applicabili all'operazione - Parametri formali, loro tipo e significato - Pre-condizioni, post-condizioni, invarianti di classe - Eccezioni sollevate - Eventi che attivano l'operazione - Applicabilità dell'operazione - ... - #highlight(fill: myblue)[Pre-condizione]\ Espressione logica riguardante le aspettative sullo stato del sistema prima che venga eseguita un'operazione - Esplicita in modo chiaro che è responsabilità della procedura chiamante controllare la correttezza degli argomenti passati - Ad esempio, per l'operazione *`CalcolaRadiceQuadrata(valore)`* , la pre-condizione potrebbe essere: “ *`valore ≥ 0`* ” - #highlight(fill: myblue)[Post-condizione]\ Espressione logica riguardante le aspettative sullo stato del sistema dopo l'esecuzione di un'operazione - Ad esempio, per l'operazione *CalcolaRadiceQuadrata(valore)* , la post-condizione potrebbe essere: `valore == risultato * risultato` - #highlight(fill: myred)[Invariante di classe]\ Vincolo di classe (espressione logica) che deve essere sempre verificato - sia all'inizio - sia alla fine di tutte le operazioni pubbliche della classe Può non essere verificato solo durante l'esecuzione dell'operazione - ECCEZIONE Si verifica quando un'operazione - viene invocata nel rispetto delle sue pre-condizioni - ma non è in grado di terminare la propria esecuzione nel rispetto delle post-condizioni ==== Esempio Modello del Dominio “Vendita Servizi” per il Villaggio Turistico #cfigure("images/2024-03-26-12-01-43.png",100%) Modello del Dominio “Ospite” per il Villaggio Turistico #cfigure("images/2024-03-26-12-02-40.png", 100%) Modello del Dominio “Pagamenti” per il Villaggio Turistico #cfigure("images/2024-03-26-12-03-09.png", 100%) Modello del Dominio “Log” per il Villaggio Turistico #cfigure("images/2024-03-26-12-03-33.png", 100%) === Architettura Logica: Struttura *N.B.* Le parti "Struttura", "Interazione" e "Comportamento" dell'architettura logica vanno sviluppate contestualmente (in contemporanea?). - La parte strutturale dell'Architettura Logica dovrebbe essere composta di due tipi differenti di diagrammi UML - #text(blue)[Diagramma dei Package] \ che fornisce una visione di alto livello dell'architettura - #text(blue)[Diagramma delle classi] \ (uno o più diagrammi in base alla complessità) che fornisce una visione più dettagliata del contenuto dei singoli package - Sarebbe opportuno organizzare sin da subito l'Architettura Logica usando un pattern architetturale chiamato #text(blue)[*Boundary-Control-Entity*] (BCE) ==== BCE - BCE è un pattern architetturale che suggerisce di basare l'architettura di un sistema sulla partizione sistematica degli use case in oggetti di tre categorie: - #highlight(fill: myred)[informazione] - #highlight(fill: myred)[presentazione] - #highlight(fill: myred)[controllo] #cfigure("images/2024-03-26-12-06-04.png", 65%) Noi useremo una convenzione più semplice → coloriamo package e classi in modo diverso - A ciascuna di queste dimensioni corrisponde uno specifico insieme di classi - Tale pattern è stato introdotto anche in RUP e sono state adottate icone ben particolari - BCE è un pattern architetturale che suggerisce di basare l'architettura di un sistema sulla partizione sistematica degli use case in oggetti di tre categorie: - informazione - presentazione - controllo - #highlight(fill: myblue)[_Entity:_] è la dimensione relativa alle entità cui corrisponde l'insieme delle classi che includono funzionalità relative alle informazioni che caratterizzano il problema; sostanzialmente ci dice quali sono le entità di interesse nel dominio del problema - costituiscono gran parte del modello del dominio - #highlight(fill: myblue)[_Boundary:_] è la dimensione relativa alle funzionalità che dipendono dall'ambiente esterno cui corrisponde l'insieme delle classi che incapsulano l'interfaccia del sistema verso il mondo esterno - #highlight(fill: myblue)[_Control:_] è la dimensione relativa agli enti che incapsulano il controllo - il loro compito è di fare da _collante_ tra le interfacce e le entità - Impostare l'architettura di un sistema software distinguendo tra _boundary_ , _control_ ed _entity_ costituisce un solido punto di partenza per l'organizzazione dell'Architettura Logica di molte applicazioni - L'analista tende ad affrontare la complessità dei problemi partizionando i problemi stessi in sotto-problemi - È del tutto logico che un analista eviti di associare alle entità di un dominio - sia le funzionalità di una specifica applicazione - sia le funzionalità tipiche della interazione con l'utente - La conseguenza è che l'architettura di un sistema software risulta quasi fisiologicamente articolata in una sequenza di livelli (_layer_) verticali che viene tipicamente mantenuta anche in fase di progetto e implementazione ==== Layer - È naturale separare la parte che realizza le entità dell'applicazione (dominio) dalla parte che realizza l'interazione con l'utente (logica di presentazione), introducendo una parte centrale di connessione (control) - Nello specifico: - il livello di #text(blue)[*_presentazione_*] comprende le parti che realizzano l'interfaccia utente - Per aumentare la riusabilità delle parti, questo livello èprogettato e costruito astraendo quanto più possibile dai dettagli degli specifici dispositivi di I/O - il livello di #text(blue)[*_applicazione_*] comprende le parti che provvedono a elaborare l'informazione di ingresso, a produrre i risultati attesi e a presentare le informazioni in uscita - il livello delle #text(blue)[*_entità_*] forma il (modello del) dominio applicativo ==== Struttura: Package - Usando come base di partenza il lavoro di analisi svolto nelle fasi precedenti e tenendo in considerazione il pattern BCE si può iniziare la creazione del Diagramma dei Package che rappresenta la visione dal alto livello dell'Architettura Logica - Il primo package che si può identificare è il package costituito dal #text(blue)[Modello del Dominio] creato nella fase precedente - tale Modello (se ben realizzato) costituisce la parte “#text(blue)[entity]” dell'architettura - Poi è possibile creare un package per ognuna delle diverse funzionalità identificate nella Tabella delle Funzionalità (“control”); ciascuna delle righe della tabella diventa un package di controllo - Vengono creati uno o più package per la parte di “boundary” - Infine si identificano le _dipendenze logiche_ tra i package #cfigure("images/images/2024-03-26-13-48-53-png.png", 90%) #cfigure("images/2024-03-26-13-49-53.png", 90%) #pagebreak() ==== Esempio Diagramma dei Package per il Villaggio Turistico #cfigure("images/2024-03-26-13-50-45.png", 100%) ==== Struttura: Classi - Dopo aver stabilito la struttura di alto livello dell'Architettura Logica #text(red)[si dettagliano le classi che compongono ogni package] - Il Package del Dominio è già stato identificato nel Modello del Dominio - Se le classi da specificare per ogni package sono poche si può realizzare un unico diagramma delle classi - Altrimenti è possibile creare un diagramma delle classi separato per ogni package - Attenzione a non introdurre scelte di progettazione in questa fase - Indicare solo quelle classi che sono deducibili dal problema - in genere viene inserita almeno una classe che realizza le funzionalità indicate nelle specifiche - se nel diagramma dei package è stata indicata una funzionalità che nella fase precedente era stata poi scomposta si possono indicare le classi che realizzano le sotto-funzionalità - indicare le classi che rappresentano le maschere di interazione con l'utente identificate nelle fasi precedenti ==== Esempio - Diagramma delle classi per il Villaggio Turistico - Diagramma delle classi: `InterfacciaCommesso` & `GestionePuntoVendita` #cfigure("images/2024-03-26-13-52-51.png", 90%) - Diagramma delle classi per il Villaggio Turistico - Diagramma delle classi: `InterfacciaLog` & `Log` #cfigure("images/2024-03-26-13-53-41.png", 100%) === Architettura Logica: Interazione - Descrivere le interazioni tra le entità identificate nella parte strutturale attraverso opportuni Diagrammi di Sequenza - I #text(blue)[Diagrammi di sequenza] evidenziano - lo scambio di messaggi (le interazioni) tra gli oggetti - l'ordine in cui i messaggi vengono scambiati tra gli oggetti (sequenza di invocazioni delle operazioni) - Non spingere la definizione dei diagrammi di sequenza sino ai minimi dettagli - Utilizzare i diagrammi solo per descrivere il funzionamento del sistema - in risposta a sollecitazioni esterne - in fasi particolarmente significative - nei casi più critici - Non serve mostrare tutti i diagrammi di interazione, ma magari fare vedere quelli più interessanti e/o complicati ==== Esempio Diagramma di sequenza per il Villaggio Turistico #cfigure("images/2024-03-26-13-56-06.png", 100%) *N.B.* Mai fare vedere la password nel modello del dominio. L'interfaccia che gestisce il login avrà un auto-anello, quindi solo lei dovrà gestire il controllo password; #underline[come] realizzare questa cosa si vedrà in progettazione. === Architettura Logica: Comportamento - Descrivere il comportamento delle entità identificate nella parte strutturale attraverso opportuni Diagrammi di Stato o delle Attività - Diagramma di Stato per mostrare come si comportano alcune entità complesse a seguito delle interazioni e degli eventi che avvengono nel sistema - Diagramma delle Attività per dettagliare funzionamenti complessi delle entità - Non spingere la definizione dei diagrammi sino ai minimi dettagli - Lo stato di un oggetto è dato dal valore dei suoi attributi e delle sue associazioni - In molti domini applicativi, esistono oggetti che, a seconda del proprio stato, rispondono in maniera diversa ai messaggi ricevuti - Dispositivi (spento, in attesa, operativo, guasto, ecc.) - Transazioni complesse (in definizione, in esecuzione, completata, fallita, ecc.) - In questi casi, è opportuno disegnare un diagramma di stato per l'oggetto, mostrando i possibili stati e gli eventi che attivano transizioni da uno stato all'altro - A un oggetto possono essere assegnate responsabilità che comportano un insieme di elaborazioni complesse che devono essere eseguite in un ordine particolare - In questi casi, è opportuno disegnare un diagramma di attività per l'oggetto, mostrando le diverse elaborazioni che devono essere portate a termine e l'ordine di tali elaborazioni ==== Esempio Diagramma di stato per `AnomalieMessaggi` #cfigure("images/2024-03-26-13-57-51.png", 100%) === Definizione del Piano di Lavoro - Dopo la creazione dell'Architettura Logica è possibile iniziare a suddividere il lavoro - In particolare è necessario: - suddividere le responsabilità ai diversi membri del team di progetto e sviluppo - stabilire le tempistiche per la progettazione di ciascuna parte - stabilire i tempi di sviluppo di ciascun sotto-sistema - programmare i test di integrazione tra le parti - identificare i tempi di rilascio delle diverse versioni del prototipo - identificare un piano per gli sviluppi futuri ==== Esempio #cfigure("images/2024-03-26-13-58-40.png", 100%) === Definizione del Piano del Collaudo - Al termine dell'Analisi del Problema, i modelli che definiscono il dominio e l'Architettura Logica dovrebbero dare sufficienti informazioni su #text(blue)[*_cosa_*] le varie parti del sistema debbano fare senza specificare ancora molti dettagli del loro comportamento - Il “#text(blue)[*_cosa fare_*]” di una parte dovrà comprendere anche le forme di interazione con le altre parti - Lo scopo del #text(blue)[*_piano del collaudo_*] è cercare di precisare il comportamento atteso da parte di una entità prima ancora di iniziarne il progetto e la realizzazione - Focalizzando l'attenzione sulle interfacce delle entità e sulle interazioni è possibile impostare scenari in cui specificare in modo già piuttosto dettagliato la “risposta” di una parte a uno “stimolo” di un'altra parte - Lo sforzo di definire nel modo #text(red)[più preciso possibile] un piano del collaudo di un sistema prima ancora di averne iniziato la fase di progettazione viene ricompensato da - una #text(blue)[miglior comprensione] dei requisiti - un approfondimento nella #text(blue)[comprensione dei problemi] - una più precisa definizione dell'insieme delle funzionalità (operazioni) che ciascuna parte deve fornire alle altre per una #text(blue)[effettiva integrazione] nel “tutto” che costituirà il sistema da costruire - comprendere il #text(blue)[significato delle entità] e specificarne nel modo più chiaro possibile il #text(blue)[comportamento atteso] ==== Definizione Piano del Collaudo - Un piano del collaudo va concepito e impostato da un punto di #text(blue)[_*vista logico*_], cercando di individuare categorie di comportamenti e punti critici - In molti casi tuttavia può anche risultare possibile definire in modo precoce #text(blue)[piani di collaudo concretamente eseguibili], avvalendosi di strumenti del tipo JUnit/NUnit che sono ormai diffusi in tutti gli ambienti di programmazione - Lo sforzo di definire un piano di collaudo concretamente eseguibile promuove uno sviluppo #text(red)[controllato, sicuro e consapevole] del codice poiché il progettista e lo sviluppatore possono verificare subito in modo concreto la correttezza di quanto sviluppato ==== JUnit - JUnit (https://junit.org/junit5/docs/current/user-guide/) è un framework per unit-testing per il linguaggio Java - Dovreste conoscerlo già bene da Fondamenti T-2 ==== NUnit - NUnit (http://nunit.org/) è un framework per unit-testing per tutti i linguaggi .Net - NUnit è inizialmente derivato da JUnit, ma è stato totalmente riscritto dalla versione 3 - Troverete la documentazione e la guida all'installazione a https://github.com/nunit/docs/wiki/Framework-Release-Notes == Progettazione === Introduzione - #text(red)[Obiettivo:] attraverso una serie di raffinamenti successivi dell'Architettura Logica arrivare ad ottenere #text(blue)[l'Architettura del Sistema]\ #text(blue)[Vanno considerati anche tutti gli aspetti vincolanti che sono stati trascurati nelle fasi precedenti] - Questa fase deve mirare non solo a individuare e descrivere una soluzione al problema (#text(red)[what/how]), ma soprattutto a descrivere i #text(blue)[motivi] (#text(red)[why]) che l'hanno determinata - #text(red)[Risultato]: - Architettura del Sistema - Schema Persistenza - Piano finale del Collaudo - Indicazioni per il Deployment #cfigure("images/2024-04-26-12-52-24.png",15%) + #text(blue)[*Progettazione Architetturale*]\ #underline[Obiettivo:] definire l'Architettura del Sistema tenendo conto di tutti i vincoli e delle forze in gioco + #text(blue)[*Progettazione di Dettaglio*]\ #underline[Obiettivo:] progettare nel dettaglio ogni aspetto del Sistema + #text(blue)[*Progettazione della Persistenza*]\ #underline[Obiettivo:] progettare i meccanismi per la persistenza dei dati + #text(blue)[*Progettazione del Collaudo*]\ #underline[Obiettivo:] definire in modo chiaro e preciso come il sistema dovrà essere collaudato una volta terminata l'implementazione + #text(blue)[*Progettazione per il Deployment*]\ #underline[Obiettivo:] progettare il sistema in modo da rendere semplice il deployment sulle macchine e per garantire la sicurezza #cfigure("images/2024-04-26-12-55-41.png",100%) === Progettazione Architetturale - Nella Progettazione Architetturale gli ingegneri devono prendere delle decisioni che influenzano profondamente il sistema - Basandosi sulle proprie esperienze e conoscenze devono rispondere ad alcune domande fondamentali: + C'è un'architettura applicativa generica che può essere utilizzata come modello per il sistema che sto progettando? + Come sarà distribuito il sistema tra più processori? + Quale stile o quali stili sono adatti al sistema? + Quale sarà l'approccio fondamentale utilizzato per strutturare il sistema? + Come saranno scomposte in moduli le unità strutturali del sistema? + Quale strategia sarà usata per controllare l'operato delle unità del sistema? #cfigure("images/2024-04-26-12-57-50.png",100%) ==== Requisiti Non Funzionali - L'architettura del sistema influenza - le #highlight(fill: myred)[prestazioni] - la #highlight(fill: myred)[robustezza] - la #highlight(fill: myred)[distribuibilità] - la #highlight(fill: myred)[manutenibilità] di un sistema - La struttura dell'architettura tipicamente è condizionata - dalla #text(blue)[tipologia di applicazione] che si vuole realizzare - dai #text(blue)[requisiti non funzionali] - Se le #text(blue)[*prestazioni*] sono un requisito critico l'architettura dovrebbe essere progettata - localizzando le operazioni critiche all'interno di un piccolo numero di componenti - minimizzando le comunicazioni possibile tra essi - Questo porta a dover definire componenti “#text(blue)[grandi]” per ridurre la comunicazione - Se la #text(blue)[*protezione dei dati (_security_)*] è un requisito critico l'architettura dovrebbe essere progettata - con una struttura “stratificata” - collocando le risorse più critiche nello strato più interno e protetto - Questo porta a dover definire una struttura con un alto livello di convalida di protezione a ogni strato - *NB:* Quando si valuta l'aspetto della protezione dei dati tenere conto di tutte le indicazioni che sono emerse nella parte della Security Engineering - Se la sicurezza (safety) è un requisito critico l'architettura dovrebbe essere progettata - in modo tale che le operazioni relative siano tutte collocate in un singolo componente o in un piccolo insieme di componenti - riduzione dei costi e dei problemi di convalida della sicurezza, possibilità di poter fornire sistemi di protezione correlati - Questo porta a dover definire componenti “#text(blue)[grandi]” per localizzare le operazioni - Se la #text(blue)[*disponibilità*] è un requisito critico l'architettura dovrebbe essere progettata - per comprendere componenti ridondanti - in modo che sia possibile sostituirli e aggiornarli senza fermare il sistema - Questo porta a dover sviluppare un numero maggiore di componenti rispetto a quelli strettamente necessari - Se la #text(blue)[*manutenibilità*] è un requisito critico l'architettura dovrebbe essere progettata - usando componenti piccoli, atomici, autonomi - che possano essere modificati velocemente - i produttori di informazione dovrebbero essere separati dai consumatori e le strutture dati condivise dovrebbero essere evitate - Questo porta a dover sviluppare componenti di piccole dimensioni - Ci sono dei conflitti potenziali tra alcune di queste architetture così come abbiamo visto sussistono conflitti tra i requisiti non funzionali - Esempio: usare componenti “grossi” migliora le prestazioni ma peggiora la manutenibilità e viceversa - Se sono entrambi requisiti critici occorre trovare un compromesso ==== Esempio Nell'Analisi del Problema (<NAME>) sono emersi tre requisiti non funzionali che impongono dei vincoli al sistema: - Tempo di risposta - Usabilità - Sicurezza Nello specifico caso in esame, Usabilità e Sicurezza hanno pochi conflitti a parte l'eventuale richiesta di un ulteriore login se per caso scade la sessione di lavoro. L'Usabilità impatta molto di più la struttura delle interfacce che andranno progettate in modo tale da mantenere nelle stesse View le informazioni necessarie alle funzionalità richieste Diversa la questione che riguarda Tempo di risposta e Sicurezza, aggiungere strati (layer) e meccanismi di cifratura per migliorare la sicurezza ovviamente porta ad un peggioramento delle prestazioni del sistema, occorre quindi trovare un bilanciamento tra i due aspetti. Considerando la tipologia di sistema che deve essere sviluppato, si ritiene maggiormente critico l'aspetto di sicurezza dei dati in quanto la “T<NAME>” mette in luce che nel caso di attacchi al sistema andati a buon fine si rischia un'esposizione molto alta con perdite finanziarie e di immagine. Inoltre, gli utenti principali di tale sistema sono operatori umani che spesso non sono in grado di percepire se il Sistema impiega qualche frazione di secondo in più o in meno nella risposta, non si hanno vincoli real-time da soddisfare. ==== Scelta Architettura - La scelta dell'Architettura del Sistema deve basarsi su: - Architettura Logica definita in fase di Analisi del Problema - Trade-off requisiti non funzionali - Tipologia di applicazione che si intende sviluppare - Adozione di Pattern Architetturali - Blackboard - MVC/BCE - Layers - Client/Server - Broker - Pipe & Filters - ... ===== Blackboard - Il pattern Blackboard aiuta a strutturare quelle applicazioni in cui vengono applicate strategie di soluzione non deterministiche (tipici problemi di intelligenza artificiale) - I diversi sotto-sistemi condividono la stesse conoscenze attraverso la Blackboard al fine di costruire una soluzione approssimata o parziale #cfigure("images/2024-04-26-13-09-07.png",80%) ===== MVC - Il pattern MVC divide le applicazioni in tre distinte parti: - Il model che gestisce i dati - Il controller che manipola i dati - La view che mostra i dati #cfigure("images/2024-04-26-13-10-16.png",90%) ===== Layer - Il pattern Layer aiuta a strutturare quelle applicazioni che possono essere scomposte in gruppi di sotto-attività in cui ciascun gruppo si trova a un ben definito livello di astrazione #cfigure("images/2024-04-26-13-10-44.png",20%) ===== Client/Server - Il pattern client/server aiuta a strutturare un'applicazione come un insieme di servizi forniti da uno o più server e un insieme di client che utilizza tali servizi #cfigure("images/2024-04-26-13-11-26.png",90%) Tre diverse possibilità: #cfigure("images/2024-04-26-13-11-54.png",90%) ===== Broker - Il pattern Broker può essere usato per strutturare sistemi distribuiti con un disaccoppiamento tra i diversi sotto-sistemi che comunicano tra loro attraverso remote server invocation - Il Broker è responsabile della coordinazione delle comunicazioni,come inoltro richieste, invio risposte ed eccezioni #cfigure("images/2024-04-29-16-49-33.png",100%) ===== Pipe & Filters - Il pattern Pipe & Filters aiuta a strutturare quelle applicazioni che processano flussidi dati - Ogni passo del processo è incapsulato in un apposito filtro e i dati attraversano una pipe di filtri - Variando l'ordine dei filtri si possono ottenere diversi tipi di sistemi #cfigure("images/2024-04-26-13-12-43.png",90%) ===== Conclusioni - Come non esiste un processo di sviluppo ideale, non esiste un'Architettura ideale sempre utilizzabile - Talvolta è necessario usare stili architetturali diversi per parti diverse del sistema al fine di soddisfare tutti i vincoli imposti dai requisiti - L'adozione dei pattern architetturali può aiutare a trovare il giusto compromesso tra tutte le forze in gioco ===== Esempio: Villaggio Turistico #cfigure("images/2024-04-26-13-13-35.png",100%) ==== Scelte Tecnologiche - L'uso di una specifica tecnologia (intesa anche come linguaggio di programmazione, piattaforma, strumento, etc.) non è sempre neutro - In taluni casi potrebbe risultare vantaggioso scegliere le tecnologie già in fase di progettazione legando così il progetto alla specifica tecnologia - Nel caso si decida di scegliere la tecnologia in fase di progettazione, va specificato chiaramente e va fatta un'analisi costi/benefici - Vanno attentamente studiate le parti della tecnologia adottata in modo che sia poi possibile inserirle nei diagrammi di progettazione === Progettazione di dettaglio - La Progettazione di Dettaglio definisce il dettaglio dell'Architettura del Sistema nelle sue tre viste: - Struttura - Interazione - Comportamento - Quindi non più architettura logica, ma architettura di sistema - Per realizzare un sistema funzionante, occorre considerare GUI, DB, Framework, librerie, componenti, modifiche al modello per avere #text(blue)[software estensibile e modulare...] - È compito della Progettazione di Dettaglio #text(blue)[identificare e definire altre classi] in accordo alla specifica architettura scelta, siamo arrivati al _come_ - Durante la Progettazione di Dettaglio, i modelli prodotti nell'Analisi devono essere #text(blue)[estesi] al fine di progettare i quattro layer principali che compongono il sistema - #highlight(fill: myblue)[Application Logic] - logica dell'applicazione e controllo degli altri componenti - #highlight(fill: myblue)[Presentation logic] - gestione dell'interazione con l'utente a livello logico nuovi oggetti: finestre, menù, bottoni, toolbar , ... - #highlight(fill: myblue)[Data logic] - gestione dei dati che il sistema deve manipolare - #highlight(fill: myblue)[Middleware] - gestione dell'interazione con i sistemi esterni, con la rete e tra i sotto-sistemi - Durante la Progettazione di Dettaglio, i modelli di Analisi devono essere #text(blue)[modificati] al fine di: - definire in dettaglio le classi e delle loro relazioni - supportare #text(blue)[caratteristiche specifiche] per comunicazioni, - diagnostica, protezione dei dati,... - #text(blue)[riuso] di classi e/o componenti disponibili - miglioramento delle #text(blue)[prestazioni] - supporto alla #text(blue)[portabilità] - ... - #text(blue)[*Massima indipendenza possibile*] da - Linguaggio (e ambiente) di programmazione - DBMS - Sistema Operativo - Hardware - Le caratteristiche specifiche del contesto utilizzato devono essere tenute in conto solo se - #text(blue)[sono vincolanti] (requisiti non funzionali) - si è #text(blue)[esplicitamente scelto] di legarsi a una tecnologia nella progettazione architetturale, ad esempio una specifica tecnologia utilizzabile solo da un linguaggio di programmazione #cfigure("images/2024-04-26-13-17-41.png",90%) ==== Architettura: Struttura - Durante la Progettazione di Dettaglio della parte di Struttura è necessario definire - #text(blue)[tipi di dato] che non sono stati definiti in precedenza - #text(blue)[navigabilità delle associazioni] tra classi - #text(blue)[strutture dati] necessarie per l'effettiva implementazione del sistema - #text(blue)[operazioni] che non erano emerse durante la fase di Analisi del Problema - eventuali #text(blue)[nuove classi] necessarie per il corretto funzionamento del sistema - Attenzione alla presenza dei “Sistemi Esterni” individuati in fase di Analisi del Problema - Se nella tabella “Tabella dei Sistemi Esterni” era stato individuato un problema nel “Livello di Protezione” e il Sistema Esterno non risulta avere il livello di sicurezza minimo richiesto occorre applicate il #text(red)[*pattern Adapter*] - si ingloba (wrappa) il Sistema Esterno in una nostra struttura - si progetta la struttura in modo tale che soddisfi i livelli minimi di sicurezza richiesti - Attenzione se si è deciso di vincolarsi a una specifica tecnologia - Va condotta una #text(blue)[attenta analisi] e #text(red)[valutazione del livello di protezione offerto] dalla tecnologia scelta - Se tale livello non risulta essere quello minimo richiesto dall'applicazione occorre progettare specifiche parti del sistema per prevenire i buchi di sicurezza legati alla specifica tecnologia - Ove possibile cercare di applicare il pattern Adapter - Applicazione dei #text(red)[*design pattern*] al fine di realizzare #text(blue)[*software di qualità*] facilmente estensibile e modulare - Applicazione dei #text(red)[principi di progettazione] con particolare attenzione al #text(red)[“Dependency Inversion Principle”] - Disaccoppiare i layer del sistema porta molti vantaggi - possibile cambiare implementazione di parti del sistema senza che la modifica si ripercuota sulla restante parte: #text(red)[*design for change*] - possibile cambiare l'aspetto grafico anche variando la tecnologia realizzativa senza dover modificare l'application logic - facile inserire nuove funzionalità con impatto minimo sul sistema ==== Struttura: Esempio #cfigure("images/2024-04-26-13-22-07.png",100%) #cfigure("images/2024-04-26-13-22-26.png",100%) #cfigure("images/2024-04-26-13-22-43.png",100%) #cfigure("images/2024-04-26-13-23-04.png",100%) #cfigure("images/2024-04-26-13-23-22.png",50%) #cfigure("images/2024-04-26-13-23-57.png",100%) ==== Architettura: Interazione - Durante la Progettazione di Dettaglio della parte di Interazione è necessario - #text(blue)[ridefinire i protocolli di interazione] emersi in fase di Analisi dettagliandoli tenendo conto delle nuove entità emerse in progettazione, quindi definiamo il _come_ - #text(blue)[progettare accuratamente] i protocolli di interazione verso i sistemi esterni - #text(blue)[definire nuovi protocolli di interazione] tra le classi che sono state introdotte nella progettazione ===== Interazione: Esempio #cfigure("images/2024-04-26-13-25-50.png",100%) #cfigure("images/2024-04-26-13-31-15.png",100%) #cfigure("images/2024-04-26-13-31-32.png",100%) === Architettura: Comportamento - Durante la progettazione di dettaglio della parte di Comportamento è necessario - #text(blue)[definire gli algoritmi] che implementano le operazioni complesse/complicate in modo chiaro e preciso avvalendosi eventualmente di diagrammi delle attività - #text(blue)[dettagliare] i diagrammi di stato/attività già definiti nella fase precedente - eventualmente #text(blue)[aggiungere diagrammi] di stato/attività per le nuove entità emerse in questa fase === Progettazione della persistenza - La persistenza dei dati è un fattore cruciale nello sviluppo di un sistema - Il progettista dopo un'attenta valutazione di - vincoli imposti dai requisiti funzionali (tempi di risposta, requisiti di protezione e privacy, ...) - tipologia di accesso accesso ai dati (lettura, scrittura, ricerche) - frequenza di accesso ai dati (quanto spesso devo accedere ai dati?) - criticità e consistenza dei dati (quanto spesso cambiano i dati? quali sono i costi di eventuale “perdite” nelle modifiche dei dati?) dovrà scegliere la tecnica migliore di persistenza - Per ogni sistema va valutato attentamente quale strategia dà il miglior bilanciamento tra i vincoli e le forze in gioco nel sistema - Non è sempre detto che l'adozione di un (R)DBMS sia la risposta corretta - Per esempio se dobbiamo memorizzare dei log la strategia migliore è quella delle scrittura su file: - la maggior parte delle funzionalità “scrivono” solamente una o più righe nel log e l'accesso deve essere molto veloce: il log non deve pesare troppo nei tempi di risposta nel sistema - solo gli strumenti di analisi accedono in lettura al loge solitamente occorre analizzare ogni singola riga nel corretto ordine temporale, non c'è bisogno di fare ricerche ==== Quando usare un DBMS - In generale possiamo affermare che quando si ha a che fare con: - gestionali che trattano un numero considerevole di dati anche di natura eterogenea - dati che cambiano molto spesso e devono essere costantemente aggiornati - la “perdita” di modifiche può essere un problema - necessità di ripristino di versioni precedenti a seguito di un malfunzionamento #text(blue)[la scelta consigliata è quella di avvalersi di un DBMS] #line(length: 100%) - L'output di questa fase può essere rappresentato da: - lo schema E-R del DB che dovrà supportare l'applicazione - il formato del/i file che dovranno essere scritti/letti dall'applicazione - Sarebbe bene che sia nel caso di DB che di file ci fosse una #text(red)[piccola analisi del rischio] per capire se - il DB è protetto in modo adeguato - il/i file necessitano di meccanismi di protezione - Il punto di partenza di tale analisi sono #text(blue)[i livelli di protezione e privacy richiesti per i diversi dati] che saranno memorizzati ==== Esempio: DB Villaggio Turistico #cfigure("images/2024-04-26-19-02-08.png",100%) ==== Esempio: log Villaggio Turistico - Formato file per Log delle operazioni `DataOra operazione esecutore` - Formato file per Log dei messaggi `DataOra messaggio protetto invio/ricezione autore` === Progettazione del collaudo - La base di partenza di questa attività è il Piano del Collaudo sviluppato nell'analisi - Dopo la Progettazione di Dettaglio è possibile scrivere i #text(blue)[test unitari di ciascuna classe] - Successivamente vanno progettati con cura anche #text(blue)[i test di integrazione] del sistema - L'output di questa attività è rappresentato dalla Suite completa dei test unitari e di integrazione === Progettazione per il deployment - Seguiremo le linee guida già viste nel blocco della sicurezza: + Includere supporto per visionare e analizzare le configurazioni + Minimizzare i privilegi di default + Localizzare le impostazioni di configurazione + Fornire modi per rimediare a vulnerabilità di sicurezza ==== Deployment: Esempio #cfigure("images/2024-04-26-19-04-46.png",100%) #underline[Lato server:] - i server dovranno essere installati su macchine all'interno di una rete privata - la rete privata dovrà essere opportunamente protetta da un firewall a cifratura di pacchetti - l'unico punto di contatto verso l'esterno è il Broker === Design Pattern Nel 1977, <NAME> disse: #align(center)[_«Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use the solution a million times over, without ever doing it the same way twice»_] Parlava di costruzioni civili e di città - La stessa frase è applicabile anche alla progettazione object-oriented - In questo caso, le soluzioni utilizzeranno - oggetti, classi e interfacce - invece che pareti e porte... - #text(blue)[Obiettivi] - Risolvere problemi progettuali specifici - Rendere i progetti object-oriented più flessibili e riutilizzabili - Ogni design pattern - Cattura e formalizza l'esperienza acquisita nell'affrontare e risolvere uno specifico problema progettuale - Permette di riutilizzare tale esperienza in altri casi simili - Ogni design pattern ha #text(blue)[*quattro elementi essenziali*] - un #text(blue)[*nome*] (significativo) - identifica il pattern - il #text(blue)[*problema*] - descrive quando applicare il pattern - la #text(blue)[*soluzione*] - descrive il pattern, cioè gli elementi che lo compongono (classi e istanze) e le loro relazioni, responsabilità e collaborazioni - le #text(blue)[*conseguenze*] - descrivono vantaggi e svantaggi dell'applicazione del pattern e permettono di valutare le alternative progettuali ==== L'importanza dei nomi dei Pattern - Gli schemi progettuali del software hanno nomi suggestivi: - _Observer, Singleton, Strategy ..._ - Perché i nomi sono importanti? - Supportano il _chunking_, ovvero fissano il concetto nella nostra memoria e ci aiutano a capirlo - Facilitano la comunicazione tra progettisti ==== Classificazione dei Design Pattern - #highlight(fill: myblue)[Pattern di creazione] (creational pattern)\ Risolvono problemi inerenti il processo di creazione di oggetti - #highlight(fill: myblue)[Pattern strutturali] (structural pattern)\ Risolvono problemi inerenti la composizione di classi o di oggetti - #highlight(fill: myblue)[Pattern comportamentali] (behavioral pattern)\ Risolvono problemi inerenti le modalità di interazione e di distribuzione delle responsabilità tra classi o tra oggetti #cfigure("images/2024-05-03-13-03-37.png",100%) ==== Pattern SINGLETON - Assicura che una classe abbia una sola istanza fornisce un punto di accesso globale a tale istanza - La classe deve: - tenere traccia della sua sola istanza - intercettare tutte le richieste di creazione, al fine di garantire che nessuna altra istanza venga creata; sostanzialmente viene dato a chi da la richiesta di creazione il riferimento all'istanza - fornire un modo per accedere all'istanza unica ```C public class Singleton { ... attributi membro di istanza ... private static Singleton instance = null; protected Singleton() { inizializzazione istanza } public static Singleton GetInstance() { if(_instance == null) _instance = new Singleton(); return _instance; } ... metodi pubblici, protetti e privati ... }``` - Alternativa: classe non istanziabile (`static class`) con soli membri statici - `Math` - `Convert` - ... - Perché un _singleton_? - Il _singleton_ #text(blue)[*può implementare 1+ interfacce*] - Il _singleton_ #text(blue)[*può essere specializzato*] ed è possibile creare nella `GetInstance` un'istanza specializzata che dipende dal contesto corrente ```C public static Singleton GetInstance() { if(_instance == null) _instance = CreateInstance(); return _instance; } private static Singleton CreateInstance() { if(...) return new SubSingletonA(); else if(...) return new SubSingletonB(); else return new SubSingletonC(); }``` #cfigure("images/2024-05-03-13-07-12.png",50%) ==== Pattern OBSERVER - #text(blue)[*Contesto*] - Talvolta una modifica a un oggetto (il #text(blue)[*soggetto*]) richiede che altri oggetti (#text(blue)[*osservatori*]) siano modificati a loro volta, o quantomeno richiedano di essere notificati se il soggetto viene modificato - Questa relazione può essere esplicitamente codificata nel soggetto, ma questo richiede che questo sappia come gli osservatori debbano essere aggiornati - si crea accoppiamento tra gli oggetti (#text(blue)[*closely coupled*]) e #text(blue)[*non possono essere facilmente riusati*] #cfigure("images/2024-05-03-13-09-40.png",50%) - #text(blue)[*Soluzione*] - Creare una relazione uno-a-molti più lasca tra un oggetto e gli altri che dipendono da esso - Una modifica dell'oggetto farà sì che gli altri #text(blue)[*ricevano una notifica*], consentendo loro di aggiornarsi di conseguenza #cfigure("images/2024-05-03-13-10-49.png",90%) - Ogni `Subject` può attaccarsi o staccarsi da un `Observer` - Con questo pattern il Soggetto da chi sono gli Osservatori, mentre gli Osservatori non sanno chi è il soggetto ===== Esempio Boss-Worker - È necessario modellare un'interazione tra due componenti - un #text(blue)[*Worker*] che effettua un'attività (o lavoro) - un #text(blue)[*Boss*] che controlla l'attività dei suoi Worker - Ogni _Worker_ deve notificare al proprio Boss: - quando il lavoro inizia - quando il lavoro è in esecuzione - quando il lavoro finisce - Soluzioni possibili: + #text(blue)[*class-based*] _callback relationship_ + #text(blue)[*interface-based*] _callback relationship_ + #text(blue)[*pattern Observer*] (lista di notifiche) + #text(blue)[*delegate-based*] _callback relationship_ + #text(blue)[*event-based*] _callback relationship_ #heading(level: 6, numbering: none)[Class-based callback relationship] #cfigure("images/2024-05-03-13-33-18.png",90%) #heading(level: 6, numbering: none)[Interface-based callback relationship] #cfigure("images/2024-05-03-13-34-46.png",100%) #heading(level: 6, numbering: none)[Pattern Observer (lista di notifiche)] #cfigure("images/2024-05-03-13-35-30.png",100%) ==== Pattern Model / View / Controller (MVC) - Utilizzato per realizzare le interfacce utenti in _Smalltalk-80_ - Permette di suddividere un'applicazione, o anche la sola interfaccia dell'applicazione, in tre parti - #text(blue)[*Modello*]: elaborazione/stato - #text(blue)[*View*]: (o viewport) output - #text(blue)[*Controller*]: input #line(length: 100%) #text(blue)[*Modello*] - Gestisce un insieme di dati logicamente correlati - Risponde alle interrogazioni sui dati - Risponde alle istruzioni di modifica dello stato - Genera un evento quando lo stato cambia - Registra (in forma anonima) gli oggetti interessati alla notifica dell'evento - In Java, deve estendere la classe `java.util.Observable` #text(blue)[*View*] - Gestisce un'area di visualizzazione, nella quale presenta all'utente una vista dei dati gestiti dal modello - Mappa (parte de) i dati del modello in oggetti visuali - Visualizza tali oggetti su un particolare dispositivo di output - Si registra presso il modello per ricevere l'evento di cambiamento di stato - In Java, deve implementare l'interfaccia `java.util.Observer` #text(blue)[*Controller*] - Gestisce gli input dell'utente (mouse, tastiera, ...) - Mappa le azioni dell'utente in comandi - Invia tali comandi al modello e/o alla view che effettuano le operazioni appropriate - In Java, è un #text(blue)[_listener_] #cfigure("images/2024-05-03-13-38-55.png",55%) Con view passiva: #cfigure("images/2024-05-03-13-39-41.png",55%) - In questo caso è il Presenter a parlare con il Model - Posso avere diversi Presenter per lo stesso Model ==== Pattern FLYWEIGHT - Descrive come condividere oggetti “leggeri” (cioè a granularità molto fine) in modo tale che il loro uso non sia troppo costoso - Un _flyweight_ è un #text(blue)[*oggetto condiviso*] che può essere utilizzato simultaneamente ed efficientemente da più clienti (del tutto indipendenti tra loro) - Benché condiviso, #text(blue)[*non deve essere distinguibile da un oggetto non condiviso *] - Non deve fare ipotesi sul contesto nel quale opera - Per assicurare una corretta condivisione, i clienti - non devono istanziare direttamente i flyweight - ma devono ottenerli esclusivamente tramite una `FlyweightFactory` ```C private DictionaryKeyType, FlyweightType> flyweights; ... public FlyweightType GetFlyweight(KeyType key) { if(!flyweights.ContainsKey(key)) { flyweights.Add(key, CreateFlyweight(key)); } return flyweights[key]; }``` - Distinzione tra stato intrinseco e stato estrinseco - #text(blue)[*Stato intrinseco*]: - #text(blue)[*Non dipende dal contesto di utilizzo*] e quindi #text(blue)[*può essere condiviso*] da tutti i clienti - Memorizzato nel _flyweight_ - #text(blue)[*Stato estrinseco*] - #text(blue)[*Dipende dal contesto di utilizzo*] e quindi #text(blue)[*non può essere condiviso*] dai clienti - Memorizzato nel cliente o calcolato dal cliente - Viene passato al _flyweight_ quando viene invocata una sua operazione #cfigure("images/2024-05-03-13-43-19.png",100%) ===== Esempio - Si supponga di usare il pattern flyweight per condividere delle icone tra vari clienti #cfigure("images/2024-05-03-13-43-59.png",100%) - Lo #text(blue)[*stato intrinseco*] (memorizzato nel flyweight) comprenderà tutte le informazioni che i clienti devono (e possono) condividere: - Nome dell'icona - Bitmap dell'icona - Dimensioni originali, ... - Lo #text(blue)[*stato estrinseco*] (memorizzato nel cliente) comprenderà il contesto in cui l'icona dovrà essere disegnata (dipendente dal singolo cliente): - Posizione dell'icona - Dimensioni richieste, ... ==== Pattern STRATEGY - Permette di - definire un insieme di algoritmi tra loro correlati, - incapsulare tali algoritmi in una gerarchia di classi e - rendere gli algoritmi intercambiabili #cfigure("images/2024-05-03-13-46-13.png",90%) #cfigure("images/2024-05-03-13-47-41.png",90%) ===== Esempio - #text(blue)[*Allineamento del testo di un paragrafo*]\ Esistono politiche diverse di allineamento #cfigure("images/2024-05-03-13-48-58.png",90%) - #text(blue)[*AlignerBase*] - suddivide il testo in linee (`Format`) - delega alle sue sottoclassi l'allineamento delle singole linee (`FormatLine`) - `Paragraph` utilizza i servizi di un _“Aligner”_ specificato dinamicamente run-time - È possibile realizzare gli “Aligner” utilizzando il pattern #text(blue)[_*flyweight*_] Esempio ==== Pattern ADAPTER - Converte l'interfaccia originale di una classe nell'interfaccia (diversa) che si aspetta il cliente - Permette a classi che hanno interfacce incompatibili di lavorare insieme - Si inserisce, tra le due classi, l'interfaccia Adapter, che ingloba la classe che deve erogare i servizi, in modo che possa comunicare con la classe che li deve usare - Si usa quando - si vuole riutilizzare una classe esistente - la sua interfaccia non è conforme a quella desiderata - Noto anche come #text(blue)[_*wrapper*_] - Si realizza con composizione-delega #cfigure("images/2024-05-03-13-51-00.png",90%) ===== Esempio #cfigure("images/2024-05-03-13-51-38.png",80%) ==== Pattern DECORATOR - Permette di #text(blue)[*aggiungere responsabilità*] a un oggetto dinamicamente - Fornisce un'#text(blue)[*alternativa flessibile alla specializzazione*] - In alcuni casi, le estensioni possibili sono talmente tante che per poter supportare ogni possibile combinazione, si dovrebbe definire un numero troppo elevato di sottoclassi - TextBox - BorderTextBox - FilledTextBox - VerticalTextBox - BorderFilledTextBox - BorderVerticalTextBox - BorderFilledVerticalTextBox - FilledVerticalTextBox - E se volessi - 2 o più bordi - Cambiare il font - ... #cfigure("images/2024-05-03-13-53-22.png",90%) - #text(blue)[*Component*] (*interfaccia o classe astratta*) - Dichiara l'interfaccia di tutti gli oggetti ai quali deve essere possibile aggiungere dinamicamente responsabilità - #text(blue)[*ConcreteComponent*] - Definisce un tipo di oggetto al quale deve essere possibile aggiungere dinamicamente responsabilità - #text(blue)[*Decorator*] (*classe astratta*) - Mantiene un riferimento a un oggetto di tipo Component e definisce un'interfaccia conforme all'interfaccia di Component - #text(blue)[*ConcreteDecorator*] - Aggiunge responsabilità al componente referenziato #cfigure("images/2024-05-03-13-55-03.png",90%) ==== Ereditarietà Dinamica - Una sotto-classe deve sempre essere una #text(blue)[*versione più specializzata*] della sua super-classe (o classe base) - Un buon test sul corretto utilizzo dell'ereditarietà è che sia valido il #text(blue)[*principio di sostituibilità di Liskov*]:\ _“B è una sotto-classe di A se e solo se ogni programma che utilizzi oggetti di classe A può utilizzare oggetti di classe B senza che il comportamento logico del programma cambi”_ - Perché ciò sia valido, è necessario che: - le *pre-condizioni* di tutti i metodi della sotto-classe siano uguali o più deboli - le *post-condizioni* di tutti i metodi della sotto-classe siano uguali o più forti - ogni metodo ridefinito nella sotto-classe deve mantenere la *semantica* del metodo originale #cfigure("images/2024-05-03-13-57-52.png",90%) - Il metodo `Modifica` della classe `ModificatoreDiDimensioni` - funziona correttamente su un `Rettangolo` - ma NON funziona correttamente su un `Quadrato` - Quindi non è possibile passare un'istanza di `Quadrato` dove è prevista un'istanza di `Rettangolo` - il principio di sostituibilità di Liskovè violato! - *Conclusione*: un quadrato NON è un rettangolo perché pone dei nuovi vincoli al concetto di rettangolo - Come possiamo tenere conto di ciò che il rettangolo e il quadrato hanno in comune? #cfigure("images/2024-05-03-14-14-23.png",90%) - Cosa intendiamo esattamente per Rettangolo e per Quadrato? - #text(blue)[*Rettangolo*]: parallelogramma i cui angoli sono retti - #text(blue)[*Parallelogramma*]: quadrilatero i cui lati opposti sono paralleli tra loro - #text(blue)[*Quadrilatero*]: poligono avente quattro lati e quattro angoli - Quadrilateri notevoli sono il quadrato, il rettangolo, il parallelogramma, il rombo e il trapezio - #text(blue)[*Poligono*]: figura geometrica limitata da una linea poligonale chiusa - #text(blue)[*Rombo*]: parallelogramma equilatero in cui gli angoli adiacenti sono diversi tra loro - #text(blue)[*Quadrato*]: parallelogramma equilatero ed equiangolo - Cosa intendiamo esattamente per Rettangolo e per Quadrato nella nostra applicazione? - *Ipotesi*: abbiamo a che fare esclusivamente con parallelogrammi #text(blue)[*1. Lati e angoli NON sono modificabili*] - Definire quattro classi concrete che derivano dalla classe astratta `Parallelogramma` (o implementano `IParallelogramma`): `Rettangolo , Quadrato , Rombo , ParallelogrammaGenerico` - Usare una factory che in base ai valori dei lati e degli angoli istanzia un rettangolo (che NON deve avere i lati uguali), un quadrato, un rombo o un parallelogramma generico #text(blue)[*2. Lati e angoli sono modificabili*] - Definire un'unica classe concreta `Parallelogramma` le cui istanze possono comportarsi a seconda del loro stato come: un rettangolo, un quadrato, un rombo, o un parallelogramma generico - Come può un oggetto cambiare comportamento, al cambiare del suo stato? - #underline[1 possibilità]: #text(blue)[*si cambia la classe dell'oggetto run-time*] - nella maggior parte dei linguaggi di programmazione a oggetti, questo non è possibile (inoltre, è meglio che un oggetto non possa cambiare classe durante la sua esistenza) - la classe di un oggetto deve basarsi sulla sua essenza e non sul suo stato - #underline[2 possibilità]: #text(blue)[*si utilizza il _pattern_ State*] che usa un #text(blue)[*meccanismo di delega*], grazie al quale l'oggetto è in grado di comportarsi #text(blue)[*come se*] avesse cambiato classe ==== Pattern STATE #cfigure("images/2024-05-03-14-21-05.png",80%) - Localizza il comportamento specifico di uno stato e suddivide il comportamento in funzione dello stato - Le classi concrete contengono la logica di transizione da uno stato all'altro - Permette anche di emulare l'ereditarietà multipla #cfigure("images/2024-05-03-14-21-45.png",100%) ==== Pattern COMPOSITE - Permette di comporre oggetti in una #text(blue)[*struttura ad albero*], al fine di rappresentare una #text(blue)[*gerarchia di oggetti contenitori-oggetti contenuti*] - Permette ai clienti di #text(blue)[*trattare in modo uniforme oggetti singoli e oggetti composti*] #cfigure("images/2024-05-03-14-22-54.png",80%) - #text(blue)[*Component*] (classe astratta) - Dichiara l'interfaccia - Realizza il comportamento di default - #text(blue)[*Client*] - Accede e manipola gli oggetti della composizione attraverso l'interfaccia di *Component* - #text(blue)[*Leaf*] - Descrive oggetti che non possono avere figli -foglie - Definisce il comportamento di tali oggetti - #text(blue)[*Composite*] - Descrive oggetti che possono avere figli -contenitori - Definisce il comportamento di tali oggetti #cfigure("images/2024-05-03-14-24-35.png",70%) - Il contenitore dei figli deve essere un attributo di #text(blue)[*Composite*] e può essere di qualsiasi tipo (array, lista, albero, tabella hash, ...) #line(length: 100%) - #text(blue)[*Riferimento esplicito al genitore*] (parent) - Semplifica l'attraversamento e la gestione della struttura - L'attributo che contiene il riferimento al genitore e la relativa gestione devono essere posti nella classe #text(blue)[*Component*] - #text(blue)[*Invariante*] - Tutti gli elementi che hanno come _parent_ lo stesso componente devono essere (gli unici) figli di quel componente - incapsulare l'assegnamento di parent nei metodi `Add` e `Remove` della classe Composite , oppure - incapsulare le operazioni di `Add` e `Remove` nella set dell'attributo _parent_ della classe `Component` public class Composite : Component ```C{ ... public void Add(Component aChild) { if(aChild.Parent != null) throw new ArgumentException(...); _children.Add(aChild); aChild._parent = this; } ... }``` ```C public class Composite : Component { ... public void Remove(Component aChild) { if(aChild.Parent != this) throw new ArgumentException(...); if(!_children.Contains(aChild)) throw new ArgumentException(...); _children.Remove(aChild); aChild._parent = null; } ... }``` ```C public class Component { ... public Composite Parent { get { return _parent; } set { if(value != _parent) { if(_parent != null) _parent.Remove(this); if(value != null) value.Add(this); } } } ... }``` - #text(blue)[*Massimizzazione dell'interfaccia `Component`*] - Un obiettivo del pattern Composite è quello di fare in modo che il cliente veda solo l'interfaccia di Component: in `Component` devono essere inserite tutte le operazioni che devono essere utilizzate dai clienti - nella maggior parte dei casi, Component definisce una realizzazione di default che le sotto classi devono ridefinire - Alcune di queste operazioni possono essere prive di significato per gli oggetti foglia (`Add` ,`Remove` , ...) - #text(blue)[*Trasparenza*] - Dichiaro tutto al livello più alto, in modo che il cliente possa trattare gli oggetti in modo uniforme ma... #text(blue)[*il cliente potrebbe cercare di fare cose senza senso*], come aggiungere figli alle foglie - Se scegliamo la trasparenza - `Add` e `Remove` devono avere una realizzazione di default che genera un'eccezione - dovremmo disporre di un modo per verificare se è possibile aggiungere figli all'oggetto su cui si vuole agire ```C // Il cliente conosce solo Component Component parent = ComponentFactory.CreateInstance(...); ... Component child = ComponentFactory.CreateInstance(...); ... // Prima di inserire un figlio, // occorre controllare se è possibile if(parent.IsComposite()) parent.Add(child); ``` - #text(blue)[*Sicurezza*] - Tutte le operazioni sui figli vengono messe in `Composite` - a questo punto, qualsiasi invocazione sulle foglie genera un errore in fase di compilazione ma... #text(blue)[*il cliente deve conoscere e gestire due interfacce differenti*] - Se scegliamo la sicurezza - dobbiamo disporre di un modo per verificare se l'oggetto su cui si vuole agire è un `Composite` ```C // Il cliente conosce Component e Composite Component child = ComponentFactory.CreateComponent(...); Composite parent1 = ComponentFactory.CreateComposite(...); parent1.Add(child); ... Component parent2 = ComponentFactory.CreateComponent(...); // Errore di compilazione parent2.Add(child); // Prima di inserire un figlio, // occorre controllare se è possibile e fare un cast if(parent2 is Composite) ((Composite) parent2).Add(child); ``` ==== Pattern VISITOR - Permette di #text(blue)[*definire una nuova operazione*] da effettuare su gli elementi di una struttura, #text(blue)[*senza dover modificare le classi degli elementi coinvolti*] - Ad esempio, si consideri la rappresentazione di un programma come “#text(blue)[*abstract syntax tree*]” (AST) - i cui nodi descrivono elementi sintattici del programma - Su tale albero devono poter essere effettuate molte operazioni di tipo diverso - Controllare che tutte le variabili siano definite - Eseguire delle ottimizzazioni - Generare il codice macchina - Stampare l'albero in un formato leggibile - ... Per l'AST utilizziamo il _pattern Composite_ #cfigure("images/2024-05-03-18-17-58.png",90%) - In seguito potremmo voler effettuare #text(blue)[*altri tipi di operazioni*] - controllare che le variabili siano state inizializzate prima dell'uso - ristrutturare automaticamente il programma - calcolare varie metriche - ... - Se distribuiamo le operazioni sui vari tipi di nodo, otteniamo un sistema che è difficile da - capire - modificare - estendere - La soluzione è quella di eliminare le singole operazioni dall'AST (la cui responsabilità principale è quella di rappresentare un programma sotto forma di albero) - #text(blue)[*Tutto il codice relativo ad un singolo tipo di operazione*] (ad es., generazione del codice) viene raccolto in #text(blue)[*una singola classe*] - I nodi dell'AST devono #text(blue)[*accettare la visita*] delle istanze di queste nuove classi (#text(blue)[_*visitor*_]) - Per aggiungere un #text(blue)[*nuovo tipo di operazione*], è sufficiente progettare una #text(blue)[*nuova classe*] - Il Visitor deve dichiarare #text(blue)[*un'operazione per ogni tipo di nodo*] concreto #cfigure("images/2024-05-03-18-20-32.png",100%) - Ogni nodo deve dichiarare #text(blue)[*un'operazione per accettare un generico _visitor_*] #cfigure("images/2024-05-03-18-21-23.png", 90%) #line(length: 100%) - #text(blue)[*Visitor*] (classe astratta o interfaccia) - Dichiara un metodo #text(blue)[`Visit`] per ogni classe di elementi concreti - #text(blue)[*ConcreteVisitor*] - Definisce tutti i metodi #text(blue)[`Visit`] - Globalmente #text(blue)[*definisce l'operazione da effettuare sulla struttura*] e (se necessario) ha un proprio stato #cfigure("images/2024-05-03-18-23-17.png",100%) - #text(blue)[*Element*] (classe astratta o interfaccia) - Dichiara un metodo #text(blue)[`Accept`] che accetta un Visitor come argomento - #text(blue)[*ConcreteElement*] - Definisce il metodo #text(blue)[`Accept`] #cfigure("images/2024-05-03-18-24-20.png",90%) - #text(blue)[*ObjectStructure*] - Può essere realizzata come Composite o come normale collezione (array, lista, ...) - Deve poter enumerare i suoi elementi - Deve dichiarare un'interfaccia che permetta a un cliente di far visitare la struttura a un Visitor #cfigure("images/2024-05-03-18-25-00.png",50%) #line(length: 100%) - #text(blue)[*Facilita l'aggiunta di nuove operazioni*] - È possibile aggiungere nuove operazioni su una struttura esistente, semplicemente aggiungendo un nuovo visitor concreto - Senza il pattern Visitor, sarebbe necessario aggiungere un metodo ad ogni classe degli elementi della struttura - Ogni Visitor concreto - Raggruppa i metodi necessari a eseguire una data operazione - Nasconde i dettagli di come tale operazione debba essere eseguita - #text(blue)[*Incapsulamento*] - Ogni Visitor deve essere in grado di accedere allo stato degli elementi su cui deve operare - È difficile aggiungere una nuova classe `ConcreteElement` - Per ogni nuova classe `ConcreteElement` è necessario inserire un nuovo metodo `Visit` in tutti i `Visitor` esistenti - la gerarchia `Element` deve essere poco o per nulla modificabile - cioè essere #text(blue)[*stabile*] - #text(blue)[*Visita di elementi non correlati*] - Non è necessario che tutti gli elementi da visitare derivino da una classe comune `VisitClasseA(ClasseGerarchiaA a);`\ `VisitClasseB(ClasseGerarchiaB b);` - #text(blue)[*Stato*] - Durante l'operazione ogni Visitor può modificare il proprio stato - ad esempio, per accumulare dei valori o altro ```C public class CompositeElement : Element { ... private List<Element> _children; ... public override void Accept(Visitor visitor) { foreach (Element aChild in _children) aChild.Accept(visitor); visitor.VisitCompositeElement(this); } ... } ``` #cfigure("images/2024-05-03-18-29-03.png",90%) - #text(blue)[*Double dispatch*] - L'operazione che deve essere effettuata dipende dal tipo di due oggetti - il visitor - l'elemento - `Accept` è un'operazione di tipo #text(blue)[*double dispatch*] Esempio + EsempioDecorator ==== Anti Pattern - Oltre ai pattern utili esistono anche gli anti-pattern, che descrivono situazioni ricorrenti e soluzioni notoriamente dannose - Esempio: _Interface Bloat_, che consiste nell'aggiungere così tante funzionalità a un'interfaccia da renderla impossibile da implementare (o usare!) - Sostanzialmente, sono soluzioni che non soddisfano i design principle! ==== Pattern ABSTRACT FACTORY - #text(blue)[*Problema*]: - creazione di oggetti connessi o dipendenti tra loro, senza bisogno che il client debba specificare i nomi delle classi concrete all'interno del proprio codice - esempio: ```C Menu m; if (style == Macos) m = new MacosMenu; else if(style == ...) m = new... ``` - la stessa cosa va ripetuta per pulsanti, view... - #text(blue)[*Requisito*]: - si vuole un sistema indipendente da come gli oggetti vengono creati, composti e rappresentati - si vuole permettere la configurazione del sistema come scelta tra diverse famiglie di prodotti - si vuole che i prodotti che sono organizzati in famiglie siano vincolati ad essere utilizzati con prodotti della stessa famiglia - #text(blue)[*Soluzione*]: - Definizione di una classe - astrae la creazione di una famiglia di oggetti - istanze diverse costituiscono implementazioni diverse di membri di tale famiglia #cfigure("images/2024-05-03-18-32-32.png",50%) - #text(blue)[*Soluzione*]: - La creazione dei prodotti è responsabilità delle classi `ConcreteFactory` #cfigure("images/2024-05-03-18-33-42.png",50%) #cfigure("images/2024-05-03-18-34-15.png",90%) - #text(blue)[*Conseguenze*]: - isola le classi concrete - il codice successivo all'istanziazione è indipendente dalla classe concreta - consente di cambiare in modo semplice la famiglia di prodotti utilizzata - la coerenza col resto del codice è assicurata dall'utilizzo delle interfacce astratte e non delle classi concrete, secondo l'OCP - promuove la coerenza nell'utilizzo dei prodotti - #text(blue)[*Conseguenze*]: - difficile aggiungere supporto per nuove tipologie di prodotti - Dato che AbstractFactory definisce tutte le varie tipologie di prodotti che è possibile istanziare, aggiungere una tipologia richiede di modificare l'interfaccia della factory == Diagramma dei componenti e di Deployment === Diagramma dei Componenti - Da UML 2.0 il concetto di componente si è evoluto rispetto alla versione precedente dello standard - Specifica un #text(blue)[contratto formale di servizi offerti e richiesti] in termini di interfacce (eventualmente esposte tramite porte) - Il concetto di componente è strettamente legato a quello di #text(blue)[*struttura composita*] che spesso viene impiegata per rappresentare le parti interne del componente - Un componente è tipicamente specificato da uno o più classificatori (ad es. classi) e può essere implementato da uno o più artefatti (file eseguibile, script, ...) - Gli internals (parti interne) sono inaccessibili solo attraverso le interfacce ==== Struttura Composita - Il Diagramma di Struttura Composita ha l'obiettivo di rappresentare la struttura interna (le parti) di un classificatore (classe, componente...), inclusi i punti di interazione (porte) utilizzati per accedere alle caratteristiche della struttura #cfigure("images/2024-05-09-10-49-46.png",80%) - Introdotto per scomporre gerarchicamente un classificatore, mostrandone la struttura interna: - mostra la struttura interna di un classificatore complesso - mostra in modo separato l'#text(blue)[*interfaccia*] di un classificatore dalla sua #text(blue)[*struttura interna*] - descrive i ruoli che i diversi elementi della struttura giocano per soddisfare l'obiettivo della struttura stessa e le interazioni richieste - Questo permette al progettista di prendere un oggetto complesso e spezzarlo in parti più piccole e semplici - È una sorta di strumento di zoom utile per gestire la complessità di rappresentazione ==== Package vs. Struttura Composita - Per capire bene la differenza tra i package e le strutture composite bisogna pensare che - i primi rappresentano un raggruppamento logico al momento dell'analisi - mentre le seconde fanno riferimento a quello che succede durante l'esecuzione - Di conseguenza le strutture composite sono adatte a rappresentare i componenti e le loro parti, e sono usate spesso nei diagrammi dei componenti #line(length: 100%) - Da UML 2 è una specializzazione della metaclasse `Class` - Quindi un componente può avere attributi e metodi, una struttura interna, porte e connettori - Da UML 2 l'icona del componente è cambiata #cfigure("images/2024-05-09-10-51-40.png",90%) #cfigure("images/2024-05-09-10-52-00.png",90%) - Interfaccia fornita e interfaccia richiesta devono essere compatibili a livello di tipo (attributi e associazioni) e di vincoli sul comportamento (operazioni, eventi) #cfigure("images/2024-05-09-10-52-26.png",60%) ==== Componenti: White-box #cfigure("images/2024-05-09-10-53-06.png",80%) - I classificatori interni (internals) che realizzano un componente possono essere mostrati in due modi: - innestati nel componente #cfigure("images/2024-05-09-10-53-31.png",60%) - In modo esplicito tramite la dipendenza di #text(blue)[*realization*] #cfigure("images/2024-05-09-10-54-05.png",50%) - Il componente _Ordine_ è implementato istanziando le classi _Ordine_ e _RigaOrdine_ - La #text(blue)[*realization*] è una dipendenza specializzata tra due insiemi di elementi di modellazione, di cui uno rappresenta la specifica e l'altro una sua implementazione - Per un componente la #text(blue)[*realization*] definisce i classificatori che realizzano il contratto offerto dal componente stesso in termini delle sue interfacce offerte e richieste #cfigure("images/2024-05-09-10-55-01.png",100%) - Le parti interne sono collegate direttamente tra loro (#text(blue)[assembly connector]) oppure connesse a porte sul confine del componente (#text(blue)[delegated connector]) - I delegated connector sono utilizzati per esporre servizi di una “parte” all'esterno del container ==== Connettori Multiple Wiring #cfigure("images/2024-05-09-10-56-22.png",90%) - Entrambi i componenti, Ordine e OrdineInterno, richiedono l'interfaccia Persona: l'applicazione non conosce, fino al momento dell'esecuzione, quale componente, Cliente o Organizzazione, fornirà il servizio richiesto - Si tratta di #text(blue)[*_un'interazione polimorfica_*] #cfigure("images/2024-05-09-10-56-41.png",90%) #line(length: 100%) - UML 2.0 permette di connettere alla stessa porta più interfacce #cfigure("images/2024-05-09-10-57-23.png",90%) ==== Componenti e sottosistemi - Mentre in UML 1.x un #text(blue)[*subsystem*] è un tipo di package - In UML 2 è un tipo di componente - È quindi possibile specificare per un subsystem le interfacce richieste e quelle fornite, per evidenziare le relazioni con altri subsystem #cfigure("images/2024-05-09-10-58-13.png",100%) #line(length: 100%) ==== Il diagramma - Il diagramma dei componenti deve essere impiegato solamente negli stadi finali della fase di progettazione del sistema - Tale diagramma rispecchia molto da vicino la struttura che dovrebbe avere il codice e, in un qualche modo, rappresenta l'architettura del sistema - Potrebbe essere pensato come lo stadio finale dell'evoluzione dell'architettura logica che in fase di analisi viene rappresentata attraverso il diagramma dei package ==== Esempio Villaggio Turistico #cfigure("images/2024-05-09-10-59-12.png",90%) === Diagramma di Deployment - I diagrammi di deployment #text(blue)[*documentano la distribuzione fisica*] di un sistema, mostrando i vari pezzi di software in esecuzione sulle macchine fisiche - I diagrammi di deployment quindi mostrano: - i collegamenti che permettono la comunicazione fisica tra i pezzi hardware - le relazioni tra macchine fisiche e processi software, con l'indicazione dei vari punti in cui viene eseguito il codice - Gli elementi principali del diagramma: - #highlight(fill: myblue)[Artifact] - rappresenta una specifica porzione fisica di informazioni utilizzata o prodotta dal processo di sviluppo del software - esempi di artifact(manufatti): i modelli (un diagramma dei casi d'uso, un diagramma delle classi, ...), file sorgenti, script, file eseguibili, ... - tipicamente viene utilizzata una relazione di dipendenza \<\<manifest>> che illustra gli elementi di modellazione (in genere, componenti) utilizzati nella costruzione o generazione di un artefatto - #highlight(fill: myblue)[Node] - un'unità sulla quali risiedono e/o sono eseguiti componenti/artefatti - i nodi comunicano tra loro tramite CommunicationPath - l'allocazione degli artefatti su un nodo viene rappresentata con una relazione di dipendenza \<\<deploy>> tra il nodo e l'artefatto - #highlight(fill: myblue)[Device] - è una risorsa fisica computazionale con capacità elaborative sulla quale possono essere allocati artefatti per l'esecuzione - “Manifest” è la relazione di dipendenza che illustra gli elementi di modellazione utilizzati nella costruzione o generazione di un artefatto #cfigure("images/2024-05-09-11-01-48.png",90%) ==== Esempio Villaggio Turistico #cfigure("images/2024-05-09-11-03-02.png",90%) #line(length: 100%) - Un #text(blue)[*nodo*] rappresenta qualsiasi cosa possa eseguire un lavoro: un server, un device o un'unità organizzativa - È una risorsa su cui gli artefatti possono essere allocati per l'esecuzione, questo fatto viene rappresentato con una dipendenza di tipo \<\<deploy>> tra il nodo e l'artefatto #cfigure("images/2024-05-09-11-03-42.png",80%) L'immagine ci dice che su ogni `AppServer` viene installato `Order.jar`, e ogni `AppServer` comunica con un `DBServer`. #cfigure("images/2024-05-09-11-04-33.png",100%) Tipicamente viene utilizzato il #text(red)[*type-level*], ma l'#text(red)[*instance-level*] è più dettagliato. #line(length: 100%) - L'Execution Environment è un nodo che offre l'ambiente per l'esecuzione di specifici tipi di componenti che sono allocati su di esso ```<<OS>> - <<databasesystem>> - <<J2EE container>> - ... ``` #cfigure("images/2024-05-09-11-08-07.png",30%) Con l'#text(red)[*instance-level*] stiamo specificando che, per far funzionare un particolare componente, su quel dispositivo devono essere presenti tutti quegli artefatti. - Deployment Specification: è un insieme di proprietà che determinano i parametri di esecuzione di un artefatto allocato su un nodo #cfigure("images/2024-05-09-11-10-21.png",90%) ==== Esempio Villaggio Turistico #cfigure("images/2024-05-09-11-11-01.png",100%) - In questo caso, `Broker.exe` e `Login.exe` devono essere presenti sulla stessa macchina `ServerLogin` - C'è un solo `ClientLog`, e possono esserci tanti (indefiniti) `ClientPuntoVendita` e `ClientHotel` - Nella parte sottostante non è necessario specificare il deployment del componente `ServerLogin`, perché già specificato sopra - Il fatto che siano separati non implica che ci debbano essere due interfacce di rete diverse, ma solo che i percorsi sono diversi *Importante:* in una applicazione web il deployment degli artefatti che manifestano #underline[un client] non avviene sul client in sè, ma sul server; il client in questi casi è un semplice browser web. == Progettazione Concettuale (E/R) #cfigure("images/2024-05-09-16-52-44.png",90%) === Raccolta dei requisiti - I requisiti devono innanzitutto essere acquisiti - Le fonti possono essere molto diversificate tra loro: - #text(teal)[utenti], attraverso: - interviste - documentazione apposita - #text(teal)[documentazione esistente]: - normative (leggi, regolamenti di settore) - regolamenti interni, procedure aziendali - realizzazioni preesistenti - #text(teal)[modulistica] - La raccolta dei requisiti è un'attività difficile e non standardizzabile - in genere procede di pari passo con la fase di analisi (la prima analisi stimola nuove domande, ecc...) === Interagire con gli utenti - È un'attività da considerare con molta attenzione, in quanto: - utenti diversi possono fornire informazioni diverse - utenti a livello più alto hanno spesso una visione più ampia ma meno dettagliata - In generale, risulta utile: - effettuare spesso #text(teal)[verifiche] di comprensione e coerenza - verificare anche per mezzo di #text(teal)[esempi] (generali e relativi a casi limite) - richiedere #text(teal)[definizioni] e #text(teal)[classificazioni] - far evidenziare gli #text(teal)[aspetti essenziali] rispetto a quelli marginali === Requisiti: documentazione descrittiva - Regole generali: - scegliere il corretto #text(teal)[livello di astrazione] - #text(teal)[standardizzare] la struttura delle frasi - #text(teal)[suddividere] le frasi articolate - #text(teal)[separare] le frasi sui #text(teal)[dati] da quelle sulle #text(teal)[funzioni] (operazioni) - Per meglio evidenziare i concetti che sono espressi nei requisiti, è opportuno: - costruire un #text(teal)[glossario dei termini] - individuare #text(green)[omonimi] e #text(green)[sinonimi] e unificare i termini - rendere esplicito il #text(green)[riferimento fra termini] - riorganizzare le frasi per concetti ==== Esempio: BD bibliografica (1) Si vogliono organizzare i dati di interesse per automatizzare la gestione dei riferimenti bibliografici, con tutte le informazioni da riportarsi in una bibliografia. Per ogni pubblicazione deve esistere un codice identificante #underline[costituito da sette caratteri, indicanti le iniziali degli autori, l'anno di pubblicazione e un carattere aggiuntivo per la discriminazione delle collisioni] (ad es. BL2007a) - Dettagli marginali tendono solo a distrarre e non forniscono nessuna indicazione sulla struttura dello schema che si deve progettare ==== Esempio: BD bibliografica (2) Si vogliono organizzare i dati di interesse per automatizzare la gestione dei riferimenti bibliografici, con tutte le informazioni da riportarsi in una bibliografia. *Le pubblicazioni sono di due tipi, monografie (per le quali interessano editore, data e luogo di pubblicazione) e articoli su rivista (con nome della rivista, volume, numero, pagine e anno di pubblicazione); per entrambi i tipi si debbono ovviamente riportare i nomi degli autori.* Per ogni pubblicazione deve esistere un codice identificante... - Il paragrafo in grassetto fornisce informazioni utili per derivare lo schema concettuale, in quanto introduce concetti importanti nella realtà in esame ==== Un altro esempio più articolato - Si vuole realizzare una base di dati per una società che eroga corsi, di cui vogliamo rappresentare i dati deipartecipantiai corsi e deidocenti. - Per gli studenti(circa 5000), identificati da un codice, si vuole memorizzare il codice fiscale, il cognome, l'età, il sesso, il luogodi nascita, il nome dei loro attuali datori di lavoro, i posti dove hanno lavorato in precedenza insieme al periodo, l'indirizzo e il numero di telefono, icorsiche hanno frequentato (i corsi sono in tutto circa 200) e il giudizio finale. - Rappresentiamo anche iseminariche stanno attualmente frequentando e, per ogni giorno, i luoghie le ore dove sono tenute le lezioni. - I corsi hanno un codice, untitoloe possono avere varie edizioni con date di inizio e fine e numero di partecipanti. - Se gli studenti sono liberi professionisti, vogliamo conoscere l'area di interesse e, se lo possiedono, iltitolo. Per quelli che lavorano alle dipendenze di altri, vogliamo conoscere invece il loro livello e la posizione ricoperta. - Per gliinsegnanti(circa 300), rappresentiamo il cognome, l'età, ilpostodove sono nati, il nome del corso che insegnano, quelli che hanno insegnato nel passato e quelli che possono insegnare. Rappresentiamo anche tutti i loro recapiti telefonici. I docenti possono essere dipendenti interni della società o collaboratori esterni. ==== Glossario dei termini, omonimi e sinonimi - Raramente i requisisti espressi in linguaggio naturale sono privi di ambiguità. È infatti frequente il caso di\ #text(teal)[Omonimi]: lo stesso termine viene usato per descrivere concetti differenti (es: libro e copia di libro, posto: di lavoro e geografico)\ #text(teal)[Sinonimi]: termini diversi vengono usati per descrivere lo stesso concetto (es: studente e partecipante) - Un modo conveniente per rappresentare sinteticamente i concetti più rilevanti emersi dall'analisi è il glossario dei #text(teal)[termini], il cui scopo è fornire per ogni concetto rilevante: - Una breve descrizione del concetto - Eventuali sinonimi - Relazioni con altri concetti del glossario stesso ===== Esempio #cfigure("images/2024-05-09-17-00-53.png",90%) ==== Ristrutturazione dei requisiti - Oltre a costruire il glossario, al fine di semplificare le analisi successive, è utile riformulare i requisiti: - Eliminare le omonimie - Usare un termine univoco per ogni concetto - Riorganizzare le frasi raggruppandole in base al concetto cui si riferiscono Nell'esempio: - Frasi di carattere generale - Frasi riferite ai partecipanti - Frasi riferite ai docenti - Frasi riferite ai corsi - Frasi riferite alle società ===== Esempio: frasi relative ai partecipanti Per i partecipanti (circa 5000), identificati da un codice, rappresentiamo il codice fiscale, il cognome, l'età, il sesso, la città di nascita, i nomi dei loro attuali datori di lavoro e di quelli precedenti (insieme alle date di inizio e fine rapporto), le edizioni dei corsi che stanno attualmente frequentando e quelli che hanno frequentato nel passato, con la relativa votazione finale. ==== Dai concetti allo schema E/R - Va sempre ricordato che un concetto non è di per sé un'entità, un'associazione, un attributo, o altro #text(teal)[DIPENDE DAL CONTESTO!] - Come regole guida, un concetto verrà rappresentato come - Entità - se ha proprietà significative e descrive oggetti con esistenza autonoma - Attributo - se è semplice e non ha proprietà - Associazione - se correla due o più concetti - Generalizzazione/specializzazione - se è caso più generale/particolare di un altro ==== Strategie di progettazione - Per affrontare progetti complessi è opportuno adottare uno specifico modo di procedere, ovvero una #text(green)[strategia di progettazione] - I casi notevoli sono: - Strategia #highlight(fill: teal)[top-down:]\ Si parte da uno schema iniziale molto astratto ma completo, che viene successivamente raffinato fino ad arrivare allo schema finale - Strategia #highlight(fill: teal)[bottom-up:]\ Si suddividono le specifiche in modo da sviluppare semplici schemi parziali ma dettagliati, che poi vengono integrati tra loro - Strategia #highlight(fill: teal)[inside-out:]\ Lo schema si sviluppa “a macchia d'olio”, partendo dai concetti più importanti, che quindi vengono espansi aggiungendo quelli a essi correlati, e così via ===== Pro e controlo delle strategie #cfigure("images/2024-05-09-17-08-07.png",90%) ===== Un approccio “misto” - Nella pratica si fa spesso uso di una strategia ibrida, nella quale: + si individuano i concetti principali e si realizza uno #text(teal)[schema scheletro], che contiene solamente i concetti più importanti + sulla base di questo si può #text(teal)[decomporre] + poi si raffina, si espande, si integra ... vediamo cosa succede nel caso della società di formazione... ===== Società di formazione: schema scheletro #cfigure("images/2024-05-09-17-10-42.png",70%) #heading(level: 5, numbering: none)[Raffinamento di Partecipanti] #cfigure("images/2024-05-09-17-11-51.png",90%) - Dato che i partecipanti possono essere o dipendenti o professionisti, facciamo una gerarchie totale ed esclusiva (t,e) - I dipendenti possono avere (impiego corrente) un unico datore di lavoro, mentre i datori possono avere da 0 a n dipendenti - Impiego passato si riferisce alla classe generale Partecipanti perché uno che adesso è un Professionista può essere stato, in passato, un Dipendente #heading(level: 5, numbering: none)[Raffinamento di Corsi] #cfigure("images/2024-05-09-17-12-33.png",90%) - La chiave di Edizioni Corsi è il Codice del corso e la Data inizio #heading(level: 5, numbering: none)[Raffinamento di Docenti] #cfigure("images/2024-05-09-17-13-09.png",90%) #heading(level: 5, numbering: none)[Integrazione: schema di riferimento] #cfigure("images/2024-05-09-17-14-14.png",90%) #heading(level: 5, numbering: none)[Integrazione: Partecipanti e Corsi] #cfigure("images/2024-05-09-17-17-59.png",90%) #heading(level: 5, numbering: none)[Integrazione: Docenti e Corsi] #cfigure("images/2024-05-09-17-18-50.png",90%) - C'è un vincolo non espresso sulla data di Docenza corrente e Docenza passata ==== Qualità di uno schema concettuale - #text(teal)[Lo schema E/R deve essere verificato] accuratamente per verificare che risponda a requisiti di: - #highlight(fill: teal)[Correttezza] - Non devono essere presenti errori (sintattici o semantici) - #highlight(fill: teal)[Completezza] - Tutti i dati di interesse devono essere specificati - #highlight(fill: teal)[Leggibilità] - Riguarda anche aspetti prettamente estetici dello schema - #highlight(fill: teal)[Minimalità] - È importante capire se esistono elementi ridondanti nello schema; in alcuni casi ciò non è un problema, ma può essere viceversa una scelta di progettazione volta a favorire l'esecuzione di certe operazioni ==== Metodologia basata sulla strategia mista #text(green)[Analisi dei requisiti] - Analizzare i requisiti ed eliminare le ambiguità - Costruire un glossario dei termini, raggruppare i requisiti #text(green)[Passo base] - Definire uno schema scheletro con i concetti più rilevanti #text(green)[Passo di decomposizione] (se necessario o appropriato) - Decomporre i requisiti con riferimento ai concetti nello schema scheletro #text(green)[Passo iterativo] (da ripetere finché non si è soddisfatti) - Raffinare i concetti presenti sulla base delle loro specifiche - Aggiungere concetti per descrivere specifiche non descritte #text(green)[Passo di integrazione] (se si è decomposto) - Integrare i vari sottoschemi in uno schema complessivo, facendo riferimento allo schema scheletro #text(green)[Analisi di qualità] (ripetuta e distribuita) - Verificare le qualità dello schema e modificarlo ==== Riassumendo - La #text(teal)[fase di analisi dei requisiti] è fondamentale per poter progettare una base di dati che rispetti i requisiti - Mancando la possibilità di standardizzarla, tale fase si avvale necessariamente di regole di buon senso e di una serie di strumenti che riducono il rischio di commettere errori grossolani, oltre a costituire una valida documentazione - Per la #text(green)[progettazione dello schema E/R] sono possibili diverse strategie, di cui quella #text(teal)[mista] è senz'altro la più diffusa e adeguata anche nel caso di progetti estremamente complessi == Dalla Progettazione all'Implementazione === Introduzione - Arrivati a questo punto apparentemente occorre “solamente” implementare tutte le classi che abbiamo individuato nelle varie fasi (analisi, progettazione, ecc.) - “Sfortunatamente” anche a questo livello occorre effettuare delle scelte progettuali che hanno un impatto sulle caratteristiche del SW (efficienza, riusabilità, ecc.) - Il #text(blue)[*progetto di dettaglio*] rappresenta una descrizione del sistema molto vicina alla codifica, ovvero che la vincola in maniera sostanziale - Per esempio, descrivendo non solo le classi in astratto ma anche i loro attributi e metodi, con relativi tipi e firma === Progettazione di Dettaglio - Durante la progettazione di dettaglio è necessario definire - #highlight(fill: myblue)[Tipi di dato] che non sono stati definiti nel modello OOA - #highlight(fill: myblue)[Navigabilità delle associazioni] tra classi e relativa implementazione - #highlight(fill: myblue)[Strutture dati] necessarie per l'implementazione del sistema - #highlight(fill: myblue)[Operazioni] necessarie per l'implementazione del sistema - #highlight(fill: myblue)[Algoritmi] che implementano le operazioni - #highlight(fill: myblue)[Visibilità] di classi, (attributi,) operazioni, ... ==== Navigabilità di un'Associazione - Possibilità di spostarsi da un qualsiasi oggetto della classe origine a uno o più oggetti della classe destinazione (a seconda della molteplicità) - I messaggi possono essere inviati solo nella direzione della freccia Ogni docente deve avere un riferimento al proprio dipartimento di afferenza #cfigure("images/2024-05-17-17-38-14.png",90%) - #text(blue)[*A livello di analisi del problema*], le associazioni di composizione e di aggregazione hanno una direzione precisa detti #text(blue)[*A il contenitore*] e #text(blue)[*B l'oggetto contenuto*], è A che contiene B, e non viceversa - #text(blue)[*A livello implementativo*], un'associazione può essere - #text(blue)[*mono-direzionale*] quando da A si deve poter accedere a B, ma non viceversa - #text(blue)[*bi-direzionale*] quando da A si deve poter accedere a B e da B si deve poter accedere velocemente ad A - Dal punto di vista implementativo, la #text(blue)[*bi-direzionalità*] - è molto efficiente - ma occorre tenere sotto controllo la consistenzadelle strutture dati utilizzate per la sua implementazione #cfigure("images/2024-05-17-17-39-28.png",90%) ==== Implementazione delle Associazioni #heading(level: 5, numbering: none)[Associazioni con molteplicità 0..1 o 1..1] - Aggiungere alla classe cliente un attributo membro che rappresenta - il #text(blue)[*riferimento all'oggetto*] della classe fornitore - e/o l'#text(blue)[*identificatore univoco*] dell'oggetto della classe fornitore (solo se persistente) - o il #text(blue)[*valore dell'oggetto*] della classe fornitore (solo nel caso di #text(blue)[*composizione*] e #text(blue)[*molteplicità 1..1*]) #cfigure("images/2024-05-17-17-39-50.png",60%) #cfigure("images/2024-05-17-17-40-07.png",60%) #heading(level: 5, numbering: none)[Associazioni con molteplicità 0..\* o 1..\*] - Aggiungere alla classe cliente un attributo membro che referenzia un'#text(blue)[*istanza di una classe contenitore*] - Una #text(blue)[*classe contenitore*] è una classe le cui istanze sono #text(blue)[*collezioni*] di (riferimenti a) oggetti della classe fornitore - La classe contenitore può essere - realizzata, oppure - presa da una libreria (preferibilmente) #cfigure("images/2024-05-17-17-40-36.png",80%) #cfigure("images/2024-05-17-17-40-51.png",80%) #cfigure("images/2024-05-17-17-41-03.png",80%) #cfigure("images/2024-05-17-17-41-12.png",80%) #cfigure("images/2024-05-17-17-41-22.png",80%) ==== Classi Contenitore - Una #text(blue)[*classe contenitore*] (o semplicemente contenitore) è una classe le cui istanze contengono oggetti di altre classi - Se gli oggetti contenuti sono in #text(blue)[*numero fisso*], è sufficiente un vettore predefinito del linguaggio - Se gli oggetti contenuti sono in #text(blue)[*numero variabile*], un vettore predefinito non basta e occorre una classe contenitore - Esempi di classi contenitore sono - Vettori, stack, liste, alberi, ... - Funzionalità minime di una classe contenitore - #text(blue)[*Inserire, rimuovere, trovare*] un oggetto in una collezione - #text(blue)[*Enumerare*] (iterare su) gli oggetti della collezione - I contenitori possono essere classificati in funzione - del modo in cui contengono gli oggetti - #text(blue)[*contenimento per riferimento*]: gli oggetti sono reference type - #text(blue)[*contenimento per valore*]: gli oggetti sono value type - dell'omogeneità o eterogeneità di tali oggetti - #text(blue)[*oggetti omogenei*]: tutti gli oggetti contenuti sono dello stesso tipo - #text(blue)[*oggetti eterogenei*]: gli oggetti contenuti possono essere di tipo diverso ===== Contenimento per Riferimento - L'oggetto contenuto #text(blue)[*esiste per conto proprio*] - L'oggetto contenuto può essere #text(blue)[*in più contenitori contemporaneamente*] - Quando un oggetto viene inserito in un contenitore, #text(blue)[*non viene duplicato*] ma ne viene memorizzato solo il riferimento - La distruzione del contenitore non comporta la #text(blue)[*distruzione degli oggetti contenuti*] ===== Contenimento per Valore - L'oggetto contenuto - viene memorizzato nella struttura dati del contenitore - esiste solo in quanto contenuto fisicamente in un altro oggetto - Quando un oggetto deve essere inserito in un contenitore, #text(blue)[*viene duplicato*] - La distruzione del contenitore comporta la #text(blue)[*distruzione degli oggetti contenuti*] ===== Contenimento di Oggetti Omogenei - Per implementare #text(blue)[*contenitori di oggetti omogenei*] (sia per valore, sia per riferimento) sono ideali le #text(blue)[*classi generiche*] - Il tipo degli oggetti contenuti viene lasciato generico e ci si concentra sugli algoritmi di gestione della collezione di oggetti - Quando serve una classe contenitore di oggetti appartenenti a una classe specifica, #text(blue)[*è sufficiente istanziare la classe generica*], specificando il tipo desiderato #cfigure("images/2024-05-17-17-42-03.png",60%) #cfigure("images/2024-05-17-17-42-12.png",80%) ===== Contenimento di Oggetti Eterogenei - Per implementare #text(blue)[*contenitori di oggetti eterogenei*] (solo per riferimento) è necessario usare l'#text(blue)[*ereditarietà*] e sfruttare la proprietà che un puntatore alla superclasse radice della gerarchia può puntare a un'istanza di una qualunque sottoclasse - La classe contenitore può essere generica, ma il tipo deve essere la #text(blue)[*superclasse radice della gerarchia*] (nel peggiore dei casi, `object`) === Implementazione delle Associazioni - Un modo alternativo per implementare un'associazione tra due oggetti è tramite un #text(blue)[*dizionario*] - Un dizionario è un tipo particolare di contenitore, che associa due oggetti: #text(blue)[*la chiave e il rispettivo valore*] - La chiave - Può essere un oggetto qualsiasi, non necessariamente una stringa o un intero - Deve essere unica - Il dizionario, data una chiave, ritrova in modo efficiente il valore ad essa associato #cfigure("images/2024-05-17-17-42-33.png",85%) ==== Identificazione degli Oggetti - Un oggetto (contenitore o meno) può contenere un #text(blue)[*riferimento univoco*] a un altro oggetto - Come è possibile #text(blue)[*identificare univocamente*] un oggetto per poterlo associare a un altro? - Nel caso di #text(blue)[*strutture dati interamente contenute nello spazio di indirizzamento*] dell'applicazione, un oggetto può essere identificato univocamente mediante il suo #text(blue)[*indirizzo*] (logico) #text(blue)[*di memoria*] - Nel caso di #text(blue)[*database*] o di #text(blue)[*sistemi distribuiti*], a ogni oggetto deve essere associato un #text(blue)[*identificatore univoco persistente*] tramite il quale deve essere possibile risalire all'oggetto stesso, sia che risieda in memoria, su disco o in rete - L'identificatore univoco è un attributo che al momento della creazione dell'oggetto viene inizializzato con: - un valore generato automaticamente dal sistema - il valore della chiave primaria di una tabella relazionale, ... - Il nome di tale attributo #underline[*potrebbe*] essere - idDocente - idStudente, ... ===== Un Esempio Reale - La #text(blue)[*tecnologia COM*] (MS) permette a un'applicazione di trovare, caricare e utilizzare _run-time_ i #text(blue)[*componenti*] necessari per la sua esecuzione - Ogni componente è memorizzato in una DLL (#text(red)[Dynamic Link Library]) - un file locale o remoto - Quando l'applicazione ha bisogno di un componente, #text(blue)[*il sistema deve essere in grado di localizzare la DLL*] che contiene quel particolare componente - L'indipendenza dalla collocazione fisica non consente di utilizzare un indirizzo fisico (_pathname_) - Pertanto, deve essere utilizzato un #text(red)[meccanismo di indirizzamento logico] che permetta di identificare univocamente il file che contiene il componente - Si utilizzano degli #text(red)[identificatori globali] (#text(blue)[*GUID*] = _Globally Unique Identifier_) - Il concetto di GUID è stato introdotto, con un nome leggermente diverso (#text(blue)[UUID] = Universally Unique Identifier), dall'OSF (Open Software Foundation) nelle specifiche #text(blue)[DCE] (Distributed Computing Environment) - In DCE gli UUID vengono utilizzati per identificare i destinatari delle chiamate di procedura remota (RPC) - Un GUID è un numero di 128 bit (16 byte) generato in modo da garantire l'unicità nello spazio e nel tempo: MAC (48/64 bit) + ticks (64 bit - 100ns) rappresentato così:\ `{32bb8320-b41b-11cf-a6bb-0080c7b2d682}` - COM utilizza diversi tipi di GUID - Il tipo più importante di GUID serve a identificare le classi di componenti: ogni classe di componenti COM è caratterizzata da un proprio identificatore che viene chiamato #text(blue)[*CLSID*] (Class Identifier) - Disponendo di un CLSID, un'applicazione può chiedere alla funzione di sistema #text(blue)[`CoCreateInstance`] di creare un istanza del componente e di restituire un riferimento nel spazio di indirizzamento dell'applicazione stessa - Il database di sistema di Windows (#text(blue)[*registry*]) mantiene una corrispondenza tra CLSID ed entità fisiche (DLL, EXE) che contengono l'implementazione dei componenti (server) - `CoCreateInstance` provvede a - reperire il server tramite il _registry_ - caricarlo in memoria (se non è già presente) - creare un'istanza e restituirne un riferimento #cfigure("images/2024-05-17-17-43-16.png",90%) - In .NET esiste la classe `System.Guid` che permette di gestire istanze di GUID - Ad esempio, per ottenere un nuovo GUID, è sufficiente invocare il metodo statico `Guid.NewGuid()` che, ovviamente, restituisce un `System.Guid` - Altri metodi e operatori permettono di confrontare GUID ===== Modifiche per Utilizzare il Livello di Ereditarietà Supportato - Se esistono strutture con ereditarietà multipla - Se il linguaggio di programmazione non ammette l'ereditarietà multipla - È necessario convertire le strutture con ereditarietà multipla in strutture con solo ereditarietà semplice #cfigure("images/2024-05-17-17-43-39.png",70%) #heading(level: 6, numbering: none)[$1^a$ possibilità (composizione e delega)] - Scegliere la più significativa tra le superclassi ed ereditare esclusivamente da questa - Tutte le altre superclassi diventano possibili “ruoli” e vengono connesse mediante composizione - Le caratteristiche delle superclassi escluse vengono incorporate nella classe specializzata tramite composizione e delega e non tramite ereditarietà #cfigure("images/2024-05-17-17-43-54.png",65%) #heading(level: 6, numbering: none)[$2^a$ possibilità (interfaccia)] - Appiattire tutto in una gerarchia semplice e implementare un'interfaccia - In questo modo, una o più relazioni di ereditarietà si perdono e #text(blue)[*gli attributi e le operazioni corrispondenti devono essere ripetuti nelle classi specializzate*] #cfigure("images/2024-05-17-17-44-15.png",65%) #cfigure("images/2024-05-17-17-44-26.png",68%) === Miglioramento delle Prestazioni - Il software con le prestazioni migliori - fa la cosa giusta “abbastanza velocemente” (cioè, soddisfacendo i requisiti e/o le attese del cliente) - pur rimanendo entro costi e tempi preventivati - Per migliorare la velocità percepita può bastare - la #text(blue)[*memorizzazione di risultati intermedi*] - un'#text(blue)[*accurata progettazione dell'interazione con l'utente*] (ad es. utilizzando multi-threading) - Un #text(blue)[*traffico di messaggi molto elevato tra oggetti*] può invece richiedere dei cambiamenti per aumentare la velocità - Di norma, la soluzione è che un oggetto possa accedere direttamente ai valori di un altro oggetto (aggirando l'incapsulamento!) - Utilizzare metodi inline - Utilizzare la dichiarazione friend - Combinare insieme due o più classi - Questo tipo di modifica deve essere presa in considerazione solo dopo che tutti gli altri aspetti del progetto sono stati soggetti a misure e modifiche - L'unico modo per sapere se una modifica contribuirà in modo significativo a rendere il software “abbastanza veloce” è tramite le misure e l'osservazione = Framework .NET == Introduzione === Tecnologia COM - Component Object Model - Nasce nel 1993 - COM è un sistema platform-independent, distribuito, object-oriented per la creazione di componenti software binari - COM non è un linguaggio object-oriented ma uno #text(blue)[*standard*] - COM specifica un modello a oggetti e requisiti di programmazione che permettono agli oggetti COM di interagire con altri oggetti - Ad esempio un programma Java può parlare con un programma C, utilizzando la Java Native Interface - COM fa la stessa cosa del linker C quando abbiamo bisogno che più programmi parlino tra loro (link dinamico) Esempio di oggetti COM che parlano tra di loro: ```C interface IUnknown { virtual HRESULT QueryInterface(IID iid, void *ppvObject) = 0; virtual ULONG AddRef(void) = 0; virtual ULONG Release(void) = 0; }; ``` - `QueryInterface` è utilizzata per ottenere un puntatore a un'altra interfaccia (a tempo di esecuzione, non di compilazione), dato un `GUID` che identifica univocamente tale interfaccia (noto comunemente come interfaceID, o IID) - se l'oggetto COM non implementa tale interfaccia, viene restituito un errore `E_NOINTERFACE` - `AddRef` è utilizzato dai client per indicare che un oggetto COM viene referenziato (usato) - `Release` è utilizzato dai client per indicare che hanno finito di utilizzare l'oggetto COM - Le specifiche COM richiedono l'utilizzo di una tecnica chiamata #text(blue)[*reference counting*] per assicurare che i singoli oggetti rimangano “vivi” fintantoché esistono client che hanno ottenuto l'accesso a una o più delle loro interfacce e, di converso, che gli stessi oggetti vengano appropriatamente cancellati quando i clienti che li utilizzavano hanno finito di usarli e non ne hanno più bisogno; il contatore viene incrementato a ogni `AddRef` e decrementato a ogni `Release` - #text(blue)[Un oggetto COM è responsabile della liberazione della propria memoria] una volta che il suo reference count arrivi a zero - Il reference counting può causare #text(blue)[problemi se due o più oggetti hanno riferimenti circolari] - Ereditarietà solo con composizione e delega #cfigure("images/2024-04-11-09-22-06.png",80%) - La #text(blue)[*posizione*] di ciascun componente è memorizzata nel registro Windows - Di un certo componente può esistere un'unica versione installata - Questa limitazione può complicare seriamente il deployment di applicazioni basate su COM, a causa della possibilità che diversi programmi, o anche diverse versioni dello stesso programma, siano progettati per funzionare con versioni diverse dello stesso componente COM - Questa situazione è nota anche come inferno delle DLL (DLL hell) === Cos'è il Framework .NET - Ambiente di esecuzione (runtime environment) + Libreria di classi (standard + estensioni MS) - Versione 1.0 del 2002 ► v. 4.8 (versione definitiva, 7/19) - Semplifica lo sviluppo e il deployment - Aumenta l'affidabilità del codice - Unifica il modello di programmazione - È completamente indipendente da COM - È fortemente integrato con COM - Ambiente object-oriented - Qualsiasi entità è un oggetto - Classi ed ereditarietà pienamente supportati - Riduzione errori comuni di programmazione - #text(blue)[*Garbage Collector*] - Linguaggi fortemente tipizzati - #text(blue)[*Type Checker*] - Errori non gestiti ► generazione di eccezioni - Libertà di scelta del linguaggio - Funzionalità del framework disponibili in tutti i linguaggi .NET - I componenti della stessa applicazione possono essere scritti in linguaggi diversi - Ereditarietà supportata anche tra linguaggi diversi - Possibilità di estendere una qualsiasi classe .NET (non sealed) mediante ereditarietà - Diversamente da COM: - si usa e si estende la classe stessa - non si deve utilizzare composizione e delega - .NET è un'implementazione di CLI - Common Language Infrastructure - CLI e il linguaggio C\# sono standard ECMA - ECMA-334 (C\#), ECMA-335 (CLI) - Esistono altre implementazioni di CLI: - SSCLI (Shared Source CLI by Microsoft, per Windows, FreeBSD e Macintosh) - Rotor - Mono (per Linux) - DotGNU - Intel OCL (Open CLI Library) - ... === Standard ECMA-335 - Definisce la Common Language Infrastructure (CLI) nella quale applicazioni scritte in #text(blue)[*diversi linguaggi di alto livello*] possono essere eseguite in #text(blue)[*diversi ambienti di sistema*] senza la necessità di riscrivere l'applicazione per prendere in considerazione le caratteristiche peculiari di tali ambienti - CLI è un #text(blue)[*ambiente a tempo di esecuzione*], con: - un formato di file - un sistema di tipi comune - un sistema di metadati estensibile - un linguaggio intermedio - accesso alla piattaforma sottostante - una libreria di classi base - Concetti chiave: - #highlight(fill: myblue)[(Microsoft) Intermediate Language] - (MS)IL - #highlight(fill: myblue)[Common Language Runtime] - CLR - ambiente di esecuzione runtime per le applicazioni .NET - il codice che viene eseguito sotto il suo controllo si dice *codice gestito* (managed) - #highlight(fill: myblue)[Common Type System] - CTS - tipi di dato supportati dal framework .NET - consente di fornire un modello di programmazione unificato - #highlight(fill: myblue)[Common Language Specification] - CLS - regole che i linguaggi di programmazione devono seguire per essere interoperabili all'interno del framework .NET - sottoinsieme di CTS === Codice interpretato #cfigure("images/2024-04-11-09-29-02.png",90%) === Codice nativo #cfigure("images/2024-04-11-09-29-30.png",90%) === Codice IL #cfigure("images/2024-04-11-09-31-18.png",90%) JIT: just in time #cfigure("images/2024-04-11-09-33-15.png",90%) #cfigure("images/2024-04-11-09-32-32.png",90%) === Assembly - Unità minima per la distribuzione e il versioning - Normalmente è composto da un solo file #cfigure("images/2024-04-11-09-33-50.png",90%) - Ma può essere composto anche da più file #cfigure("images/2024-04-11-09-35-05.png",70%) === Metadati - Descrizione dell'assembly - Manifest - Identità: nome, versione, cultura [, public key] - Lista dei file che compongono l'assembly - Riferimenti ad altri assembly da cui si dipende - Permessi necessari per l'esecuzione - ... - Descrizione dei tipi contenuti nell'assembly - Nome, visibilità, classe base, interfacce - Campi (attributi membro), metodi, proprietà, eventi, ... - Attributi (caratteristiche aggiuntive) - definiti dal compilatore - definiti dal framework - definiti dall'utente === Chi usa i metadati? - Compilatori - Compilazione condizionale - Ambienti RAD (Rapid Application Development) - Informazioni sulle proprietà dei componenti - Categoria - Descrizione - Editor specializzati per tipo di proprietà - Tool di analisi dei tipi e del codice - Intellisense, ILDASM, Reflector, ... - Sviluppatori - *Reflection* (introspezione) - Analisi del contenuto di un assembly, permetter agli altri di guardare dentro === Esempio Assembly ```yasm .assembly Hello { } .assembly extern mscorlib { } .method public static void main() { .entrypoint ldstr "Hello IL World!" call void [mscorlib]System.Console::WriteLine (class System.String) ret } ilasm helloil.il ``` === Dove trovare gli Assembly - #highlight(fill: myblue)[Assembly privati] - Utilizzati da un'applicazione specifica - Directory applicazione (e sub-directory) - #highlight(fill: myblue)[Assembly condivisi] - Utilizzati da più applicazioni - Global Assembly Cache (GAC) - `c:\windows\assembly` - #highlight(fill: myblue)[Assembly scaricati da URL] - Download cache - `c:\windows\assembly\download` === Deployment semplificato - Installazione senza effetti collaterali - Applicazioni e componenti possono essere - condivisi - privati - Esecuzione side-by-side - Versioni diverse dello stesso componente possono coesistere, anche nello stesso processo === Common Language Runtime #cfigure("images/2024-04-11-09-38-34.png",60%) - IL CLR offre vari servizi alle applicazioni #cfigure("images/2024-04-11-09-39-17.png",75%) #cfigure("images/2024-04-11-09-40-06.png",70%) === Garbage Collector - Gestisce il ciclo di vita di tutti gli oggetti .NET - Gli oggetti vengono distrutti automaticamente quando non sono più referenziati - A differenza di COM, non si basa sul Reference Counting - #underline(stroke: 1.5pt + green)[Maggiore velocità di allocazione] - #underline(stroke: 1.5pt + green)[Consentiti i riferimenti circolari] - #underline(stroke: 1.5pt + red)[Perdita della distruzione deterministica]: non posso sapere in che momento un determinato oggetto verrà distrutto - Inoltre, essendo più complicato del garbage collector di COM, l'esecuzione dello stesso è un po' più pesante === Gestione delle eccezioni - Praticamente uguali a quelle di Java - Un'eccezione è - una condizione di errore - un comportamento inaspettato incontrato durante l'esecuzione del programma - Un'eccezione può essere generata da - codice del programma in esecuzione - ambiente di runtime - In CLR, un'eccezione è un oggetto che eredita dalla classe `System.Exception` - Gestione uniforme, elimina - codici `HRESULT` di COM - codici di errore Win32 - ... - Concetti universali - Lanciare un'eccezione (`throw`) - Catturare un'eccezione (`catch`) - Eseguire codice di uscita da un blocco controllato (`finally`) - Disponibile in tutti i linguaggi .NET con sintassi diverse === Common Type System - Tipi di dato supportati dal framework .NET - Alla base di tutti i linguaggi .NET - Fornisce un modello di programmazione unificato - Progettato per linguaggi object-oriented, procedurali e funzionali - Esaminate caratteristiche di 20 linguaggi - Tutte le funzionalità disponibili con IL - Ogni linguaggio utilizza alcune caratteristiche - Alla base di tutto ci sono i tipi: *classi, strutture, interfacce, enumerativi, delegati* - Fortemente tipizzato (compile-time) - Object-oriented - Campi, metodi, tipi annidati, proprietà, ... - Overload di metodi (compile-time) - Invocazione metodi virtuali risolta a run-time - Ereditarietà singola di estensione - Ereditarietà multipla di interfaccia === Common Language Specification - Definisce le regole di compatibilità tra linguaggi (sottoinsieme di CTS) - Regole per gli identificatori - Unicode, case-sensitivity - Keyword - Regole per denominazione proprietà ed eventi - Regole per costruttori degli oggetti - Regole di overload più restrittive - Ammesse interfacce multiple con metodi con lo stesso nome - Non ammessi puntatori unmanaged - ... #cfigure("images/2024-04-11-09-53-51.png",90%) ==== Tipi nativi #cfigure("images/2024-04-11-09-54-55.png",90%) === Common Type System - Tutto è un oggetto - `System.Object` è la classe radice - Due categorie di tipi - Tipi riferimento - Riferimenti a oggetti allocati sull'*heap* gestito - Indirizzi di memoria - Tipi valore - Allocati sullo *stack* o parte di altri oggetti - Sequenza di byte - Sono memorizzati come in Java ==== Tipi valore - I tipi valore comprendono: - Tipi primitivi (built-in) - Int32, ... - Single, Double - Decimal - Boolean - Char - Tipi definiti dall'utente - Strutture (`struct`) - Enumerativi (`enum`) ==== Tipi valore vs tipi riferimento #cfigure("images/2024-04-11-10-02-44.png",90%) Appena dichiaro la variabile `r`, questa viene salvato nello Stack, poi, quando viene inizializzata, viene creato un riferimento della classe `Csize` nello Heap. ==== Common Type System ``` public struct Point { private int _x, _y; public Point(int x, int y) { _x = x; _y = y; } public int X { get { return _x; } set { _x = value; } } public int Y { get { return _y; } set { _y = value; } } } ``` ``` public class Rectangle { Point v1; Point v2; ... } ... Rectangle r = new Rectangle(); ``` #cfigure("images/2024-04-11-10-05-02.png",90%) ``` ... Point[] points = new Point[100]; for (int i = 0; i < 100; i++) points[i] = new Point(i, i); ... ``` - Alla fine, rimane un solo oggetto nell'heap (l'array di `Point`) ``` ... Point[] points = new Point[100]; for (int i = 0; i < 100; i++) { points[i].X = i; points[i].Y = i; } ... ``` \ ``` public class Point { private int _x, _y; public Point(int x, int y) { _x = x; _y = y; } public int X { get { return _x; } set { _x = value; } } public int Y { get { return _y; } set { _y = value; } } } ``` #cfigure("images/2024-04-11-10-18-32.png",90%) ``` ... Point[] points = new Point[100]; for (int i = 0; i < 100; i++) points[i] = new Point(i, i); ... ``` - Alla fine, rimangono 101 oggetti nell'heap (1 array di `Point` + 100 `Point` ) ``` ... Point[] points = new Point[100]; for (int i = 0; i < 100; i++) { points[i].X = i; points[i].Y = i; } ... ``` NO! ==== Tipi valore e tipi riferimento #cfigure("images/2024-04-11-10-19-45.png",100%) === Boxing / Unboxing - Un qualsiasi tipo valore può essere automaticamente convertito in un tipo riferimento (#text(blue)[*boxing*]) mediante un up cast implicito a `System.Object` ``` int i = 123; object o = i; ``` - Un tipo valore “boxed” può tornare a essere un tipo valore standard (#text(blue)[*unboxing*]) mediante un down cast esplicito ``` int k = (int) o; ``` - Un tipo valore “boxed” è un #text(blue)[*clone indipendente*], quindi se, dopo aver eseguito il boxing, cambio il valore di `i`, il valore di `k` non viene modificato #cfigure("images/2024-04-11-10-40-03.png",90%) === Bibliografia Libri di base: - <NAME>, IntroducingMicrosoft® .NET, Second Edition - <NAME>, <NAME>, Microsoft® Visual C\# `™` .NET Stepby Step - <NAME>, <NAME>, Inside C\#, Second Edition - <NAME>, XML Stepby Step, Second Edition - <NAME>, Microsoft® ADO.NET Stepby Step Libri avanzati: - <NAME>, AppliedMicrosoft® .NET Framework Programming - <NAME>, Programming Microsoft® Windows® with C\# - <NAME>, Inside Microsoft® .NET IL Assembler == Garbage Collection === Utilizzo di un oggetto - In un ambiente object-oriented, ogni oggetto che deve essere utilizzato dal programma - È descritto da un tipo - Ha bisogno di un'area di memoria dove memorizzare il suo stato - Una volta che si conosce il tipo dell'oggetto sappiamo quanta memoria allocare per lo stesso - Passi per utilizzare un oggetto di tipo riferimento: - #text(blue)[*Allocare memoria*] per l'oggetto - #text(blue)[*Inizializzare la memoria*] per rendere utilizzabile l'oggetto - #text(blue)[*Usare l'oggetto*] - #text(blue)[*Eseguire un clean up*] dello stato dell'oggetto, se necessario; se, ad esempio, all'interno di quell'oggetto c'era un riferimento a un puntatore a file, quel file deve essere chiuso - #text(blue)[*Liberare la memoria*] === Ciclo di vita di un oggetto #cfigure("images/2024-04-15-11-20-16.png",90%) === Allocazione della memoria - In C: - `malloc ( calloc , realloc )` - In C++: - `malloc ( calloc , realloc )` - `new` - In Java: - `new` - In IL: - `newobj` - In C\#: - `new` === Inizializzazione della memoria - Definite Assignment: a ogni variabile deve essere sempre assegnato un valore prima che essa venga utilizzata - il compilatore deve assicurarsi che ciò sia sempre verificato - Data-flow analysis del codice - valori di default - usati in generale per tipi valore - ad esempio, in Java le variabili di classe, locali e i componenti di un array sono inizializzati al valore di default, non le variabili di istanza, perché in quel caso è il costruttore che si deve occupare di inizializzarle - costruttore - usato per i tipi classe (Java, C++, C\#) === Definite Assignment ```C int k; if (v > 0 && (k = System.in.read()) >= 0) System.out.println(k); ``` Questo è corretto \ ```C int k; while (n < 4) { k = n; if (k >= 5) break; n = 6; } System.out.println(k); ``` Questo è sbagliato, perché il compilatore non sa il valore di `n` \ ```C int k; while (true) { k = n; if (k >= 5) break; n = 6; } System.out.println(k); ``` Questa è corretta \ ```C int k; int n=5; if (n>2) k=3; System.out.println(k); ``` Questo non è corretto perché, a differenza dell'esempio sopra, l'espressione all'interno dell'`if` non è costante; se pensiamo a `n` come variabile condivisa, il valore di `n` potrebbe cambiare tra l'assegnamento e la valutazione. === Clean up dello stato - In C++/C\#: - distruttore (più propriamente, finalizzatore): \~{nome della classe} - unico, non ereditabile, no overload, senza parametri e modificatori - invocato automaticamente alla distruzione dell'oggetto (non può essere invocato) - In java: - `finalize()` - metodo di `Object` - invocato automaticamente alla distruzione dell'oggetto (non può essere invocato) - il momento in cui viene invocato un finalizzatore dipende dalla JVM === Liberazione della memoria - In C: - `free()` - In C++: - `free()` - `delete` - In java/C\#: garbage collector (GC) === Cos'è il Garbage Collection - Modalità automatica di rilascio delle risorse utilizzate da un oggetto - Migliora la stabilità dei programmi - Evita errori connessi alla necessità, da parte del programmatore, di manipolare direttamente i puntatori alle aree di memoria - Pro: - dangling pointer: puntatore che fa riferimento a un'area di memoria non più valida - doppia de-allocazione - memory leak - Contro: - aumentata richiesta risorse di calcolo - incertezza del momento in cui viene effettuata la GC - rilascio della memoria non deterministico; quindi non posso distruggere un oggetto quando voglio io - Strategie disponibili: - Tracing - determinare quali oggetti sono (potenzialmente) raggiungibili - eliminare gli oggetti non raggiungibili - Reference counting - ogni oggetto contiene un contatore che indica il numero di riferimenti a esso - la memoria può essere liberata quando il contatore raggiunge lo 0 - Escape analysis - si spostano oggetti dallo heap allo stack - l'analisi viene effettuata a compile-time in modo da stabilire se un oggetto, allocato all'interno di una subroutine, non è accessibile al di fuori di essa - riduce il lavoro del GC === GC: Reference counting - Svantaggi: - Cicli di riferimenti - se due oggetti si referenziano a vicenda, il loro contatore non raggiungerà mai 0 - Aumento dell'occupazione di memoria - Riduzione della velocità delle operazioni sui riferimenti - ogni operazione su un riferimento deve anche incrementare/decrementare i contatori - Atomicità dell'operazione - ogni modifica a un contatore deve essere resa operazione atomica in ambienti multi-threaded - Assenza di comportamento real-time - ogni operazione sui riferimenti può (potenzialmente) causare la de-allocazione di diversi oggetti - il numero di tali oggetti è limitato solamente dalla memoria allocata === GC: Tracing - Siano #text(aqua)[p] e #text(aqua)[q] due oggetti - Sia #text(aqua)[q] un oggetto raggiungibile - Diremo che p è raggiungibile in maniera ricorsiva se e solo se: - esiste un riferimento a #text(aqua)[p] tramite #text(aqua)[q] - ovvero #text(aqua)[p] è raggiungibile attraverso un oggetto, a sua volta raggiungibile - Un oggetto è pertanto raggiungibile in due soli casi: - è un oggetto radice - creato all'avvio del programma (oggetto globale) - creato da una sub-routine (oggetto scope, riferito da variabile sullo stack) - è referenziato da un oggetto raggiungibile - la raggiungibilità è una chiusura transitiva - La definizione di garbage tramite la raggiungibilità non è ottimale - può accadere che un programma utilizzi per l'ultima volta un certo oggetto molto prima che questo diventi irraggiungibile - Distinzione: - garbage *sintattico* \ (oggetti che il programma non può raggiungere) - garbage *semantico* \ (oggetti che il programma non vuolepiù usare) - problema solo parzialmente decidibile, quindi non possono essere creati algoritmi per risolvere questo problema ``` Object x = new Foo(); Object y = new Bar(); x = new Quux(); // qui l'oggetto Foo è garbage sintattico if(x.check_something()) x.do_something(y); // qui y *potrebbe* essere garbage semantico ``` === Allocazione della memoria - In fase di inizializzazione di un processo, il CLR - Riserva una regione contigua di spazio di indirizzamento managedheap - Memorizza in un puntatore (`NextObjPtr`) l'indirizzo di partenza della regione #cfigure("images/2024-04-15-11-42-57.png",90%) - Quando deve eseguire una `newobj`, il CLR - Calcola la dimensione in byte dell'oggetto e aggiunge all'oggetto due campi di 32 (o 64) bit - Un puntatore alla tabella dei metodi - Un campo `SyncBlockIndex` - Controlla che ci sia spazio sufficiente a partire da `NextObjPtr` - in caso di spazio insufficiente: - garbage collection - `OutOfMemoryException` - `thisObjPtr= NextObjPtr;` - `NextObjPtr += sizeof(oggetto);` - Invoca il costruttore dell'oggetto ( `this` $equiv$ `thisObjPtr` ) - Restituisce il riferimento all'oggetto #cfigure("images/2024-04-15-11-47-22.png",90%) === Garbage Collector - Verifica se nell'heap esistono oggetti non più utilizzati dall'applicazione - Ogni applicazione ha un insieme di radici (_root_) - Ogni radice è un puntatore che contiene l'indirizzo di un oggetto di tipo riferimento oppure vale `null` - Le radici sono: - Variabili globali e field statici di tipo riferimento - Variabili locali o argomenti attuali di tipo riferimento sugli stack dei vari thread - Registri della CPU che contengono l'indirizzo di un oggetto di tipo riferimento - *Gli oggetti “vivi”* sono quelli *raggiungibili* direttamente o indirettamente dalle radici - *Gli oggetti garbage* sono quelli *NON raggiungibili* direttamente o indirettamente dalle radici - Quando parte, il GC ipotizza che tutti gli oggetti siano garbage - Quindi, scandisce le radici e per ogni radice *marca* - l'eventuale oggetto referenziato e - Tutti gli oggetti a loro volta raggiungibili a partire da tale oggetto - Se durante la scansione incontra un oggetto già marcato in precedenza, lo salta - sia per motivi di prestazioni - sia per gestire correttamente riferimenti ciclici - Una volta terminata la scansione delle radici, tutti gli oggetti NON marcati sono non raggiungibili e quindi garbage ==== Fase 1: Mark #cfigure("images/2024-04-15-11-50-46.png",90%) - Rilascia la memoria usata dagli oggetti non raggiungibili - *Compatta* la memoria ancora in uso, *modificando nello stesso tempo tutti i riferimenti agli oggetti spostati!* Quindi sposta tutti gli oggetti in ordine dall'inizio dell'heap. - Unifica la memoria disponibile, aggiornando il valore di `NextObjPtr` - Tutte le operazioni che il GC effettua sono possibili in quanto - Il tipo di un oggetto è sempre noto - È possibile utilizzare i metadati per determinare quali field dell'oggetto fanno riferimento ad altri oggetti ==== Fase 2: Compact #cfigure("images/2024-04-15-11-52-49.png",90%) === Finalization - Non è responsabilità del GC, ma del programmatore - Se un oggetto contiene esclusivamente - tipi valore e/o - riferimenti a oggetti managed (maggior parte dei casi), non è necessario eseguire alcun codice particolare - Se un oggetto contiene almeno un riferimento a un oggetto _unmanaged_ (in genere, una risorsa del S.O.) - file, connessione a database, socket, mutex, bitmap, ...\ #text(blue)[*è necessario eseguire del codice per rilasciare la risorsa, prima della deallocazione dell'oggetto*] - Ad esempio, un oggetto di tipo `System.IO.FileStream` - Prima deve aprire un file e memorizzare in un suo field l'handle del file (una risorsa di S.O. unmanaged) - Quindi usa tale handle nei metodi *Read* e *Write* - Infine, deve rilasciare l'handle nel metodo `Finalize` - In C\# - NON è possibile definire il metodo `Finalize` - È necessario definire un *distruttore* (sintassi C++) ``` public class OSHandle { //' Field contenente l'handledella risorsa unmanaged private readonly IntPtr handle; public IntPtr Handle { get { return _handle; } } public OSHandle(IntPtr handle) { _handle = handle; } ~OSHandle() { CloseHandle(_handle); } [System.Runtime.InteropServices.DllImport(“Kernel32”)] private extern static bool CloseHandle(IntPtr handle); } ``` - Il compilatore C\# trasforma il codice del distruttore ``` ~OSHandle() { CloseHandle(_handle); } ``` nel seguente codice (ovviamente in IL): ``` protected override void Finalize() { try { CloseHandle(_handle); } finally { base.Finalize(); } } ``` - L'invocazione del metodo `Finalize` non avviene in modo deterministico - Inoltre, non essendo un metodo pubblico, il metodo `Finalize` non può essere invocato direttamente - Nel caso di utilizzo di risorse che devono essere rilasciate appena termina il loro uso, questa situazione è problematica - Si pensi a file aperti o a connessioni a database che vengono chiusi solo quando il GC invoca il corrispondente metodo `Finalize` - In questi casi, è di fondamentale importanza rilasciare (`Dispose`) o chiudere (`Close`) la risorsa in modo deterministico === Rilascio deterministico senza gestione delle eccezioni ``` ... Byte[] bytesToWrite = new Byte[] {1,2,3,4,5}; FileStream fs; fs = new FileStream(“Temp.dat”, FileMode.Create); fs.Write(bytesToWrite, 0, bytesToWrite.Length); fs.Close(); ... ``` === Rilascio deterministico con gestione delle eccezioni ``` ... Byte[] bytesToWrite = new Byte[] {1,2,3,4,5}; FileStream fs = null; try { fs = new FileStream(“Temp.dat”, FileMode.Create); fs.Write(bytesToWrite, 0, bytesToWrite.Length); } finally { if(fs != null) fs.Close(); } ... ``` === Il pattern Dispose Se un tipo `T` vuole offrire ai suoi utilizzatori un servizio di clean up esplicito, deve implementare l'interfaccia `IDisposable` ``` public interface IDisposable { void Dispose(); } ``` - I clienti di T possono utilizzare l'istruzione `using` ``` using (T tx = ...) { utilizzo di tx... #Invocazione automatica di tx.Dispose() } ``` === Rilascio deterministico con using ``` ... Byte[] bytesToWrite = new Byte[] {1,2,3,4,5}; using (FileStream fs = new FileStream(“Temp.dat”, FileMode.Create)) { fs.Write(bytesToWrite, 0, bytesToWrite.Length); } ... ``` - Il tipo della variabile definita nella parte iniziale di `using` deve implementare l'interfaccia IDisposable - All'uscita del blocco 'using' , viene sempre invocato automaticamente il metodo Dispose === Il pattern Dispose (altro esempio di utilizzo) ``` public class CursorReplacer : IDisposable { private readonly Cursor _previous; public CursorReplacer() { _previous = Cursor.Current; Cursor.Current = Cursors.WaitCursor; } public void Dispose() { Cursor.Current = _previous; } } ``` ``` List<DbTableWrapper> tableWrappers = new List<DbTableWrapper>(); // Recupero di tutte le tabelle selezionate using (CursorReplacer cursorReplacer = new CursorReplacer()) { foreach (DbServerWrapper serverWrapper in SelectedDbServerWrappers) foreach (DbCatalogWrapper catalogWrapper in serverWrapper.SelectedDbCatalogWrappers) foreach (DbTableWrapper tableWrapper in catalogWrapper.SelectedDbTableWrappers) { tableWrappers.Add(tableWrapper); } } ``` == Tipi in .NET - Dal punto di vista del modo in cui le istanze vengono gestite in memoria (rappresentazione, tempo di vita, ...), i tipi possono essere distinti in: - _Reference type_ - _Value type_ - Dal punto di vista sintattico (sintassi del linguaggio C\#), i tipi possono essere distinti in: - Classi - `class` - Interfacce - `interface` - Strutture - `struct` - Enumerativi - `enum` - Delegati - `delegate` - Array - `[]` - In .NET, si concretizzano sempre in una classe (anche nel caso di tipi built-ine di interfacce) - In generale, un tipo può contenerela definizione di 0+: - #highlight(fill: myblue)[Costanti] - sempre implicitamente associate al tipo - #highlight(fill: myblue)[Campi] (field) - read-only o read-write, associati alle istanze o al tipo - #highlight(fill: myblue)[Metodi] - associati alle istanze o al tipo - #highlight(fill: myblue)[Costruttori] - di istanza o di tipo - #highlight(fill: myblue)[Operatori] - sempre associati al tipo - #highlight(fill: myblue)[Operatori di conversione] - sempre associati al tipo - #highlight(fill: myblue)[Proprietà] - associate alle istanze o al tipo - #highlight(fill: myblue)[Indexer] - sempre associati alle istanze - #highlight(fill: myblue)[Eventi] - associati alle istanze o al tipo - #highlight(fill: myblue)[Tipi] - annidati === Modificatori di visibilità #cfigure("images/2024-04-17-10-02-56.png",100%) #cfigure("images/2024-04-17-17-46-42.png",100%) - Non sono applicabili nei seguenti casi: - #highlight(fill: myblue)[Costruttori di tipo] (statici) sempre inaccessibili - invocati direttamente dal CLR - #highlight(fill: myblue)[Distruttori] (finalizer) sempre inaccessibili - invocati direttamente dal CLR - #highlight(fill: myblue)[Membri di interfacce] sempre pubblici - #highlight(fill: myblue)[Membri di enum] sempre pubblici - #highlight(fill: myblue)[Implementazione esplicita di membri di interfacce] visibilità particolare (pubblici/privati), non modificabile - #highlight(fill: myblue)[Namespace] sempre pubblici === Regole - *Massimizzare l'incapsulamento minimizzando la visibilità* - Information hiding a livello di assembly - Dichiarare `public` solo i tipi significativi dal punto di vista concettuale - Information hiding a livello di classe - Dichiarare `public` solo metodi, proprietà ed eventi significativi dal punto di vista concettuale - Dichiarare `protected` solo le funzionalità che devono essere visibili nelle classi derivate, ma non esternamente ad esempio, costruttori particolari, metodi e proprietà virtuali non public - Information hidinga livello di field - Field `private` e proprietà `public` - Field `private` e proprietà `protected` === Costanti - Una *costante* è un simbolo che identifica un valore che non può cambiare - Il *tipo* della costante può essere solo un tipo considerato primitivo dal CLR (compreso `string`) - Il *valore* deve essere determinabile _a tempo di compliazione_ - Ad esempio, in `Int32` esistono: ``` public const int MaxValue = 2147483647; public const int MinValue = -2147483648; ``` - In una classe contenitore di dimensioni prefissate, si potrebbe definire: ``` public const int MaxEntries = 100; // Warning! ``` - Si noti l'utilizzo della maiuscola iniziale - È possibile applicare `const` anche alle variabili locali === Field - Un *field* è un _data member_ che può contenere: - un *valore* (un istanza di un _value type_) - un *riferimento* (a un'istanza di un _reference type_) in genere, la realizzazione di un'associazione - Può essere: - di *istanza* (_default_) - di *tipo* (`static`) - Può essere: - *read-write* (_default_) - *read-only* (`readonly`) \ inizializzato nella definizione o nel costruttore - Esiste sempre un *valore di default* (`0 , 0.0, false, null`) - Qual è la differenza tra le seguenti definizioni: ``` public const int MaxEntries = 100; public static readonly int MaxEntries = 100; ``` - Nel primo caso, la costante `MaxEntries` viene *“iniettata”* nel codice del cliente - se il valore viene modificato e se il cliente e il fornitore sono in assembly diversi, *è necessario ricompilare anche il codice del cliente* - Nel secondo caso, l'accesso al `fieldMaxEntries` è quello standard: il valore è in memoria ed è necessario reperirlo - se il valore viene modificato e se il cliente e il fornitore sono in _assembly_ diversi, *NON è necessario ricompilare anche il codice del cliente* === Regole - Definire `const` solo le costanti *“vere”*, cioè i valori veramente immutabili nel tempo (nelle versioni del programma), negli altri casi utilizzare field statici read-only - il valore di `MaxEntries` non è una costante “vera” perché in una versione successiva del programma potrebbe cambiare - *Costanti* - il nome dovrebbe iniziare con una lettera maiuscola - di solito, dovrebbe essere pubblica (ma non è sempre così) - *Field* - il nome dovrebbe iniziare con “\_” seguito da una lettera minuscola - deve essere privata (accesso sempre mediante proprietà) - *Field read-only* - scegliere, a seconda delle situazioni, una delle due convenzioni precedenti === Modificatori di metodi - `virtual` - `abstract` - `override` - `override sealed / sealed override` - Applicabili a: - *Metodi* - *Proprietà* (metodi `get` e `set`) - *Indexer* (metodi `get` e `set`) - *Eventi* (metodi `add` e `remove`) di istanza (cioè non statici) === Modificatore `virtual` - *L'implementazione di un metodo virtuale può essere modificata* da un membro override di una classe derivata (discendente) - Quando il metodo virtuale viene invocato, viene valutato il tipo run-time dell'oggetto su cui è invocato per vedere la presenza di un membro sovrascritto - Late binding - Polimorfismo - *Per default, i metodi non sono virtuali* ``` protected virtual void Method() { ... } public virtual int Property { get { ... } set { ... } } public virtual int this[int index] { get { ... } } ``` === Modificatore `abstract` - Si usa il modificatore `abstract` per indicare che il metodo non contiene alcuna implementazione - I metodi astratti hanno le seguenti caratteristiche - Un metodo virtuale è implicitamente virtuale - La dichiarazione di metodi astratti è permessa solo in classi astratte - L'implementazione di un metodo astratto verrà fornita da un metodo sovrascrivente ``` protected abstract void Method(); public abstract int Property { get; set; } public abstract int this[int index] { get; } ``` === Modificatore `override` - Un metodo override *fornisce una (nuova) implementazione* di un metodo ereditato da una classe base - Il metodo sovrascritto da una dichiarazione override è detto metodo basesovrascitto(overridden) - Il metodo base sovrascritto - Deve essere *virtual*, *abstract*, o *override* - Deve avere la stessa firma (signature) del metodo override - Una dichiarazione override *non può cambiare l'accessibilità* del metodo base sovrascritto (diverso da Java) - L'uso del modificatore `sealed` impedisce a una qualsiasi classe derivata l'ulteriore sovrascrittura del metodo ``` protected override void Method() { ... } public override sealed int Property { get { ... } set { ... } } public override int this[int index] { get { ... } } ``` === Metodi ==== Passaggio degli argomenti - Tre tipi di argomenti: - *In* (`default` in C\#) - L'argomento deve essere inizializzato - L'argomento viene passato per *valore* (per *copia*) - Eventuali modifiche del valore dell'argomento *non hanno effetto* sul chiamante - *In/Out* (`ref` in C\#) - L'argomento deve essere inizializzato - L'argomento viene passato per *riferimento* - Eventuali modifiche del valore dell'argomento *hanno effetto* sul chiamante - *Out* (`out` in C\#) - L'argomento può NON essere inizializzato - L'argomento viene passato per *riferimento* - Le modifiche del valore dell'argomento (l'inizializzazione è obbligatoria) *hanno effetto* sul chiamante ==== Passaggio degli argomenti In - *Value type* - Viene passata una copia dell'oggetto - Eventuali modifiche vengono effettuate sulla copia e *non hanno alcun effetto* sull'oggetto originale - *Reference type* - Viene passata una copia del riferimento all'oggetto - Eventuali modifiche dell'oggetto referenziato hanno effetto - Eventuali modifiche del riferimento vengono effettuate sulla copia e *non hanno alcun effetto* sul riferimento originale ``` Point p1 = new Point(0,0); Method1(p1); Console.WriteLine("{0}",p1); static void Method1(Point p) { p.X = 100; p.Y = 100; } ``` - Se `Point` è una classe le modifiche vengono effettuate sull'oggetto referenziato\ `(100,100)` - Se `Point` è una struttura le modifiche vengono effettuate sulla copia\ `(0,0)` ==== Passaggio degli argomenti In/Out - *Value type* - Viene passato l'indirizzo dell'oggetto - Eventuali modifiche *agiscono direttamente sull'oggetto* originale - *Reference type* - Viene passato l'indirizzo del riferimento all'oggetto - Eventuali modifiche dell'oggetto referenziato *hanno effetto* - Eventuali modifiche del riferimento *agiscono direttamente sul riferimento originale* ``` Point p1 = new Point(0,0); Method2(ref p1); Console.WriteLine("{0}",p1); static void Method2(ref Point p) { p.X = 100; p.Y = 100; } ``` - Se `Point` è una classe\ `(100,100)` - Se `Point` è una struttura\ `(100,100)` ==== Passaggio degli argomenti ```C class/struct Persona ... ... Persona p1 = new Persona(“Tizio”); // p1 == Tizio* Method1(p1); // p1 == Tizio Method2(ref p1); // p1 == Sempronio ... static void Method1(Persona p) { p = new Persona(“Caio”); //* p == Caio } static void Method2(ref Persona p) { p = new Persona(“Sempronio”); //* p == Sempronio } ``` - `p1` all'inizio fa riferimento a un'istanza di `Persona` con nome "Tizio" - quando viene invocato ```c Method1()``` nello scope della funzione la variabile `p` fa riferimento a un'istanza di `Persona` di nome "Caio", ma quando si esce dalla funzione il record di attivazione viene distrutto e quindi nel `main` `p1` fa ancora riferimento all'istanza di `Persona` di prima, di nome "Tizio" - Nella funzione ```c Method2()``` viene creato un riferimento tra `p` e `p1`, cioè la variabile `p` punta alla variabile `p1`, che a sua volta punta all'istanaza di `Persona` "Tizio"; quindi quando si invoca il metodo ```c new Persona()```, siccome tutte le operazioni fatte su `p` vengono fatte su `p1`, è la variabile `p1` che punta a una nuova istanza di `Persona` "Sempronio"; quindi anche quando si esce dalla funzione e il record di attivazione viene distrutto, la variabile `p1` continua a puntare all'istanza di `Persona` "Sempronio" ==== Passaggio degli argomenti Out - *Value type* e *Reference type* - Viene passato l'indirizzo dell'oggetto o del riferimento all'oggetto come nel caso In/Out - Non è necessario che l'oggetto o il riferimento siano inizializzati prima di essere passati come argomento - L'oggetto o il riferimento *DEVONO essere inizializzati* nel metodo a cui sono stati passati come argomento ``` Point p1; Method3(out p1); static void Method3(out Point p) { // In questo punto il compilatore suppone che // p NON sia inizializzato p.X = 100; p.Y = 100; // Errore di compilazione! p = new Point(100,100); // È indispensabile } ``` ==== Regole - Utilizzare prevalentemente il passaggio _standard_ per valore - Utilizzare il passaggio per riferimento (`ref` o `out`) solo se strettamente necessario - 2+ valori da restituire al chiamante - 1+ valori da utilizzare e modificare nel metodo - Scegliere `ref` se l'oggetto passato come argomento deve essere già stato inizializzato - Scegliere `out` se è responsabilità del metodo inizializzare completamente l'oggetto passato come argomento ==== Esempi ```C public static void Swap<T>(ref T arg1, ref T arg2) { T temp = arg1; arg1 = arg2; arg2 = temp; } public static void SplitCognomeNome(string cognomeNome, out string cognome, out string nome) { string[] words = cognomeNome.Split(' '); if (words.Length == 2) { cognome = words[0]; nome = words[1]; } else { ... } } ``` ==== Numero variabile di argomenti - Si supponga di dover scrivere: ```C Add(a,b); // a+b Add(10,20,30); // 10+20+30 Add(x1,x2,x3,x4); // x1+x2+x3+x4 ``` - Soluzioni possibili: - Overloadingdel metodo *`Add`* - *Svantaggio*: posso solo codificare un numero finito di metodi - Definire un solo metodo Addche accetti un numero variabile di argomenti ```C int Add(params int[] operands) { int total = 0; foreach (int operand in operands) total += operand; return total; } ``` - Non solo posso scrivere: ```C Add(a,b); Add(10,20,30); Add(x1,x2,x3,x4); ``` - Ma anche: ```C Add(); // restituisce 0 int[] numbers = { 10,20,30,40,50 }; Add(numbers); Add(new int[] { 10,20,30,40,50 }); Add(new int[] { x1,x2,x3,x4,x5 }); ``` - Zucchero sintattico: ```C Add(x1,x2,x3,x4); ``` è uguale a ```C Add(new int[] { x1,x2,x3,x4 }); ``` === Costruttori di istanza - *Responsabilità*: inizializzare correttamente lo stato dell'oggetto appena creato (nulla di più!) - In mancanza di altri costruttori, esiste sempre un costruttore di _default_ senza argomenti che, semplicemente, invoca il costruttore senza argomenti della classe base - Nel caso delle *classi*, il costruttore senza argomenti può essere definito dall'utente - Nel caso delle *strutture*, il costruttore senza argomenti NON può essere definito dall'utente (per motivi di efficienza) - In entrambi i casi, è possibile definire altri costruttori con differente signaturee differente visibilità ```C public abstract class DataAdapterManager { private readonly IDataTable _dataTable; private readonly IConnectionManager _connectionManager; protected DataAdapterManager(IDataTable dataTable, IConnectionManager connectionManager) { if(dataTable == null) throw new ArgumentNullException("dataTable"); if(connectionManager == null) throw new ArgumentNullException("connectionManager"); _dataTable = dataTable; _connectionManager = connectionManager; } ... } ``` ```C public class XmlDataAdapterManager : DataAdapterManager { private readonly Encoding _encoding; public XmlDataAdapterManager(IDataTable dataTable, XmlConnectionManager xmlConnectionManager) : this(dataTable, xmlConnectionManager, Encoding.Unicode) { } public XmlDataAdapterManager(IDataTable dataTable, XmlConnectionManager xmlConnectionManager, Encoding encoding) : base(dataTable, xmlConnectionManager) { _encoding = encoding; } ...} ``` === Costruttori di tipo - *Responsabilità*: inizializzare correttamente lo stato comune a tutte le istanze della classe - _field_ statici - Dichiarato `static` - Implicitamente `private` - Sempre senza argomenti - no _overloading_ - Può accedere esclusivamente ai membri (_field_, metodi, ...) statici della classe - Se esiste, viene invocato automaticamente dal CLR - Prima della creazione della prima istanza della classe - Prima dell'invocazione di un qualsiasi metodo statico della classe - Non basare il proprio codice sull'ordine di invocazione di costruttori di tipo ```C class MyType { static int _x = 5; #Viene definito implicitamente un costruttore di tipo ... } class MyType { static int _x; static MyType() { _x = 5; } #Del tutto analogo al caso precedente ... } class MyType { static int _x = 5; static MyType() { _x = 10; } #_x viene prima inizializzato a 5 e quindi a 10 ... } ``` === Regole - Definire un costruttore di tipo solo se strettamente necessario, cioè se i campi statici della classe - NON possono essere inizializzati in linea - Devono essere inizializzati solo se la classe viene effettivamente utilizzata ```C public class A { private static XmlDocument _xmlDocument; static A() { _xmlDocument = new XmlDocument(); _xmlDocument.Load (...); } ... } ``` === Costruttori ed eccezioni - Supponiamo che - un costruttore lanci un'eccezione e - l'eccezione non venga gestita all'interno del costruttore stesso (quindi arrivi al chiamante) - *Nel caso di costruttori di istanza* nessun problema!\ In C++ è una situazione non facilmente gestibile - *Nel caso di costruttori di tipo* la classe NON è più utilizzabile!\ `TypeInitializationException` === Interfacce - In C\#, un'interfaccia può contenere esclusivamente: - *Metodi* - considerati pubblici e astratti - *Proprietà* - considerate pubbliche e astratte - *_Indexer_* - considerati pubblici e astratti - *Eventi* - considerati pubblici e astratti - In CLR, un'interfaccia è considerata una particolare classe astratta di sistema che (ovviamente) non deriva da `System.Object` - però, le classi che la implementano derivano per forza da `System.Object` - Un'interfaccia - Può essere implementata sia dai _reference type_, sia dai _value type_ - È considerata sempre un *reference type* - *Attenzione*: se si effettua il cast di un _value type_ a un'interfaccia, avviene un *boxing del value type* (con conseguente copia del valore)! ==== Implementazione di un'interfaccia ```C public interface IBehavior { void Method(); int Property { get; set; } int this[int index] { get; } } public class A : IBehavior { public void Method() // virtual sealed { ... } public int Property // virtual sealed { get { ... } set { ... } } public int this[int index] // virtual sealed { get { ... } } } ``` ```C public class A : IBehavior { public virtual void Method() { ... } public virtual int Property { get { ... } set { ... } } public virtual int this[int index] { get { ... } } } public class B : A { public override void Method() ... public override int Property ... public override int this[int index ] ... }``` ==== Implementazione di un'interfaccia: classe astratta ```C public abstract class A : IBehavior { public abstract void Method(); public abstract int Property { get; set; } public abstract int this[int index] { get; } } public class B : A { public override void Method() ... public override int Property ... public override int this[int index] ... }``` - Siccome `A` è una classe astratta, la sottoclasse `B` che la estende deve ridefinire tutti i metodi astratti di `A` ==== Implementazione esplicita di un'interfaccia ```C public class A : IBehavior { void IBehavior.Method() { ... } int IBehavior.Property { get { ... } set { ... } } int IBehavior.this[int index] { get { ... } } } A a = new A(...); a.Method(); // Non compila! ((IBehavior) a).Method(); // Ok! ``` - Questo per - Name hiding - Avoiding name ambiguity \ ```C public interface IMyInterface1 { void Close(); } public interface IMyInterface2 { void Close(); } public class MyClass : IMyInterface1, IMyInterface2 { void IMyInterface1.Close() {...} void IMyInterface2.Close() {...} public void Close() {...} } MyClass a = new MyClass (...); ((IMyInterface1) a).Close(); // Ok! ((IMyInterface2) a).Close(); // Ok! a.Close(); // Ok! ``` #pagebreak() === Interfaccia vs. Classe astratta #cfigure("images/2024-04-17-10-57-57.png",100%) #cfigure("images/2024-04-17-10-58-30.png",100%) #cfigure("images/2024-04-17-10-59-03.png",100%) #cfigure("images/2024-04-17-10-59-31.png",100%) == Classi e Interfacce Base === Framework .NET: Overview #cfigure("images/2024-04-18-13-06-04.png",100%) === `System.Object` - La radice della gerarchia dei tipi - tutte le classi nel framework.NET Framework sono derivate da `Object` - Ogni metodo definito nella classe `Object` è disponibile in tutti gli oggetti del sistema #cfigure("images/2024-04-18-13-06-35.png",90%) - Le classi derivate possono (e/o devono) sovrascrivere (override) alcuni di tali metodi, tra cui: - `Equals` - Supporta il confronto tra oggetti - `ToString` - Crea una stringa “comprensibile”che descrive un'istanza della classe - `GetHashCode` - Genera un numero corrispondente al valore (stato) dell'oggetto per consentire l'uso di tabelle hash - `Finalize` - Effettua operazioni di “pulizia”prima che un oggetto venga automaticamente distrutto === `Object.Equals` - `public virtual bool Equals(object obj);` - Valore di ritorno: `true` se `this` è uguale a `obj`, cioè se referenziano lo stesso oggetto, altrimenti false #cfigure("images/2024-04-18-13-10-43.png",90%) - Le seguenti condizioni devono essere `true` per tutte le implementazioni del metodo Equals\ Nell'elenco, `x`, `y`, e `z` rappresentano riferimenti non nulli a oggetti - `x.Equals(x)` restituisce true - `x.Equals(y)` restituisce lo stesso valore di `y.Equals(x)` - `x.Equals(y)` restituisce truese sia x che y sono `NaN` - `(x.Equals(y) && y.Equals(z))` restituisce `true` se e solo se `x.Equals(z)` restituisce `true` - Chiamate successive a `x.Equals(y)` restituiscono sempre lo stesso valore fintantoché gli oggetti rteferenziatida `x` e `y` non vengono modificati - `x.Equals` (un riferimento `null`) restituisce `false` - Le implementazioni di `Equals` non devono generare eccezioni - I tipi che sovrascrivono `Equals` devono anche sovrascrivere `GetHashCode`; altrimenti, `Hashtable` potrebbe non funzionare correttamente - Se il linguaggio permette l'overloading di operatori e, per un certo tipo, si effettua l'overloading dell'operatore di uguaglianza, tale tipo deve anche sovrascrivere il metodo `Equals` Tale implementazione del metodo `Equals` *deve restituire gli stessi risultati dell'operatore di uguaglianza* ```C public class Point { private readonly int _x, _y; ... public override bool Equals(object obj) { //Check for null and compare run-time types. if(obj == null || GetType() != obj.GetType()) return false; Point p = (Point) obj; return (_x == p._x) && (_y == p._y); } public override int GetHashCode() { return _x ^ _y; } }``` === Object.Equals ```C public class SpecialPoint : Point { private readonly int _w; ... public SpecialPoint(int x, int y, int w) : base(x, y) { _w = w; } public override bool Equals(object obj) { return base.Equals(obj) && _w == ((SpecialPoint) obj)._w; } public override int GetHashCode() { return base.GetHashCode() ^ _w; } }``` ```C public class Rectangle { private readonly Point _a, _b; ... public override bool Equals(object obj) { if(obj == null || GetType() != obj.GetType()) return false; Rectangle r = (Rectangle) obj; // Uses Equals to compare variables. return _a.Equals(r._a) && _b.Equals(r._b); } public override int GetHashCode() { return _a.GetHashCode() ^ _b.GetHashCode(); } }``` ```C public struct Complex { private readonly double _re, _im; ... public override bool Equals(object obj) { return obj is Complex && this == (Complex) obj; } public override int GetHashCode() { return _re.GetHashCode() ^ _im.GetHashCode(); } public static bool operator ==(Complex x, Complex y) { return x._re == y._re && x._im == y._im; } public static bool operator !=(Complex x, Complex y) { return !(x == y); } }``` === `System.ValueType` #cfigure("images/value-type.jpg",100%) #pagebreak() === `System.Boolean` #cfigure("images/2024-04-18-13-21-43.png",100%) === `System.Int32` #cfigure("images/2024-04-18-13-22-21.png",100%) === `System.IComparable` - Confronta l'istanza corrente con un altro oggetto dello stesso tipo - *Valore di ritorno*: un 32-bit signed integer che indica l'ordine relativo degli oggetti confrontati - La semantica del valore restituito è la seguente: - Minore di zero - l'istanza `this` precede `obj` - Zero - l'istanza `this` è uguale a `obj` - Maggiore di zero - l'istanza `this` segue `obj` - Per definizione, ogni oggetto segue un riferimento `null` - Il parametro `obj` deve essere dello stesso tipo della classe o valuetype che implementa questa interfaccia; altrimenti, va lanciata una `ArgumentException` #cfigure("images/2024-04-18-13-23-39.png",60%) === `System.IComparable` - Note per gli Implementatori: Per ogni oggetto `A`, `B` e `C`, devono valere le seguenti condizioni: - `A.CompareTo(A)` deve restituire zero - Se `A.CompareTo(B)` restituisce zero allora anche `B.CompareTo(A)` deve restituire zero - Se `A.CompareTo(B)` restituisce zero e `B.CompareTo(C)` restituisce zero allora anche `A.CompareTo(C)` deve restituire zero - Se `A.CompareTo(B)` restituisce un valore diverso da zero allora `B.CompareTo(A)` deve restituire un valore dal segno opposto - Se `A.CompareTo(B)` restituisce un valore x diverso da zero, e `B.CompareTo(C)` un valore `y` dello stesso segno di `x`, allora `A.CompareTo(C)` deve restituire un valore dello stesso segno di `x` e `y` - Se volessi: - Ordinare i punti in ordine decrescente - Ordinare dei film - Per genere, oppure - Per titolo - Ordinare degli studenti - Per cognome e nome, oppure - Per matricola, oppure - Per corso di studio - ... ==== `System.Collections.IComparer` - Questa interfaccia è usata, ad esempio, dai metodi `Array.Sort` e `Array.BinarySearch` - Fornisce un modo per personalizzare il criterio di ordinamento #cfigure("images/240418-13h26m00s-screenshot.png",100%) === `System.IConvertible` - Questa interfaccia fornisce metodi per convertire il valore di un'istanza di un tipo che implementa l'interfaccia in un valore equivalente di un tipo CLR - I tipi *CLR* sono `Boolean, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime, Char,` e `String` - Se non esiste una conversione sensata verso un tipo CLR, l'implementazione particolare del corrispondente metodo dell'interfaccia deve lanciare una InvalidCastException - Ad esempio, questa interfaccia è implementata dal tipo Boolean; l'implementazione del metodo ToDateTimelancia un'eccezione in quanto non esiste alcun valore DateTimeequivalente a un valore del un tipo Boolean #cfigure("images/2024-04-18-13-49-39.png",20%) === `System.Convert` - In `System.Int32`, l'implementazione dell'interfaccia `System.IConvertible` è un esempio di “_explicit interface implementation_”: ```C int x = 32; double d = x.ToDouble (...); // No! ``` È necessario scrivere: ```C ((IConvertible) x).ToDouble (...) ``` - Se necessario, utilizzare la classe Convert: ```C Convert.ToDouble(x) ``` #cfigure("images/2024-04-18-13-50-59.png",20%) === System.Convert - Lancia un'eccezione se la conversione non è supportata ```C bool b = Convert.ToBoolean(DateTime.Today); // InvalidCastException ``` - Effettua conversioni controllate ```C int k = 300; byte b = (byte) k; // b == 44 byte b = Convert.ToByte(k); // OverflowException ``` - In alcuni casi, esegue un arrotondamento: ```C double d = 42.72; int k = (int) d; // k == 42 int k = Convert.ToInt32(d); // k == 43 ``` - È utile anche quando si ha una stringche deve essere convertita in valore numerico: ```C string myString = "123456789"; int myInt = Convert.ToInt32(myString);``` === Conversione di tipo - *Una conversione di ampliamento* avviene quando un valore di un tipo viene convertito verso un altro tipo che è di dimensione uguale o superiore - Da `Int32` a `Int64` - Da `Int32` a `UInt64` - Da `Int32` a `Single` (con possibile perdita di precisione) - Da `Int32` a `Double` - Una conversione di restrizione avviene quando un valore di un tipo viene convertito verso un altro tipo che è di dimensione inferiore - Da `Int32` a `Byte` - Da `Int32` a `SByte` - Da `Int32` a `Int16` - Da `Int32` a `UInt16` - Da `Int32` a `UInt32` - *Conversioni implicite* - non generano eccezioni - *Conversioni numeriche*\ Il tipo di destinazione dovrebbe essere in grado di contenere, senza perdita di informazione, tutti i valori ammessi dal tipo di partenza\ Eccezione: ```C int k1 = 1234567891; float b = k1; int k2 = (int) b; // k2 == 1234567936 ``` - *Up cast*\ *Principio di sostituibilità:* deve sempre essere possibile utilizzare una classe derivata al posto della classe base ```C B b = new B(...); // class B : A A a = b; ``` - *Conversioni esplicite* - possono generare eccezioni - *Conversioni numeriche* Il tipo di destinazione non sempre è in grado di contenere il valore del tipo di partenza ```C int k1 = -1234567891; uint k2 = (uint) k1; // k2 == 3060399405 ``` ```C int k1 = -1234567891; uint k2 = checked((uint) k1); // OverflowException ``` ```C int k1 = -1234567891; uint k2 = Convert.ToUInt32(k1); // OverflowException ``` - *Conversioni esplicite* - possono generare eccezioni - *Down cast* ```C A a = new B(...); // class B : A B b = (B) a; // Ok ``` ```C a = new A(...); b = (B) a; // InvalidCastException ``` ```C if(a is B) // if(a.GetType() == typeof(B)) { b = (B) a; // Non genera eccezioni ... } ``` ```C b = a as B; // b = (a is B)? (B) a : null; if(b != null) { ... } ``` - *Boxing - up cast* (conversione implicita) ```C int k1 = 100; object o = k1; // Copia! k1 = 200; ``` - *Unboxing - down cast* (conversione esplicita) ```C int k2 = (int) o; // k1 = 200, k2 = 100 ``` ```C double d1 = (double) k1; // Ok d1 = k1; // Ok d1 = o; // Non compila! d1 = (double) o; // InvalidCastException d1 = (int) o; // Ok ``` ==== Conversione di tipo definite dall'utente ```C public static implicit operator typeOut(typeIn obj) public static explicit operator typeOut(typeIn obj) ``` - Metodi statici di una classe o di una struttura - La keyword `implicit` indica l'utilizzo automatico (cast implicito) Il metodo non deve generare eccezioni - La keyword `explicit` indica la necessità di un cast esplicito Il metodo può generare eccezioni - `typeOut` è il tipo del risultato del cast - `typeIn` è il tipo del valore da convertire - `typeIn` o `typeOut` deve essere il tipo che contiene il metodo === Conversioni a string - Conversioni a `string` (di un `Int32`): - ```C ToString()``` ```c int k1 = -1234567891; string str = k1.ToString(); // str == “ - 1234567891”``` - ```c ToString(string formatString)```\ l'istanza è formattata secondo il `NumberFormatInfo` dell'impostazione cultura (_culture_) corrente ```C k1.ToString(“X”); // = “B669FD2D” k1.ToString(“C”); // = “ - € 1.234.567.891,00” k1.ToString(“C0”); // = “ - € 1.234.567.891” k1.ToString(“N0”); // = “ - 1.234.567.891” k1.ToString(“E”); // = “ - 1,234568E+009”``` - Conversioni a `string` (di un `Int32`): - ```C String.Format(string format, params object[] args)``` Il parametro `format` è costituito da uno o più elementi di formato nella forma: ```C {index[,alignment][:formatString]}``` ```C int k1 = -1234567891; String.Format (“{0}”,k1); // = “ - 1234567891” String.Format (“{0:X}”,k1); // = “B669FD2D” String.Format (“{0,5:X}”,k1); // = “B669FD2D” String.Format (“{0,10:X}”,k1); // = “ ΔΔ B669FD2D” String.Format (“{0, - 10:X}”,k1); // = “B669FD2D ΔΔ ” String.Format (“{0:N0}”,k1); // = “ - 1.234.567.891” ``` === Conversioni da string - Conversioni da `string` (in un `Int32`): - ```C Int32.Parse(string str) Int32.Parse(“ - 1234567891”); // - 1234567891 Int32.Parse(“ - 1.234.567.891”); // FormatException Int32.Parse(“”); // FormatException Int32.Parse(“ - 1234567891999”); // OverflowException Int32.Parse(null); // ArgumentNullException``` - ```C Int32.Parse(string str, System.Globalization.NumberStyles style)``` `NumberStyles` determina lo stile permesso per i parametri stringa passati ai metodi Parsedelle classi basi numeriche - I simboli da usare per la valuta, il separatore delle migliaia, il separatore decimale e il simbolo del segno sono specificati da `NumberFormatInfo` - Gli attributi di NumberStylessono indicati usando l'OR (inclusivo) bit-a-bit dei vari flag di campo ```C Int32.Parse(“ - 1.234.567.891”, System.Globalization.NumberStyles.Number); // ok Int32.Parse(“B669FD2D”, System.Globalization.NumberStyles.HexNumber); // ok ``` #cfigure("images/2024-04-18-14-02-35.png",25%) === Conversioni a/da string - Conversioni a `string` (di un `Int32`): - ```C Convert.ToString(int value, int toBase) toBase= 2, 8, 10, 16``` ```C int k1 = -1234567891; Convert.ToString (k1); // “ - 1234567891” Convert.ToString (k1,10); // “ - 1234567891” Convert.ToString (k1,16); // “b669fd2d”``` - Conversioni da `string` (in un `Int32`): - ```C Convert.ToInt32(string str, int fromBase) fromBase= 2, 8, 10, 16``` ```C Convert.ToInt32(“-1234567891”); // -1234567891 Convert.ToInt32(“-1234567891”,10); // -1234567891 Convert.ToInt32(“B669FD2D”,16); // -1234567891 Convert.ToInt32(“0xB669FD2D”,16); // -1234567891 Convert.ToInt32(“B669FD2D”,10); // FormatException``` === `System.Double` - Segue le specifiche IEEE 754 - Supporta ±0, ±Infinity, NaN - Epsilon rappresenta il più piccolo Double positivo > 0 - Il metodo TryParse è analogo al metodo Parse, ma non lancia eccezioni in caso di fallimento della conversione - Se la conversione ha successo, il valore di ritorno è true e il parametro di uscita è posto pari al risultato della conversione - Se la conversione fallisce, il valore di ritorno è false e il parametro di uscita è posto pari a zero #cfigure("images/2024-04-18-14-04-29.png",45%) === `System.Enum` - `Enum` fornisce metodi per - Confrontare istanze di questa classe - Convertire il valore di un'istanza nella sua rappresentazione a stringa - Convertire la rappresentazione a stringa di un numero in un'istanza della classe - Creare un'istanza di un'enumerazione e valore specifico - È possibile trattare un `Enum` come un campo bit #cfigure("images/2024-04-18-16-02-37.png",40%) === `System.DateTime` - Rappresenta un istante nel tempo, tipicamente espresso come data e ora del giorno - Il tipo di valore `DateTime` rappresenta le date e le ore con valori che vanno dalla mezzanotte del 1 gennaio 0001 d.C. (Era Comune) alle 11:59:59 P.M., 31 dicembre 9999 d.C. - I valori temporali sono misurati in unità di 100 ns chiamate tick - `DateTime` rappresenta un istante nel tempo, mentre `TimeSpan` rappresenta un intervallo di tempo #cfigure("images/2024-04-18-16-04-04.png",55%) === `System.String` #cfigure("images/2024-04-18-16-05-35.png",90%) - Una stringa immutabile di caratteri `Unicode` a lunghezza - Una `String` è detta immutabile perché, una volta creata, il suo valore non può essere modificato - I metodi che sembrano modificare una `String`, in realtà restituiscono una nuova `String` contenente la modifica - Se è necessario modificare il contenuto effettivo di un oggetto tipo stringa, utilizzare la classe `System.Text.StringBuilder` - Per la classe `String` l'operatore di uguaglianza `==` è ridefinito, quindi, al contrario di Java, l'operatore ritorna `true` se le due stringhe che compara hanno lo stesso contenuto lessico-grafico === `System.ICloneable` #cfigure("images/2024-04-18-16-06-07.png",30%) - Supporta la clonazione, che crea una nuova istanza di una classe con lo stesso stato di un'istanza esistente - `Clone` crea un nuovo oggetto che è una copia dell'istanza corrente - `Clone` può essere implementato come: - una *copia superficiale* (shallow), vengono duplicati solo gli oggetti di primo livello, non vengono create nuove istanze di alcun campo ```C public object Clone() { return MemberwiseClone(); } ``` - una *copia profonda* (deiep), tutti gli oggetti vengono duplicati - `Clone` restituisce una nuova istanza dello stesso tipo (o eventualmente un tipo derivato) dell'oggetto corrente ==== `System.Collections.IEnumerable` - `GetEnumerator` restituisce un enumeratore che può essere utilizzato per scorrere una collezione - Espone l'enumeratore, che supporta una semplice iterazione su una collezione #cfigure("images/2024-04-18-16-09-07.png",60%) #cfigure("images/2024-04-18-16-12-59.png",40%) - Gli enumeratori permettono solamente di leggere i dati della collezione - Gli enumeratori non possono essere usati per modificare la collezione - `Reset` riporta l'enumeratore allo stato iniziale - `MoveNext` si sposta all'elemento successivo, restituendo - `true` se l'operazione ha successo - `false` se l'enumeratore ha oltrepassato l'ultimo elemento - `Current` restituisce l'oggetto attualmente referenziato ==== `System.Collections.IEnumerator` - Non deve essere implementata direttamente da una classe contenitore - Deve essere implementata da una classe separata (eventualmente annidata nella classe contenitore) che fornisce la funzionalità di iterare sulla classe contenitore - Tale suddivisione di responsabilità permette di utilizzare contemporaneamente più enumeratori sulla stessa classe contenitore - La classe contenitore deve implementare l'interfaccia `IEnumerable` - Se una classe contenitore viene modificata, tutti gli enumeratori a essa associati vengono invalidati e non possono più essere utilizzati (`InvalidOperationException`) ```C IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) { MyType obj = (MyType) enumerator.Current; ... } ``` \ ```C foreach (MyType obj in enumerable) { ... }``` ```C public class Contenitore : IEnumerable { ... public IEnumerator GetEnumerator() { return new Enumeratore(this); } class Enumeratore : IEnumerator { public Enumeratore(Contenitore contenitore ) ... } }``` === `System.Array` #cfigure("images/2024-04-18-16-18-17.png",80%) - Array mono-dimensionali ```C int[] a = new int[3]; int[] b = new int[] {3, 4, 5}; int[] c = {3, 4, 5}; // array of references SomeClass[] d = new SomeClass[10]; // array of values (directly in the array) SomeStruct[] e = new SomeStruct[10]; ``` - Array multidimensionali (frastagliati): ogni array può avere dimensione diversa, per questo non possono essere inizializzati direttamente ("in un colpo solo") ```C // array of references to other arrays int[][] a = new int[2][]; // cannot be initialized directly a[0] = new int[] {1, 2, 3}; a[1] = new int[] {4, 5, 6}; ``` - Array multidimensionali (matrici) ```C // block matrix int[,] a = new int[2, 3]; // can be initialized directly int[,] b = {{1, 2, 3}, {4, 5, 6}}; int[,,] c = new int[2, 4, 2]; ``` - *Frastagliati* (come in Java) ```C int[][] a = new int[2][]; a[0] = new int[3]; a[1] = new int[4]; ... int x = a[0][1]; ``` #cfigure("images/2024-04-18-16-20-39.png",50%) - Matrici (come in C, più compatti ed efficienti) ```C int[,] a = new int[2, 3]; ... int x = a[0, 1]; ``` #cfigure("images/2024-04-18-16-20-57.png",45%) == Delegati ed eventi === Delegati - Sono oggetti che possono contenere il riferimento (_type safe_) a un metodo, tramite il quale il metodo può essere invocato - *Oggetti funzione* (_functor_): oggetti che si comportano come una funzione (metodo) - Simili ai puntatori a funzione del C/C++, ma _object-oriented_ e molto più potenti - Utilizzo standard: funzionalità di *callback* - *Elaborazione asincrona* - *Elaborazione cooperativa* (il chiamato fornisce una parte del servizio, il chiamante fornisce la parte rimanente - es. qsortin C) - *Gestione degli eventi* (chi è interessato a un certo evento si registra presso il generatore dell'evento, specificando il metodo che gestirà l'evento) ==== C/C++: Puntatori a funzioni ```C int funX(char c); int funY(char c); int (g)(char c) = NULL; ... g = cond1? funX : funY; oppure: g = cond1? &funX : &funY; ... ... g('H') ... ≡ ... (g)('H') ... ``` ==== C/C++: Array di puntatori a funzioni ```C void fun0(char s); void fun1(char s); void fun2(char s); void (fun[])(char s) { fun0, fun1, fun2 }; ... fun[m]("stringa di caratteri"); ≡ (fun[m])("stringa di caratteri"); ``` #cfigure("images/2024-05-16-10-25-22.png",60%) ==== C/C++: Elaborazione cooperativa ```C void qsort(void base, int num, int width, int (compare)(void , void ));``` #cfigure("images/2024-05-16-10-27-11.png",90%) === Delegati - *Dichiarazione* di un nuovo *tipo* di *delegato* che può contenere il riferimento a un metodo che ha un unico argomento intero e restituisce un intero:\ ```C delegate int Azione(int param);``` - *Definizione* di un *delegato*: ```C Azione azione;``` - *Inizializzazione* di un delegato: ```C azione = new Azione(nomeMetodoStatico); azione = new Azione(obj.nomeMetodo); azione = nomeMetodoStatico; // C2. azione = obj.nomeMetodo; // C2.``` - *Invocazione del metodo* referenziato dal delegato: ```C int k1 = azione(10);``` ==== Delegati: Multicasting - È possibile assegnare al delegato una *lista di metodi* (invocation list) - All'atto della chiamata del delegato, i metodi vengono invocati - in *sequenza* - in *modo sincrono* - Per aggiungere un metodo alla lista: `+=` ```C Azione azione = Fun1; ... azione(10) ... // Fun1(10) azione += Fun2; ... azione(10) ... // Fun1(10), Fun2(10)``` - Per *togliere un metodo* dalla lista: `-=` ```C azione -= Fun1; ... azione(10) ... // Fun2(10)``` #line(length: 100%) - Un'istanza di delegato incapsula uno o più metodi (con una lista di parametri e tipo restituito specifici), ciascuno dei quali è indicato come entità invocabile (*callable entity*) - per i #text(blue)[*metodi statici*], un'entità invocabile consiste solo in un metodo - per i #text(blue)[*metodi di istanza*], un'entità invocabile consiste in un'istanza e un metodo su quell'istanza - Un delegato - applica solo una singola firma del metodo (non un nome) - non conosce o non si preoccupa della classe dell'oggetto a cui fa riferimento - Ciò rende i delegati utili per chiamate anonime (*anonymous invocation*) #cfigure("images/2024-05-16-10-32-48.png",90%) - Possiamo intendere un delegato come un array con due colonne - quella di destra contiene il metodo - quella di sinistra contiene il riferimento all'istanza su cui il metodo è applicato (`NULL` nel caso di metodi statici) - L'invocazione di un'istanza del delegato la cui lista di metodi contiene più elementi procede richiamando ciascuno dei metodi nella lista, in modo sincrono, in ordine - A ogni metodo così invocato viene passato lo stesso insieme di parametri fornito all'istanza del delegato - Se tale chiamata di delegato include parametri di tipo riferimento - ogni invocazione di metodo avverrà con un riferimento alla stessa variabile - le modifiche a tale variabile da parte di un metodo nella lista saranno visibili ai metodi successivi in lista - Se la chiamata del delegato include parametri di output o un valore di ritorno - il loro valore finale verrà dall'invocazione dell'ultimo delegato nell'elenco #cfigure("images/2024-05-16-10-33-37.png",100%) - In C\#, la dichiarazione di un nuovo tipo di delegato definisce automaticamente una nuova classe derivata dalla classe `System.MulticastDelegate` ```C System.Object System.Delegate System.MulticastDelegate Azione``` - Pertanto, sulle istanze di Azione è possibile invocare i metodi definiti a livello di classi di sistema ==== Esempio Boss-Worker - È necessario modellare un'interazione tra due componenti - un *Worker* che effettua un'attività (o lavoro) - un *Boss* che controlla l'attività dei suoi Worker - Ogni Worker deve notificare al proprio Boss: - quando il lavoro inizia - quando il lavoro è in esecuzione - quando il lavoro finisce - Soluzioni possibili: + class-based callback relationship + interface-based callback relationship + pattern Observer(lista di notifiche) + delegate-based callback relationship + event-based callback relationship ==== Una Relazione di Chiamata Basata su Delegati - Un delegato è un'entità _type-safe_ che si pone tra 1 caller e 0+ call target e che agisce come un'interfaccia con un solo metodo ```C interface IWorkerEvents { void WorkStarted(Worker worker); void WorkProgressing(Worker worker); int WorkCompleted(Worker worker); } delegate void WorkStarted(Worker worker); delegate void WorkProgressing(Worker worker); delegate int WorkCompleted(Worker worker);``` #cfigure("images/2024-05-16-11-12-01.png",90%) *Dai Delegati agli Eventi*\ - L'utilizzo di campi pubblici per la registrazione fornisce un accesso eccessivo - I client possono sovrascrivere altri client precedentemente registrati\ ```C peter.Started = WorkStarted;``` - I client possono invocare i chiamati\ ```C peter.Completed(peter);``` - Fornire metodi di registrazione pubblica abbinati al campo del delegato è una soluzione migliore, ma pesante se implementata manualmente - Il modificatore event automatizza il supporto per - #text(blue)[*public [un]registration*] - #text(blue)[*private implementation*] #cfigure("images/2024-05-16-11-15-06.png",90%) *Personalizzare la Registrazione a Eventi*\ - È possibile definire gestori di registrazione a eventi - Uno dei vantaggi di scrivere metodi propri di registrazione è l'aumentato controllo - La sintassi alternativa, analoga a una proprietà, supporta gestori di registrazione definiti dall'utente - Consente di rendere la registrazione condizionale o diversamente personalizzata - Sintassi di accesso lato client non modificata - È necessario fornire spazio per i client registrati ```C class Worker { ... public event WorkProgressing Progressing { add { if(DateTime.Now.Hour < 12) { _progressing += value; } else { throw new InvalidOperationException ("Must register before noon."); } } remove { _progressing -= value; } } private WorkProgressing _progressing; ... }``` === Eventi - *Evento*: “Fatto o avvenimento determinante nei confronti di una situazione oggettiva o soggettiva” - In programmazione, un evento può essere scatenato - Dall'interazione con l'utente (click del mouse, ...) - dalla logica del programma - *Event sender* - l'oggetto (o la classe) che scatena (raiseso triggers) l'evento (sorgente dell'evento) - *Event receiver* - l'oggetto (o la classe) per il quale l'evento è determinante e che quindi desidera essere notificato quando l'evento si verifica (cliente) - *Event handler* - il metodo (dell'_event receiver_) che viene eseguito all'atto della notifica - Quando si verifica l'evento, il sender invia un messaggio di notifica a tutti i receiver - in pratica, invoca gli eventhandler di tutti i receiver - In genere, il sender NON conosce né i _receiver_, né gli _handler_ - Il meccanismo che viene utilizzato per collegare sender e receiver/handler è il delegato (che permette *invocazioni anonime*) ==== Dichiarazione di un Evento - Convenzione .NET - Un evento incapsula un delegato - è necessario dichiarare un tipo di delegato prima di poter dichiarare un evento - Per convenzione, i delegati degli eventi in .NET hanno 2 parametri - la *sorgente* che ha scatenato l'evento e - i *dati* relativi all'evento - Molti eventi, inclusi eventi della GUI come i click del mouse, non generano dati - In tali situazioni, è sufficiente usare il delegato dell'evento fornito dalla libreria di classi per gli eventi senza dati, ```C System.EventHandler``` - Delegati di eventi personalizzati sono necessari solamente quando un evento genera dati ```C public delegate void EventHandler(object sender, EventArgs e); System.Object System.Delegate System.MulticastDelegate System.EventHandler``` - La classe `System.EventArgs` viene utilizzata quando un evento non deve passare informazioni aggiuntive ai propri gestori - Se i gestori dell'evento hanno bisogno di informazioni aggiuntive, è necessario derivare una classe dalla classe EventArgs , aggiungere i dati necessari e utilizzare il delegate ```C EventHandler<TEventArgs>``` ```C public event EventHandler Changed;``` - In pratica, `Changed` è un delegato, ma la _keyword_ #text(blue)[`event`] ne limita - la visibilità e - le possibilità di utilizzo - Una volta dichiarato, l'evento può essere trattato come un delegato di tipo speciale - In particolare, può: - essere #text(blue)[`null`] se nessun cliente si è registrato - essere associato a uno o più metodi da invocare ==== Invocazione di un Evento - Per scatenare un evento è opportuno definire un metodo protetto virtuale `OnNomeEvento` e invocare sempre quello public event EventHandler Changed ; protected virtual void OnChanged() ```C { if ( Changed != null ) Changed ( this , EventArgs.Empty ); } ... OnChanged (); ...``` - #underline[*Limitazione rispetto ai delegati*]\ L'invocazione dell'evento può avvenire solo all'interno della classe nella quale l'evento è stato dichiarato (benché l'evento sia stato dichiarato #text(blue)[`public`]) - Al di fuori della classe in cui l'evento è stato dichiarato, un evento viene visto come un *delegato con accessi molto limitati* - Le sole operazioni effettuabili dal cliente sono: - #text(blue)[agganciarsi a un evento]: aggiungere un nuovo delegato all'evento mediante l'operatore `+=` - #text(blue)[sganciarsi da un evento]: rimuovere un delegato dall'evento mediante l'operatore `-=` ===== Agganciarsi a un Evento Per iniziare a ricevere le notifiche di un evento, il cliente deve: - *Definire il metodo* (_event handler_) che dovrà essere invocato all'atto della notifica dell'evento (con la stessa signature dell'evento): ```C void ListChanged(object sender, EventArgs e) { ... }``` - *Creare un delegato* dello stesso tipo dell'evento, farlo riferire al metodo e aggiungerlo alla lista dei delegati associati all'evento : ```C List.Changed += new EventHandler(ListChanged); List.Changed += ListChanged; // C# 2.0``` ===== Sganciarsi da un Evento Per smettere di ricevere le notifiche di un evento, il cliente deve: - *Rimuovere il delegato* dalla lista dei delegati associati all'evento: ```C List.Changed -= new EventHandler ( ListChanged ); List.Changed -= ListChanged ; // C# 2.0``` #line(length: 100%) - Poiché `+=` e `-=` sono gli unici operatori permessi su un evento al di fuori del tipo che dichiara l'evento, il codice esterno al tipo - può aggiungere e rimuovere handlerper un evento, ma - non può in nessun altro modo ottenere o modificare la lista di handlersottostante - Gli eventi forniscono agli oggetti un modo utile per segnalare modifiche allo stato a clienti di tali oggetti - Gli eventi sono un componente fondamentale *per la creazione di classi che possano essere riutilizzate in un gran numero di programmi differenti* = Principi di Design == Qualità della progettazione - La #text(blue)[*Qualità della progettazione*] è un concetto vago - La qualità dipende da specifiche #text(blue)[*priorità dell' organizazione*] - Un buon progetto potrebbe essere - il più affidabile, - il più efficiente, - il più manutenibile, - il più economico, ... - Gli argomenti qui discussi riguardano principalmente la #text(blue)[*manutenibilità del progetto*] == Cosa rende un design “cattivo”? #text(blue)[*✓ Misdirection*]: non soddisfa i requisiti #text(blue)[*✓ Rigidità del software*]: una singola modifica influisce su molte altre parti del sistema #text(blue)[*✓ Fragilità del software*]: una singola modifica influisce su parti inaspettate del sistema #text(blue)[*✓ Immobilità del software*]: è difficile da riutilizzare in un'altra applicazione #text(blue)[*✓ Viscosità*]: è difficile fare la cosa giusta, ma facile fare la cosa sbagliata === Rigidità del Software - La tendenza per il software a essere #text(blue)[*difficile da modificare*] - #text(blue)[*Sintomo*]: ogni modifica provoca una cascata di modifiche successive nei moduli dipendenti - #text(blue)[*Effetto*]: i manager hanno timore ad accettare che gli sviluppatori risolvano problemi non critici - non sanno se/quando gli sviluppatori termineranno le modifiche === Fragilità del Software - La tendenza del software a #text(blue)[*“rompersi” in molti punti*] ogni volta che viene modificato: i cambiamenti tendono a causare #text(blue)[*comportamenti inaspettati*] in altre parti del sistema (spesso in aree che non hanno alcuna relazione concettuale con l'area che è stata modificata) - #text(blue)[*Sintomo*]: ogni correzione peggiora le cose, introducendo più problemi di quelli risolti: tale software è impossibile da manutenere - #text(blue)[*Effetto*]: ogni volta che i manager autorizzano una correzione, temono che il software si “rompa” in modo inaspettato === Immobilità del Software - L'#text(blue)[*impossibilità di riutilizzare il software*] di altri progetti o di parti dello stesso progetto - #text(blue)[*Sintomo*]: uno sviluppatore scopre di aver bisogno di un modulo simile a quello scritto da un altro sviluppatore. Ma il modulo in questione ha troppe dipendenze. Dopo molto lavoro, lo sviluppatore scopre che il lavoro e il rischio necessari per separare le parti desiderabili del software dalle parti indesiderabili sono troppo grandi per essere tollerati - #text(blue)[*Effetto*]: e così il software viene semplicemente riscritto anziché riutilizzato === Viscosità del Software - Gli sviluppatori di solito trovano più di un modo per apportare una modifica - alcuni preservano il design, altri no (cioè sono hack) - La tendenza a #text(blue)[*incoraggiare modifiche al software che sono hack*] piuttosto che modifiche al software che preservano l'intento di progettazione originale - #text(blue)[*Viscosità del design*]: i metodi che preservano il design sono più difficili da utilizzare rispetto agli hack - #text(blue)[*Viscosità dell'ambiente*]: l'ambiente di sviluppo è lento e inefficiente (tempi di compilazione molto lunghi, il sistema di controllo dei sorgenti richiede ore per archiviare pochi file, ...) - #text(blue)[*Sintomo*]: è facile fare la cosa sbagliata, ma difficile fare la cosa giusta, cioè è difficile fare modifiche se seguano il design indicato nel documento - #text(blue)[*Effetto*]: la manutenibilità del software degenera a causa di hack, scorciatoie, correzioni temporanee, ... === Perché esistono risultati di progettazione scadenti? - Ragioni ovvie: - mancanza di capacità/pratica di progettazione - tecnologie in evoluzione - vincoli di tempo/risorse - complessità del dominio, ... - Non così ovvie: - #text(blue)[*la “putrefazione” del software è un processo lento*] - anche un design originariamente pulito ed elegante può degenerare nel corso dei mesi/anni - i #text(blue)[*requisiti*] spesso cambiano in modi che non erano stati previsti dal design (o dal progettista) originale - le #text(blue)[*dipendenze*] tra moduli non pianificate e improprie si insinuano: le dipendenze non vengono gestite == Modifiche ai Requisiti - Come ingegneri del software, sappiamo benissimo che i requisiti cambiano - In effetti, la maggior parte di noi si rende conto che il documento dei requisiti è il #text(blue)[*documento più volatile*] dell'intero progetto - Se i nostri progetti falliscono a causa del costante arrivo di requisiti in continua evoluzione, #text(blue)[*la colpa è della nostra progettazione*] - Dobbiamo in qualche modo trovare un modo per rendere i nostri progetti resistenti a tali cambiamenti e proteggerli dalla putrefazione == Gestione delle Dipendenze - Ciascuno dei quattro sintomi sopra menzionati è causato (direttamente o indirettamente) da #text(blue)[*dipendenze improprie tra moduli*] del software - È l'#text(blue)[*architettura delle dipendenze*] che si sta degradando e con essa la capacità del software di essere manutenuto - Per prevenire il degrado dell'architettura delle dipendenze, è necessario gestire le dipendenze tra i moduli in un'applicazione - La progettazione orientata agli oggetti è piena di #text(blue)[*principi*] e #text(blue)[*tecniche*] per la gestione delle dipendenze dei moduli == Principi di Design - The #text(blue)[*Single Responsibility Principle*] (SRP) - The #text(blue)[*Dependency Inversion Principle*] (DIP) - The #text(blue)[*Interface Segregation Principle*] (ISP) - The #text(blue)[*Open/Closed Principle*] (OCP) - The #text(blue)[*Liskov Substitution Principle*] (LSP) === Premessa ==== Il principio zero - Il principio zero è un principio di logica noto come #text(blue)[*rasoio di Occam*]:\ “_Entia non sunt multiplicanda praeter necessitatem_”\ ovvero: non bisogna introdurre concetti che non siano strettamente necessari - È la forma “colta” di un principio pratico:\ “_Quello che non c'è non si rompe_” (<NAME>) - Tra due soluzioni bisogna preferire quella - che introduce il minor numero di ipotesi - che fa uso del minor numero di concetti ==== Semplicità e semplicismo - La #text(blue)[*semplicità*] è un fattore importantissimo - il software deve fare i conti con una notevole componente di complessità, generata dal contesto in cui deve essere utilizzato - quindi è estremamente importante #text(blue)[*non aggiungere altra complessità*] arbitraria - Il problema è che - la semplicità richiede uno #text(blue)[*sforzo non indifferente*] (#text(blue)[è molto più facile essere complicati che semplici]) - in generale le soluzioni più semplici vengono in mente per ultime - Bisogna fare poi molta attenzione a essere semplici ma non semplicistici\ “_Keep it as simple as possible but not simpler_” (<NAME>) ==== Divide et impera - La #text(blue)[decomposizione] è una tecnica fondamentale per il controllo e la gestione della complessità - Non esiste un solo modo per decomporre il sistema - la #text(blue)[*qualità della progettazione*] dipende direttamente dalla #text(blue)[*qualità delle scelte di decomposizione*] adottate - In questo contesto il #text(blue)[*principio fondamentale*] è: minimizzare il grado di accoppiamento tra i moduli del sistema - Da questo principio è possibile ricavare diverse regole: - minimizzare la quantità di interazione fra i moduli - eliminare tutti i riferimenti circolari fra moduli - ... ==== Rendere privati tutti i dati degli oggetti - Le modifiche ai dati pubblici rischiano sempre di “aprire” il modulo: - possono avere un effetto domino che porta a richiedere modifiche in molte posizioni impreviste - gli errori possono essere difficili da trovare e correggere completamente - le correzioni possono provocare errori altrove #cfigure("images/2024-04-22-17-37-29.png",100%) === The Single Responsibility Principle - _There should never be more than one reason for a class to change_ (R. Martin) - _A class has a single responsibility: it does it all, does it well, and does it only_ (1-Responsibility Rule) - Se una classe ha più di una responsabilità, queste diventano accoppiate - Le modifiche a una responsabilità possono compromettere o inibire la capacità della classe di realizzare le altre - Questo tipo di accoppiamento porta a #text(blue)[*design fragili*] che si rompono in modi inaspettati quando modificati #cfigure("images/2024-04-22-17-38-36.png",90%) ==== Esempio #cfigure("images/2024-04-22-17-39-18.png",90%) - Un'applicazione è di geometria computazionale - usa `Rectangle` per aiutarsi con la matematica delle forme geometriche - non disegna mai il rettangolo sullo schermo - L'altra applicazione è di natura grafica - può anche fare un po' di geometria computazionale, ma - disegna sicuramente il rettangolo sullo schermo - La classe `Rectangle` ha #text(blue)[*due responsabilità*]: - la prima responsabilità è fornire un modello matematico della geometria di un rettangolo - la seconda responsabilità è disegnare il rettangolo su un'interfaccia grafica ==== Esempio - Refactoring - Un progetto migliore consiste nel #text(blue)[separare le due responsabilità in due classi completamente distinte] - #text(blue)[Si estrae una classe]: si crea una nuova classe e si spostano i campi e i metodi opportuni dalla vecchia classe alla nuova classe #cfigure("images/2024-04-22-17-40-54.png",80%) === The Dependency Inversion Principle - #text(blue)[*Depend upon abstractions*]\ #text(blue)[*Do not depend upon concretions*] - Ogni dipendenza dovrebbe puntare a un'interfaccia o a una classe astratta - Nessuna dipendenza dovrebbe puntare a una classe concreta - I moduli di alto livello (i clienti) non dovrebbero dipendere dai moduli di basso livello (i fornitori di servizi)\ Entrambi dovrebbero dipendere da astrazioni #cfigure("images/2024-04-22-17-43-15.png",50%) - I #text(blue)[*moduli di basso livello*] contengono la maggior parte del codice e della logica implementativa e quindi #text(blue)[*sono i più soggetti a cambiamenti*] - Se #text(blue)[*i moduli di alto livello*] dipendono dai dettagli dei moduli di basso livello (sono accoppiati in modo troppo stretto), i cambiamenti si propagano e le conseguenze sono: - #text(blue)[*Rigidità*]: bisogna intervenire su un numero elevato di moduli - #text(blue)[*Fragilità*]: si introducono errori in altre parti del sistema - #text(blue)[*Immobilità*]: i moduli di alto livello non si possono riutilizzare perché non si riescono a separare da quelli di basso livello - Soluzione: - i moduli di basso livello implementano un'intefaccia - i moduli di alto livello utilizzano quell'interfaccia #cfigure("images/2024-04-22-17-43-41.png",100%) - Questo principio funziona perché: - #text(blue)[*le astrazioni*] contengono pochissimo codice (in teoria nulla) e quindi #text(blue)[*sono poco soggette a cambiamenti*] - i #text(blue)[*moduli non astratti sono soggetti a cambiamenti*] ma questi cambiamenti sono sicuri perché nessuno dipende da questi moduli - I dettagli del sistema sono stati isolati, separati da un #text(blue)[*muro di astrazioni stabili*], e questo impedisce ai cambiamenti di propagarsi (#text(blue)[*design for change*]) - Nel contempo i singoli moduli sono #text(blue)[*maggiormente riusabili*] perché sono disaccoppiati fra di loro (#text(blue)[*design for reuse*]) ==== Dipendenze transitive - “_...all well structured object-oriented architectures have clearly-defined layers, with each layer providing some coherent set of services though a well-defined and controlled interface_” (Grady Booch) - I sistemi software dovrebbero essere stratificati, cioè organizzati a livelli - Le #text(blue)[*dipendenze transitive*] devono essere eliminate #cfigure("images/2024-04-22-17-45-51.png",80%) #cfigure("images/2024-04-22-17-46-39.png",90%) ==== Dipendenze cicliche - Le #text(blue)[*dipendenze cicliche*] devono essere eliminate #cfigure("images/2024-04-22-17-47-24.png",90%) ==== Stabilità delle astrazioni #cfigure("images/2024-04-22-17-47-58.png",90%) === The Interface Segregation Principle - #text(blue)[*Clients should not be forced to depend upon interfaces that they do not use*] - Molte interfacce specifiche per un cliente sono meglio di un'unica interfaccia general purpose ==== Fat Interface #cfigure("images/2024-04-22-17-55-04.png",90%) === The Interface Segregation Principle - I clienti non dovrebbero dipendere da servizi che non utilizzano - Le _fat interface_ creano una forma indiretta di accoppiamento (inutile) fra i clienti -se un cliente richiede l'aggiunta di una nuova funzionalità all'interfaccia, ogni altro cliente è costretto a cambiare anche se non è interessato alla nuova funzionalità - Questo crea un'inutile sforzo di manutenzione e può rendere difficile trovare eventuali errori - Se i servizi di una classe possono essere suddivisi in gruppi e ogni gruppo viene utilizzato da un diverso insieme di clienti, creare interfacce specifiche per ogni tipo di cliente e implementare tutte le interfacce nella classe ==== Segregated Interfaces #cfigure("images/2024-04-22-17-58-26.png",100%) #cfigure("images/2024-04-22-17-59-19.png",100%) === The Open/Closed Principle - #text(blue)[*Il principio più importante per la progettazione di entità riutilizzabili*] - _Software entities (classes, modules, functions _, ...)_ should be open for extension, but closed for modification_ - #text(blue)[*Open*]: - #text(blue)[*Possono essere estese*] aggiungendo nuovo stato o proprietà comportamentali - #text(blue)[*Closed*]: - Hanno un'interfaccia ben-definita, pubblica e stabile che #text(blue)[*non può essere cambiata*] - Dobbiamo scrivere i moduli in modo che - #text(blue)[*possano essere estesi*], - #text(blue)[*senza*] la necessità di #text(blue)[*essere modificati*] - In altre parole, vogliamo - cambiare quello che fanno i moduli - senza cambiare il codice dei moduli - Apparentemente si tratta di una #text(blue)[*contraddizione*]: come può un modulo immutabile esibire un comportamento che non sia fisso nel tempo? - La risposta risiede #text(blue)[*nell'astrazione*] : è possibile creare astrazioni che rendono un modulo immutabile, ma rappresentano un gruppo illimitato di comportamenti - Il segreto sta nell'utilizzo di #text(blue)[*interfacce*] (o di #text(blue)[*classi astratte*]) - A un'interfaccia #text(blue)[*immutabile*] possono corrispondere innumerevoli classi concrete che realizzano comportamenti diversi - Un modulo che utilizza astrazioni - non dovrà mai essere modificato, dal momento che le astrazioni sono immutabili (#text(blue)[*il modulo è chiuso per le modifiche*]) - potrà cambiare comportamento, se si utilizzano nuove classi che implementano le astrazioni (#text(blue)[*il modulo è aperto per le estensioni*]) ==== Esempio 1 - Consideriamo un semplice programma che si occupa di copiare su una stampante i caratteri digitati su una tastiera - Assumiamo, inoltre, che la piattaforma di implementazione non possieda un sistema operativo in grado di supportare l'indipendenza dal dispositivo #cfigure("images/2024-04-22-18-03-59.png",60%) ```C void Copy() { int c; while ((c = ReadKeyboard()) != EOF) WritePrinter(c); } ``` ``` Copy ``` ``` ReadKeyboard WritePrinter ``` - #text(blue)[*I due moduli di basso livello sono riutilizzabili*]: possono essere usati in tanti altri programmi per accedere alla tastiera e alla stampante - è la stessa riusabilità offerta dalle librerie di classi - #text(blue)[*Il modulo “Copy” non è riutilizzabile*] in un qualsiasi contesto che non includa una tastiera o una stampante - È un peccato, perché tale modulo contiene “l'intelligenza del sistema” - è il modulo “Copy” che incapsula la funzionalità cui siamo interessati per il riuso - Consideriamo un nuovo programma che copi caratteri da tastiera a un file su disco - Potremmo modificare il modulo “Copy” per fornirgli questa nuova funzionalità - Con l'andar del tempo, più e più dispositivi verranno aggiunti a questo programma di copia, e il modulo “Copy” sarà tappezzato di istruzioni if/else, diventando dipendente da diversi moduli di più basso livello - alla fine diverrà #text(blue)[*rigido*] e #text(blue)[*fragile*] ```C enum OutputDevice { Printer, Disk }; void Copy(OutputDevice dev) { int c; while ((c = ReadKeyboard()) != EOF) { if (dev == Printer) WritePrinter(c); else WriteDisk(c); } } ``` - Un modo per caratterizzare il problema visto in precedenza è di notare che il modulo che contiene la politica di alto livello (Copy) dipende dai moduli di dettaglio e di più basso livello che controlla (WritePrintere ReadKeyboard) - Se potessimo trovare un modo di rendere il modulo Copy indipendente dai dettagli che controlla, allora - potremmo #text(blue)[*riutilizzarlo*] liberamente - potremmo produrre altri programmi che usano questo modulo per #text(blue)[*copiare caratteri da un qualsiasi dispositivo di input a un qualsiasi dispositivo di output*] ```C interface IReader { int Read(); } interface IWriter { void Write(char); } void Copy(IReader r, IWriter w) { int c; while ((c = r.Read()) != EOF) w.Write(c); }``` #cfigure("images/2024-04-22-18-06-54.png",50%) ==== Esempio 2 #cfigure("images/2024-04-22-18-07-24.png",100%) - #text(blue)[*Se dovessi creare una nuova*] shape, come `Triangle`, #text(blue)[dovrei modificare] `drawShape` - In un'applicazione complessa l'istruzione `switch/case` verrebbe ripetuta più e più volte per ogni operazione possa essere effettuata su una shape - Ancor peggio, ogni modulo che contenesse una tale istruzione `switch/case` statement #text(blue)[*manterrebbe una dipendenza da qualsiasi shape*] possa essere disegnata - Quindi, ogni volta una singola shape dovesse essere modificata in un qualsiasi modo, tutti i moduli dovrebbero essere ricompilati ed eventualmente modificati #cfigure("images/2024-04-22-18-10-04.png",100%) ==== Esempio 3 #cfigure("images/2024-04-22-18-10-47.png",75%) - Supponiamo di dover utilizzare un nuovo tipo di server! #cfigure("images/2024-04-22-18-11-15.png",80%) - `Client` è chiuso alle modifiche dell'implementazione di `IServer` - `Client` è aperto all'estensione tramite nuove implementazioni di `IServer` - Senza `IServer` , `Client` sarebbe aperto alle modifiche di `Server` #cfigure("images/2024-04-22-18-12-06.png",90%) ==== Esempio 4 #cfigure("images/2024-04-22-18-12-33.png",90%) - E se volessimo accendere un motore? #cfigure("images/2024-04-22-18-12-50.png",100%) ==== Conlcusioni - Se la maggior parte dei moduli di un'applicazione segue OCP, allora - è possibile aggiungere nuove funzionalità all'applicazione - #text(blue)[*aggiungendo nuovo codice*] - invece che #text(blue)[*cambiando codice funzionante*] - il codice che già funziona non è esposto a rotture === The Liskov Substitution Principle - _Subclasses should be substitutable for their base classes_ (Barbara Liskov) - _All derived classes must honor the contracts of their base classes_ (Design by Contract - <NAME>) - Il cliente di una classe base deve continuare a funzionare correttamente se gli viene passato un sottotipo di tale classe base - In altre parole: un cliente che usa istanze di una classe A deve poter usare istanze di una qualsiasi sottoclasse di A #text(blue)[*senza accorgersi della differenza*] ==== Example #cfigure("images/2024-04-22-18-15-04.png",100%) #cfigure("images/2024-04-22-18-15-25.png",100%) - OCP si basa sull'uso di classi concrete derivate da un'astrazione (interfaccia o classe astratta) - LSP costituisce una guida per creare queste classi concrete mediante l'ereditarietà - La principale causa di violazioni al principio di Liskov è dato dalla #text(blue)[*ridefinizione di metodi virtuali*] nelle classi derivate: è qui che bisogna riporre la massima attenzione - La chiave per evitare le violazioni al principio di Liskov risiede nel #text(blue)[*Design by Contract*] (<NAME>) == Design by Contract - Nel Design by Contract ogni metodo ha - un insieme di #text(blue)[*pre-condizioni*] - requisiti minimi che devono essere soddisfatti dal #underline[chiamante] perché il metodo possa essere eseguito correttamente - un insieme di #text(blue)[*post-condizioni*] - requisiti che devono essere soddisfatti dal #underline[metodo] nel caso di esecuzione corretta - Questi due insiemi di condizioni costituiscono #text(blue)[*un contratto*] tra chi invoca il metodo (cliente) e il metodo stesso (e quindi la classe a cui appartiene) - le #text(blue)[*pre-condizioni vincolano il chiamante*] - le #text(blue)[*post-condizioni vincolano il metodo*] - se il chiamante garantisce il verificarsi delle pre-condizioni, il metodo garantisce il verificarsi delle post-condizioni - Quando un metodo viene ridefinito in una sottoclasse - le #text(blue)[*pre-condizioni*] devono essere #text(blue)[*identiche o meno stringenti*] - le #text(blue)[*post-condizioni*] devono essere #text(blue)[*identiche o più stringenti*] - Questo perché un cliente che invoca il metodo conosce il contratto definito a livello della classe base, quindi non è in grado: - di soddisfare pre-condizioni più stringenti o - di accettare post-condizioni meno stringenti - In caso contrario, il cliente dovrebbe conoscere informazioni sulla classe derivata e questo porterebbe a una violazione del principio di Liskov ```C public class BaseClass { public virtual int Calculate(int val) { Precondition(-10000 <= val && val <= 10000); int result = val / 100; Postcondition(-100 <= result && result <= 100); return result; } } public class SubClass : BaseClass { public override int Calculate(int val) { Precondition(-20000 <= val && val <= 20000); int result = Math.Abs(val) / 200; Postcondition(0 <= result && result <= 100); return result; } }``` == Il Quadrato è un Rettangolo? ```C public class Rectangle { private double _width; private double _height; public double Width { get { return _width; } set { _width = value; } } public double Height { get { return _height; } set { _height = value; } } public double Area { get { return Width * Height; } } }``` - Immaginiamo che questa applicazione funzioni correttamente e sia installata in diversi ambienti - Come per tutti i software di successo, le necessità degli utenti cambiano e si rendono necessarie nuove funzionalità - Immaginiamo che, un bel giorno, gli utenti chiedano la possibilità di manipolare quadrati oltre che rettangoli #cfigure("images/2024-04-22-18-18-52.png",30%) - L'ereditarietà è una relazione IsA - In altre parole, perché un nuovo tipo di oggetto verifichi la relazione IsAcon un tipo di oggetto esistente, la classe del nuovo oggetto deve essere derivata dalla classe dell'oggetto esistente - Chiaramente, un quadrato è un rettangolo per tutti gli utilizzi e intenti normali - Poiché vale la relazione IsA, è logico medellare Square come sottoclasse di `Rectangle` - Questo utilizzo della relazione IsA è considerato da molti come una delle tecniche più importanti dell'Analisi Object Oriented - Un quadrato è un tipo particolare di rettangolo, quindi la classe `Square` deve venire derivata dalla classe `Rectangle` - Questo modo di pensare, però, può portare a problemi sottili, ma significativi - In genere, tali problemi non vengono scoperti se non nella fase di implementazione dell'applicazione ```C public class Square : Rectangle { public new double Width { get { return base.Width; } set { base.Width = value; base.Height = value; } } public new double Height { get { return base.Height; } set { base.Height = value; base.Width = value; } } }``` - È necessario ridefinire le proprietà `Width` e `Height` ... - Notevoli differenze tra Java e C++/C\# - In Java tutti i metodi sono virtuali - a parte i metodi `final` - In C++ / C\# è possibile definire - sia metodi virtuali, - sia #text(blue)[*metodi non virtuali*] (non polimorfici) ```C ... Square s = new Square(); s.Width = 5; // 5 x 5 ... ... Method1(s); //? ... void Method1(Rectangle r) { r.Width = 10; }``` - Se invochiamo `Method1` con un riferimento a un oggetto `Square`, l'oggetto `Square` non funzionerà correttamente in quanto l'altezza non verrà modificata - Questa è una chiara violazione di LSP - `Method1` non funziona per sottotipi dei suoi parametri - Il motivo di questo malfunzionamento è che Width e Height non sono state dichiarate virtuali in Rectangle ```C public class Rectangle { ... public virtual double Width { ... } public virtual double Height { ... } ... } public class Square : Rectangle { public override double Width { ... } public override double Height { ... } }``` - Possiamo risolvere facilmente - In ogni modo, quando la creazione di una classe derivata ci obbliga a modificare la classe base, spesso significa che il design è difettoso - Infatti, viola l'OCP - Potremmo rispondere argomentando che il vero difetto di progettazione è stato dimenticare di rendere virtuali Width e Height , e solo ora lo stiamo risolvendo - Tuttavia, questo è difficile da giustificare poiché impostare l'altezza e la larghezza di un rettangolo sono operazioni estremamente primitive -con quale ragionamento le avremmo dovute rendere virtuali se non prevedendo l'esistenza del quadrato? - A questo punto abbiamo due classi, `Square` e `Rectangle`, che apparentemente funzionano correttamente - Indipendentemente da ciò che facciamo con un oggetto `Square`, questo rimarrà coerente con un quadrato matematico - E indipendentemente da ciò che facciamo con un oggetto `Rectangle`, questo rimarrà un rettangolo matematico - Inoltre, possiamo passare uno `Square` a una funzione che accetta un riferimento a un `Rectangle` e lo `Square` agirà comunque come un quadrato e rimarrà consistente - Pertanto, potremmo concludere che il modello ora è consistente e corretto in sé - Tuttavia, #text(blue)[*un modello consistente in sé non è necessariamente consistente con tutti i suoi utenti!*] ```C public void Scale(Rectangle rectangle) { rectangle.Width = rectangle.Width * ScalingFactor; rectangle.Height = rectangle.Height * ScalingFactor; } ``` - `Scale` invoca membri di ciò che crede essere un `Rectangle` - Sostituendovi uno Square otterremo che il quadrato verrà ridimensionato due volte! - E allora qui sta il #text(blue)[*vero problema*]: il programmatore che ha scritto `Scale` era giustificato nel presumere che la modifica della larghezza di un `Rectangle` lasci invariata la sua altezza? - Chiaramente, il programmatore di `Scale` ha fatto questa ipotesi assai ragionevole - Passare uno `Square` a funzioni i cui programmatori hanno fatto questa ipotesi provocherà problemi - Pertanto, esistono funzioni che accettano riferimenti a oggetti `Rectangle` , ma non possono operare correttamente su oggetti `Square` - Queste funzioni espongono una violazione di LSP - L'aggiunta del sottotipo `Square` di `Rectangle` ha guastato queste funzioni: l'OCP è stato violato - Cosa non va nel modello di `Square` e `Rectangle`? - Dopo tutto, un quadrato non è un rettangolo? - La relazione IsA non vale? - No! Un quadrato sarà anche un rettangolo, ma un oggetto `Square` non è sicuramente un oggetto `Rectangle` - Perché? Perché il #text(blue)[*comportamento di un oggetto `Square` non è consistente con il comportamento di un oggetto `Rectangle`*] - Dal punto di vista comportamentale, uno `Square` non è un `Rectangle`!\ E il software si basa proprio sul comportamento - LSP chiarisce che #text(blue)[*in OOD la relazione IsA riguarda il comportamento*] - Non comportamento privato intrinseco, ma #text(blue)[*comportamento pubblico estrinseco*] - Comportamento da cui dipendono i clienti - Ad esempio, l'autore di `Scale` dipendeva dal fatto che i rettangoli si comportano in modo tale che #text(blue)[*le loro altezza e larghezza possano variare indipendentemente l'una dall'altra*] - Tale indipendenza delle due variabili è un #text(blue)[*comportamento pubblico estrinseco*] da cui probabilmente dipenderanno altri programmatori - Affinché LSP possa valere, e con esso OCP, #text(blue)[*tutti i sottotipi devono essere conformi al comportamento che i clienti si aspettano dalle classi base che utilizzano*] - La regola per le pre-condizioni e le post-condizioni per i sottotipi è:\ “quando si ridefinisce una routine, si può sostituire #text(blue)[*la sua pre-condizione solo con una più debole*] e #text(blue)[*la sua post-condizione solo con una più forte*]” - In altre parole, quando si utilizza un oggetto attraverso l'interfaccia della sua classe base, #text(blue)[*l'utente conosce solo le pre-condizioni e le post-condizioni della classe base*] - Pertanto, le classi derivate non devono aspettarsi che tali utenti obbediscano a pre-condizioni più forti di quelle richieste dalla classe base - devono accettare tutto ciò che la classe base può accettare - Inoltre, le classi derivate devono essere conformi a tutte le post-condizioni della classe base - i loro comportamenti e output non devono violare nessuno dei vincoli stabiliti per la classe base - Il contratto di `Rectangle` - Altezza e larghezza sono indipendenti, si può modificarne una mantenendo costante l'altra - `Square` viola il contratto della classe base == Il Quadrato è un Rettangolo? - Guardando al codice di test della classe `Rectangle` possiamo avere qualche idea del contratto di `Rectangle`: ```C [TestFixture] public class RectangleFixture { [Test] public void SetHeightAndWidth() { Rectangle rectangle = new Rectangle(); int expectedWidth = 3, expectedHeight = 7; rectangle.Width = expectedWidth; rectangle.Height = expectedHeight; Assertion.AssertEquals(expectedWidth, rectangle.Width); Assertion.AssertEquals(expectedHeight, rectangle.Height); } }``` ```C [TestFixture] public class RectangleFixture { [Test] public void SetHeightAndWidth() { Rectangle rectangle = GetShape(); ... } protected virtual Rectangle GetShape() { return new Rectangle(); } } [TestFixture] public class SquareFixture : RectangleFixture { protected override Rectangle GetShape() { return new Square(); } }``` == Principi di Architettura dei Package - #text(blue)[*Reuse/Release Equivalency Principle*] (REP) - #text(blue)[*Common Closure Principle*] (CCP) - #text(blue)[*Common Reuse Principle*] (CRP) === Release/Reuse Equivalency Principle - _The granule of reuse is the granule of release_ - Un elemento riutilizzabile, sia esso un componente, una classe o un insieme di classi, non può essere riutilizzato a meno che non sia gestito da un sistema di rilascio di qualche tipo - I clienti dovrebbero rifiutare di riutilizzare un elemento a meno che l'autore non prometta di tenere traccia dei numeri di versione e di mantenere le vecchie versioni per qualche tempo - un criterio per raggruppare le classi in package è il riutilizzo - Poiché i pacchetti sono l'unità di rilascio in Java, sono anche l'unità di riutilizzo - Pertanto, gli architetti farebbero bene a raggruppare in package le classi riutilizzabili assieme === Common Closure Principle - _Classes that change together, belong together_ - Il lavoro per gestire, testare e rilasciare un pacchetto in un sistema di grandi dimensioni non è banale - Più pacchetti cambiano in un dato rilascio, maggiore è il lavoro per ricostruire, testare e distribuire il rilascio - vorremmo #text(blue)[*ridurre al minimo il numero di pacchetti che vengono modificati in un dato ciclo di rilascio del prodotto*] - Per raggiungere questo obiettivo, raggruppiamo assieme classi che pensiamo cambieranno insieme === Common Reuse Principle - _Classes that aren't reused together should not be grouped together_ - Una dipendenza da un package è una dipendenza da tutto ciò che è contenuto nel package - Quando un package cambia e il suo numero di rilascio viene aggiornato, tutti i client di quel package devono verificare di funzionare con il nuovo package - anche se nulla di ciò che hanno usato all'interno del package è effettivamente cambiato - Pertanto, le classi che non vengono riutilizzate insieme non dovrebbero essere raggruppate insieme === Discussione - Questi tre principi non possono essere soddisfatti contemporaneamente - REP e CRP semplificano la vita ai riutilizzatori, mentre CCP semplifica la vita ai manutentori - CCP cerca di rendere i package più grandi possibile (dopotutto, se tutte le classi stanno in un solo package, allora solo quel package cambierà) - CRP, tuttavia, cerca di creare package molto piccoli - All'inizio di un progetto, gli architetti possono impostare la struttura dei package in modo tale che CCP domini per facilità di sviluppo e manutenzione - Successivamente, quando l'architettura si stabilizza, gli architetti possono ri-fattorizzare la struttura dei package per massimizzare REP e CRP per i riutilizzatori esterni == Relazioni tra i Package - #text(blue)[*Acyclic Dependencies Principle*] (ADP) - #text(blue)[*Stable Dependencies Principle*] (SDP) - #text(blue)[*Stable Abstractions Principle*] (SAP) === Acyclic Dependencies Principle - _The dependencies between packages must not form cycles_ - Una volta apportate le modifiche a un package, gli sviluppatori possono rilasciare i package al resto del progetto - Prima di poter eseguire questo rilascio, tuttavia, devono verificare che il package funzioni - Per farlo, devono compilarlo e collegarlo a tutti i package da cui dipende - Una singola dipendenza ciclica che sfugge al controllo può rendere l'elenco delle dipendenze molto lungo - Quindi, qualcuno deve osservare la struttura delle dipendenze dei package con regolarità e interrompere i cicli ovunque compaiano ==== Esempio: Grafo dei Package Aciclico #cfigure("images/2024-04-22-18-48-39.png",70%) ==== Esempio: Grafo dei Package Ciclico #cfigure("images/2024-04-22-18-49-05.png",70%) ==== Discussione - Nello scenario aciclico per rilasciare il package protocol, gli ingegneri dovrebbero compilarlo con l'ultima versione del package comm_error ed eseguire i loro test - Nello scenario ciclico per rilasciare il package protocol, gli ingegneri dovrebbero compilarlo con l'ultima versione di comm_error, gui, comm, process, modem, file ed eseguire i loro test - Come rompere un ciclo: - Inframezzare un nuovo package - Aggiungere una nuova interfaccia ==== Rompere il Ciclo Introducendo un'Interfaccia #cfigure("images/2024-04-22-18-52-30.png",80%) === Stable Dependencies Principle - _The dependencies between packages in a design should be in the direction of the stability of the packages_.\ _A package should only depend upon packages that are more stable than it is_. - I design non possono essere completamente statici - Una certa volatilità è necessaria se il progetto deve essere mantenuto - Raggiungiamo questo obiettivo conformandoci al CCP - Alcuni package sono progettati per essere volatili, ci aspettiamo che cambino - Un pacchetto con molte dipendenze in entrata è molto stabile perché richiede molto lavoro per riconciliare qualsiasi modifica con tutti i pacchetti dipendenti ==== Esempio #cfigure("images/2024-04-22-18-53-44.png",90%) === Stable Abstractions Principle - _Stable packages should be abstract packages_ - La stabilità è relativa alla quantità di lavoro richiesta per apportare una modifica - Un pacchetto con molte dipendenze in entrata è molto stabile perché richiede molto lavoro per riconciliare le modifiche con tutti i pacchetti dipendenti ==== Esempio #cfigure("images/2024-04-22-18-55-31.png",90%) === Stable Dependencies/Abstractions Principles ==== Discussione - I package in alto sono instabili e flessibili - I package in basso sono molto difficili da modificare, perché ogni modifica a un package ne provoca altre - I package altamente stabili nella parte inferiore del grafo delle dipendenze possono essere molto difficili da modificare, ma secondo l'OCP non devono essere difficili da estendere - Se anche i pacchetti stabili in fondo sono molto astratti, possono essere facilmente estesi - È possibile creare la nostra applicazione a partire da package instabili facili da modificare e package stabili facili da estendere = Sicurezza == Progettazione per la Sicurezza - #text(blue)[*La sicurezza non è qualcosa che può essere aggiunto al sistema*] - La sicurezza #text(red)[*deve essere progettata insieme al sistema*] prima dell'implementazione - “Sicurezza” #text(blue)[*è anche un problema implementativo*]: spesso le vulnerabilità sono introdotte durante la fase di implementazione - È possibile ottenere un'implementazione non sicura da una progettazione sicura - Non è possibile ottenere un'implementazione sicura partendo da una progettazione non sicura == Progettazione Architetturale - La scelta dell'architettura del sistema influenza profondamente la sicurezza - Un'architettura inappropriata non garantisce - riservatezza ed integrità delle informazioni - il livello di disponibilità richiesto - Due problemi fondamentali vanno considerati quando si progetta l'architettura del sistema: - _Protezione_: come dovrebbe essere organizzato il sistema in modo che i beni critici possano essere protetti dagli attacchi esterni? - _Distribuzione_: come dovrebbero essere distribuiti i beni in modo da minimizzare gli effetti di un attacco andato a buon fine? - I due problemi sono potenzialmente in conflitto: - se si mettono tutti i beni in un unico posto si può costruire un buon livello di protezione a un costo non eccessivo - se però la protezione fallisce tutti i beni sono compromessi - distribuire i beni porta ad un maggiore costo per la protezione - ci sono più possibilità che la protezione possa fallire se i beni sono distribuiti, ma se questo avviene vi è la perdita solo parziale dei beni - Tipicamente la migliore architettura per fornire un alto grado di protezione è quella a layer - I beni critici da proteggere sono posizionati al livello più basso - Il numero di layer necessari varia da applicazione ad applicazione e dipende dalla criticità dei beni che devono essere protetti - Per migliorare la protezione inoltre sarebbe bene che le credenziali di accesso ai diversi livelli fossero diverse tra loro - Esempio: se si adotta un meccanismo di accesso con password, ogni livello deve avere una propria password diversa da quelle degli altri livelli === Esempio #cfigure("images/2024-04-23-14-12-12.png",100%) - Se la protezione dei dati è un requisito critico si potrebbe anche usare un'architettura client-server con i meccanismi di protezione nella macchina server - La versione tradizionale client-server ha molte limitazioni - Se la sicurezza viene compromessa - le perdite associate ad un attacco saranno alte Esempio: tutte le credenziali di accesso verranno compromesse - i costi di recupero saranno anch'essi elevati Esempio: tutte le credenziali di accesso al sistema andranno rigenerate - Il sistema è inoltre maggiormente soggetto ad attacchi DoS che sovraccaricano il server - Una possibile soluzione può essere quella di adottare una architettura distribuita in cui il server viene replicato in punti diversi della rete === Esempio #cfigure("images/2024-04-23-14-13-01.png",100%) === Esempio - I beni del sistema sono distribuiti in diversi nodi della rete ognuno dei quali ha un proprio meccanismo di protezione dei dati - I dati “più importanti” sono replicati nei diversi nodi - Attacco ad uno specifico nodo: - alcuni beni non saranno disponibili - il sistema comunque potrà ancora funzionare e fornire i servizi più importanti - grazie alla replicazione, il ripristino dei dati nel nodo attaccato sarà più facile e meno costoso #line(length: 100%) - Tipico problema: lo stile architetturale più appropriato per la sicurezza potrebbe essere in conflitto con gli altri requisiti dell'applicazione (analisi trade-off) - Esempio: a. riservatezza dei dati memorizzati su un vasto database b. accesso molto veloce ai dati - Soddisfare entrambi i requisiti nella stessa architettura presenta molti problemi / a.: - layer per garantire la riservatezza - diminuzione netta della velocità di accesso ai dati / b.: - architettura “snella” - diminuzione netta della riservatezza - Tipico problema: lo stile architetturale più appropriato per la sicurezza potrebbe essere in conflitto con gli altri requisiti dell'applicazione (analisi trade-off) - Va valutato attentamente quale «requisito» è prioritario e l'architettura sarà scelta di conseguenza == Linee Guida di Progettazione - Non ci sono regole rigide per ottenere un sistema sicuro - #text(blue)[*Differenti tipi di sistema richiedono differenti misure tecniche per ottenere un livello di sicurezza accettabile*] - La posizione e i requisiti di diversi gruppi di utenti influenzano pesantemente #text(blue)[*cosa è*] e #text(blue)[*cosa non è*] accettabile - Ci sono comunque linee guida generali di ampia applicabilità per la progettazione di sistemi sicuri che possono fungere da: - mezzo per migliorare la consapevolezza dei problemi di sicurezza in un team di progettisti software - base per una lista di controlli da fare durante il processo di validazione del sistema + Basare le decisioni della sicurezza su una politica esplicita + Evitare un singolo punto si fallimento + Fallire in modo certo + Bilanciare sicurezza e usabilità + Essere consapevoli dell'esistenza dell'ingegneria sociale + Usare ridondanza e diversità riduce i rischi + Validare tutti gli input + Dividere in compartimenti i beni + Progettare per il deployment + Progettare per il ripristino === Basare la Sicurezza su Policy - La #text(blue)[*Security Policy*] è un documento di alto livello che definisce “cosa” è la sicurezza ma non “come” ottenerla - La policy non dovrebbe definire i meccanismi usati per fornire e far rispettare la sicurezza - Gli aspetti della security policy dovrebbero originare dei requisiti di sistema - In pratica ciò è poco probabile, specie se viene adottato un processo di sviluppo rapido - I progettisti dovrebbero quindi consultare la policy sia nelle decisioni di progettazione che nella loro valutazione ==== Progettazione delle Politiche - Le politiche di sicurezza devono essere incorporate nella progettazione al fine di: - specificare come le informazioni possono essere accedute - quali precondizioni devono essere testate per l'accesso - a chi concedere l'accesso - Tipicamente le politiche vengono rappresentate come un insieme di regole e condizioni - Tali regole devono essere incorporate in uno specifico componente del sistema chiamato “#text(blue)[*_Security Authority_*]” che avrà il compito di far rispettare le politiche all'interno dell'applicazione - A livello progettuale le politiche di sicurezza sono suddivise in sei specifiche categorie: - #highlight(fill: myred)[Identity policies:] definiscono le regole per la verifica delle credenziali degli utenti - #highlight(fill: myred)[Access control policies:] definiscono le regole da applicare sia alle richieste di accesso alle risorse sia all'esecuzione di specifiche operazioni messe a disposizione dall'applicazione - #highlight(fill: myred)[Content-specific policies:] definiscono le regole da applicare a specifiche informazioni durante la memorizzazione e la comunicazione - #highlight(fill: myred)[Network and infrastructure policies:] definiscono le regole per controllare il flusso dei dati e il deployment sia delle reti che dei servizi infrastrutturali di hosting pubblici e privati - #highlight(fill: myred)[Regulatory policies:] definiscono le regole a cui l'applicazione deve sottostare per soddisfare i requisiti legali e di regolamentazione delle leggi in vigore nel Paese/Stato in cui il sistema opera - #highlight(fill: myred)[Advisor and information policies:] queste regole non sono imposte, ma sono caldamente consigliate in riferimento alle regole dell'organizzazione e al ruolo delle attività di business. Per esempio queste regole possono essere applicate per informare il personale sull'accesso ai dati sensibili o per stabilire comunicazioni commerciali con partner esterni === Evitare Punto Singolo di Fallimento - Nei sistemi critici è buona norma di progettazione quella di cercare di #text(blue)[*evitare un singolo punto di fallimento*] - Questo perché un singolo fallimento in una parte del sistema non si trasformi nel fallimento di tutto il sistema - Per quanto riguarda la sicurezza questo significa che #text(blue)[*non ci si dovrebbe affidare a un singolo meccanismo per assicurarla*], ma si dovrebbero impiegare differenti tecniche - Questo viene spesso chiamato “#text(red)[*difesa in profondità*]” - Esempio: se si usa la password per autenticare si dovrebbe anche includere un meccanismo sfida e risposta === Fallire in Modo Certo - Qualche tipo di fallimento è inevitabile in tutti i sistemi, ma i sistemi critici per la sicurezza dovrebbero sempre #text(red)[*_fallire in modo sicuro_*] - Non si dovrebbero avere procedure di fall-back meno sicure del sistema stesso - Anche se il sistema fallisce #text(blue)[*non deve essere consentito a un attaccante di accedere ai dati riservati*] - Esempio: i dati dei pazienti dovrebbero essere scaricati sul client all'inizio di ogni sessione clinica, così se il server fallisce i dati sono comunque mantenuti sul client. I dati vengono cifrati per non essere letti da personale non autorizzato. Questa pratica non vale per username e password, non è necessario inserire la password nel modello del dominio. === Bilanciare Sicurezza e Usabilità - Sicurezza e usabilità sono spesso in contrasto - #text(blue)[per avere sicurezza bisogna introdurre un numero di controlli] che garantiscano che gli utenti siano autorizzati a usare il sistema e che nello stesso tempo agiscano in accordo alle politiche di sicurezza - questo inevitabilmente ricade sull'utente che ha bisogno di più tempo per imparare ad utilizzare il sistema - #text(red)[*Ogni volta che si aggiunge una caratteristica di sicurezza al sistema questo inevitabilmente diventa meno usabile*] - A volte può diventare contro produttivo introdurre nuove caratteristiche di sicurezza a spese dell'usabilità - Esempio: obbligare l'utente all'adozione di password forti === Essere Consapevoli dell'Ingegneria Sociale - #text(red)[*Ingegneria sociale*]: trovare modi per convincere con l'inganno utenti accreditati al sistema a rivelare informazioni riservate - Questi approcci si avvantaggiano della “#text(blue)[*volontà di aiutare*]” delle persone e della loro fiducia nell'organizzazione - Dal punto di vista della progettazione contrastare l'ingegneria sociale #text(blue)[*è quasi impossibile*] - Se la sicurezza è molto critica non si dovrebbe affidarsi solo a meccanismi di autenticazione basati su password, ma bisognerebbe utilizzare meccanismi di autenticazione forte - Meccanismi di log che tracciano sia la locazione che l'identità dell'utente e programmi di analisi del log potrebbero essere utili ad identificare brecce nella sicurezza === Usare Ridondanza e Diversità - Ridondanza significa #text(blue)[*mantenere più di una versione*] del software e dei dati nel sistema - Diversità significa #text(blue)[*che le diverse versioni del sistema non dovrebbero usare la stessa piattaforma o essere basati sulle stesse tecnologie*] - In questo modo una vulnerabilità della piattaforma o della tecnologia non influirà su tutte le versioni e non condurrà a un comune punto di fallimento - Esempio: - mantenere i dati dei pazienti sia sul client che sul server - client e server devono avere un diverso sistema operativo - attacco basato su vulnerabilità del SO non influenza sia client che server === Validare tutti gli Input - Un comune attacco al sistema consiste nel fornire input inaspettati che causano un comportamento imprevisto - crash - perdita della disponibilità del servizio - esecuzione di codice malevolo - Tipici esempi sono buffer overflow e SQL injection - Si possono evitare molti di questi problemi progettando la validazione dell'input in tutto il sistema - Nei requisiti dovrebbero essere definiti tutti i controlli che devono essere applicati - Bisogna usare la conoscenza dell'input per definire questi controlli === Dividere in Compartimenti i Beni - #text(blue)[*Compartimentalizzare*] significa organizzare le informazioni nel sistema in modo che gli #text(red)[*utenti abbiano accesso solo alle informazioni necessarie*] piuttosto che a tutte le informazioni del sistema - Gli effetti di un attacco in questo modo sono più contenuti: qualche informazione sarà persa o danneggiata, ma è poco probabile che tutte le informazioni del sistema siano coinvolte - Esempio: - lo staff clinico può avere accesso soltanto ai record dei pazienti che hanno un appuntamento o sono ricoverati nella clinica - esiste un meccanismo per gestire accessi inaspettati === Progettazione per il Deployment - Molti problemi di sicurezza sorgono perché il sistema #text(red)[*non viene configurato correttamente*] al momento del deployment - Bisogna sempre progettare il sistema in modo che - siano inclusi programmi di utilità per semplificare il deployment - verificare potenziali errori di configurazione e omissioni nel sistema di deployment === Progettazione per il Ripristino - Bisogna sempre progettare il sistema con l'assunzione che gli errori di sicurezza possano accadere - Si deve quindi pensare a come ripristinare il sistema dopo possibili errori e riportarlo a uno stato operazionale sicuro - Esempio: - persone non autorizzate accedono ai dati dei pazienti - non è noto come abbiano ottenuto le credenziali per l'accesso - occorre quindi cambiare tutte le credenziali del sistema in modo che la persona non autorizzata non abbia accesso al meccanismo di cambiamento delle password == Progettazione per il Deployment - Il deployment di un sistema coinvolge: - configurazione del sistema per operare nell'ambiente: - semplice impostazione di parametri delle preferenze degli utenti - definizione di regole e modelli di business che governano l'esecuzione del software - installazione del sistema sui computer dell'ambiente - configurazione del sistema installato === Deployment del Software #cfigure("images/2024-04-23-14-26-30.png",100%) #line(length: 100%) - Nella fase di deployment vengono spesso introdotte in modo accidentale delle vulnerabilità - Esempio: - il software deve spesso essere configurato con una lista di utenti autorizzati - quando il software è rilasciato questa lista consiste di un login per l'amministratore generico come “admin” e la password di default è “<PASSWORD>” - come prima azione l'amministratore dovrebbe modificare i dati di login, ma è molto facile dimenticare di farlo - un attaccante che conosce il login di default potrebbe essere capace di guadagnare privilegi di accesso al sistema - La configurazione e il deployment sono spesso visti solo come problemi di amministrazione e quindi al di fuori del processo di ingegnerizzazione - I progettisti software hanno la responsabilità di progettare per il deployment - Bisogna sempre fornire supporti per il deployment che riducano la probabilità che gli amministratori compiano degli errori quando configurano il software - Esistono delle linee guida per la progettazione per il deployment === Linee Guida 1. Includere supporto per visionare e analizzare le configurazioni 2. Minimizzare i privilegi di default 3. Localizzare le impostazioni di configurazione 4. Fornire modi per rimediare a vulnerabilità di sicurezza ==== Supporto per le Configurazioni - Si devono sempre includere #text(blue)[*programmi di utilità*] che consentano agli amministratori di esaminare la configurazione corrente del sistema - Sorprendentemente questi programmi #text(blue)[*mancano*] nella maggior parte dei sistemi software - Gli utenti sono spesso frustrati dalla difficoltà di trovare i dettagli della configurazione - per un quadro completo della configurazione spesso occorre visionare diversi menu e questo porta a errori e omissioni - Idealmente in fase di visualizzazione delle configurazioni si dovrebbero evidenziare impostazioni critiche per la sicurezza ==== Minimizzare i Privilegi di Default - Il software deve essere progettato in modo tale che la #text(red)[*configurazione di default fornisca i minimi privilegi essenziali*] - In questo modo vengono limitati i danni di un possibile attacco - Esempio: - l'autenticazione di default dell'amministratore dovrebbe solo consentire l'accesso a un modulo che permette all'amministratore di inserire nuove credenziali - non dovrebbe essere consentito l'accesso a nessuna altra funzionalità - quando vengono modificate le credenziali, quella di default dovrebbe essere automaticamente cancellata ==== Localizzare le Impostazioni di Configurazione - Quando si progetta il supporto per le configurazioni del sistema bisognerebbe assicurarsi che ogni risorsa che appartiene alla stessa parte del sistema venga configurata nella stessa posizione - Se le informazioni di configurazione non sono localizzate - è facile dimenticarsi di farlo - può capitare di non essere a conoscenza dell'esistenza di meccanismi per la sicurezza già inclusi nel sistema - se tali meccanismi presentano configurazioni di default si potrebbe essere esposti ad attacchi ==== Rimediare a Vulnerabilità - Bisogna includere #text(red)[*meccanismi diretti*] per: - aggiornare il sistema - riparare le vulnerabilità di sicurezza che vengono scoperte - Questi potrebbero includere - verifiche automatiche per aggiornamenti di sicurezza - download di tali aggiornamenti non appena sono disponibili - Va comunque considerato che gli aggiornamenti devono coinvolgere contemporaneamente centinaia di PC su cui tipicamente il software è installato == Testare la Sicurezza - Il test di un sistema gioca #text(blue)[*un ruolo chiave*] nel processo di sviluppo software e dovrebbe essere eseguito con molta attenzione - È quindi sorprendente che #text(blue)[*l'area dei test della sicurezza sia quella più trascurata durante lo sviluppo del sistema*] - Questo può essere attribuito a diversi fattori: - mancanza di comprensione dell'importanza dei test relativi alla sicurezza - mancanza di tempo - mancanza di conoscenza su come svolgere un test di sicurezza - mancanza di tool integrati per compiere test - Il test della sicurezza è un lavoro molto lungo e tedioso, spesso molto più complesso dei test funzionali che vengono svolti normalmente - Inoltre esso coinvolge diverse discipline - ci sono tradizionali test per accertare la sicurezza dei requisiti applicativi che possono essere svolti normalmente dal team di testing - ma esistono dei test non funzionali di “rottura” del sistema che devono essere condotti da esperti di sicurezza - Black box testing - White box testing === Black Box Testing - Questo test ha come assunzione di base la non conoscenza dell'applicazione - I tester affrontano l'applicazione come farebbe un attaccante - indagando sulle informazioni riguardanti la struttura interna - successivamente applicano un insieme di tentativi di violazione del sistema basati sulle informazioni ottenute - Esempio: se un URL di una applicazione contiene una estensione “.cgi” allora può essere inferito che l'applicazione è stata sviluppata con la tecnologia CGI e applicare quindi le ben conosciute tecniche di violazione di questa tecnologia - I tester possono impiegare una varietà di strumenti per scansionare e indagare l'applicazione - ci sono centinaia di tool in rete per l'hacking di applicazioni che permettono di “scandagliare” le porte dei sistemi perpetuando attacchi sfruttando le debolezze ben conosciute di svariati linguaggi di programmazione - Questo test non prende in esame solo debolezze del codice, ma vengono svolti test mirati anche al livello infrastrutturale - errori di configurazione di reti e host - falle di sicurezza nelle macchine virtuali - problemi legati ai linguaggi di implementazione === White Box Testing - Questo test ha come assunzione di base la completa conoscenza dell'applicazione - I tester hanno accesso a tutte le informazioni di configurazione e anche al codice sorgente - Essi operano una revisione del codice cercando possibili debolezze - Inoltre scrivono test per stabilire come trarre vantaggio dalle debolezze scoperte - Tipicamente questi tester sono ex-sviluppatori o persone che conoscono molto bene l'ambiente di sviluppo - I tool a disposizione differiscono molto da quelli usati nel black box test - Tipicamente sono tool di debugging che consentono di trovare bachi e vulnerabilità specifici del sistema - I bachi tipici riguardano problemi di corsa critici e la mancanza di verifica dei parametri di input e sono specifici di ogni applicazione - Questi test portano a scoprire anche altri problemi come i memory leak e problemi di prestazione che contribuiscono al danneggiamento della disponibilità e dell'affidabilità dell'intero sistema == Capacità di Sopravvivenza del Sistema TUTO QUESTO CAPITOLO NON È DA STUDIARE - Con il termine #text(blue)[*capacità di sopravvivenza*] (_survivability_) si intende la capacità del sistema di continuare a fornire i servizi essenziali agli utenti legittimi - mentre è sotto attacco - dopo che parti del sistema sono state danneggiate come conseguenza di un attacco o di un fallimento - La capacità di sopravvivenza è una proprietà dell'intero sistema, non dei singoli componenti di questo - Il lavoro sulla capacità di sopravvivenza è molto critico poiché l'economia e la vita sociale dipendono da infrastrutture controllate da computer - L'analisi e la progettazione della capacità di sopravvivenza dovrebbero essere parte del processo di ingegnerizzazione dei sistemi sicuri - #text(blue)[La disponibilità dei servizi critici è l'essenza della sopravvivenza] - Questo significa conoscere - quali sono i servizi #text(blue)[maggiormente critici] - come questi servizi possono essere compromessi - qual è la #text(blue)[qualità minima dei servizi] che deve essere mantenuta - come proteggere questi servizi - come #text(blue)[ripristinare velocemente] il sistema se i servizi diventano non disponibili === Esempio - Un sistema informatico che gestisce l'invio delle ambulanze in risposta alle chiamate di emergenza - Servizi: - prendere le chiamate e inviare le ambulanze - log delle chiamate - gestione locazione delle ambulanze - Il servizio critico è quello legato a prendere le chiamate e inviare le ambulanze perché necessita di un processo real-time per la gestione degli eventi === Analisi della Sopravvivenza - Il Survivable Analysis Systems è un metodo di analisi ideato agli inizi del 2000 per: - valutare le vulnerabilità nel sistema - supportare la progettazione di architetture e caratteristiche che promuovono la sopravvivenza del sistema - In questo metodo la sopravvivenza del sistema - dipende da tre strategie complementari - è un processo a 4 fasi === Strategie - #highlight(fill: myblue)[Resistenza:] - evitare problemi costruendo all'interno del sistema le capacità di respingere attacchi - es: firma digitale per l'autenticazione - #highlight(fill: myblue)[Identificazione:] - individuare problemi costruendo all'interno del sistema le capacità di riconoscere attacchi e fallimenti e valutare il danno risultante - es: aggiungere checksum ai dati critici - #highlight(fill: myblue)[Ripristino:] - tollerare problemi costruendo all'interno del sistema le capacità di fornire servizi essenziali durante un attacco - ripristinare le complete funzionalità dopo l'attacco === Fasi Analisi di Sopravvivenza #cfigure("images/2024-04-24-16-59-07.png",100%) === Principali Attività - #highlight(fill: myblue)[Capire il sistema:] riesaminare gli obiettivi del sistema, i requisiti e l'architettura - #highlight(fill: myblue)[Identificare servizi critici:] identificare i servizi che devono essere mantenuti e i componenti che devono svolgere tale compito - #highlight(fill: myblue)[Simulare gli attacchi:] identificare gli scenari o i casi d'uso dei possibili attacchi insieme ai componenti influenzati da questi attacchi - #highlight(fill: myblue)[Analizzare la sopravvivenza:] identificare - i componenti che sono sia essenziali che a rischio - le strategie di sopravvivenza basate su resistenza, identificazione e ripristino === Esempio #cfigure("images/2024-04-24-17-00-19.png",100%) === Esempio - Sistema che gestisce l'equità dei prezzi nei mercati internazionali - Qual è il minimo supporto che il sistema fornisce già per la sopravvivenza? - gli account dei clienti e i prezzi internazionali sono replicati in tutti i nodi - Servizio chiave che deve sempre essere mantenuto: capacità di piazzare ordini - mantenere l'integrità dei dati - ordini accurati e che riflettano le vendite e gli acquisti degli utenti === Esempio - Per mantenere questo servizio ci sono tre componenti del sistema - _autenticazione dell'utente_ : consente agli utenti autorizzati di accedere al sistema - quotazione dei prezzi: consente che la vendita e l'acquisto degli stock dei beni siano quotati - piazzamento ordini: consente di vendere o comprare beni al dato prezzo di mercato - Questi componenti fanno uso dei dati - relativi agli utenti - accedono al database delle transazioni === Esempio - Possibili attacchi al sistema: - utente malevolo guadagna le credenziali di accesso di utente verso cui nutre forte rancore - vengono piazzati ordini di vendita e acquisto in modo tali da causare seri problemi all'utente legittimo - utente non autorizzato corrompe il database delle transazioni guadagnando permessi per eseguire direttamente query SQL - riconciliare gli acquisti e le vendite diventa quindi impossibile === Esempio #cfigure("images/2024-04-24-17-01-24.png",100%) === Capacità di Sopravvivenza - Aggiungere le tecniche di sopravvivenza costa soldi - Spesso le aziende sono molto riluttanti ad investire sulla sopravvivenza, specie se non hanno mai subito attacchi e perdite - È comunque sempre buona norma investire nella sopravvivenza prima piuttosto che dopo aver già subito un attacco - L'analisi della sopravvivenza non è ancora inclusa nella maggior parte dei processi di ingegnerizzazione del software - Con la crescita dei sistemi critici sembra probabile che questo tipo di analisi sarà sempre più utilizzato == Conclusioni - La sicurezza deve #text(blue)[*essere onnipresente attraverso tutto il ciclo di sviluppo del software*] - Inoltre la sicurezza deve essere tenuta in considerazione anche attraverso tutti gli strati dell'infrastruttura su cui l'applicazione viene sviluppata - Per ottenere questo è imperativa l'adozione di un processo che tenga in considerazione le problematiche relative alla sicurezza sin dalle prime fasi dello sviluppo del sistema - È inoltre necessario che vengano compiuti #text(blue)[*severi test periodici*] a verifica del livello di sicurezza del sistema
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rich-counters/0.1.0/lib.typ
typst
Apache License 2.0
#let richcounter(identifier: none, inherited_levels: 0, inherited_from: heading) = { // create the underlying counter for the rich counter let cntr = counter(identifier) // get the parent counter let parent_cntr = if type(inherited_from) == dictionary { if inherited_levels == 0 { inherited_levels = inherited_from.inherited_levels + 1 } inherited_from.raw } else if type(inherited_from) == counter { inherited_from } else { counter(inherited_from) } // helper function for `sync` let rel_slice(num) = num.slice(0, calc.min(num.len(), inherited_levels)) // updates the underlying counter if the relevant levels of the parent counter changed let sync = () => { let num = cntr.get() let rel_parent_num = rel_slice(parent_cntr.get()) if rel_slice(num) < rel_parent_num or num.len() <= inherited_levels { cntr.update(rel_parent_num + (inherited_levels - rel_parent_num.len() + 1)*(0,)) } } // `step` function for this counter let step = (depth: 1) => { context sync() cntr.step(level: inherited_levels + depth) } // `display` function for this counter let display = (numbering_style) => { sync() context cntr.display(numbering_style) } return (raw: cntr, step: step, display: display, inherited_levels: inherited_levels) }