repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/SkiFire13/eh-presentation-shellcode
https://raw.githubusercontent.com/SkiFire13/eh-presentation-shellcode/master/task1.b.typ
typst
#import "@preview/polylux:0.3.1": * #import "unipd.typ": * #new-section[ Task 1.b ] #slide[ #let code = text(size: 18pt, ```asm ; Store the argument string on stack xor eax, eax push eax ; Use 0 to terminate the string push "//sh" push "/bin" mov ebx, esp ; Get the string address ; Construct the argument array argv[] push eax ; argv[1] = 0 push ebx ; argv[0] points "/bin//sh" mov ecx, esp ; Get the address of argv[] ; For environment variable xor edx, edx ; No env variables ; Invoke execve() xor eax, eax ; eax = 0x00000000 mov al, 0x0b ; eax = 0x0000000b int 0x80 ```) #let task = [ - The code executes the `/bin//sh` binary (same as `/bin/sh`) - Change it to execute the `/bin/bash` binary - Avoid using double slashes (`//`) #v(15%) ] #place(dx: 62%, dy: 30%, box(width: 35%, task)) #code ] // #let elems = (`"\0\0\0\0"`, `"//sh"`, `"/bin"`, "0", "ptr") // #grid( // columns: (6em,), // rows: (1.4em,) * 5, // row-gutter: 0pt, // column-gutter: 0pt, // ..elems.map(it => rect(width: 100%, height: 100%, outset: 0pt, align(center, it))) // ) #new-section[ Task 1.b: Solution ] #slide[ #let code = text(size: 18pt, ```asm ; Store the argument string on stack mov eax, "###h" shr eax, 24 push eax push "/bas" push "/bin" mov ebx, esp ; Get the string address ; Construct the argument array argv[] xor eax, eax push eax ; argv[1] = 0 push ebx ; argv[0] points "/bin/bash" mov ecx, esp ; Get the address of argv[] ; For environment variable xor edx, edx ; No env variables ; Invoke execve() xor eax, eax ; eax = 0x00000000 mov al, 0x0b ; eax = 0x0000000b int 0x80 ```) #let notes = uncover(2, mode: "transparent")[ #align(center)[ `"###h"` $arrow.b.double$ `0x68232323` $arrow.b.double #place(dy: -0.3em, text(size: 18pt, "shift right"))$ `0x00000068` $arrow.b.double$ `"h\0\0\0"` ] ] #place(dx: 60%, dy: 15%, box(width: 40%, notes)) #code ] // TODO: Show stack? #slide[ #align(center, v(-10%) + scale(x: 90%, y: 90%, image("exe1b.png"))) ] #slide[ #align(center, v(-10%) + scale(x: 90%, y: 90%, image("obj1b.png"))) ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/029%20-%20Aether%20Revolt/002_Quiet%20Moments.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Quiet Moments", set_name: "<NAME>", story_date: datetime(day: 07, month: 12, year: 2016), author: "<NAME>", doc ) #emph[Under the oppression of the Consulate crackdown, the Gatewatch are limited in their ability to discover what the dangerous artificer Tezzeret is plotting. With Tezzeret still maintaining control and leadership of the Consulate, the Gatewatch find themselves embroiled in the local conflict between rebelling renegade groups and the government forces. In between the skirmishes, Gideon Jura tries to determine the thin line between intervention and imposition.] #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Gideon peered into his cup. The things that remained constant across the Multiverse never ceased to surprise him. Sure, here the #emph[kaapi] was served hot and foamy, a flavor and texture distinct from the Ravnican coffee Jace seemed to guzzle with every meal back in his sanctum, but the bitter bite of the drink and the tingling jolt it gave a tired mind remained the same. Gideon looked up from his perch. The small café at which he sat offered a good vantage point of the dazzling square before him. Graceful architecture framed a bright blue sky painted with swirling clouds. An exquisite fountain anchored the ornate design of the plaza. Gideon imagined the square filled with people, as it surely must have been before the crackdown—a stark contrast to the few odd pedestrians that hurried across the open area now, their heads down and eyes locked on their paths. Yet even under the current political duress, the city of Ghirapur gleamed. #figure(image("002_Quiet Moments/01.jpg", width: 100%), caption: [Consulate Surveillance | Art by <NAME>], supplement: none, numbering: none) Weeks have passed since the Gatewatch came to Kaladesh. Weeks since their clash with Tezzeret, since the crackdown and the seizure of inventions. They've spent so much time in hiding, moving from safe house to safe house, aiding Pia and the renegades where they could, seeking out information on Tezzeret's plans. And still, Gideon was not sure they should be here. Jace and Liliana's alarm at Tezzeret's presence seemed genuine, but both had been scant in the details of the specific threat he poses. Yes, Tezzeret inserting himself into the politics and leadership of Kaladesh certainly caused Gideon concern and was reason enough for the Gatewatch to investigate. But Tezzeret's entanglement with Kaladeshi forces, along with the relationship between the Consulate and the renegades made things...complicated. Cutting down Eldrazi and the threat they posed to Zendikar and Innistrad left little room for questions. His sural slicing through whirring gears of Kaladeshi-forged automatons, battling Consulate forces that were just trying to defend the laws of the land... Far more complicated. Gideon sipped his coffee. A good commander must maintain a clear head, even in the confusion and mayhem of an engagement. Temper the need of brash action with critical evaluation of the conflict at hand. How he valued this quiet moment, a lull between the fights of recent days. He took a deep breath. Boil it down to the basics. #emph[The Gatewatch is on Kaladesh to determine and neutralize the threat of Tezzeret.] Gideon shook his head. Even this wasn't completely accurate. If he was honest with himself, they were here for Chandra. #emph[He] was here for Chandra. His friend. Tezzeret had been an additional reason, a discovered threat. Yes, Tezzeret was now why the Gatewatch was here. But Chandra was the original reason why they all came—and Pia was the reason Chandra had stayed. They were why the Gatewatch now battled on the side of the renegade forces. #emph[The enemies of my enemies are my allies] —but should the Gatewatch be taking sides in this local conflict#emph[?] Should the Gatewatch be empowering local rebel forces, or should they have tried to work with Kaladeshi authorities, tried to work with Baan and the Consulate to illuminate the danger and threat of Tezzeret from within—a threat that Gideon still had #emph[no solid answers or definition for?] Yet at the same time, how could he have possibly worked with Baan, knowing now what he did about what the Consulate did to Chandra's parents? How could he have abandoned Pia and betrayed Chandra's trust? Gideon thought back to his youth, wrongfully shackled by those who claimed to wield the law. He thought back to his time on Ravnica, wielding his hieromancy for Boros and fighting on the side of justice. He had seen this conflict several times before, of the force of law against those who refuted it. He had stood on both sides of this fight. He felt like he knew less now than ever about what to do. A small thopter flitted onto his table. He frowned, reaching a hand out. The thopter hovered into his outstretched palm, where its aether coils pulsed three times, long, short, long, before it flew off into the afternoon. Gideon sighed. #emph[Pia had news.] Quiet moment over. Gideon finished the last of his coffee and stood, beginning his circuitous route back to Yahenni's penthouse. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Hours Later] He found her on the roof. At first, he thought her hair was still aflame, but as he walked closer he realized the sun merely danced off the reds and oranges in a way that shimmered. She sat on the barrier at the edge, facing away from him, her feet dangling over. He came to a stop next to her and followed her gaze out over the city. Yahenni's penthouse was tall enough to offer them a spectacular view, and Gideon marveled briefly at how any being could accumulate such wealth in so short a life—just before the sight of Ghirapur stole away his thoughts. Sprawling streets and towering buildings stretched out before them, metals and chrome gleaming in the waning sunlight, aglow with aether blues that became more prominent as the shadows deepened. #figure(image("002_Quiet Moments/02.jpg", width: 100%), caption: [Inspiring Vantage | Art by Jonas De Ro], supplement: none, numbering: none) "Your home is beautiful." Gideon leaned against the barrier. "This was my home. Maybe still is. I'm not sure." She bit her lip, her eyes locked on the horizon. "You know, in all the mayhem, this is the first time I've really gotten to take a good look." Gideon's gaze swept from the horizon to the cobblestone street below. "It's beautiful, Chandra." Chandra scowled. "Currently ruined with all those stupid Consulate banners dangling from every window and building they could stick 'em on." She threw hands up. "How'd they get them made so fast, anyway? Makes no sense." Gideon sighed. "Chandra..." "And why were you so quiet in that meeting back there? Just letting my mom talk and plan the renegades' next attacks, not once offering our help." Chandra turned and glared at Gideon. "Your silence was loud as hell, Gids. We're here to take down the Consulate and you—" "No, we're not." Gideon hesitated, just for a moment. Hedge his words, or speak the truth? His eyes locked with Chandra. Her gaze burned away his doubts. Speak directly. Always. "We came for you." A flicker of flame flared through Chandra's hair, and Gideon felt a surge of heat. "Oh, you're only here because, what, I needed saving or something?" "We're here because we care about you, Chandra." Gideon smiled. Soft. Gentle. "We each took an oath to keep watch. That watch also means watching out for each other. We've got each other's backs." He frowned. "Even Liliana's. I think." Chandra laughed, genuine yet tinged with frustration. "Then why didn't you speak up while my mom was laying out their plans to overthrow the Consulate? If you have my back, you gotta have hers too. I want to help her. I #emph[need] to help her. And I need your help to...help her." Chandra stamped in frustration. "You know what I mean. Right?" Gideon hoisted himself onto the barrier and sat next to Chandra. "Yeah. I do, Chandra. We want to help you. #emph[I] want to help you. But the Gatewatch's focus must be Tezzeret. Not the Consulate." Chandra frowned. "But Tezzeret #emph[is] the Consulate. At least, he is now." Her eyes narrowed. "And the Consulate deserves to burn." Gideon shook his head. "Don't let your personal vendetta cloud our purpose here, Chandra." Chandra turned on Gideon, anger sparking behind her eyes. "You say you have my back, Gids. But are you here as Gideon of the Gatewatch, or are you here as Gideon, my friend?" Gideon sighed. "I... I don't know. I had hoped they could be the same thing." A few curses tumbled out of Chandra's lips before she, with effort, swallowed them, letting loose a yell and sent a jet of fire out into the darkening sky. (Gideon refrained from chastising her about potentially revealing their position.) The two stood quietly for some time. Finally, Gideon broke the silence. "I don't know the details of what happened between your parents and the Consulate. I don't know everything that happened here on Kaladesh. I do know, as your friend, I want nothing more than to shield you from that pain, to help you find justice." A small smile crossed Chandra face. Gideon smiled, then furrowed his brows. "...But that doesn't mean just lighting them all on fire." Chandra rolled her eyes. "All you do is try to tell me what #emph[not] to light on fire." "Untrue. Sometimes I tell you what #emph[to] light on fire." A chuckle escaped Chandra despite herself. "You and your stupid rules." Gideon shook his head. "I know all these may seem like unimportant details, but they matter." Gideon gestured out over the city. "We can't just go from plane to plane, meddling with each world's affairs, imposing our judgment and will. Otherwise, the line separating us from tyrannical mages would grow dangerously thin." Chandra gave Gideon a quizzical look. "Are you quoting my oath back at me?" Gideon shrugged. "Maybe you're having an influence on me." Chandra laughed, a laugh that broke into a snort. "For a law-bound indestructible soldier, you sure think a lot." "For a human fireball, you sure are compassionate and kind. We're all more than our powers, Chandra." Chandra looked down at her hands, little sparks and embers dancing along her fingertips. Gideon held up his own hands, his left tracing over the sural strapped to his right wrist. "I've learned the importance of knowing and setting limits. Otherwise you, and those you love, will bear the burden of your hubris." Questions lingered behind Chandra's eyes. Gideon took a deep breath and tried to speak, to share the story he has told no one—but his past remained a weight, heavy and unmovable, in the pit of his stomach. The two sat, the silence stretching taut while the sun slid behind the horizon. As the last rays of light disappeared, he felt her hand fall on his shoulder. He smiled at her borrowing his familiar gesture. "I trust you, <NAME>." Chandra gave Gideon's shoulder a comforting squeeze. "And, as much as I hate it, I'll try to focus on stopping Tezzeret....for now. Maybe. No promises." Chandra stood from her perch on the barrier, jumping back onto the roof. "But I'm also still going to help my mom and the renegades. Not as a member of the Gatewatch, but as <NAME>'s daughter." Gideon stood as well. "As you should. Spend time with your mom. Beyond all of this...you deserve the time to catch up with her. Plus, knowing the renegade's plans will only help us when we move against Tezzeret." Gideon started walking toward the stairs back down off the roof. "We should confer with the rest of the Gatewatch, and perhaps Ajani, on how we can learn and stop whatever Tezzeret is planning." Chandra watched him go for a moment. "H<NAME>." Gideon turned around. "I care about you too." Chandra caught up to Gideon, slugged him in the arm, then brushed passed him, bounding down the stairs two at a time. Gideon, for his part, tried to ignore the tightening in his chest as he followed her back down. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #emph[Days Pass] "We need to talk." Gideon slammed the door shut, fuming. Liliana rolled her eyes as she sauntered across the room. "Go ahead, talk away." "We don't kill." "No, the large cat-man doesn't kill." Liliana threw open the wardrobe Yahenni had set aside for the Gatewatch and began rifling through it. "Not anymore," she said, doing an eerily accurate imitation of the Planeswalker. She rolled her eyes. "So righteous. Much mystery." "Neither do we." Gideon walked forward and closed the wardrobe door, forcing Liliana to look at him. Liliana laughed. "Um. I'm sorry. I seem to recall watching you cut down foes like weeds in Thraben." "Those were Eldrazi monstrosities. These are people." "We only kill ugly things, then? Because the short one, he would've still qualified." Liliana reopened the wardrobe and resumed her search. Gideon sputtered in disbelief. "We do not kill unless we must! And that just now—" "That just now was a situation where 'we must.' Those Consulate forces saw us. Identified us. Attacked us. You think if we, what, knocked them unconscious, they would awaken and just magically forget they saw us walking out of this penthouse?" Liliana pulled out a large white kurta, gave it a quick appraising glance, and threw it over her shoulder. "Wiping memories isn't my specialty, and you've got our resident mind wiper running around on those stupid little recon missions. I only did what I'm best at." She turned, giving him a demure smile. "Death is just a tool in our toolbox. I'm just particularly good with that tool." "Death is a tool we should avoid using at all costs. That may be hard to grasp as a death mage." Gideon realized he was clenching and unclenching his hands into fists. He took a deep breath. "Oh, please. Do you know how many people I've #emph[not] killed since arriving here?" Liliana threw the kurta at Gideon. "Plus, maybe if you put on a local shirt and blended in more, we wouldn't have been spotted." Gideon caught the shirt and glared at Liliana. #emph[Deep breaths.] He quietly folded the shirt. #emph[She's trying to provoke you] . He put the shirt down on a nearby chaise. "You do not need to assign the blame of their deaths to me. I take responsibility for the lives I end." Liliana rolled her eyes. Gideon kept his gaze on her. "I want to trust you, Liliana. I find that difficult when you betray the basic tenets of what we do." "We don't even know what it is we do." Liliana's face shifted from sarcastic mirth to deadly seriousness in a flash. "We're wasting our time playing Consulate and renegades when we should be eliminating Tezzeret." "You're right." Gideon took a little satisfaction as Liliana stepped back, eyeing him closely. "That's why we have Jace shadowing Consulate forces to uncover more of Tezzeret's plans. That's why Nissa and Yahenni are tracking the flow of aether in the city to try to find any potential locations where Tezzeret may be basing his operations. It's hard to stop a man if you don't know where he's hiding." Liliana scoffed. "What about Chandra escorting her mother to rally the renegades? Cat-man guarding the grandmother to do the same? Are those a part of the orders of the Gatewatch as well?" "It doesn't hurt to have renegade allies at the ready if it comes to a conflict." Gideon's voice lacked the conviction of his words. "Ah, of course. So we're just waiting for an army for you to command. Into a magically non-lethal combat. Against forces that are sending folks to capture or murder us." Liliana slinked close to Gideon, looking up into his face. "I can promise you Tezzeret won't have the same rules as you, Gideon. And if we don't stop him, he will kill far more people than I." She spoke barely above a whisper, her words a soft hiss lingering in the air. "After all, there's just one I want to kill on this plane. And he so, so has it coming to him." With that, she turned and walked toward the stairs. "What did he do to you?" Gideon's words stopped her, and Liliana turned back, an eyebrow arched into a question. "The way you speak. He must have done something to you. Taken something personal from you." Gideon returned her gaze, his face a mask of calm conviction. "He was the leader of an interplanar criminal organization that smuggled dangerous goods across worlds. His cruelty and madness is only outstripped by his propensity to manipulate and murder friends and foes alike. He's burned villages just to make a point." Gideon shook his head. "That's why you think I would want to stop him. Why do #emph[you] want to stop him? To kill him?" For a moment, Liliana looked genuinely speechless. Gideon watched her closely. He saw a flicker of something within her eyes, a decision made behind those pools of violet. "He hurt something important to me. Destroyed something that was mine." The words were flat, but beneath her tone, Gideon heard the barbs of anger and hatred. #figure(image("002_Quiet Moments/03.jpg", width: 100%), caption: [Art by <NAME>inski], supplement: none, numbering: none) "Keep out of my way, and I will end him and this whole charade." Liliana turned and glided up the stairs, her heels ringing out in sharp staccato as she ascended. Gideon sighed and ran a hand over his face. He was certain that wasn't the whole truth. But he was also certain that was the most truth than he had gotten out of Liliana yet. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) #strong[Days Later, Bomat District] #figure(image("002_Quiet Moments/04.jpg", width: 100%), caption: [Ballista Charger | Art by Sung Choi], supplement: none, numbering: none) The Consulate charger barreled toward him, the scream of metal wheels against stone streets tearing at his ears. #emph[Breathe in.] Gideon angled his left shoulder toward the vehicle racing directly at him and raised his arms in a guarded stance, his feet squared and braced for impact. #emph[See the foe.] His skin shimmered, waves of golden light cascading across his body. This charger was not so different from an enraged hydra rampaging through a town back on Theros—only instead of feral, bestial eyes, he saw, in the fleeting instant before impact, the terrified pupils of the driver. #emph[Breathe out.] The charger smashed into Gideon. His feet scraped backward with the force, digging into the ground and sending shards of broken cobblestone flying. The charger tore itself to pieces, fragments breaking around him, gears and jagged metal slashing across his magically impervious body, golden rays of light sparking as those pieces collided against him. Even amidst the chaos of the exploding vehicle, Gideon's eyes remained fixed on that of the driver, and as the hapless man flew forward, his vehicle shattering to pieces around him, Gideon reached out and enveloped the man in his arms, turning as he did so to absorb the forward force of the pilot and shield him from the flying shrapnel. A blink of an eye. One moment, a formidable Consulate charger raced down the street. The next, a heap of scrap laid spread out before Gideon and the very dazed-looking pilot still cocooned in his arms. "You can probably call it a day." Gideon set the pilot down and clapped a friendly hand his shoulder. If the pilot had a response, it was lost as a massive metallic fist slammed into Gideon, sending him flying and crashing through the wall of a nearby building. The pilot looked up, eyes catching the blank stare of a steely gray automaton, towering above him at twelve feet in height, decked out in the reds and golds of the Consulate. #figure(image("002_Quiet Moments/05.jpg", width: 100%), caption: [Built to Last | Art by <NAME>], supplement: none, numbering: none) The pilot paused for just a moment, then fled as fast as he could in the opposite direction while the steely gray automaton stomped toward the vaguely Gideon-shaped hole in the wall. Its march was cut short as another automaton, uncannily similar in its design but built from golden metals, ran and slammed into it head-first. The Consulate construct regained its balance and the two began to brawl, just as a small female figure clad in blue and burgundy dashed towards the hole. "Gideon! Are you okay? I'm so sorry—I didn't see the #emph[second] Consulate construct!" Gideon emerged from the rubble, shaking his head and brushing dust from his shoulders. "I'm fine, Saheeli—though I'm mildly concerned that you missed seeing #emph[that.] " Gideon gestured toward the battling behemoths just the Consulate automaton landed a clean hit, knocking the golden one backward to crash through another wall. Saheeli shrugged. "They're surprisingly stealthy for their size." She raised her hands and Gideon felt a surge of mana as she gestured toward the broken scrap from the Consulate charger. Gideon watched with admiration as the gears and pieces reassembled themselves into two perfect smaller replicas of the larger battling automatons. At another wave of Saheeli's hands, the two smaller constructs launched themselves into the fray, clambering over the Consulate automaton, severing aether cables and prying at its armor plating, even as the larger golden automaton pressed its relentless assault. Saheeli made a thrusting gesture and the golden automaton mirrored it, punching through the Consulate machine's chest and ripping out a tangled mass of tubes and glass, sending liquid aether splashing all over. The Consulate automaton stumbled to its knees, then fell with a deafening clatter to the ground. Saheeli pumped a fist in triumph. "That's Consulate design for you. Sturdy, but predictable. Always housing the power core in the same place on all their units." Gideon started to speak, but the sound of approaching footsteps had them both turn to face the incoming threat, his sural unfurled and her filigree metal spinning into shape. A massive cloaked figure leapt from a nearby rooftop and landed before them, almost soundlessly. Gideon and Saheeli took a reflexive step back, then Gideon breathed a sigh of relief as he recognized the blue eye peering at them from beneath the hood. "Ajani. What are you doing here?" Ajani stood to his full height. "We heard the commotion." "We #emph[all] heard the commotion." Gideon turned and saw Liliana stride out from behind a nearby building, followed by Jace. From another roadway, Nissa and Yahenni rounded the corner, even as Chandra and Pia came running down a side alley. "<NAME>, it looks like #emph[I] was here." Chandra surveyed the still smoldering scraps and remnants littering the streets, as well as the multiple holes in various walls and buildings. "You guys smashed things up good." She waved at some unseen person through the wall Gideon had smashed into moments ago. A meek "hello" floated back. Gideon coughed, trying to recapture the group's attention. "Thanks for coming to assist, everyone, but if you all heard the noise, then no doubt Consulate reinforcements are on their way too. We should regroup with Saheeli at a new safe house and—" "There's no more time." Saheeli strode forward to the center of the gathered group. "As I was telling Gideon, or trying to tell him before all this happened, I've found where Tezzeret is hiding." Mild pandemonium broke out as the news hit the gathered folk. Gideon held up his hands, then looked back to her. Saheeli continued. "He has locked himself away in a private workshop, hidden in the central Aether Spire. That's where he's keeping the winning inventor of the Fair and where he's working on something to do with her creation." #figure(image("002_Quiet Moments/06.jpg", width: 100%), caption: [Aetherflux Reservoir | Art by Cliff Childs], supplement: none, numbering: none) "This fits what we've learned." Nissa stepped forward, nodding. Yahenni also spoke up. "Miss Nissa and I have recently determined an unusual flux of aether being diverted to that particular reservoir from the Aether Hub. "Then we storm the Spire and take Tezzeret down!" Chandra seemed ready to charge off already, but Saheeli was shaking her head. "The lab is sure to be heavily guarded. He also has the winning inventor in his grasp. She is—that is, Rashmi's my friend." Saheeli's voice caught, ever so slightly. "We need to get in, rescue her, and get out. I can't do it alone, but perhaps with one or two others..." "If it's infiltration, Jace should go." Gideon nodded to his friend. "He would also be best equipped to determine what Tezzeret is trying to—" "I'll go." Liliana stepped forward, pushing past Jace to stand between him and Gideon. "If Tezzeret is there, I'm there." Saheeli looked from Jace to Liliana to Gideon. Jace looked surprised, but Gideon caught his shoulders subtly drop, a release of tension and nerves. Gideon stared hard at Liliana. Liliana's blank expression revealed nothing. The seconds ticked by, each moment of indecision a growing weight on Gideon's shoulder. #emph[I want to trust you. Can I trust you?] #emph[Saheeli's voice interrupted his thoughts. "We need to decide. Now."] "Fine. Liliana will go." Saheeli nodded, satisfied, and started down the path toward Weldfast. Liliana followed closely. "Liliana," Gideon called after her. "Do what is right." Gideon watched a million unspoken responses flit behind Liliana's calm demeanor. One surfaced and carried across the square back to him. "I'll do what must be done." Gideon watched the two disappear down a side alley. A low growl from Ajani pulled his attention back to the assembled. "We should support them where we can." Gideon nodded to the leonin. "Ajani's right. If we cause a diversion, maybe we can pull some of Tezzeret's forces onto us." "I think we could do one better." Pia smiled, a grin that grew as she continued talking. "If this is as important as Saheeli says, other targets may be soft to a strike right now. Maybe we don't strike just for a diversion, but strike to capture something we need." "I take it you have a target in mind?" "We take the Aether Hub." Pia's eyes gleamed with excitement. "If we succeed, we could cut off power to the Spire and also to whatever Tezzeret is working on. We would also bring aether to the renegade inventors, to the people. It's a symbolic and material victory." "That sounds good—but if we succeed, there's no doubt Tezzeret and Baan would bring out their biggest weapons to stop us. I've fought battles where we expend our resources capturing that we cannot hold. I don't want to see that happen here." "Oh, the Consulate isn't the only one with powerful inventions on their side." Pia's smile was wide as ever, with a healthy dash of conspiracy. "We've been working on something big. All that's missing is the aether to power it and complete it." "Pardon." Ajani's rough cadence broke into the conversation. "There are sounds a few streets over. They are likely to be Consulate forces—in great numbers." "Let's move then. Mrs. Nalaar and Chandra, mobilize the renegades. Nissa, Jace, and Ajani, with me. We're going to run disruption until the renegades are ready to begin the assault. Hit, run, then disappear. Then when the renegades are ready, with Jace's telepathy and Pia's thopters, we'll coordinate the attack on the Aether Hub." Pia turned to go as the rest of the Planeswalkers moved toward Gideon. Chandra, however, stood still, her arms crossed. "Really, Gids? You're gonna go battle the Consulate and I don't get to come?" Gideon shook his head. "We're supporting Liliana and Saheeli's mission to thwart Tezzeret by creating a distraction." Chandra rolled her eyes in a manner distinctly like Liliana. "Call it what you want. Sounds like blasting some deserving jerks to me." In the distance, the sound of metal gears clanking and the stomp of boots stalked closer. Gideon ignored it, and kept his eyes on Chandra. "We'll need your firepower in the actual attack on the Aether Hub. In the meantime, I'm sure the renegades—and your mom—need your inspiration and presence more." Chandra snuck a look at Pia, who smiled and nodded. She looked back to Gideon, mild panic in her eyes. "Gids. No. No no no. You know I'm bad at the inspiring people thing. With the speeches and the talking." "You'll be brilliant. Just speak from your heart. Or don't speak at all." Gideon smiled, broad, open, honest. "Lead by example. Lead by your strength." Chandra's eyebrows scrunched, a storm of concern, but she shrugged and gave a terse nod, then turned and left with Pia. The sound of approaching Consulate forces was obvious now, and Gideon let his sural hang loose and ready. He watched Ajani spring into a hiding place on the rooftop and noticed Nissa ready her staff, vines already growing and protruding from between the gaps in the cobblestone, while Jace...well, just kind of stood there. And then a shimmer, so fleeting he wasn't sure he saw it. Huh. Mind magic: Gideon would never get quite used to it. "They're there! Stop them!" The shout of a Consulate enforcer broke across the square. Gideon readied his weapon, the telltale glow of light already spreading across his body. Quiet moment over.
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/construct-01.typ
typst
Other
// Test gray color conversion. // Ref: true #stack(dir: ltr, rect(fill: luma(0)), rect(fill: luma(80%)))
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/05-features/shaping/apply.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template // ### Lookup application === 应用#tr[lookup] // Now we have a list of lookups, which each contain rules. These rules are then applied to the glyph stream, lookup by lookup. 完成上面的步骤后,我们手上就有了一个#tr[lookup]的列表,表中的每个#tr[lookup]中都有一些规则。这个列表会逐个#tr[lookup]地进行处理,将其中的规则应用到#tr[glyph]流中。 // I think of the shaping process as being like an old punched-tape computer. (If you know what a Turing machine is, that's an even better analogy.) The input glyphs that are typed by the user are written on the "tape" and then a "read head" goes over the tape cell-by-cell, checking the current lookup matches at the current position. 我认为这种#tr[shaping]流程有点像使用打孔纸带的老式计算机(图灵机会是更好的术语,如果你知道它的话)。这些输入的#tr[glyph]就像是往纸带上打了孔,然后读取头会一格一格的阅读这些纸带,来确定当前的#tr[lookup]是否匹配当前位置的内容。 #figure( caption: [应用#tr[lookup]的流程就像老式打孔纸带计算机], placement: none, include "slide-9.typ" ) // If the lookup matches, the shaper takes the appropriate action (substitution in the cases we have seen so far). It then moves on to the next location. Once it has gone over the whole tape and performed any actions, the next lookup gets a go (we call this "applying" the lookup). 如果当前#tr[lookup]匹配了当前的位置,#tr[shaper]将会执行相应的行动,比如我们之前举例的#tr[glyph]#tr[substitution]。之后(无论是否执行了其中任何规则)读取头就会移动到下一格继续处理这个#tr[lookup]。直到这样逐步处理完整个纸带后,下一个#tr[lookup]才会被选为当前#tr[lookup],纸带也重新回到开头位置,重复这一被称为“应用#tr[lookup]”的过程。 // Notice we have said that the rules are applied lookup by lookup. This is where it becomes important to explicitly arrange our rules into lookups. Consider the difference between this: 请仔细阅读上面的流程,它表示规则是按#tr[lookup]为单位执行的。这一特性就使#tr[lookup]和规则的组织关系变得重要起来。考虑如下两段代码: #let code1 = ```fea feature liga { sub a by b; sub b by c; } liga; ``` #let code2 = ```fea feature liga { lookup l1 { sub a by b; } l1; lookup l2 { sub b by c; } l2; } liga; ``` #figure( placement: none, grid( columns: (1fr, 2fr), column-gutter: 1em, code1, code2, ) ) // How would these features be applied to the glyph stream `c a b b a g e`? 这两个特性引用于#tr[glyph]流 `c a b b a g e` 时会有什么不同呢? // In the first case, *both* rules are considered at each position and the first to match is applied. An `a` is substituted by a `b` and a `b` is substituted by a `c`, so the output would be `c b c c b g e`. 对于左边的代码,这两条规则属于一个#tr[lookup],所以在每个位置上,只有匹配此位置规则会被应用。也就是 `a` #tr[substitution]为 `b`,`b` #tr[substitution]为 `c`。最终的结果为 `c b c c b g e`。 // But in the second case, the first rule is applied at each position - leading to `c b b b b g e` - *and then* the tape is rewound and the second rule is applied at each position. The final output is `c c c c c g e`. 而对于右边的代码,流程是每个位置先检查并应用第一条#tr[lookup]中的规则,这就把#tr[glyph]流变成了 `c b b b b g e`。然后纸带重新回到开头位置,开始在每个位置上处理第二条#tr[lookup]中的规则。最终结果为 `c c c c c g e`。 // In short, rules in separate lookups act in sequence, rules in a single lookup act in parallel. Making your lookups explicit ensures that you get what you mean. 简而言之,在不同#tr[lookup]中的规则会按顺序匹配,在同一#tr[lookup]中的规则会同时进行匹配。明确的写出#tr[lookup]能确保最终的处理结果是符合你期望的。 #note[ // > There is another reason why it's good to put rules explicitly into lookups; in OpenType, there are sixteen different types of rule, and a lookup may only contain rules of the same type. The compiler which packs these rules into the font tries to be helpful and, if there are different types of rule in the same feature, splits them into separate lookups, without telling you. But we have seen that when you split rules into separate lookups, you can end up changing the effect of those rules. This can lead to nasty debugging issues. 推荐将规则明确放入#tr[lookup]中还有另一个原因。在OpenType中有 16 种不同类型的规则,而一个#tr[lookup]中只能含有相同类型的规则。将规则打包进字体的编译器在发现一个特性中有不同类型的规则时,为了更加智能的辅助整个流程,会将它们按类型放入各自独立的#tr[lookup]中。而这一切都是默默发生的。但实际上,改变规则划分为#tr[lookup]的方式实际上会改变其最终效果,这就可能导致一些难以调查的奇怪问题。 ]
https://github.com/NiklasEi/ndc_spin
https://raw.githubusercontent.com/NiklasEi/ndc_spin/main/templates/invoice/template.typ
typst
#import "invoice.typ": * #let input = if sys.inputs.keys().contains("input") {json.decode(sys.inputs.input);} else {json("sample.json");} #show: invoice.with( language: "de", // or "en" banner-image: image(input.banner), invoice-id: input.id, // // Uncomment this to create a cancellation invoice // cancellation-id: "2024-03-24t210835", issuing-date: input.issuingDate, delivery-date: input.deliveryDate, due-date: input.dueDate, biller: input.biller, hourly-rate: 100, // For any items with `dur-min` but no `price` recipient: input.recipient, items: input.items, )
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/grotesk-cv/0.1.3/template/cv.typ
typst
Apache License 2.0
#import "@preview/grotesk-cv:0.1.3": cv #let metadata = toml("info.toml") #let left-pane = ( "profile", "experience", "education", ) #let right-pane = ( "skills", "languages", "other_experience", "references", ) #show: cv.with( metadata, use-photo: true, left-pane: left-pane, right-pane: right-pane, left-pane-proportion: 71%, )
https://github.com/barrel111/readings
https://raw.githubusercontent.com/barrel111/readings/main/notes/discrete-prob.typ
typst
#import "@local/preamble:0.1.0": * #show: project.with( course: "CS", sem: "Summer", title: "Discrete Probability", subtitle: "", ) = Events and Probability == Events Random phenonmenon are observed by means of experiments. Each experiment results in an _outcome_. The collection of all possible outcomes $omega$ is called the _sample space_ $Omega$. Any subset $A subset.eq Omega$ of the sample space $Omega$ can be regarded as a representation of some _event_. #definition( "Indicator Function", )[Let $cal(P)$ be a property that an element $x$ of some set $E$ may or may not satisfy. Then the indicator function for $cal(P)$, $bb(1)_(cal(P)): E arrow {0, 1}$ is defined by $ bb(1)_(cal(P))(x) = cases(1 #h(15pt) &"if" x "satisfies" cal(P)\,, 0 &"otherwise.") $] #example[For any set $A subset.eq Omega$ we may define an indicator function $bb(1)_(A): Omega to {0, 1} $ using the set membership property: $ bb(1)_(A)(omega) = cases(1 #h(15pt) &"if" x in A\,, 0 &"otherwise.") $] We say that an outcome $omega in Omega$ _realizes_ an event $A subset.eq Omega$ if $omega in A$. Two event $A, B subset.eq Omega$ are said to be _incompatible_ if $A sect B = nothing$-- that is, no outcome can realize both $A$ and $B$. We refer to $nothing$ as the _impossible event_. Conversely, we refer to $Omega$ as the _certain event_. For a family of sets ${A_k}_(k in NN)$, we use the notation $sum_(k = 1)^infinity A_k$ to denote $union_(k = 1)^infinity A_k$ if the family is pairwise disjoint. #definition("Exhaustive")[A family of events is _exhaustive_ if any outcome $omega$ realizes at least one of them.] #definition("Mutually Exclusive")[A family of events is _mutually exclusive_ if any two distinct events among them are incompatible.] #definition( "Partition", )[A family of sets ${A_k}$ partition $Omega$ if $ sum_(k = 1)^infinity A_k = Omega. $ In other words, we say that the events ${A_k}$ are _mutually exclusive_ and _exhaustive_. Furthermore, in terms of indicator functions, $ sum_(k = 1)^infinity bb(1)_(A_k) = 1. $] If $B subset.eq A$, event $B$ is said to _imply_ event $A$, because $omega in Omega$ realizes $A$ whenever it realizes $B$. In terms of indicator functions, $ bb(1)_(B)(omega) <= bb(1)_(A)(omega).$ == Probability Probability theory assigns to each event a number, the _probability_ of said event. We require the collection, $cal(F)$, of events to which a probability is assigned to be a $sigma$-field. #definition( $sigma"-field"$, )[Let $cal(F)$ be a collection of subsets of $Omega$ such that + the certain event $Omega$ is in $cal(F)$, + if $A in cal(F)$, then $overline(A) in cal(F)$, + if ${A_k}_(k in NN)$ is a countable collection of sets in $cal(F)$ then $union_(k = 1)^infinity A_k in cal(F).$ Then $cal(F)$ is a _$sigma$-field_ (or _$sigma$-algebra_) on $Sigma$. Here, we may also refer to it as the _$sigma$-field of events_.] #remark[Particularly, $cal(F)$ may not be the collection of all subsets of $Omega$.] The _trivial $sigma$-field_ is the collection of all subsets $2^Omega$ of $Omega$. The _gross $sigma$-field_ is the $sigma$-field of two members ${nothing, Omega}$. Usually, if $Omega$ is countable we take the $sigma$-field of events to be the trivial $sigma$-field. The _probability_ of an event measures the likeliness of its occurence. #definition("Probability Measure")[A _probability_ on $(Omega, cal(F))$ is a mapping $P: cal(F) to RR$ such that + (_non-negativity_) $0 <= P(A) <= 1$, + (_unit measure_) )$P(Omega) = 1$, + (_sigma additivity_) $P(sum_(k = 1)^infinity A_k) = sum_(k = 1)^infinity P(A_k)$.] The triple $(Omega, cal(F), P)$ is called a _probability space_ or _probability model_. #remark[Notationally, we may replace intersection with commas i.e. $P(A, B) = P(A sect B)$.] #remark[One may think of the axioms above as being motivatived by the heuristic interpretation of probability as _emperical frequency_.] Some basic consequences of the axioms above are as follows. #prop[For any event $A in cal(F)$ $ P(overline(A)) = 1 - P(A) $ and in particular, $P(nothing) = 0.$] #proof[Using additivity, $ 1 = P(Omega) = P(A + overline(A)) = P(A) + P(overline(A)). $ By the fact that $P(Omega) = 1$, $P(nothing) = 0$ immediately follows. ] #prop[Probability is _monotone_, that is to say $ A subset.eq B implies P(A) <= P(B). $] #proof[Using subadditivity, $ P(B) = P(A union (B - A)) = P(A) + P(B - A) >= P(A). $] #prop[Probability is sub-$sigma$-additive, that is to say $ P(union.big_(k = 1)^infinity A_k) <= sum_(k = 1)^infinity P(A_k). $] #proof[Using subadditvity and monotonicity, $ P(union.big_(k = 1)^infinity A_k) = P(union.big_(k = 1)^infinity (A_k - union.big_(ell = 1)^(k - 1) A_k)) = sum_(k = 1)^infinity P(A_k - union.big_(ell = 1)^(k - 1) A_k) <= sum_(k = 1)^infinity P(A_k). $] #definition("Negligible")[A set $N subset Omega$ is called _$P$-negligible_ if it is contained in an event $A in cal(F)$ of probability $P(A) = 0$.] #prop[A countable union of negligible sets is a negligible set.] #proof[ Let $N_k$, $k >= 1$, be $P$-negligble sets. By definition, there exists a sequence $A_k$, $k >= 1$ of events of null probability such that $N_k subset.eq A_k$, $k >= 1$. We then have, $ N := union_(k >= 1) N_k subset,eq A := union_(k >= 1) A_k. $ Note that $P(A) = 0$. So, by $sigma$-subadditivity and non-negativity of $P$, $P(N) = 0$.] #definition("Almost Surely")[A property $cal(P)$ relative to the samples $omega in Sigma$ is said to hold _$P$-almost-surely_ ("$P$-a.s.") if $ P({omega; omega "verifies property" cal(P)}) = 1. $] #remark[If there is no ambiguity, we may abbreviate $P$-almost-surely to just almost-surely.] #definition("Non-Decreasing Sets")[A sequence of events ${A_n}_(n >= 1)$ is _non-decreasing_ if $A_n subset.eq A_(n + 1)$ for all $n >= 1$.] #definition("Non-Increasing Sets")[A sequence of events ${A_n}_(n >= 1)$ is _non-decreasing_ if $A_(n + 1) subset.eq A_(n + 1)$ for all $n >= 1$.] #prop[Let ${A_n}_(n >= 1)$ be a non-decreasing sequence of events. Then, $ P(union_(k = 1)^infinity A_n) = lim_(n arrow.t infinity) P(A_n). $ ]<non-dec-events> #proof[ Note that $ A_n = A_1 + (A_2 - A_1) + dots + (A_n - A_(n - 1)) \ union.big_(k = 1)^infinity A_k = A_1 + (A_2 - A_1) + dots + (A_n - A_(n - 1)) $ Thus, $ P(union.big_(k = 1)^infinity A_k) &= P(A_1) + sum_(j = 2)^infinity P(A_j - A_(j - 1) ) \ &= lim_(n arrow.t infinity) { P(A_1) + sum_(j = 2)^n P(A_j - A_(j - 1))} = lim_(n arrow.t infinity) P(A_n). $] #corollary[Let ${B_n}_(n >= 1)$ be a non-increasing sequence of events. Then, $ P(sect.big_(n = 1)^infinity B_n) = lim_(n arrow.t infinity) P(B_n). $] #proof[ Note that ${overline(B_n)}$ is a non-decreasing sequence of events. Thus, by @non-dec-events and De-Morgan's law we have, $ P(sect.big_(n = 1)^infinity B_ n) = 1 - P(union.big_(n = 1)^infinity overline(B_n)) = 1 - lim_(n arrow.t infinity) P(overline(B_n)) = lim_(n arrow.t infinity) (1 - P(overline(B_n))) = lim_(n arrow.t infinity) P(B_n) $] Next, we introduce the $liminf$ and $limsup$ for sets. #definition("Liminf I")[The $liminf$ of a sequence ${A_n}_(n in NN)$ of sets is defined to be $ liminf_(n arrow.t infinity) A_n = union.big_(n = 1)^infinity sect.big_(j >= n) A_j. $] #definition("Limsup I")[The $limsup$ of a sequence ${A_n}_(n in NN)$ of sets is defined to be $ limsup(n arrow.t infinity) A_n = sect.big_(n = 1)^infinity union.big_(j >= n) A_j. $] The following lemma give useful interpretations for these. #lemma[$x in liminf_(n arrow.t infinity) A_n$ iff $x in.not A_n$ for finitely many $n$.] #proof[$x in liminf_(n arrow.t infinity) A_n$ iff $x in sect.big_(j >= n)^infinity A_j$ for some $n in NN$. By definition, the latter is true iff $x in A_j$ for every $j >= n$ i.e. $x in.not A_j$ implies $j <= n$. Thus, $x in.not A_n$ for finitely many $n$.] #remark[For this reason, a shorthand for the limit infimum is "$x$ is in $A_n$ all but finitely often", also expressed as $A_n$ a.b.f.o.] #lemma[$x in limsup_(n arrow.t infinity) A_n$ iff for every $n in NN$, there exists $m >= n$ such that $x in A_m$.] #proof[$x in limsup_(n arrow.t infinity) A_n$ iff $x in union.big_(j >= n) A_j$ for every $n in N$. The latter is true iff $x in A_j$ for some $j >= n$, for every $n in NN$.] #remark[For this reason, a shorthand for the limit supremum is "$x$ is in $A_n$ infinitely often", also expressed as $A_n$ i.o.] We can also define $limsup$ and $liminf$ in terms of indicator functions. #lemma("Liminf II")[The $liminf$ of a sequence ${A_n}_(n in NN)$ of sets is given by $ liminf_(n arrow.t infinity) A_n = {x in Omega bar liminf_(n arrow.t infinity) bb(1)_(A_n)(x) = 1} $] #proof[Note that the indicator function only acquires values in ${1, 0}$. For any $x in Omega$, $liminf_(n arrow.t infinity) bb(1)_(A_n)(x) = 1$ iff $bb(1)_(A_n)(x) < 1$ for finitely many $n in NN$. Thus, $bb(1)_(A_n)(x) = 0$ for finitely many $n in NN$ and $x in.not A_n$ for finitely many $n in NN$ too.] #lemma("Limsup II")[The $limsup$ of a sequence ${A_n}_(n in NN)$ of sets is given by $ limsup_(n arrow.t infinity) A_n = {x in Omega bar limsup_(n arrow.t infinity) bb(1)_(A_n)(x) = 1}. $] #proof[Note that the indicator function only acquires values in ${0, 1}$. For any $x in Omega$, $limsup_(n arrow.t infinity) bb(1)_(A_n)(x) = 1$ iff for every $sup_(j >= n) bb(1)_(A_j)(x) = 1$ for every $n in NN$. The later is true iff there exists $j >= n$ for every $n in NN$ such that $bb(1)_(A_j)(x) = 1$.] #prop("Borel-Cantelli Lemma")[For any sequence of events ${A_n}_(n >= 1),$ $ sum_(k = 1)^infinity P(A_n) < infinity implies P(A_n "i.o.") = 0 $] #proof[ The set $union.big_(k >= n)^infinity A_k$ decreases with $n$. Thus, by sequential continuity of probability, $ P(A_n "i.o.") = P(sect.big_(n = 1)^infinity union.big_(k >= n) A_k) = lim_(n arrow.t infinity) P(union.big_(k >= n) A_k). $ Then, by $sigma$-subadditivity, $ P(union.big_(k >= n) A_k) <= sum_(k >= n)P(A_k). $ By the fact that $sum_(k = 1)^infinity P(A_n) < infinity$, the right hand-side of the inequality goes to $0$ as $n arrow.t infinity$.] #text("Counting Models", weight: "bold", size: 12pt) A common setting is one where the set $Omega$ of all possible outcomes is finite and (for some reason) we are led to believe that all the outcomes $omega$ have the same probability. As the probabilities must sum up to one, each outcome has probability $1/abs(Omega)$. Since the probability of an event $A$ is the sum of the probabilities of all outcomes $omega in A$, we have $ P(A) = abs(A)/abs(Omega). $ In this setting, computing $P(A)$ merely requires _counting_ the elements in the sets $A$ and $Omega$. Now, we review some useful tools that can help with counting. #prop("Stirling's Formula I")[$ n! tilde sqrt(2 pi n) (n/e)^n. $] #prop("Stirling's Formula II")[$ sqrt(2 pi n) (n/e)^n <= n! <= sqrt(2 pi n) (n/e)^n e^(1/(12n)). $] #remark[ For a simpler, cruder bound, $e^(1/(12n)) <= 1.09 < 2$ for all $n in NN$.] We can apply this to estimate the binomial coefficients. #prop[$ binom(n, k) <= ((e n)/k)^k $] #proof[ $ binom(n, k) &= (n(n - 1) dots.c (n - k + 1))/k! \ &<= (n^k)/k! <= n^k/(sqrt(2 pi k) (k/e)^k) <= 1/sqrt(2 pi k) dot ((e n)/k)^k <= ((e n)/k)^k. $ ] == Independence and Conditioning #definition("Independent")[Two events $A$ and $B$ are called _independent_ if $ P(A sect B) = P(A) P(B). $] #definition("Jointly Independent")[A family ${A_n}_(n in NN)$ of events is called independent if for all finite indices $i_1, dots, i_r in NN$, $ P(A_(i_1) sect A_(i_2) sect dots sect A_(i_r)) = P(A_(i_1)) times P(A_(i_2)) times dots.c times P(A_(i_r)). $ One also says that the $A_n$'s are _jointly independent_.] #prop[Suppose that the family of event ${A_n}_(n in NN)$ is independent. Then, so is the family ${tilde(A_n)}_(n in NN)$, where for each $n$, $tilde(A_n) = A_n$ or $overline(A_n)$ (the choice may vary with the index).] #proof[ ] = Random Variables == Probability Distribution and Expectation == Generating Functions == Conditional Expectation = Bounds and Inequalities == The Three Basic Inequalities == Frequently Used Bounds
https://github.com/mattyoung101/uqthesis_eecs_hons
https://raw.githubusercontent.com/mattyoung101/uqthesis_eecs_hons/master/pages/abstract.typ
typst
ISC License
= Abstract In this paper, we present a novel approach to writing a thesis at the University of Queensland. Whereas previous theses were written in LaTeX, they can now be written in Typst. We demonstrate that this creates a 420% improvement in productivity and ease of use. #lorem(100)
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/examples/floating-label-barchart.typ
typst
#import "@preview/cetz:0.2.0" #cetz.canvas({ import cetz.draw: * let data = ( (0, 60), (1, 10), (2,-20), (3, 2), (4, 5), ) let month = ( "Jan", "Feb", "Mar", "Apr", "May" ) // this works set-style( axes: ( grid: ( stroke: blue ), minor-grid: ( stroke: 0.5pt + red ), ) ) // this doesnt actually do anything set-style( mark: (fill: black, scale: 2), stroke: (thickness: 0.4pt, cap: "round"), ) // set-style(axes: (stroke: none, tick: (stroke: none))) cetz.plot.plot(size: (6,6), axis-style: "scientific", y-min: -50, y-max: 75, y-grid: true, x-grid: "minor", y-format: v => [#v%], grid: ( stroke: blue), x-min: -1, x-max: 6, y-tick-step: 15, y-minor-tick-step: 5, x-tick-step: 1, x-minor-tick-step: 0.25, { cetz.plot.add-bar(data, bar-width: .7, style: i => ( stroke: blue, fill: if data.at(i).at(1) >= 0 { green } else { red } )) cetz.plot.annotate({ for (x, y) in data { let k = 1 let anchor = if y >= 0 { "south" } else { k = -1 "north" } content((x, y + k * 2), [*#month.at(x)*], anchor: anchor, padding: .1) } }) }) })
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum_05.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Edge cases. + Empty \ +Nope \ a + 0.
https://github.com/typst-community/valkyrie
https://raw.githubusercontent.com/typst-community/valkyrie/main/src/assertions-util.typ
typst
Other
#let assert-base-type(arg, scope: ("arguments",)) = { assert( "valkyrie-type" in arg, message: "Invalid valkyrie type in " + scope.join("."), ) } #let assert-base-type-array(arg, scope: ("arguments",)) = { for (name, value) in arg.enumerate() { assert-base-type(value, scope: (..scope, str(name))) } } #let assert-base-type-dictionary(arg, scope: ("arguments",)) = { for (name, value) in arg { assert-base-type(value, scope: (..scope, name)) } } #let assert-base-type-arguments(arg, scope: ("arguments",)) = { for (name, value) in arg.named() { assert-base-type(value, scope: (..scope, name)) } for (pos, value) in arg.pos().enumerate() { assert-base-type(value, scope: (..scope, "[" + pos + "]")) } } #let assert-types(var, types: (), default: none, name: "") = { assert( type(var) in (type(default), ..types), message: "" + name + " must be of type " + types.join( ", ", last: " or ", ) + ". Got " + type(var), ) } #let assert-soft(var, condition: () => true, message: "") = { if (var != none) { assert(condition(var), message: message) } } #let assert-positive(var, name: "") = { assert-soft( var, condition: var => var >= 0, message: name + " must be positive", ) } #let assert-positive-type(var, name: "", types: (float, int), default: none) = { assert-types(var, types: types, default: default, name: name) assert-positive(var, name: name) } #let assert-boilerplate-params( default: none, assertions: none, pre-transform: none, post-transform: none, ) = { if (assertions != none) { assert-types(assertions, types: (type(()),), name: "Assertions") } if (pre-transform != none) { assert-types(pre-transform, types: (function,), name: "Pre-transform") } if (post-transform != none) { assert-types(post-transform, types: (function,), name: "Post-transform") } }
https://github.com/donabe8898/typst-report
https://raw.githubusercontent.com/donabe8898/typst-report/main/README.md
markdown
Apache License 2.0
# typst-report シン・おれのレポート環境 usage - typstのドキュメントにすべてを置いてきた
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/spacing-01.typ
typst
Other
// Test spacing collapsing before spacing. #set align(right) A #h(0pt) B #h(0pt) \ A B \ A #h(-1fr) B
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/genealotree/0.1.0/examples/full_example.typ
typst
Apache License 2.0
#import "@preview/genealotree:0.1.0": genealogy-init, add-phenos, add-person, add-persons, add-union, add-unions, draw-tree #import "@preview/cetz:0.2.2": canvas, draw #import draw: * #set page(width: auto, height: auto, margin: .5cm) #set text(size: 11pt) #let my-geneal = genealogy-init() #(my-geneal.config.union-dist = 3.5) #(my-geneal.config.siblings-dist = 4) #(my-geneal.config.union-vline = 2) #(my-geneal.config.person-radius = 1) #let my-geneal = add-phenos(my-geneal, phenos: (hop: green, bim: blue, blop: yellow, slurp: red)) // SubTree1 #let my-geneal = add-person(my-geneal, "I1", sex: "f", alive: false, pheno-label: "S", geno-label: ([$X-S$], [$X-m$])) #let my-geneal = add-person(my-geneal, "I2", sex: "m", alive: false, pheno-label: "S", geno-label: ([$X-S$], [$X-m$])) #let my-geneal = add-person(my-geneal, "II1", sex: "m", pheno-label: "S") #let my-geneal = add-person(my-geneal, "II1*", sex: "f", geno-label: ([$X-S$], [$X-m$]), phenos: ("ill", "bim", "hop")) #let my-geneal = add-person(my-geneal, "II2", sex: "m", pheno-label: "S", geno-label: ([$X-S$], [$X-m$]), phenos: ("ill", "bim", "hop",)) #let my-geneal = add-person(my-geneal, "II2*", sex: "f") #let my-geneal = add-person(my-geneal, "II3*", sex: "m") #let my-geneal = add-persons( my-geneal, ( "II3": ( sex: "f", phenos: ("ill",), pheno-label: "S", geno-label: ([$X-S$], [$X-m$]) ), "III1": (sex: "m"), "III1*": (sex: "f") ) ) #let my-geneal = add-person(my-geneal, "III2", sex: "m") #let my-geneal = add-person(my-geneal, "III3", sex: "f") #let my-geneal = add-person(my-geneal, "III3*", sex: "m") #let my-geneal = add-person(my-geneal, "III4", sex: "f") #let my-geneal = add-person(my-geneal, "III5", sex: "f") #let my-geneal = add-person(my-geneal, "III6", sex: "f") #let my-geneal = add-person(my-geneal, "IV1", sex: "m") #let my-geneal = add-person(my-geneal, "IV2", sex: "f") #let my-geneal = add-person(my-geneal, "IV3", sex: "f") #let my-geneal = add-person(my-geneal, "IV4", sex: "m") #let my-geneal = add-person(my-geneal, "IV5", sex: "f") #let my-geneal = add-person(my-geneal, "IV6", sex: "f") #let my-geneal = add-person(my-geneal, "IV7", sex: "m") #let my-geneal = add-person(my-geneal, "IV8", sex: "f") #let my-geneal = add-person(my-geneal, "IV9", sex: "f") #let my-geneal = add-person(my-geneal, "IV10", sex: "m") #let my-geneal = add-unions( my-geneal, (("I1", "I2"), ("II1", "II2", "II3")), (("II1", "II1*"), ("III1",)) ) // #let my-geneal = add-union(my-geneal, ("I1", "I2"), ("II1", "II2", "II3")) // #let my-geneal = add-union(my-geneal, ("II1", "II1*"), ("III1",)) #let my-geneal = add-union(my-geneal, ("II2", "II2*"), ("III2",)) #let my-geneal = add-union(my-geneal, ("II3", "II3*"), ("III3", "III4", "III5", "III6")) #let my-geneal = add-union(my-geneal, ("III1", "III1*"), ("IV1", "IV2", "IV3", "IV4", "IV5")) #let my-geneal = add-union(my-geneal, ("III3", "III3*"), ("IV6", "IV7", "IV8", "IV9", "IV10")) // SubTree2 #let my-geneal = add-person(my-geneal, "II1r", generation: 2, sex: "m") #let my-geneal = add-person(my-geneal, "II2r", generation: 2, sex: "f") #let my-geneal = add-person(my-geneal, "III1r", sex: "m") #let my-geneal = add-person(my-geneal, "IV1r", sex: "m", phenos: ("hop",)) #let my-geneal = add-person(my-geneal, "IV2r", sex: "m", phenos: ("bim", "hop", "blop", "ill", "slurp")) #let my-geneal = add-union(my-geneal, ("II1r", "II2r"), ("III1r",)) #let my-geneal = add-union(my-geneal, ("III1r", "III6"), ("IV1r", "IV2r")) #canvas(length: 0.5cm, { // Draw the tree draw-tree(my-geneal) })
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/entries/mid_season/driver.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/templates/entries.typ": * #import "/templates/headers.typ": * #import "/templates/text.typ": * #create_default_entry( title: [Driver & Auton Practice], date: [November 18th, 2023], witness: [Juan], design: [Imaad], content: [ #box_header( title: [Driver Practice], color: red.lighten(60%) ) \ #entry_text() First we began with maintenance on the robot. This started with changing the lexan on our intake because it had snapped and needed a replacement. Also reattaching the catapult we took off to fix yesterday. Next, we focused on driver practice with Imaad going around the field and practicing regular driver functions like intaking, scoring, and shooting triballs across the center barrier. #box_header( title: [Auton Practice], color: purple.lighten(60%) ) \ #entry_text() Lastly, we did some auton practice. We used a custom function that calculates the ticks required to travel a distance inputed into the function, which we decided to measure in inches. ```cpp void move_inches( double distance, // distance to move in inches double ticks_per_revolution = TICKS_6_1, // ticks per rotation double wheel = OMNI_4_IN, // 4 inch omni wheels double motor_velocity = VELOCITY_6_1, // velocity of the motor double velocity_coefficient = 0.5) { // speed multiplier double circumference = wheel * M_PI; // distance traveled for each revolution double revolutions = distance / circumference; // required number of revolutions double ticks = ticks_per_revolution * revolutions; // calculate number of ticks double velocity = motor_velocity * velocity_coefficient; // set max speed left_side_motors.move_relative(ticks, velocity); // move left side right_side_motors.move_relative(ticks, velocity); // move right side } ``` ] )
https://github.com/kdog3682/typkit
https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/types.typ
typst
#let RatioObjectArray = ( (fill: "blue", value: 4), (fill: "purple", value: 5), ) #let Integer = 63 #let RatioObjectArray = none #let Integer = none #let ContentString = none #let Array = none #let String = none #let StudentObject = ( grade: 6, name: "<NAME>", ) #let DateObject = ( season: "Autumn", year: 1991, ) #let StudentSessionObject = ( date: DateObject, subject: "Math", topics: ( "ratios", "percentages" ), student: StudentObject, )
https://github.com/0x1B05/nju_os
https://raw.githubusercontent.com/0x1B05/nju_os/main/lecture_notes/content/02_应用视角的操作系统.typ
typst
#import "../template.typ": * #pagebreak() = 应用视角的操作系统 == 汇编代码和最小可执行文件 === 构造最小的 Hello, World “应用程序” ```c int main() { printf("Hello, World\n"); } ``` gcc 编译出来的文件一点也不小 - `objdump` 工具可以查看对应的汇编代码 - `--verbose` 可以查看所有编译选项 (真不少) - `printf` 变成了 `puts@plt` - `-Wl,--verbose` 可以查看所有链接选项 (真不少) - 原来链接了那么多东西 - 还解释了 `end` 符号的由来 - `-static` 会链接 `libc` (大量的代码) `.c`-(cc)->`.i`-(cc)->`.s`-(as)->`.o`-(ld)->`a.out` === 强行构造最小的 Hello, World? 我们可以手动链接编译的文件, 直接指定二进制文件的入口 - 直接用 `ld` 链接失败 - `ld` 不知道怎么链接 `printf` - 不调用 `printf` 可以链接 - 但得到奇怪的警告 (可以定义成 `_start` 避免警告) - 而且 Segmentation Fault 了 - `while (1);` 可以链接并正确运行 问题: 为什么会 Segmentation Fault? - 当然是观察程序的执行了 - 初学者必须克服的恐惧: STFW/RTFM ([ M 非常有用 ](https://sourceware.org/gdb/documentation/)) - `starti` 可以帮助我们从第一条指令开始执行程序 === 解决异常退出 CPU 是无情的执行指令的机器, 有办法让程序 “停下来” 吗? 纯 “计算” 的状态机: 不行 - 没有 “停机” 的指令 - 解决办法: 用一条特殊的指令请操作系统帮忙 ``` movq $SYS_exit, %rax = exit( movq $1, %rdi = status=1 syscall = ); ``` - 把 “系统调用” 的参数放到寄存器中 - 执行 syscall, 操作系统接管程序 - 程序把控制权完全交给操作系统 - 操作系统可以改变程序状态甚至终止程序 === 对一些细节的补充解释 为什么用 gcc 编译? gcc 会进行预编译 (可以使用 *ASSEMBLER* 宏区分汇编/C 代码) ANSI Escape Code 的更多应用 #link("https://git.busybox.net/busybox/tree/editors/vi.c")[ vi.c ] from busybox `dialog --msgbox 'Hello, OS World!' 8 32` `ssh -o 'HostKeyAlgorithms +ssh-rsa' sshtron.zachlatta.com` 更重要的问题: 怎样才能变强? 问正确的问题, 用正确的方式找答案 syscall (2), syscalls (2) -- RTFM & RTFSC Q & A 论坛;Q & A 机器人 === 汇编代码的状态机模型 Everything is a state machine: 计算机 = 数字电路 = 状态机 - 状态 = 内存 M + 寄存器 R - 初始状态 = ABI 规定 (例如有一个合法的 %rsp) - 状态迁移 = 执行一条指令 - 我们花了一整个《计算机系统基础》解释这件事 - gdb 同样可以观察状态和执行 操作系统上的程序 - 所有的指令都只能计算 - deterministic: mov, add, sub, call, ... - non-deterministic: rdrand, ... - syscall 把 (M,R) 完全交给操作系统 `.c`-(cc)->`.i`-(cc)->`.s`-(as)->`.o`-(ld)->`a.out` low level 理解: (M, R)-(取 M[R[pc]], 执行)->次态(M1,R1)-(系统调用,syscall)-> == 理解高级语言程序 你能写一个 C 语言代码的 “解释器” 吗? #tip("Tip")[ gdb 类似于一个 C 语言的解释器 ] 如果能, 你就完全理解了高级语言 和 “电路模拟器”, “RISC-V 模拟器” 类似 实现 gdb 里的 “单步执行” ```c while (1) { stmt = fetch_statement(); execute(stmt); } ``` “解释器” 的例子: 用基础结构模拟函数调用和递归 - 试试汉诺塔吧 递归实现 ```c void hanoi(int n, char from, char to, char via) { if(n==1){ printf("%c -> %c\n",from,to); }else{ hanoi(n-1,from,via,to); hanoi(1,from,to,via); hanoi(n-1,via,to,from); } } ``` 这个问题已经超出了 90% 程序员的能力范围 ChatGPT 竟然改写对了!而且给出了非常优雅 (但也有缺陷) 的实现 ```c void hanoi_non_recursive(int n, char from, char to, char via) { struct Element { int n; char from; char to; char via; }; std::stack<Element> elements; elements.push({n, from, to, via}); while (!elements.empty()) { auto e = elements.top(); elements.pop(); if (e.n == 1) { printf("%c -> %c\n", e.from, e.to); } else { elements.push({e.n - 1, e.via, e.to, e.from}); elements.push({1, e.from, e.to, e.via}); elements.push({e.n - 1, e.from, e.via, e.to}); } } } ``` 当然, ChatGPT 也没能完全理解 === 简单 C 程序的状态机模型 (语义) 对 C 程序做出简化 简化: 改写成每条语句至多一次运算/函数调用的形式 真的有这种工具 ([ C Intermediate Language ](https://cil-project.github.io/cil/)) 和[ 解释器 ](https://gitlab.com/zsaleeba/picoc) 状态机定义 - 状态 = 堆 + 栈 - 初始状态 = main 的第一条语句 - 状态迁移 = 执行一条语句中的一小步 #tip("Tip")[ 这还只是 “粗浅” 的理解 ] Talk is cheap. Show me the code. (<NAME>) 任何真正的理解都应该落到可以执行的代码 状态 - Stack frame 的列表 + 全局变量 初始状态 - 仅有一个 frame: main(argc, argv) ;全局变量为初始值 状态迁移 - 执行 frames.top.PC 处的简单语句 - 函数调用 = push frame (frame.PC = 入口) - 函数返回 = pop frame 然后看看我们的非递归汉诺塔 (更本质), 更正确的实现: ```c #include <assert.h> #include <stdio.h> typedef struct Frame { int pc, n; char from, to, via; } Frame; #define call(...) ({ *(++top) = (Frame){.pc = 0, __VA_ARGS__}; }) #define ret() ({ --top; }) #define goto(loc) ({ f->pc = (loc)-1; }) void hanoi2(int n, char from, char to, char via) { Frame stk[64], *top = stk - 1; call(n, from, to, via); for (Frame *f; (f = top) >= stk; (f->pc)++) { n = f->n; from = f->from; to = f->to; via = f->via; switch (f->pc) { case 0: if (n == 1) { printf("%c -> %c\n", from, to); goto(4); } break; case 1: call(n - 1, from, via, to); break; case 2: call(1, from, to, via); break; case 3: call(n - 1, via, to, from); break; case 4: ret();break; default: assert(0); } } } ``` 从这里看函数状态迁移: - 调用:在栈帧的顶部加个栈帧, pc=0; - 返回:把顶部的栈帧抹除; - 执行:取顶部栈帧的 pc 执行; #tip("Tip")[ 赋值语句, `if` 语句, `goto` 语句这三个就可以改写所有的 C 程序. 这就是编译器! ] == 理解编译器 我们有两种状态机 - 高级语言代码 .c - 状态: 栈, 全局变量;状态迁移: 语句执行 - 汇编指令序列 .s - 状态: (M,R);状态迁移: 指令执行 编译器是二者之间的桥梁: $.s="compile"\(.c\)$ 那到底什么是编译器? 不同的优化级别产生不同的指令序列 凭什么说一个 $.s="compile"(.c)$ 是 “对的” 还是 “错的”? === $.s="compile"(.c)$: 编译正确性 .c 执行中所有*外部观测者可见的行为*, 必须在 .s 中保持一致 - External function calls (链接时确定) - 如何调用由 Application Binary Interface (ABI) 规定 - 可能包含系统调用, 因此不可更改, 不可交换 - 编译器提供的 “不可优化” 标注 - `volatile` [load | store | inline assembly] - Termination - .c 终止当且仅当 .s 终止 *在此前提下, 任何翻译都是合法的* (例如我们期望更快或更短的代码) - 编译优化的实际实现: (context-sensitive) rewriting rules - 代码示例: 观测编译器优化行为和 compiler barrier == 操作系统上的软件 (应用程序) === 操作系统中的任何程序 任何程序 = minimal.S = 调用 syscall 的状态机 可执行文件是操作系统中的对象 与大家日常使用的文件 (a.c, README.txt) 没有本质区别 操作系统提供 API 打开, 读取, 改写 (都需要相应的权限) 查看可执行文件 vim, cat, xxd 都可以直接 “查看” 可执行文件 vim 中二进制的部分无法 “阅读”, 但可以看到字符串常量 使用 `xxd` 可以看到文件以 "\x7f" "ELF" 开头 Vscode 有 binary editor 插件 === 系统中常见的应用程序 Core Utilities (coreutils) - Standard programs for text and file manipulation - 系统中安装的是 #link("https://www.gnu.org/software/coreutils/")[ GNU Coreutils ] - 有较小的替代品 #link("https://www.busybox.net/")[ busybox ] 系统/工具程序 bash, #link("https://www.gnu.org/software/binutils/")[ binutils ], apt, ip, ssh, vim, tmux, jdk, python, ... 这些工具的原理不复杂 (例如 apt 是 dpkg 的套壳), 但琐碎 [ Ubuntu Packages ](https://packages.ubuntu.com/) (和 apt-file 工具) 支持文件名检索 其他各种应用程序 Vscode, 浏览器, 音乐播放器…… === 打开程序的执行: Trace (追踪) 如果知道程序和操作系统的交互, 就可以勾勒出程序运行所有的轮廓. In general, trace refers to the process of following anything from the beginning to the end. For example, the traceroute command follows each of the network hops as your computer connects to another computer. 这门课中很重要的工具: strace - System call trace(打印出所有的系统调用) - 允许我们观测状态机的执行过程 - Demo: 试一试最小的 Hello World - 在这门课中, 你能理解 strace 的输出并在你自己的操作系统里实现相当一部分系统调用 (mmap, execve, ...) strace 是一个非常重要的命令行工具, 帮助我们 “观测” 应用程序和操作系统的边界.实际上, 任何程序的执行就是状态机在计算机上的运行, 因此 “用合适的方式观测状态机执行” 就是我们理解程序的根本方法.调试器, trace, profiler 提供了不同侧面的理解手段, 这三个工具将会在课程中反复出现. 如果你感到 strace 的结果不那么友善, 用适当的工具处理它就非常重要了.课堂上我们展示了用命令行工具进行处理的 “传统方法”: ```sh ❯ strace ls |& grep -e read -e write ``` 可以实现系统调用的过滤等. === 操作系统中 “任何程序” 的一生 任何程序 = minimal.S = 调用 syscall 的状态机 - 被操作系统加载 - 通过另一个进程执行 execve 设置为初始状态 - 状态机执行 - 进程管理: fork, execve, exit, ... - 文件/设备管理: open, close, read, write, ... - 存储管理: mmap, brk, ... - 调用 `_exit (exit_group)` 退出 (初学者对这一点会感到有一点惊讶) - 说好的浏览器, 游戏, 杀毒软件, 病毒呢?都是这些 API 吗? - 我们有 strace, 就可以自己做实验了! === 动手实验: 观察程序的执行 工具程序代表: 编译器 (gcc) - 主要的系统调用: `execve`, `read`, `write` - `strace -f gcc a.c` (gcc 会启动其他进程) - 可以管道给编辑器 `vim -` - `:set nowrap` - 编辑器里还可以 `%!grep` (细节/技巧):`%!grep execve`,`%!grep -e execve -e open`, `%!grep -v ENOENT` - `:%s/, /\r/g`, 可以清晰地看到参数 图形界面程序代表: 编辑器 (`xedit`) - 主要的系统调用: `poll`, `recvmsg`, `writev` - `strace xedit` - 图形界面程序和 X-Window 服务器按照 X11 协议通信 - 虚拟机中的 xedit 将 X11 命令通过 ssh (X11 forwarding) 转发到 Host > 系统里面只有一个程序有访问屏幕的权限, 其他的程序都会跟这个程序通信来进行屏幕的操作 === 各式各样的应用程序 都在操作系统 API (syscall) 和操作系统中的对象上构建 - 窗口管理器 - 管理设备和屏幕 (read/write/mmap) - 进程间通信 (send, recv) - 任务管理器 - 访问操作系统提供的进程对象 (readdir/read) - 参考 gdb 里的 `info proc *` - 杀毒软件 - 文件静态扫描 (read) - 主动防御 (ptrace) - 其他更复杂的安全机制…… == 编程实践 === minimal ==== demo01 hello.c ```c #include <stdio.h> int main() { printf("hello world!"); } ``` #tip("Tip")[ C 在没有显式`return`的时候会默认`return 0` ] ```sh ❯ gcc hello.c ❯ file a.out a.out: ELF 64-bit LSB pie executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=c2dcf81554e16f44aa79827b6fcb46af0 f7feb1c, for GNU/Linux 3.2.0, not stripped ``` #tip("Tip")[ `file`可以帮忙猜一个文件是什么. ] `objdump -d a.out`查看反汇编, 发现其实不多, 还发现把`printf`优化成了`puts@plt`, 省了一个换行.`puts`函数真正的实现是在 libc 语言的标准库里. `gcc -static hello.c`发现 好长! `gcc -static --verbose hello.c`可以查看到很多有用的信息 `gcc -static -Wl,--verbose hello.c`可以打印出 gcc 的链接选项. 有关`Wl`: `-Wl` 是 GCC 编译器的一个选项, 用于向链接器 (ld) 传递参数. 在 `-Wl` 后面, 可以跟随一个`,`和一系列要传递给链接器的参数.每个参数必须以逗号分隔.这些参数会被直接传递给链接器, 影响链接器的行为和生成的可执行文件. 常见的使用情况包括: - 指定连接器使用的库路径: 可以使用 `-Wl,-L` 参数指定链接器要搜索的库文件路径.例如, `-Wl,-L/usr/local/lib` 将告诉链接器在 `/usr/local/lib` 路径下搜索库文件. - 指定连接器链接的库: 使用 `-Wl,-l` 参数来指定链接器要链接的库.例如, `-Wl,-lmylib` 将告诉链接器链接名为 `mylib.so` 或 `mylib.a` 的库文件. - 指定连接器的其他选项: 除了库路径和库名称之外, 还可以使用 `-Wl` 将其他选项传递给链接器.例如, `-Wl,--no-as-needed` 将禁用链接时的需要性检查. ==== demo02 直接强行走一遍流程: hello.c ```c int main() { printf("hello world!"); } ``` ```sh ❯ gcc -c hello.c ....(一些warning) ❯ objdump -d hello.o hello.o: file format elf64-x86-64 Disassembly of section .text: 0000000000000000 <main>: 0: f3 0f 1e fa endbr64 4: 55 push %rbp 5: 48 89 e5 mov %rsp,%rbp 8: 48 8d 05 00 00 00 00 lea 0x0(%rip),%rax = f <main+0xf> f: 48 89 c7 mov %rax,%rdi 12: b8 00 00 00 00 mov $0x0,%eax 17: e8 00 00 00 00 call 1c <main+0x1c> 1c: b8 00 00 00 00 mov $0x0,%eax 21: 5d pop %rbp 22: c3 ret ❯ ld hello.o ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000 ld: hello.o: in function `main': hello.c:(.text+0x18): undefined reference to `printf' ``` ```c int main() {} ``` ```sh ❯ gcc -c hello.c ❯ objdump -d hello.o hello.o: file format elf64-x86-64 Disassembly of section .text: 0000000000000000 <main>: 0: f3 0f 1e fa endbr64 4: 55 push %rbp 5: 48 89 e5 mov %rsp,%rbp 8: b8 00 00 00 00 mov $0x0,%eax d: 5d pop %rbp e: c3 ret ❯ ld hello.o ld: warning: cannot find entry symbol _start; defaulting to 0000000000401000 ❯ ld hello.o -e main ❯ objdump -d a.out a.out: file format elf64-x86-64 Disassembly of section .text: 0000000000401000 <main>: 401000: f3 0f 1e fa endbr64 401004: 55 push %rbp 401005: 48 89 e5 mov %rsp,%rbp 401008: b8 00 00 00 00 mov $0x0,%eax 40100d: 5d pop %rbp 40100e: c3 ret ❯ ./a.out [1] 2048 segmentation fault ./a.out ``` 得到"最小"的 C 程序, 但是运行会有 segmentation fault. 有关`ld`的`-e`(entry symbol)选项: 链接可执行文件时, 使用 `-e` 可以告诉链接器将程序的控制权设置为指定的符号所在的地址, 从而作为程序的起始点. 在命令 `ld hello.o -e main` 中, `-e main` 的作用是将程序的入口点设置为 `main` 函数所在的地址, 程序将从 `main` 函数开始执行. ```c int main(){while(1);} ``` 重复上面操作发现死循环可以正常执行 现在用 gdb 来调试, 使用 `starti` ```sh (gdb) starti Program stopped. 0x0000000000401000 in main () ...(layout asm, info registers) > 0x401000 <main> endbr64 0x401004 <main+4> push %rbp 0x401005 <main+5> mov %rsp,%rbp 0x401008 <main+8> mov $0x0,%eax 0x40100d <main+13> pop %rbp 0x40100e <main+14> ret (gdb) si 0x0000000000401004 in main () 0x0000000000401005 in main () 0x0000000000401008 in main () 0x000000000040100d in main () 0x000000000040100e in main () (gdb) p $rsp $1 = (void *) 0x7fffffffe4c0 (gdb) x $rsp 0x7fffffffe4c0: 0x00000001 (gdb) si 0x0000000000000001 in ?? () ``` 破案了, `rsp` 存储了当前线程的堆栈顶部的地址.这里弹出了一个非法的地址, 寄! #tip("Tip")[ - RBP(Base Pointer): 栈底指针. - RSP(Stack Pointer): 栈顶指针. - EAX: 通用寄存器.一个 32 位的寄存器, 经常用于存储函数的返回值或临时变量. ] ==== demo03 minimal.S ```c #include <sys/syscall.h> .globl _start _start: movq $SYS_write, %rax // write( movq $1, %rdi // fd=1, movq $st, %rsi // buf=st, movq $(ed-st), %rdx // count=ed-st syscall // ); movq $SYS_exit, %rax // exit( movq $1, %rdi // status=1, syscall // ); st: .ascii "\033[01;31mHello, OS World\033[0m\n" ed: ``` ```sh ❯ gcc -c minimal.S ❯ ld minimal.o ❯ ./a.out Hello, OS World ``` 把 `minimal` 对应的 `a.out` 使用 vim 打开 然后`:%!xxd` 这也是一个命令行哲学, 举例: ``` 1 2 1 1 22 2 3 1 1 ``` 想要把 1 留下, 其余的删掉.`:%!grep 1` === hanoi 给了 chatgpt 一个更难的题, 翻车了 (思路基本正确, 但不再优雅) ```c int f(int n) { if (n <= 1) return 1; return f(n - 1) + g(n - 2); } int g(int n) { if (n <= 1) return 1; return f(n + 1) + g(n - 1); } ``` (你们会写这个的非递归吗, 提示, pc 可以带 f 和 g 的, 一个`f.0`, 一个`g.1`) 先看看汇编代码 ``` f_g.o: file format elf64-x86-64 Disassembly of section .text: 0000000000000000 <f>: 0: f3 0f 1e fa endbr64 4: 55 push %rbp 5: 48 89 e5 mov %rsp,%rbp 8: 53 push %rbx 9: 48 83 ec 18 sub $0x18,%rsp d: 89 7d ec mov %edi,-0x14(%rbp) 10: 83 7d ec 01 cmpl $0x1,-0x14(%rbp) 14: 7f 07 jg 1d <f+0x1d> 16: b8 01 00 00 00 mov $0x1,%eax 1b: eb 1e jmp 3b <f+0x3b> 1d: 8b 45 ec mov -0x14(%rbp),%eax 20: 83 e8 01 sub $0x1,%eax 23: 89 c7 mov %eax,%edi 25: e8 00 00 00 00 call 2a <f+0x2a> 2a: 89 c3 mov %eax,%ebx 2c: 8b 45 ec mov -0x14(%rbp),%eax 2f: 83 e8 02 sub $0x2,%eax 32: 89 c7 mov %eax,%edi 34: e8 00 00 00 00 call 39 <f+0x39> 39: 01 d8 add %ebx,%eax 3b: 48 8b 5d f8 mov -0x8(%rbp),%rbx 3f: c9 leave 40: c3 ret 0000000000000041 <g>: 41: f3 0f 1e fa endbr64 45: 55 push %rbp 46: 48 89 e5 mov %rsp,%rbp 49: 53 push %rbx 4a: 48 83 ec 18 sub $0x18,%rsp 4e: 89 7d ec mov %edi,-0x14(%rbp) 51: 83 7d ec 01 cmpl $0x1,-0x14(%rbp) 55: 7f 07 jg 5e <g+0x1d> 57: b8 01 00 00 00 mov $0x1,%eax 5c: eb 1e jmp 7c <g+0x3b> 5e: 8b 45 ec mov -0x14(%rbp),%eax 61: 83 c0 01 add $0x1,%eax 64: 89 c7 mov %eax,%edi 66: e8 00 00 00 00 call 6b <g+0x2a> 6b: 89 c3 mov %eax,%ebx 6d: 8b 45 ec mov -0x14(%rbp),%eax 70: 83 e8 01 sub $0x1,%eax 73: 89 c7 mov %eax,%edi 75: e8 00 00 00 00 call 7a <g+0x39> 7a: 01 d8 add %ebx,%eax 7c: 48 8b 5d f8 mov -0x8(%rbp),%rbx 80: c9 leave 81: c3 ret ``` ```c typedef enum { FUNC_F, FUNC_G } FuncType; typedef struct Frame { int pc, n, retVal; FuncType funcType; } Frame; #define call(func, arg) \ ({ *(++top) = (Frame){.pc = 0, .n = (arg), .funcType = (func)}; }) #define ret(value) \ ({ \ top->retVal = (value); \ --top; \ }) #define goto(loc) ({ f->pc = (loc)-1; }) int main(int argc, char *argv[]) { Frame stk[128], *top = stk - 1; int f_result = 0, g_result = 0; call(FUNC_F, 5); // Example: f(5) for (Frame *f; (f = top) >= stk; (f->pc)++) { int n = f->n; FuncType funcType = f->funcType; // int retVal = f->retVal; if (funcType == FUNC_F) { switch (f->pc) { case 0: if (n <= 1) { ret(1); goto(3); } break; case 1: call(FUNC_F, n - 1); break; case 2: call(FUNC_G, n - 2); break; case 3: ret((f - 1)->retVal + f->retVal); break; default: assert(0); } } else if (funcType == FUNC_G) { switch (f->pc) { case 0: if (n <= 1) { ret(1); goto(3); } break; case 1: call(FUNC_F, n + 1); break; case 2: call(FUNC_G, n - 1); break; case 3: ret((f - 1)->retVal + f->retVal); break; default: assert(0); } } } f_result = stk[0].retVal; printf("f2(5) = %d\n", f_result); // Output should be f(5) return 0; } ``` === compiler ```c void spin_1() { int i; for (i = 0; i < 100; i++) { // Empty loop body } } void spin_2() { volatile int i; for (i = 0; i < 100; i++) { // Empty loop body } } int return_1() { int x; for (int i = 0; i < 100; i++) { // Compiler will assign [%0] an assemebly asm("movl $1, %0" : "=g"(x)); // x=1 } return x; } int return_1_volatile() { int x; for (int i = 0; i < 100; i++) { // Compiler will assign [%0] an assemebly asm volatile("movl $1, %0" : "=g"(x)); // x=1 } return x; } int foo(int *x) { *x = 1; *x = 1; return *x; } void external(); int foo_func_call(int *x) { *x = 1; external(); *x = 1; return *x; } int foo_volatile1(int volatile *x) { *x = 1; *x = 1; return *x; } int foo_volatile2(int *volatile x) { *x = 1; *x = 1; return *x; } int foo_barrier(int *x) { *x = 1; asm("" : : : "memory"); // 空的汇编, 它可以把所有的内存都改掉 *x = 1; return *x; } ``` === strace ```sh ❯ strace ./a.out execve("./a.out", ["./a.out"], 0x7fff2fa08dd0 /* 59 vars */) = 0 write(1, "\33[01;31mHello, OS World\33[0m\n", 28Hello, OS World ) = 28 exit(1) = ? +++ exited with 1 +++ ``` ```sh ❯ strace -f gcc hello.c &| vim - ``` `:%!grep execve`, `:%!grep -v ENOENT`, `:%s/, /,\r/g`处理过后: ``` execve("/usr/bin/gcc", ["gcc", "hello.c"], 0x7ffecbcd1e10 /* 69 vars */) = 0 execve("/usr/lib/gcc/x86_64-linux-gnu/11/cc1", ["/usr/lib/gcc/x86_64-linux-gnu/11"..., "-quiet", "-imultiarch", "x86_64-linux-gnu", "hello.c", "-quiet", "-dumpd execve("/usr/bin/as", ["as", "--64", "-o", "/tmp/ccrL6MYD.o", "/tmp/ccbvDLa4.s"], 0x68b5c0 /* 74 vars */ <unfinished ...> execve("/usr/lib/gcc/x86_64-linux-gnu/11/collect2", ["/usr/lib/gcc/x86_64-linux-gnu/11"..., "-plugin", "/usr/lib/gcc/x86_64-linux-gnu/11"..., "-plugin-opt=/usr/ execve("/usr/bin/ld", ["/usr/bin/ld", "-plugin", "/usr/lib/gcc/x86_64-linux-gnu/11"..., "-plugin-opt=/usr/lib/gcc/x86_64-"..., "-plugin-opt=-fresolution=/tmp/cc ``` #tip("Tip")[ 发现把所有中间结果 都输出到了临时文件里面. ] == 阅读材料 decode core utils:https://www.maizure.org/projects/decoded-gnu-coreutils/ binutils:https://www.gnu.org/software/binutils/ gdb: https://sourceware.org/gdb/current/onlinedocs/gdb.html/ === gdb reverse execution 需要实践一下 process record and replay: https://sourceware.org/gdb/current/onlinedocs/gdb.html/Process-Record-and-Replay.html#Process-Record-and-Replay running programs backward: https://sourceware.org/gdb/current/onlinedocs/gdb.html/Reverse-Execution.html#Reverse-Execution === tui https://sourceware.org/gdb/current/onlinedocs/gdb.html/TUI.html#TUI
https://github.com/EliasRothfuss/vorlage_typst_doku-master
https://raw.githubusercontent.com/EliasRothfuss/vorlage_typst_doku-master/main/chapter/umsetzung.typ
typst
= Umsetzung und Ergebnisse <cha:umsetzung> Je nach Art der Arbeit kann diese Kapitelüberschrift auch Ergebnisse~lauten, z.~B. bei rein messtechnischen Aufgaben. Beschreibung der Umsetzung des zuvor gewählten Vorgehens (theoretische Untersuchung, Erhebungen, Durchführung von Experimenten, Prototypenaufbau, Implementierung eines Prozesses, etc.). Verifikation anhand der zuvor erarbeiteten Anforderungen und Validierung in Bezug auf das zuvor gestellte Ziel. Diskussion der Ergebnisse. Spätestens hier auch auf die Zuverlässigkeit der gewonnenen Erkenntnisse eingehen (z.~B. anhand der Genauigkeit von Messergebnissen).
https://github.com/gym-8/solving-physics
https://raw.githubusercontent.com/gym-8/solving-physics/master/README.md
markdown
MIT License
# Installation The easiest method is to import `solving-physics: task` from the `@preview` package: ```typ #import "@preview/solving-physics:0.1.0": * ``` # Usage ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ ], find: [ $F$ --- ? ], fig: image("./example.png", width: 5cm) )[ #lorem(100) ] ``` ![usage](./examples/example1.png) # Stroke ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ ], find: [ $F$ --- ? ], stroke: "full" )[] ``` ![full stroke](./examples/example2.svg) ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ ], find: [ $F$ --- ? ], stroke: "find" )[] ``` ![find stroke](./examples/example3.svg) ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ ], find: [ $F$ --- ? ], stroke: none )[] ``` ![none stroke](./examples/example4.svg) # Given width If you have so large given you may use `given-width`: ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ \ #lorem(10) ], given-width: 6em, find: [ $F$ --- ? ], )[] ``` ![Given width](./examples/example5.svg) # Figure align You may locate you figure on the center of body by `fig-align: top + center` ```typ #task( given: [ $mu = 0.4$ \ $g = 10$ \ $m = 20$ ], find: [ $F$ --- ? ], fig: image("./example.png", width: 60%), fig-align: top + center )[ #lorem(100) ] ``` ![Figure align](./examples/example6.png)
https://github.com/Mufanc/hnuslides-typst
https://raw.githubusercontent.com/Mufanc/hnuslides-typst/master/templates/cover.typ
typst
#import "/configs.typ" #import "/utils/colors.typ" #import "/utils/fonts.typ": font #import "/utils/background.typ": bgimage #let square-block(content) = { let font-size = 35pt let square-size = font-size * 1.2 let frame-color = colors.primary.transparentize(40%) let frame = pattern(size: (square-size, square-size))[ #place( line(start: (0%, 50%), end: (100%, 50%), stroke: (paint: frame-color, thickness: 1pt, dash: "dashed")) ) #place( line(start: (50%, 0%), end: (50%, 100%), stroke: (paint: frame-color, thickness: 1pt, dash: "dashed")) ) ] set text(font: font.GYGK, size: font-size, fill: colors.primary) show regex("."): ch => { box( width: square-size, height: square-size, fill: frame, stroke: 1pt + frame-color, place(center + horizon, ch) ) h(0.2em) } content } #let cover(annotation, title, presenter) = { bgimage("/assets/images/bg-cover.png") place(bottom, dy: -25%)[ #text(fill: colors.primary,annotation) #v(-2.5em) #square-block(text(title)) #v(-2.5em) #text(font: font.FZKT, presenter) ] pagebreak() }
https://github.com/DashieTM/ost-5semester
https://raw.githubusercontent.com/DashieTM/ost-5semester/main/blockchain/weeks/week10.typ
typst
#import "../../utils.typ": * #section("Monero") - not really traceable - senders and receivers are obscure - ring signatures and stealth addresses - focus on privacy - decentralized - launched in 2014 as a fork of bytecoin - hard forks usually each 6 months - hard forks usually to improve privacy,efficiency,etc. -> ring confidential transactions (RingCT) or bulletproofs - Proof of work - Uses RandomX, a PoW algorithm optimized for CPUs, resistance to ASIC mining #subsection("XMR (A single monero coin)") - key features - ring signatures - mix a users account keys with public keys from the blockchain -> impossible to identify sender - fungibility: Monero coin is interchangeable and indistinguishable from another - adaptive block size limit: Unlike bitcoin, monero has no predefined block size limit - criticism - intractability also means illegal activities can't be traced - good for guaranteeing freedom - bad as it gives harder crimes(homocide etc.) a way to use money without risk - regulations essentially impossible #subsection("Differences to other currencies") - dynamic max block size instead of limited blocksize like bitcoin - privacy features can lead to larger transactions - fungibility -> can't create tainted coins like with bitcoin #subsection("Ring Signatures") - conceal sender by mixing in public addresses of transactions - outside observers can't tell which user initiated transaction #subsection("Bulletproofs") - non-interactive, zero-knowledge proof, to prove a number (transaction amount) without revealing it - e.g. hide transaction amount - reduce transaction size(and hence fees) and improve speed #subsection("Stealth Addresses") - one-time addresses, generated randomly for each transaction on behalf of the recipient - ensures destination of transaction remains hidden - combination of the sender's, the recipient's public keys and random data - made in a way that the transactions can only be found with the recipient's private keys #subsection("Kovri") - Similar to TOR, but focus on creating an anonymous internal network #section("Cross-chain Atomic Swaps") You can of course simply use a central exchange, but here is the problem that you don't actually own the tokens, you own them indirectly with you owning a value on the exchange.\ The problem here is that when the exhange goes down, you are fucked, aka your money is gone. Also, you can never ensure what the exchange is doing is 100% fair.\ So what is the solution? Atomic swaps, simply remove the exchange as a midle-man. #align( center, [#image("../../Screenshots/2023_11_20_03_24_12.png", width: 70%)], ) #subsection("Swapping over hash") The idea is that you hash a secret and store it in a smart contract. This smart contract can the only be unlocked(hash lock) if the same secret is provided, or rather if the same hash is provided. E.g. we put our coins into the smart contract with the hash and unlock it when we both accept the transaction -> you get my btc and i get your monero or whatever you want to swap. #align( center, [#image("../../Screenshots/2023_11_20_03_38_02.png", width: 100%)], ) #text( teal, )[Important: Since this requires the transaction to be atomic, we need a way to reverse the transaction, hence we provide a timeout for the smart contract to automatically reverse.] #align( center, [#image("../../Screenshots/2023_11_20_03_40_36.png", width: 100%)], ) #subsubsection("Example") #align( center, [#image("../../Screenshots/2023_11_20_03_46_11.png", width: 100%)], ) #text( teal, )[Note, both blockchains have their own smart contract! E.g. both can specify their timeout themselves. You essentially have to create a smart contract when you want to trade with another existing smart contract (aka the offer here from alice).] #subsubsection("Worst Case Problem") One problem exists with this method, since we have 2 smart contracts, both parties need to access their secret that was provided by the other party, if they don't, then the smart contract of the other party automatically expires, e.g. the other party gets their money back and you in this case get nothing... #align( center, [#image("../../Screenshots/2023_11_20_03_55_56.png", width: 100%)], ) #subsection("Hashed Time Lock Contracts") Essentially the stuff above but put into a "term". #align( center, [#image("../../Screenshots/2023_11_20_03_45_24.png", width: 100%)], ) #subsection("Scalability Issues") - on-chain solutions - sharding: distribute storage - protocol improvements - off-chain solutions - state channels(payment channels) - lightning network - sidechains/blockchain interoperability #subsection("Direct Payment Channel with 2-of-2 Multisig Contracts") #text( teal, )[This essentially solves the issue from before where bob goes offline. However, this requires a payment channel! Aka might not work on swapping!] #align( center, [#image("../../Screenshots/2023_11_20_04_06_10.png", width: 50%)], ) #align( center, [#image("../../Screenshots/2023_11_20_04_06_33.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_11_20_04_09_18.png", width: 100%)], ) #subsection("Indirect Payment Channel with HTLC") Send btc from alice to charlie with bob as middle-man: #align( center, [#image("../../Screenshots/2023_11_20_04_10_16.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_11_20_04_11_02.png", width: 100%)], ) #align( center, [#image("../../Screenshots/2023_11_20_04_11_17.png", width: 60%)], )
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/.github/ISSUE_TEMPLATE/BUG_REPORT.md
markdown
The Unlicense
--- name: Bug Report about: Report a bug in the project title: "🐛" labels: "repro:required" assignees: "" --- #### Expected Behavior <!-- Concisely describe the behavior you expected --> #### Observed Behavior <!-- Concisely describe the behavior you observed --> #### Steps to Reproduce <!-- Provide a link to a live example, or an unambiguous set of steps to reproduce this bug. Include code to reproduce, if relevant --> #### Environment <!-- Please provide the following information --> - Typst Version: - Notebookinator Version: - Operating System: #### Additional Information <!-- Add any other relevant information about the problem here --> <!-- This includes screenshots, code snippets, videos, anything you think is relevant -->
https://github.com/PraneethJain/Science-1
https://raw.githubusercontent.com/PraneethJain/Science-1/main/Assignment-1/2022101093_Assignment_1.typ
typst
#align(center, text(17pt)[*Science-1*]) #align(center, text(16pt)[Assignment-1]) #align(center, text(13pt)[<NAME>, 2022010193]) = Question 1 #let n = 4 #let average_pace = 1.42 == (a) $n approx #n$ == (b) Average pace of a human is $v = 1.4 m/s$ Assuming the distance to travel is $d = #n * 100 = #calc.abs(n*100) m$ $v = d / t$ $#average_pace = #calc.abs(n*100) / t$ $t = #calc.abs(n*100) / #average_pace$ #let t = calc.round(100*n/average_pace) $t approx #t s$ The time required is approximately #calc.floor(t/60) minutes and #calc.rem(t, 60) seconds #let drift_velocity = 2.3 * calc.pow(10, -5) == (c) Assuming the drift velocity of an electron on average is #drift_velocity $m/s$ Assuming the distance to travel is $d = #n * 100 = #calc.abs(n*100) m$ $v = d / t$ $#drift_velocity = #calc.abs(n*100) / t$ #let t_2 = calc.round(100*n/drift_velocity) $t approx #t_2 s$ The time required is approximately #calc.floor(t_2/60/60/24) days and #calc.rem(calc.floor(t_2/60/60), 24) hours #let electron_speed = 2.18 * calc.pow(10, 6) #let circumference = 3.322 * calc.pow(10, -10) == (d) Speed of electron in ground state of hydrogen atom = $#electron_speed m/s$ $v = d / t$ $#electron_speed = d / #t_2$ #let d = electron_speed * t_2 $d = #d m$ Circumference of first bohr orbit in hydrogen = #circumference #let rounds = d / circumference Number of rounds = $d / "circumference"$ = $#d / #circumference$ = #rounds rounds == (e) #let area = 15e-6 #let resistivity = 1.724e-8 Assuming standard copper wires with $rho = #resistivity "ohm m"$ and area $A = #area m^2$ #let resistance = calc.round(resistivity * (n * 100) / area, digits: 2) $R = rho l / A$ = #resistance $ohm$ #let current = 5 Assuming a current of #current A #let power = current*current*resistance Power $P = I^2 R$ = #power W #pagebreak() = Question 2 == (i) Consider a spring mass system performing SHM with total energy $E$ $"PE" + "KE" = "E"$ $1/2 k x^2 + 1/2 m v^2 = E$ This is an equation of ellipse. Varying total energy will result in concentric ellipses #figure( image("SHM.png") ) == (ii) Consider a system with anharmonic oscillations with the following potential graph #figure( image("AHM_1.png") ) The phase space trajectories for each of the total energies would be #figure( image("AHM_2.png") ) #pagebreak() = Question 3 The logistic map $x_(n+1) = alpha x_n (1 - x_n)$ is usually studied for the growth parameter, $alpha$, in the range $0 lt.eq alpha lt.eq 4$. This is because $forall alpha gt 4$, the values taken by $x$ diverge. For $alpha$ lying within the range, the logistic map yields very interesting results like converging to one value, or even converging to two values (oscillating between the two), and some phenomenon like period doubling can be observed. Due to such properties, it is usually studied within this range. == Python code to plot logistic map ```python import matplotlib.pyplot as plt def step(x: float, alpha: float) -> float: return alpha * x * (1 - x) def generate(x0: float, alpha: float, generations: int = 50) -> list[float]: result = [x0] * generations for i in range(1, generations): result[i] = step(result[i - 1], alpha) return result if __name__ == "__main__": plt.plot(generate(x0=0.1, alpha=0.8), label=r"$x_0 = 0.1, \alpha=0.8$") plt.plot(generate(x0=0.1, alpha=1.5), label=r"$x_0 = 0.1, \alpha=1.5$") plt.plot(generate(x0=0.5, alpha=1.5), label=r"$x_0 = 0.5, \alpha=1.5$") plt.plot(generate(x0=0.5, alpha=0.8), label=r"$x_0 = 0.5, \alpha=0.8$") plt.plot(generate(x0=0.001, alpha=3.2), label=r"$x_0 = 0.001, \alpha=3.2$") plt.xlabel("Time") plt.ylabel("Population") plt.legend() plt.savefig("plot.png") ``` #figure( image("plot.png", height: 40%) ) #pagebreak() = Question 4 $ P(N|n) = binom(N, n) p^n q^(N-n) "where" p+q=1, p>=0, q>=0 $ $ P(N|n) = N! / (n!(N-n)!) p^n q^(N-n) $ $ ln(P(N|n)) = ln(N!) - ln(n!) - ln((N-n)!) + n ln(p) + (N-n) ln(q) $ Using Stringling approximation ($ln(N!) = N ln(N) - N$) $ ln(P(N|n)) approx N ln(N) - N - (n ln(n) - n) - ((N-n) ln(N-n) - (N-n)) + n ln(p) + (N-n) ln(q) $ $ ln(P(N|n)) = N ln(N) - N - n ln(n) + n - (N-n) ln(N-n) + (N-n) + n ln(p) + (N-n) ln(q) $ $ ln(P(N|n)) = N ln(N) - n ln(n) - (N-n) ln(N-n) + n ln(p) + (N-n) ln(q) $ Let $ln(P(N|x)) = f(x) $ $ f(x) = N ln(N) - x ln(x) - (N-x) ln(N-x) + x ln(p) + (N-x) ln(q)$ $ f^1 (x) = -1 - ln(x) +N/(N-x) - x/(N-x) +ln(N-x) + ln(p) - ln(q) $ $ f^1 (x) = ln(N-x) - ln(x) + ln(p/q) $ Consider maxima at $x=x_0$ $ f^1 (x_0) = ln(N-x_0) - ln(x_0) + ln(p/q) $ $ 0 = ln(N/x_0 - 1) + ln(p/q) $ $ ln(q/p) = ln(N/x_0 - 1) $ $ x_0 = N p/(p+q) $ $ x_0 = N p $ $ f(x_0) = N ln(N) - N p ln(N p) - N q ln(N q) + N p ln(p) + N q ln(q) $ $ f(x_0) = N ln((N p^p q^q)/ (N^p p^p N^q q^q)) $ $ f(x_0) = N ln (N / N^(p+q)) $ $ f(x_0) = 0 $ $ f^2 (x) = -1/(N-x) - 1/x $ $ f^2 (x) = - N/(N-x) $ $ f^2 (x_0) = - N/(N - N p) $ $ f^2 (x_0) = - 1/q $ Expanding $f(x)$ around $x_0$ using taylor expansion $ f(x) approx f(x_0) + (x-x_0)f^1(x) bar.v_(x=x_0) + 1/2 (x-x_0)^2 f^2(x) bar.v_(x=x_0) $ $ f(x) = 0 + (x-N p)(0) + 1/2 (x - N p)^2(-1/q) $ $ ln(P(N|n)) = -1/(2 q) (n - N p)^2 $ $ P(N|n) = e^(-1/(2 q) (n - N p)^2) $ $ P(N|n) = c_1 e^(-c_2 (n - N p)^2) $ Therefore, as N grows large, the binomial distribution tends to the Gaussian distribution. QED
https://github.com/ntjess/showman
https://raw.githubusercontent.com/ntjess/showman/main/README.md
markdown
MIT License
# Showman <img src="https://www.github.com/ntjess/showman/raw/v0.1.0/showman.jpg" style="width:1.38889in" /> ------------------------------------------------------------------------ Automagic tools to smooth the package documentation & development process. - Package your files for local typst installation or PR submission in one command - Provide your readme in typst format with code block examples, and let `showman` do the rest! In one command, it will the readme to markdown and render code block outputs as included images. - Bonus points – let `showman` know your repository path and it will ensure images will properly appear in your readme even after your package has been distributed through typst’s registry. - Execute non-typst code blocks and render their outputs # Installation **Prerequisites**: Make sure you have `typst` and `pandoc` available from the command line. Then, in a python virtual environment, run: ``` bash pip install showman ``` # Converting your readme to markdown Create a typst file with ```` ```example ```` code blocks that show the output you want to include in your readme. For instance: ``` typst #import "@preview/cetz:0.1.2" // Just to avoid showing this heading in the readme itself #set heading(outlined: false) = Hello, world! Let's do something complicated: #cetz.canvas({ import cetz.plot import cetz.palette cetz.draw.set-style(axes: (tick: (length: -.05))) // Plot something plot.plot(size: (3,3), x-tick-step: 1, axis-style: "left", { for i in range(0, 3) { plot.add(domain: (-4, 2), x => calc.exp(-(calc.pow(x + i, 2))), fill: true, style: palette.tango) } }) }) ``` ![Example 1](https://www.github.com/ntjess/showman/raw/v0.1.0/assets/example-1.png) Then, run the following command: ``` bash showman md <path-to-typst-file> ``` Congrats, you now have a readme with inline images 🎉 You can optionally specify your workspace root, output file name, image folder, etc. These options are visible under `showman md --help`. **Note**: You can customize the appearance of these images by providing `showman` the template to use when creating them. In your file to be rendered, create a variable called `showman-config` at the outermost scope: ``` typ // Render images with a black background and red text #let showman-config = ( template: it => { set text(fill: red) rect(fill: black, it) } ) ``` Behind the scenes, showman imports your file as a module and looks for this variable. If it is found, your template and a few other options are injected into the example rendering process. **Note**: If every example has the same setup (package imports, etc.), and you don’t want the text to be included in your examples, you can pass `eval-kwargs` in this config as well to specify a string that gets prefixed to every example. Alternatively, pass variables in a scope directly: ``` typ // Setup either through providing scope or import prefixes #let my-variable = 5 #let showman-config = ( eval-kwargs: ( prefix: "#import \"@preview/cetz:0.1.2\" ), // Now you can use `my-var` in your examples scope: (my-var: my-variable) ) ``` ## Caveats - `showman` uses the beautiful `pandoc` to do most of the markdown conversion heavy lifting. So, if your document can’t be processed by pandoc, you may need to adjust your syntax until pandoc is happy making a markdown document. - Typst doesn’t allow page styling inside containers. Since `showman` must use containers to extract each rendered example, you can’t use `#set page(...)` or `#pagebreak()` inside your examples. # Rendering examples in typst If you don’t care about converting your readme to markdown, it’s even easier to have example rendered alongside their code. Simply add the following preamble to your file: ```` typst #import "@preview/showman:0.1.1" #show: showman.formatter.template The code below will be rendered side by side with its output: ``` typst = Hello world! ``` ![Example 2](https://www.github.com/ntjess/showman/raw/v0.1.0/assets/example-2.png) Several keywords can be privded to customize appearance and more. See `showman.formatter.template` for more details. ```` # Publishing your package You’ve done the hard work of creating a beautiful, well-documented manual. Now it’s time to share it with the world. `showman` can help you package your files for distribution in one command, after some minimal setup. 1. Make sure you have a `typst.toml` file that follows typst [packaging guidelines](https://github.com/typst/packages) 2. Add a new block to your toml file as follows: ``` toml [tool.packager] paths = [...] ``` Where `paths` is a list of files and directories you want to include in your package. 3. Run the following command from the root of your repository: ``` bash showman package <path-to-toml-file> ``` 4. Without any other arguments, you’ve just installed your package in your system’s local typst packages folder. Now you can import it with `typst #import "@local/mypackage:<version>"`. - You can alternatively specify the path to your fork of `typst/packages` to prep your files for a PR, or specify a `--namespace` other than `local`. **Note**: You can see the full list of command options with `showman package --help`. # Executing code This package also executes non-typst code (currently bash on non-windows, python, and c++). You can use `showman execute ./path/to/file.typ` to execute code blocks in these languages, and the output will be captured in a `.coderunner.json` file in the root directory you specified. To enable this feature, you need to add the following preamble to your file: ``` typ #import "@preview/showman:0.1.1": runner #let cache = json("/.coderunner.json").at("path/to/file.typ", default: (:)) #let show-rule = runner.external-code.with(result-cache: cache) // Now, apply the show rule to languages that have a `showman execute` result: #show raw.where(lang: "python"): show-rule ``` You can optionally style `<example-input>` and `<example-output>` labels to customize how input and output blocks appear. For even deeper customization, you can specify the `container` that displays the input and output blocks that accepts a keyword `direction` and positional `input` and `output`.
https://github.com/EricWay1024/Computational-AT-mini-project
https://raw.githubusercontent.com/EricWay1024/Computational-AT-mini-project/main/template.typ
typst
#import "@preview/ctheorems:1.1.0": * #import "@preview/commute:0.2.0": node, arr, commutative-diagram #import "@preview/cetz:0.1.2" #let TODO(body) = text(blue)[*TODO* #body] #let oo = [$compose$] #let cx = [$circle.filled.small$] #let Vect = [$bold("Vect")$] #let VF = [$bold("Vect")_FF$] #let FV = [$bold("FinVec")$] #let FVR = [$bold("FinVec")_RR$] #let cC = [$cal(C)$] #let cD = [$cal(D)$] #let bC = [$upright(bold("C"))$] #let bD = [$upright(bold("D"))$] #let bM = [$upright(bold("M"))$] #let bF = [$upright(bold("F"))$] #let bH = [$upright(bold("H"))$] #let PH = [$bold("PH")$] #let Im = [$op("Im")$] #let Ker = [$op("Ker")$] #let over = [$\/$] #let mapsto = [$|->$] #let FK = [$underline(FF)_K$] #let thmboxparams = ( breakable: true, separator: [#h(0em).#h(0.2em)], padding: (top: 0.1em, bottom: 0.1em), inset: 0em, base_level: 0, ) #let thmboxparams2 = ( bodyfmt: emph, ) #let theorem = thmbox( "theorem", "Theorem", ..thmboxparams, ..thmboxparams2, ) #let axiom = thmbox( "axiom", "Axiom", ..thmboxparams, ..thmboxparams2, ) #let lemma = thmbox( "theorem", "Lemma", ..thmboxparams, ..thmboxparams2, ) #let proposition = thmbox( "theorem", "Proposition", ..thmboxparams, ..thmboxparams2, ) #let definition = thmbox( "theorem", "Definition", ..thmboxparams, ) #let example = thmbox( "theorem", "Example", breakable: true, separator: [#h(0em).#h(0.2em)], ..thmboxparams, ) #let remark = thmplain( "theorem", "Remark", breakable: true, separator: [#h(0em).#h(0.2em)], inset: 0em, base_level: 0, ) #let notation = thmplain( "theorem", "Notation", breakable: true, separator: [#h(0em).#h(0.2em)], inset: 0em, base_level: 0, ) #let corollary = thmbox( "theorem", "Corollary", ..thmboxparams, ..thmboxparams2, ) #let fw(doc) = box(width: 100%)[#doc] #let proof(title: "Proof", term) = block(width: 100%, breakable: true)[_#title._ #term #h(1fr) $qed$] #let project(title: "", subtitle: "", university: "University of Oxford", author: "", date: none, body) = { // Set the document's basic properties. set document(author: author, title: title) set page( numbering: "1", number-align: center, paper: "a4", margin: ( top: 3.6cm, // Allocating half of the vertical remaining space to the top bottom: 3.6cm, // And the other half to the bottom inside: 3.5cm, // Larger margin for binding outside: 2.5cm // Remaining space for the outer margin ) ) // width: 15cm, // height: 22.5cm, set text( font: "Linux Libertine", lang: "en", size: 12pt, ) // Title row. align(right)[ #image("imgs/ox-logo.png", width: 8em) ] align(center)[ #v(1fr) #block(text(weight: 700, 2.3em, title)) #v(1.5em) #block(text(1.5em, author)) #v(1fr) #block(text(1.5em, university)) #v(2em) #block(text(1.5em, subtitle)) #v(2em) #text(1.5em, date) ] show ref: box.with(stroke: rgb(144, 238, 144), inset: (bottom: 0pt)) show link: box.with(stroke: rgb(144, 238, 144), inset: (bottom: 0pt)) // Main body. set par(justify: true) set heading(numbering: "1.1.") set enum(numbering: "(1)") show heading: it => pad(bottom: 2pt, it) body }
https://github.com/Otto-AA/definitely-not-tuw-thesis
https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/src/styles/page-header.typ
typst
MIT No Attribution
#let page-header-styles = rest => { // Add current chapter to page header set page(header: context { let current-page = counter(page).get() let all-headings = query(heading.where(level: 1, numbering: "1.")) let is-new-chapter = all-headings.any(m => counter(page).at(m.location()) == current-page) if is-new-chapter { return } let previous-headings = query(selector(heading.where(level: 1)).before(here())).filter(h => h.numbering != none) if previous-headings.len() == 0 { return } let heading-title = previous-headings.last().body [#str(previous-headings.len()). #h(1em) #smallcaps(heading-title)] line(length: 100%) }) rest }
https://github.com/grnin/Zusammenfassungen
https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/10_Ext2_Unicode.typ
typst
// Compiled with Typst 0.11.1 #import "../template_zusammenf.typ": * #import "@preview/wrap-it:0.1.0": wrap-content /* #show: project.with( authors: ("<NAME>", "<NAME>"), fach: "BSys2", fach-long: "Betriebssysteme 2", semester: "FS24", tableofcontents: (enabled: true), language: "de" ) */ = Unicode == ASCII - American Standard Code for Information Interchange Hat _128 definierte Zeichen_ #hinweis[(7 Bit, #hex("00") bis #hex("7F"))]. 33 Kontrollzeichen, viele davon obsolet, 10 Ziffern, 33 Interpunktionszeichen, 26 Grossbuchstaben und 26 Kleinbuchstaben. #hinweis[(erste Hexzahl = Zeile, zweite Hexzahl = Spalte, d.h. #hex("41") = `A`)] #image("img/bsys_40.png") === Codepages Codepages sind _unabhängige Erweiterungen_ auf 8 Bit. Es gibt viele verschiedene, jede ist anders. Sie definieren jeweils 128 Zeichen von #hex("80") bis #hex("FF"). Die Codierung ist _nicht inhärent erkennbar_, Programme müssen wissen, welche Codepage verwendet wird, sonst wird der Text unleserlich. == Unicode Unicode hat zum Ziel, einen eindeutigen Code für _jedes vorhandene Zeichen_ zu definieren. Hat Platz für 1'112'064 Code-Points #hinweis[(21 bits)], davon 149'813 verwendet. #hex("D8 00") bis #hex("DF FF") sind wegen UTF-16 keine gültigen Code-Points. === Verschiedene Encodings Man unterscheidet _Code-Points_ #hinweis[(Nummer eines Zeichen - "welches Zeichen")] und _Code-Units_ #hinweis[(Einheit, um Zeichen in einem Encoding darzustellen - bietet den Speicherplatz für das Zeichen)].\ #hinweis[_$bold(P_i) =$_ $i$-tes Bit des unkodierten CPs, _$bold(U_i) =$_ $i$-tes Code-Unit des kodierten CPs, _$bold(B_i) =$_ $i$-tes Byte des kodierten CPs] - #link(<utf-32>)[_UTF-32:_] Jede CU umfasst _32 Bit_, jeder CP kann mit _einer CU_ dargestellt werden. - #link(<utf-16>)[_UTF-16:_] Jede CU umfasst _16 Bit_, ein CP benötigt _1 oder 2 CUs_ - #link(<utf-8>)[_UTF-8:_] Jede CU umfasst _8 Bit_, ein CP benötigt _1 bis 4 CUs_ #wrap-content( image("img/bsys_43.png"), align: top + right, columns: (50%, 50%), )[ === UTF-32 <utf-32> Direkte Kopie der Bits in die CU bei Big Endian, bei Little Endian werden $P_0$ bis $P_7$ in $B_3$ kopiert usw. Wird häufig intern in Programmen verwendet. Wegen Limitierung auf 21 Bit werden die oberen 11 Bits oft "zweckentfremdet". ] === UTF-16 <utf-16> Encoding muss Endianness berücksichtigen. Die 2 CUs werden Surrogate Pair genannt, $U_0$: high surrogate, $U_1$: low surrogate. - _UTF-16BE:_ Big Endian, CP mit 1 CU: $U_0 = B_1B_0$, CP mit 2 CUs: $U_1U_0 = B_3B_2B_1B_0$ - _UTF-16LE:_ Little Endian, CP mit 1 CU: $U_0 = B_0B_1$, CP mit 2 CUs: $U_1U_0 = B_2B_3B_0B_1$ Bei _2 Bytes_ #hinweis[(1 CU)] wird direkt gemappt und vorne mit Nullen aufgefüllt. Bei _4 Bytes_, wenn CP in #hex("10000") bis #hex("10FFFF") sind #hex("D800") bis #hex("DFFF") #hinweis[(Bits 17-21)] wegen dem Separator _ungültig_ und müssen "umgerechnet" werden: - $Q = P - #hex("10000")$, also ist $Q$ in #hex("0") bis #hex("FFFFF") - $U_1 = bits("1101 10xx xxx") + hex("D800"), U_0 = bits("1101 11xx xxxx xxxx") + hex("DC00")$ #image("img/bsys_45.png") ==== Beispiel Encoding von U+10'437 (\u{10437}) #hinweis[#fxcolor("grün", bits("00 0100 0001", suffix: false)) #fxcolor("gelb", bits("00 0011 0111"))]: 1. Code-Point $P$ minus #hex("10000") rechnen und in Binär umwandlen\ $P = hex("10437"), Q = hex("10437") - hex("10000") = hex("0437") = fxcolor("grün", #bits("00 0000 0001", suffix: false)) fxcolor("gelb", bits("00 0011 0111"))$ 2. Obere & untere 10 Bits in Hex umwandlen\ $fxcolor("grün", #hex("0001", suffix: false)) fxcolor("gelb", hex("0137"))$\ 3. Oberer Wert mit #hex("D800") und unterer Wert mit #hex("DC00") addieren, um Code-Units zu erhalten\ $U_1 = fxcolor("grün", hex("0001")) + hex("D800") = fxcolor("orange", hex("D801")), U_2 = fxcolor("gelb", hex("0137")) + hex("DC00") = fxcolor("hellblau", hex("DD37"))$\ 4. Zu BE/LE zusammensetzen\ $"BE" = underline(fxcolor("orange", #hex("D801", suffix: false)) thin fxcolor("hellblau", hex("DD37"))), thick "LE" = underline(fxcolor("orange", #hex("01D8", suffix: false)) thin fxcolor("hellblau", hex("37DD")))$ #pagebreak() === UTF-8 <utf-8> Encoding muss Endianness _nicht_ berücksichtigen. Standard für Webpages. Echte Erweiterung von ASCII. #let nextCU = bits("10xx xxxx") #table( columns: (auto, 1fr, 1fr, 1fr, 1fr, 1fr), table.header([Code-Point in], [$bold(U_3)$], [$bold(U_2)$], [$bold(U_1)$], [$bold(U_0)$], [signifikant]), [#hex("0") - #hex("7F")], [], [], [], [#bits("0xxx xxxx")], [7 bits], [#hex("80") - #hex("7FF")], [], [], [#bits("110x xxxx")], [#nextCU], [11 bits], [#hex("800") - #hex("FFFF")], [], [#bits("1110 xxxx")], [#nextCU], [#nextCU], [16 bits], [#hex("10000") - #hex("10FFFF")], [#bits("1111 0xxx")], [#nextCU], [#nextCU],[#nextCU], [21 bits], ) Die most significant Bits einer CU werden als Delimiter verwendet: #bits("0") = nur 1 CU, #bits("10") = es folgt mindestens 1 CU, #bits("110") = 2. und letzte CU, #bits("1110") = 3. und letzte CU, #bits("11110") = 4. und letzte CU. In den CUs haben die Bytes #hex("0") - #hex("7F") #hinweis[(7 signifikante Bits)], #hex("80") - #hex("7FF") #hinweis[(11 Bits)], #hex("800") - #hex("FFFF") #hinweis[(16 bits)] bzw. #hex("10000") - #hex("10FFFF") #hinweis[(21 bits)] Platz. #image("img/bsys_44.png") ==== Beispiele - _ä_: $P = hex("E4") = fxcolor("grün", #bits("00011", suffix: false)) thin fxcolor("gelb", bits("10 0110"))$\ $=> P_10 ... P_6 = fxcolor("grün", bits("00011")) = fxcolor("rot", hex("03")), P_5 ... P_0 = fxcolor("gelb", bits("100100")) = fxcolor("orange", hex("24"))$\ $=> U_1 = hex("C0") (= bits("11000000")) + fxcolor("rot", hex("03")) = hex("C3"), U_0 = hex("80") (= bits("10000000")) + fxcolor("orange", hex("24")) = hex("A4")$\ $=> ä = underline(hex("C3 A4"))$ - _ặ_: $P = hex("1EB7") = fxcolor("grün", #bits("0001", suffix: false)) thin fxcolor("gelb", #bits("111010", suffix: false)) thin fxcolor("hellblau", bits("110111"))$\ $=> P_15 ... P_12 = fxcolor("grün", hex("01")), P_11 ... P_6 = fxcolor("gelb", hex("3A")), P_5 ... P_0 = fxcolor("hellblau", hex("37"))$\ $=> U_2 = hex("E0") (= #bits("11100000")) + fxcolor("grün", hex("01")) = hex("E1"), U_1 = hex("80") + fxcolor("gelb", hex("3A")) = hex("BA"), U_0 = hex("80") + fxcolor("hellblau", hex("37")) = hex("B7")$\ $=> ặ = underline(hex("E1 BA B7"))$ === Encoding-Beispiele #table( align: (_, y) => if(y == 0) { left } else { right }, columns: (auto,) + (1fr,) * 6, table.header([Zeichen], [Code-Point], [UTF-32BE], [UTF-32LE], [UTF-8], [UTF-16BE], [UTF-16LE]), [A],[#hex("41")],[#hex("00 00 00 41")],[#hex("41 00 00 00")],[#hex("41")],[#hex("00 41")],[#hex("41 00")], [ä],[#hex("E4")],[#hex("00 00 00 E4")],[#hex("E4 00 00 00")],[#hex("C3 A4")],[#hex("00 E4")],[#hex("E4 00")], [$alpha$],[#hex("3 B1")],[#hex("00 00 03 B1")],[#hex("B1 03 00 00")],[#hex("CE B1")],[#hex("03 B1")],[#hex("B1 03")], [ặ],[#hex("1E B7")],[#hex("00 00 1E B7")],[#hex("B7 1E 00 00")],[#hex("E1 BA B7")],[#hex("1E B7")],[#hex("B7 1E")], [𐌰],[#hex("1 03 30")],[#hex("00 01 03 30")],[#hex("30 03 01 00")],[#hex("F0 90 8C B0")],[#hex("D8 00 DF 30")],[#hex("00 D8 30 DF")], ) #hinweis[Bei LE / BE werden nur die Zeichen _innerhalb_ eines Code-Points vertauscht, nicht die Code-Points an sich.] #pagebreak() = Ext2-Dateisystem == Datenträger-Grundbegriffe - _Partition:_ Ein Teil eines Datenträgers, wird selbst wie ein Datenträger behandelt. - _Volume:_ Ein Datenträger oder eine Partition davon. - _Sektor:_ Kleinste logische Untereinheit eines Volumes. Daten werden als Sektoren transferiert. Grösse ist von HW definiert #hinweis[(z.B. 512 Bytes oder 4KB)]. Enthält Header, Daten und Error-Correction-Codes. - _Format:_ Layout der logischen Strukturen auf dem Datenträger, wird vom Dateisystem definiert. == Block #wrap-content( image("img/bsys_41.png"), align: top + right, columns: (85%, 15%), )[ Ein Block besteht aus _mehreren aufeinanderfolgenden Sektoren_ #hinweis[(1 KB, 2 KB oder 4 KB (normal))]. Das gesamte Volume ist in _Blöcke aufgeteilt_ und Speicher wird _nur in Form von Blöcken_ alloziert. Ein Block enthält nur Daten einer _einzigen Datei_. - _Logische Blocknummer:_ Blocknummer vom Anfang der Datei aus gesehen, wenn Datei eine ununterbrochene Abfolge von Blöcken wäre #hinweis[(innerhalb Datei)] - _Physische Blocknummer:_ Tatsächliche Blocknummer auf dem Volume #hinweis[(auf dem Datenträger)] ] == Inodes Achtung: `!=` Index Node. Beschreibung einer Datei. Enthält _alle Metadaten_ über die Datei, _ausser Namen oder Pfad_ #hinweis[(Grösse, Anzahl der verwendeten Blöcke, Erzeugungszeit, Zugriffszeit, Modifikationszeit, Löschzeit, Owner-ID, Group-ID, Flags, Permission Bits)]. Hat eine _fixe Grösse_ je Volume: Zweierpotenz, mind. 128 Byte, max 1 Block. Der Inode _verweist auf die Blöcke_, die _Daten für eine Datei_ enthalten. Enthält ein Array _`i_block`_ mit 15 Einträgen zu je 32 Bit: #wrap-content( image("img/bsys_42.png"), align: top + right, columns: (55%, 44%), )[ - 12 Blocknummern für die _ersten 12 Blöcke_ einer Datei - 1 Blocknummer des _indirekten Blocks_, der wiederum bei 1024 Byte Blockgrösse auf 256 oder bei 4096 Byte auf 1024 Blöcke verweist. - 1 Blocknummer des _doppelt indirekten Blocks_, welcher Nummern von indirekten Blöcken enthält. Bei Blockgrösse 1024 auf $256 dot 256 = 65536$ Blöcke, bei 4096 auf $1024 dot 1024 = 1upright(M)$ Blöcke - 1 Blocknummer des _dreifach indirekten Blocks_\ #hinweis[$256 dot 256 dot 256 = 16upright(M)$ bzw. $1024 dot 1024 dot 1024 = 1upright(G)$] ] Jeder verwendete Block einer Datei hat einen direkten oder indirekten _Verweis_. === Lokalisierung Alle Inodes aller Blockgruppen gelten als _eine grosse Tabelle_. Zählung der Inodes startet mit 1. - Blockgruppe $= ("Inode" - 1) / "Anzahl Inodes pro Gruppe"$ - Index des Inodes in Blockgruppe $ = ("Inode" - 1) %$ Anzahl Inodes pro Gruppe - Sektor und Offset können anhand der Daten aus dem Superblock bestimmt werden. === Erzeugung Neue Verzeichnisse werden bevorzugt in der Blockgruppe angelegt, die von allen Blockgruppen mit _überdurchschnittlich vielen freien Inodes_ die _meisten Blöcke frei_ hat. Dateien werden möglichst in der Blockgruppe des Verzeichnisses oder in nahen Gruppen angelegt.\ Bestimmung des ersten freien Inodes in der Gruppe anhand des _Inode-Usage-Bitmaps_. Bit wird entsprechend auf 1 gesetzt und die Anzahl freier Inodes in Gruppendeskriptor und Superblock angepasst. === File-Holes Bereiche in der Datei, in der _nur Nullen_ stehen. Wird ein Eintrag auf einen Block auf 0 gesetzt, heisst das, dass der Block nur Nullen enthält. Ein solcher Block wird _nicht alloziert_. Darum kann Grösse & Anzahl der verwendeten Blöcke voneinander abweichen. == Blockgruppe Ein Volume wird in _Blockgruppen_ unterteilt. Eine Blockgruppe besteht aus _mehreren aufeinanderfolgenden Blöcken_ bis zu 8 mal der Anzahl Bytes in einem Block #hinweis[(Bsp. Blockgrösse 4KB sind bis zu 32K Blöcke in einer Gruppe)]. Anzahl Blöcke je Gruppe ist gleich für alle Gruppen. === Lage der Blockgruppen #wrap-content( image("img/bsys_46.png"), align: top + right, columns: (40%, 60%), )[ Die Lage der Blockgruppe 0 ist _abhängig von der Blockgrösse_. Blockgruppe 0 ist definiert als _die Gruppe, deren erster Block den Superblock enthält_.\ _Blockgrösse $<=$ 1024:_ Block 0 kommt vor Blockgruppe 0 #sym.arrow Block 1 ist der erste Block und beinhaltet Superblock.\ _Blockgrösse > 1024:_ Block 0 in Blockgruppe 0 #sym.arrow Superblock ist in Block 0. ] === Layout - _Block 0:_ Kopie des Superblocks - _Block $bold(1)$ bis $bold(n)$:_ Kopie der Gruppendeskriptorentabelle - _Block $bold(n + 1)$:_ Block-Usage-Bitmap mit einem Bit je Block der Gruppe #hinweis[(Welche Blöcke werden gerade verwendet)] - _Block $bold(n + 2)$:_ Inode-Usage-Bitmap mit einem Bit je Inode der Gruppe #hinweis[(Welche Inodes werden verwendet)] - _Block $bold(n + 3)$ bis $bold(n + m + 2)$:_ Tabelle aller Inodes in dieser Gruppe - _Block $bold(n + m + 3)$ bis Ende der Gruppe:_ Blöcke der eigentlichen Daten === Superblock Startet immer an _Byte 1024_ #hinweis[(Wegen eventuellen Bootdaten im Bereich vorher)] und enthält _alle Metadaten_ über das Volume: - _Anzahlen:_ Inodes frei und gesamt, Blöcke frei und gesamt, reservierte Blöcke, Bytes je Block, Bytes je Inode, Blöcke je Gruppe, Inodes je Gruppe - _Zeitpunkte:_ Mountzeit, Schreibzeit, Zeitpunkt des letzten Checks - _Statusbits:_ Um Fehler zu erkennen - _Erster Inode_, der von Applikationen verwendet werden kann - _Feature-Flags:_ Zeigen an welche Features das Volume verwendet. ==== Sparse Superblocks Feature, dass die _Anzahl der Superblocks_ stark _reduziert_. Wird über ein bestimmtes Flag aktiviert. Wenn aktiv, dann werden Kopien des Superblocks nur noch in Blockgruppe 0 und 1 sowie allen reinen Potenzen von 3, 5 oder 7 gehalten #hinweis[(0, 1, 3, 5, 7, 9, 25, 27, 49, 81, 125, 243, 343, ...)]. Dadurch ist immer noch ein _sehr hoher Wiederherstellungsgrad_ möglich, obwohl deutlich weniger Platz verwendet wird. === Gruppendeskriptor 32 Byte _Beschreibung einer Blockgruppe_. Beinhaltet: - Blocknummer des _Block-Usage-Bitmaps_ - Blocknummer des _Inode-Usage-Bitmaps_ - Nummer des ersten Blocks der _Inode-Tabelle_ - Anzahl _freier Blöcke_ und _Inodes_ in der Gruppe - Anzahl der _Verzeichnisse_ in der Gruppe ==== Gruppendeskriptortabelle Eine _Tabelle mit $bold(n)$ Gruppendeskriptoren_ für alle $n$ Blockgruppen im Volume. Benötigt selbst $32 dot n$ Anzahl Bytes; Anzahl Sektoren $= (32 dot n) / "Sektorgrösse"$. Folgt _direkt_ auf Superblock. Kopie der Tabelle direkt nach jeder Kopie des Superblocks. == Verzeichnisse Ein Verzeichnis enthält die _Dateieinträge_ bzw. den Inode, dessen Datenbereich Dateieinträge enthält. Es gibt _zwei automatisch angelegte_ Einträge: `"."` ist der Dateieintrag mit eigenem Inode, `".."` ist der Dateieintrag mit dem Inode des Elternverzeichnis. Das _Wurzelverzeichnis_ ist der Inode Nummer 2. Ein _Dateieintrag_ hat eine variable Länge von 8 - 263 Bytes: - 4 Byte _Inode_ - 2 Byte _Länge_ des _Eintrags_ - 1 Byte _Länge_ des _Dateinamens_ - 1 Byte _Dateityp_ #hinweis[(1: Datei, 2: Verzeichnis, 7: Symbolischer Link)] - 0 - 255 Byte _Dateiname_ #hinweis[(ASCII, nicht null-terminiert)] - Länge wird aus Effizienzgründen immer auf 4 Byte aligned #hinweis[(Maschinenwort)] == Links - _Hard-Link:_ gleicher Inode, verschiedene Pfade #hinweis[(Inode wird von verschiedenen Dateieinträgen referenziert)] - _Symbolischer Link:_ Wie eine Datei, Datei enthält Pfad anderer Datei. #hinweis[(Pfad $<$ 60 Zeichen: Wird in Blockreferenzen-Array gespeichert, Pfad $>=$ 60: Pfad wird in eigenem Block gespeichert)] == Vergleich FAT, NTFS, Ext2 #table( columns: (auto, auto, auto), table.header([FAT], [Ext2], [NTFS]), [ - Verzeichnis enthält alle Daten über die Datei - Datei ist in einem einzigen Verzeichnis - Keine Hard-Links möglich ], [ - Dateien werden durch Inodes beschrieben - Kein Link von der Datei zurück zum Verzeischnis - Hard-Links möglich #hinweis[(Mehrere Links zum Inode möglich)] ], [ - Dateien werden durch File-Records beschrieben - Verzeichnis enthält Namen und Link auf Datei - Link zum Verzeichnis und Name sind in einem Attribut - Hard-Links möglich #hinweis[(Attribut kann mehrfach vorkommen)] ], )
https://github.com/kotfind/hse-se-2-notes
https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/cpp/lectures/2024-10-04.typ
typst
= Шаблоны проектирования `Ctrl+C, Ctrl+V` --- плохо При разработке систем стараются предусматривать возможность будущего расширения: - Framework --- общее решение в некоторой ограниченной области - Библиотека классов. Например, STL, Boost - Шаблоны (patterns) проектирования Виды паттернов проектирования: - Паттерн создания (как создавать новые объекты): фабрика, прототип, одиночка - Структурные паттерны (как компоновать сущности): адаптер, мост, proxy - Паттерны поведения: итератор, команда, цепочка ответственности == Некоторые стандартные приемы (не шаблоны) - Интерфейс (базовый класс определяет набор чистых виртуальных функций, производные классы их реализуют) - CRTP (см. дальше) - Примеси (см. дальше) === The Curiously Recurring Template Pattern (CRTP) ```cpp template <class T> struct Base { void generic_fun() { static_cast<T*>(this)->implementation(); } }; struct Derived : public Base<Derived> { void implementation(); }; ``` Как виртуальные функции, но выбор функции происходит в compile time. === Примеси ```cpp struct Number { int n; void set(int v) { n = v; } int get() const { return n; } }; ``` Хотим добавить `undo`; ```cpp struct Number { int n; int old_n; void set(int v) { old_n = n; n = v; } void undo() { n = old_n; } // undo на один шаг int get() const { return n; } }; ``` Хотим это для произвольного класса. Если состояние --- `int`: ```cpp template <typename T> struct Undoable : public B { int before; void set(int v) { before = B::get(); B::set(v); } void undo() { B::set(before); } }; using UNumber = Undoable<Number>; ``` Если состояние любого типа: ```cpp template <typename B, typename T = typename B::value_type> struct Undoable : public B { using value_type = T; T before; void set(T v) { before = B::get(); B::set(v); } void undo() { B::set(before); } }; using UNumber = Undoable<Number>; ``` ```cpp template <typename B, typename T = typename B::value_type> struct Redoable : public B { using value_type = T; T after; void set(T v) { after = v; B::set(v);} void redo() { B::set(after); } }; using RUNmber = Redoable<Undoable<Number>>; ``` == Паттерны создания === Зависимости и ограничения Для создания объекта нужно указать класс. Конструкторы могут требовать сложных аргументов. Проблемы: - Хотим минимизировать количество зависимостей между разными частями кода. - Ограничивает множество классов === Абстрактная фабрика Взаимодействие следующих сущностей: - `AbstractFactory` (интерфейс), `ConcreteFactory` (несколько классов, конкретные реализации) - `AbstractProduct` (интерфейс), `ConcreteProduct` (несколько классов, конкретные реализации) ```cpp class Shape { // AbstractProduct public: virtual std::string text() = 0; // имя virtual double area() const = 0; // площадь virtual ~Shape(); }; class Rectangle : public Shape { public: std::string text() override { ... } double area() const override { ... } private: double w_, h_; } ``` ```cpp class ShapeFactory { public: // ...TODO }; // ...TODO ``` Нужна функция для создания фабрик: ```cpp ShapeFactory* makeShapeFactory(std::string shape) { if (shape == "triangle") { return new TriangleFactory(); } else if (shape == "rectange") { return new RectangleFactory(); } else { throw std::invalid_argument("wrong shape name"); } } ``` === Саморегистрирующиеся классы Идея: - Все фабрики наследуются от базового класса - В этом базовом классе создается статический реестр фабрик - При создании фабрики регистрируют себя ```cpp class AbstractFactory { public: using create_f = std::unique_ptr<AbstractFactory>(); staic void registrate(std::string const& name, crate_f* fp) { registry[name] = fp; } static std::unique_ptr<AbstractFactory> make(std::string const& name) { auto it = registry.find(name); return it == registry.end() ? nullptr : (it->second)(); } template <typename F> struct Registrar { explicit Registrar(std::string const& name) { AbstractFactory::registrate(name, &F::create); } } private: static std::map<std::string, create_f*> registry; }; ``` Конкретная фабрика: ```cpp class ConcreteFactory : public AbstractFactory { static std::unique_ptr<AbstractFactory> create() { return std::make_unique<ConcreteFactory>(); } }; // В cpp-файле namespace { ConcreteFactory::Registrar<ConcreteFactory> reg("my_name"); } ``` === Фабричный метод - `Product`, `ConcreteProduct` - `Creator`, `ConcreteCreator` ```cpp class Creator { public: virtual Product* Create() = 0; } ``` === Паттерн Строитель (Builder) Строим сложный объект по частям - `Builder`, `ConcreteBuilder` - `Director` --- распорядитель (вызывает методы Строителя) - `Product` ```cpp class DocBuilder { public: virtual DocBuilder& build_title(std::string& title) { ... } ... virtual Product* build() { ... } }: class HTMLBuilder : public DocBuilder { ... }; class LaTeXBuilder : public DocBuilder { ... }; ``` Пример использования: ```cpp Doc transformer(const string& src, Builder& builder); ``` === Одиночка (Singleton) ```cpp template <class T> class Singleton { public: T& get() { static T* obj; return obj; } }; ```
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-square-05.typ
typst
Other
// Size wins over width and height. // Error: 09-20 unexpected argument: width #square(width: 10cm, height: 20cm, size: 1cm, fill: rgb("eb5278"))
https://github.com/tobiaswuttke/rss-submission-template
https://raw.githubusercontent.com/tobiaswuttke/rss-submission-template/main/main.typ
typst
#import "rss-template.typ": conf // Preamble #let title = [Your Title] #let author = [Your name] #let type = [Literature Review | Dissertation Idea | Thesis Proposal (Paper Type)] #let email = [<EMAIL>] #let reviewer = [Reviewer's name] #let abstract = [#lorem(80)] #show: doc => conf( [#title], [#author], [#email], [#type], [#abstract], [#reviewer], doc ) // Start of document: = First Heading #lorem(100) == Second Heading (Please avoid third heading) #lorem(100) This is an example cite: @baiyereDigitalTransformationNew2020. See @roadmap for more details. #figure( table( columns: 4, [*Working title*], [*Study Description*], [*Status*], [*Comment*], [y], [0.3s], [0.4s], [0.8s], [],[],[],[] ), caption: [ A Table. ], )<roadmap> @figure1 is an example of a figure: #figure( image("img/HPI_logo.svg",width: 10%), caption: [ A Figure. ], )<figure1> #bibliography("lit.bib")
https://github.com/Blezz-tech/math-typst
https://raw.githubusercontent.com/Blezz-tech/math-typst/main/main.typ
typst
#import "template.typ": * #show: project.with( title: "math-typst", authors: ( "Blezz", ), ) // Документ #outline(indent: 12pt) = Справочные материалы $ sin^2 alpha + cos^2 alpha = 1 \ sin 2alpha = 2 sin alpha dot cos alpha \ cos 2 alpha = cos^2 alpha - sin^2 alpha \ sin (alpha + beta) = sin alpha dot cos beta + cos alpha dot sin beta \ cos (alpha + beta) = cos alpha dot cos beta - sin alpha dot sin beta $ #pagebreak() #include "/Варианты/Демо вариант 2024.typ" #pagebreak()
https://github.com/YuxuanQin/typst-template
https://raw.githubusercontent.com/YuxuanQin/typst-template/master/template.typ
typst
// 著者: 秦宇轩 (<NAME>) // 最后修改: 2024年 05月 18日 星期六 21:26:35 CST // 协议: MIT Liscense // // 这是模板文件,详见函数 `conf`,配置相关条目前一律加全大写 // 的函数名,以便查找。 // 费解的配置一律加注释。 #let conf( lang: [], title: none, authors: (), date: datetime.today(), abstract: [], keywords: (), doc ) = { // TEXT set text( font: ("New Computer Modern", "Noto Serif CJK SC"), size: 12pt, lang: lang) // Depends on the `lang` argument you pass // PAGE set page( paper: "a4", numbering: "1") // PARAGRAPH set par( justify: true, // Justify every line, so sentence won't pill out leading: 0.5em, // Space between each line first-line-indent: if lang == "zh" {2em} else {1em}) set heading(numbering: "1.") // Sections' number // CODE MODE show raw: set text(font: "Fira Code") // font show raw.where(block: true): block.with( // code block fill: luma(220), // background color inset: 9pt) // distance between text and the edge show raw.where(block: false): box.with( // inline fill: luma(220), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt) // LINK show link: it => text(red, font: "Fira Code", size: 10pt)[#it] /*-----------------------------------------------------*/ /*-----------------------------------------------------*/ /*--------------- DEFINE FUNCTION BEGIN ---------------*/ /*-----------------------------------------------------*/ /*-----------------------------------------------------*/ // PROOF /* --------------------------------------------------- */ /* --------------------------------------------------- */ /* ----------------- Docuemnt Begin ------------------ */ /* --------------------------------------------------- */ /* --------------------------------------------------- */ set align(center) text(25pt)[*#title*] let count = authors.len() let ncols = calc.min(count, 3) grid( columns: (1fr,) * ncols, row-gutter: 24pt, ..authors.map(author => [ #text(size: 16pt)[#author.name]\ #author.affiliation \ #link("mailto:" + author.email) ]), ) [#date.year()-#date.month()-#date.day()\ ] [ \ ] set align(left) if lang == "zh" { par(first-line-indent: 0em)[*摘要*: #abstract] } else { [*Abstract*: #abstract] } // outline show outline.entry: it => { if it.level == 1 { strong(text(red)[#it]) } else { text(red)[#it] } } [ \ \ \ ] outline( indent: auto, fill: repeat(" · "), depth: 2 ) doc } #show: doc => conf( lang: "zh", title: "寻找塔菲", authors: ( ( name: "孙笑川", affiliation: "抽象研究院", email: "<EMAIL>" ), ), abstract: [在这片文章中,我们实现实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了实现了了], doc ) #let thm(title: [], content) = block( fill: silver, inset: 10pt, stroke: black)[ #text(size: 16pt)[*#title*]\ #line(length: 100%, stroke: 0.7pt) #content ] = 引言 With `rg`, you can search through your files quickly. This example searches the current directory recursively for the text can can can can can can `Hello World`: ```hs main :: IO () main = do putStrLn "Hello World" ``` = 塔菲是谁 #lorem(20) 现在让我们来看看孙笑川大定理: #set quote(block: true) #thm(title: "测度扩张定理")[ 每个定义在代数 $cal(A)$ 上的 “预测度” $mu$ 都能扩充成一个真测度。 ] #let lang = context text.lang #lang #let proof(content) = [ #if lang != "zh" { [*证明*. #content $qed$] } else { [*Proof*. #content $qed$] } ] #proof[ 快使用算小川,呼呼哈黑。 $s d d $\ 这是新的一行 ]
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/bugs/subelement-panic_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Enum item (pre-emptive) #enum.item(none)[Hello] #enum.item(17)[Hello]
https://github.com/Error-418-SWE/Documenti
https://raw.githubusercontent.com/Error-418-SWE/Documenti/src/2%20-%20RTB/Documentazione%20interna/Verbali/24-01-08/24-01-08.typ
typst
#import "/template.typ": * #show: project.with( date: "08/01/24", subTitle: "Meeting di retrospettiva e pianificazione", docType: "verbale", authors: ( "<NAME>", ), timeStart: "14:45", timeEnd: "15:30", ); = Ordine del giorno - Valutazione dell'avanzamento; - Analisi di retrospettiva; - Valutazione RTB; - Pianificazione. == Valutazione dell'avanzamento <avanzamento> Ogni membro del gruppo, supportato dall'evidenza della board Jira, ha esposto lo stato di avanzamento delle proprie attività assegnate. Per brevità sono omesse le considerazioni riguardo i documenti Norme di Progetto, Analisi dei Requisiti e Piano di Progetto, per i quali l'avanzamento è avvenuto nel rispetto della pianificazione precedente. === Piano di Qualifica Il documento è stato revisionato e la selezione delle metriche è completa. Nel futuro prossimo il gruppo estenderà ed affinerà le metriche a supporto dei processi di ciclo di vita. La dashboard di monitoraggio è stata realizzata con Grafana e le API di Jira. === PoC Tutte le funzionalità previste sono state integrate. Rimane da chiarire se realizzare il _pattern middleware_ con Express.js o con Next.js. Inoltre è emerso un grave problema di prestazioni concorrente alla creazione di più scaffali. Il bug causa un crollo drastico del frame rate. === Automazioni È stato introdotto lo spell checking dei documenti in PR tramite le API di OpenAI. È emersa la necessità di correggere alcuni log perché l'automazione preposta presenta un bug e crea alcuni log non validi. === Analisi dei rischi Rivista la struttura del documento per migliorarne la leggibilità. == Analisi di retrospettiva === Keep doing <keep-doing> Il gruppo rileva la partecipazione di tutti i membri alle attività di progetto. La sensazione generale è che il gruppo sia a buon punto e possa candidarsi per la valutazione RTB entro la fine dello sprint successivo. === Improvements <improvements> Le norme di formattazione del testo (grassetto e corsivo) non sono state rispettate in alcune sezioni dei documenti. Il problema riguarda soprattutto l'Analisi dei Requisiti. Si è stabilito che: - i riferimenti ai documenti debbano riportare l'esatto numero di versione; - i link ai documenti vadano riportati nella sezione Riferimenti; - i link ai documenti vadano riportati per esteso; - i link debbano puntare al documento PDF contenuto nel branch `main`. Sarebbe apprezzata una maggiore proattività e propositività per non perdere ore produttive e migliorare al contempo la qualità dei documenti e dei processi. In Jira, aggiungere i ticket non urgenti al backlog e non allo sprint per non alterare il computo degli story points. == Valutazione RTB Visto lo stato di avanzamento, il gruppo ha l'obiettivo di presentare la propria candidatura per la valutazione RTB entro il 19/01/2024. == Pianificazione <pianificazione> La pianificazione dello Sprint 10 tiene conto della sua minor durata (6 giorni, uno in meno del consueto). - Procedere con la revisione dei documenti. Se necessario, l'incaricato alla revisione aggiornerà manualmente il log associato secondo le regole prestabilite; - Correggere le cause del problema prestazionale del PoC; - Correggere i bug delle automazioni; - Introdurre automazione per la compilazione del documento a seguito dell'aggiornamento manuale di un changelog; - Ampliare la dashboard di monitoraggio; - Preparare la presentazione a supporto della valutazione RTB; - Mostrare al Proponente un video demo per aggiornarlo sullo stato dei lavori. Si prevede, inoltre, che gli Sprint 11, 12 e 13 avranno ambito ridotto a causa della concorrente sessione di esami.
https://github.com/samchouse/dawson
https://raw.githubusercontent.com/samchouse/dawson/main/midterm/1/test.typ
typst
#set page( numbering: "1 / 1", header: context { if counter(page).get().first() == 1 { align(right)[By: <NAME> and <NAME>] } } ) #align(center)[= Computer Science Mock Midterm] + Consider the following document in the vim editor: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```t print("Hello, Wrld!")❚ ~ ~ ~ ~ ``` ] ) … where ❚ is your cursor location. Assuming vim is in INSERT MODE, what key sequence can a user efficiently use to navigate and correct the print error WITHOUT using the arrow keys: #enum( numbering: "a)", [Esc, K, K, K, K, K, I, o], [I, L, L, L, L, L, Esc, o], [N, J, J, J, J, J, I, o], [Esc, H, H, H, H, H, I, o], [N, H, H, H, H, H, I, o] ) + Consider the following program: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```py x = 16 y = 8 z = x / y print(type(z)) ``` ] ) What will this program output in the console? #enum( numbering: "a)", [class:int], [\<class 'int'>], [class:float], [\<class 'float'>], [2], ["2"], ["x / y"], ["16 / 8"], [Nothing: the code contains an error] ) + Consider the following program: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```py midterm_grades = [80, 70, 90] final_exam_grades = [60, 90, 90] print(midterm_grades[1:2] + final_exam_grades[1:2]) ``` ] ) What will this program output in the console? #enum( numbering: "a)", [80, 70], [[80, 70]], [160], [[160]], [70, 90], [[70, 90]], [Nothing: the code contains an error.] ) + Which of the following statements is NOT true? #enum( numbering: "a)", [Python is a programming language that is computed & executed line by line], [The "else:" code block will be skipped if the "if <condition>:" condition is True], [To upload a change in a file using git, we can use the "git push --force" command], [To display the contents of a file in the terminal, we can use the "cat" command], [To save and quit a document after editing it with vim, we use the function ":sq"], [None of the above], ) + Trace the following expression: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```py x = "SF1" y = "Dawson" z = x + y a = len(x) != len(y) and x != z and bool(y and not True) ``` ] ) \ \ \ \ \ \ + Trace the following expression: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```py t = 3 u = 0.8 a = int(t / u) == t and u != t ``` ] ) \ \ \ \ \ + Trace the following expression: #block( fill: luma(230), width: 100%, inset: 8pt, radius: 2pt, [ ```py h = "Hello" w = "World!" c = ", " def salutation(x: str, y: str) -> str: return x + y a = salutation(h, c) + w ``` ] ) \ \ \ \ + Write a function that calculates the amount of money that a company must pay a freelancer for their work each month. Assume there are 8 hours a day and 22 working days in a month, and a discount may be applied. *Inputs:* a float of hourly wage and a float discount (in form of 25.0). \ *Output:* the amount to be paid by the company. \ \ \ \ \ \ \ \ \ \ \ + Complete the function to determine whether you should upgrade the model of your phone. The phone costs \$1500. You should only upgrade if: - Your remaining bank balance will be greater than \$2000 - Your phone is more than 4 years old - You have a job ```py def should_upgrade(bank_balance: float, age: float, have_job: bool) -> bool: ``` \ \ \ + Complete the function to calculate the resultant vector of 3 vectors. Each vector starts at the end of the last vector and the first vector begins at the origin. Each vector will be a list of size two in the following format: [x_comp, y_comp] \ Ex: vec1 is [1, 5], vec2 is [-3, 2] and vec3 is [4, -8] The resultant vector is calculated by adding the x-component of each vector and adding the y-component of each vector together so that the final form is another vector. *Your solution must make use of a function that will accept an index as an argument and return the sum of each vector's component at that index.* ```py def calc_resultant(vec1: list[int], vec2: list[int], vec3: list[int]) -> list[int]: ``` \ \ \ \ \ \ \ #set enum(numbering: "Bonus 1.") + Calculate the magnitude of the resultant vector from the previous question. $ serif("Magnitude") = sqrt(x^2 + y^2) $ where $x$ is x_comp and $y$ is y_comp. You can use the $sqrt$ function through the ```py math.sqrt(x: float)``` function in Python. ```py def calc_magnitude(resultant: list[int]) -> float: ``` \ \ \ \ \ \ + Calculate the angle of the resultant vector from the previous question. $ theta = arctan(abs(y)/abs(x)) $ where $x$ is x_comp and $y$ is y_comp. You can use the $arctan$ function through the ```py math.degrees(math.atan(x: float))``` function in Python. \ \ Then adjust the angle according to the following cases: - x >= 0 and y >= 0: do nothing - x < 0 and y >= 0: $180 - theta$ - x < 0 and y < 0: $180 + theta$ - x >= 0 and y < 0: $360 - theta$ ```py import math def calc_angle(resultant: list[int]) -> float: ``` \ \ \ \ \ \ + What Linux distro do programmers use to flex on other programmers?
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/meta/figure_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Testing figures with tables. #figure( table( columns: 2, [Second cylinder], image("/assets/files/cylinder.svg"), ), caption: "A table containing images." ) <fig-image-in-table>
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/array-07.typ
typst
Other
// Test bad lvalue. // Error: 2:3-2:14 cannot mutate a temporary value #let array = (1, 2, 3) #(array.len() = 4)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/rubber-article/0.1.0/template/main.typ
typst
Apache License 2.0
#import "@preview/rubber-article:0.1.0": * #show: article.with() #maketitle( title: "The Title of the Paper", authors: ( "<NAME>", ), date: datetime.today().display("[day padding:none]. [month repr:long] [year]"), ) // Some example content has been added for you to see how the template looks like. = Introduction #lorem(60) == In this paper #lorem(20) $ x_(1,2) = (-b plus.minus sqrt(b^2 - 4 a c))/ (2 a) $ #lorem(20) === Contributions #lorem(40) = Related Work #lorem(500)
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/folding_range/multiple-content-2.typ
typst
Apache License 2.0
#let slides(..args) = args #slides[ ][ ]
https://github.com/donabe8898/typst-report
https://raw.githubusercontent.com/donabe8898/typst-report/main/template/main.typ
typst
Apache License 2.0
#import "template.typ": * // 表紙とか #show: project.with( title: "わしのレポートtypst", subtitle: "森羅万象開拓編", authors: ( (name: "HT21A021 <NAME>", email: "<EMAIL>"), ), date: "提出日: 8月10日", ) // ページ設定 #set page( numbering: "1", ) #set figure( numbering: "1", ) // 目次設定 #counter(page).update(1) #outline(title: [目次]) // 改ページ #pagebreak() = Rustはいいぞ #h(1em)それに伴ってtypstはいいぞ
https://github.com/Sematre/typst-kit-thesis-template
https://raw.githubusercontent.com/Sematre/typst-kit-thesis-template/main/sections/05_evaluation.typ
typst
= Evaluation ... == First Section ... == Second Section ... == Third Section ...
https://github.com/juanppalacios/GVSU_MSE_Project
https://raw.githubusercontent.com/juanppalacios/GVSU_MSE_Project/main/report/report.typ
typst
Other
#import "template.typ": * #show: ieee.with( title: "Working Title - Hardware Acceleration: CNN Inference for an Emergency Vehicle Classifier", abstract: none, authors: ( ( name: "<NAME>", department: [Electrical and Computer Engineering], organization: [Grand Valley State University], location: [Grand Rapids, Michigan], email: "<EMAIL>" ), ), index-terms: ("hardware acceleration", "computer vision", "machine learning", "neural network"), outline: outline(), bibliography-file: "references.bib", ) // #outline() = Abstract This paper demonstrates the deployment of an emergency vehicle classifier on an embedded device. Distracted driving poses a serious risk to the public's safety and can prevent emergency services from reaching those in need. To address this issue, a machine learning model is used to alert the driver of incoming emergency vehicles. Traditional machine learning models are trained with high-performance Graphical Processing Units (GPUs) with a high degree of accuracy. To achieve similar performance on low-power embedded devices, hardware accelerators are used to outsource heavier computational tasks. Field Programmable Gate Arrays (FPGA)-based accelerators offer reconfigurability to deploy a lightweight Convolutional Neural Network (CNN) model. The following objectives are laid out for this paper: the development of a machine learning model for emergency vehicle classification, deployment of this model to run on a low-power embedded device equiped with an FPGA, and assessing the real-time model inference performance. This research showcases the feasibility of inferring a lightweight model on a low-power embedded device with the help of an FPGA-based hardware accelerator. = Introduction The purpose of this project is to explore the field of computer vision to implement object tracking on an FPGA development board. // This product offers an unubstructed rearward view of the road. // At a high-level, a camera feeds video onto the rearview mirror device. The goal of this project is to implement a neural network capable of detecting object movement across a screen over time. This novel feature has the potential of alerting drivers to moving objects while reserving their vehicle or identifying emergency vehicles in the rearview mirror. This project has three objectives: + Develop and train a machine learning model to track objects over time (Python development) + Deploy the model onto hardware using a combination of microcontroller and FPGA (HLS/HDL development) + Assess the performance on a Gentex FDM® for viability Computer vision is a powerful tool enabling a computer to mimic the way humans see. the modern implementation of computer vision relies on machine learning. An sensor device captures an image and processing is done on an interpreting device. A neural network algorithm performs the processing, providing useful information about the image @Microsoft-Computer-Vision-2023. There are four main categoreis of computer vision applications: image classification, object detection, object tracking, and optical character recognition @Microsoft-Computer-Vision-2023. For our purposes, we are focused on object tracking. First, an object must be detected in a single image. Next, our object must be followed throughout subsequent images. Finally, our device provides useful information in order to perform specific tasks based on our object tracking data @IBM-Computer-Vision-2023. There are several ways of implementing a model onto an FPGA: using kernel managed by a CPU (HLS), or writing a model in VHDL (HDL). FPGA kernels are not just instructions, but digital circuits (hence why we have pragmas, subset of C/C++). == Problem Statement == Scope == Paper Overview = Literature Review == Data Labeling The purpose of data labeling is to provide additional information regarding a machine learning model's area of focus. This means adding contextual information such as a bounding box around a feature in a collection of training data. For example, in a data set of millions of vehicle images, adding labeling information around police vehicles helps a model learn the difference between it and a regular vehicle for better prediction outcomes. Labeled data is used in supervised learning and requires more time to manually label many thousands of images. Additional storage is required for the labeling information such as feature location in an image. There are ways to automate this process by employing a smaller machine learning model for data labeling, however, this process requires a human-in-the-loop for 100% validation. There are a few ways to implement data labeling: internal: using internal databases synthetic: augmenting databases programmatic: script approach for auto-labeling Data labeling is the most involved and important step in the machine learning model development process. If the quality of the training data is low, the model will perform poorly. The labels represent the ground-truth, meaning it is the expected feature for a model to guess correctly. There are many ways to classify objects embedded within an image. The most basic is having a single class per image. In a training set of vehicles, you can label them with a single class label. The next tier of classification involves using more than one label per class. This means that we still have a single class of object but our tags may reflect features regarding this class like a police car with sirens on or off. The most applicable classification schema may be the bounding box approach which just wraps the entirety of an object of interest. Image annotation is the term for data labeling in computer vision applications. Simple image annotation/tagging is just a single phrase to describe the object of interest. Complex image annotation goes beyond this schema by allowing our label to include information about the number of object instances or areas in an image. #figure( image("./figures/image_annotation_types.png", width: 60%), caption: [Image Annotation Schemas], )<image_ann> // == Neural Network Architecture = Methodology/Implementation = Results & Discussion = Conclusion = Appendix
https://github.com/LilNick0101/Bachelor-thesis
https://raw.githubusercontent.com/LilNick0101/Bachelor-thesis/main/content/design.typ
typst
#import "@preview/glossarium:0.2.0": gls = Progettazione Qui verrà spiegata la progettazione dell'applicazione, in particolare verrà spiegata l'architettura dell'applicazione e le scelte progettuali fatte, in sintesi ho deciso di utilizzare un'architettura a tre livelli e il pattern _MVVM_ (_Model-View-ViewModel_). Per quanto riguarda il design dell'interfaccia grafica, sono partito da un mock-up già fatto del risultato finale come punto di partenza, modificando alcuni componenti per adattarli meglio al design di _Android_ e per renderli più semplici da interagire. In generale per la struttura architetturale ho cercato di seguire le best practices dell'architettura moderna di un'applicazione _Android_ quindi ho deciso di utilizzare un'architettura a tre livelli (o _layers_), composta dai seguenti livelli: - Il *livello UI* (_UI Layer_): contiene l'interfaccia grafica che mostra i dati all'utente e permette di interagire con l'applicazione. - Il *livello dati* (_Data Layer_): contiene i dati dell'applicazione, la logica di business su di essi e le sorgenti dati dell'applicazione. - Il *livello dominio* (_Domain Layer_): è un livello facoltativo situato tra il livello UI e il livello dati ed è utilizzato per semplificare o riutilizzare codice. #figure( image("../resources/images/mad-arch-overview.png", width: 70%), caption: [Schema architettura a livelli, da _Guide to app architecture_ @mad.] ) <Architettura> L'utilizzo di questa architettura porta un codice mantenibile, testabile, scalabile e con una buona separazione delle responsabilità tra i vari livelli. == Livello UI #figure( image("../resources/images/mad-arch-overview-ui.png", width: 60%), caption: [Schema livello UI, da _Guide to app architecture_ @mad.] ) <Livello-UI> Il *livello UI* (o *livello di presentazione*) si occupa di presentare i dati all'utente e di reagire all'input dell'utente. Ad ogni interazione utente, l'interfaccia utente si aggiorna per riflettere le modifiche. L'interfaccia grafica è rappresentata dai _Composable_ di _Jetpack Compose_, cioè delle funzioni _Kotlin_ che rappresentano parti dell'interfaccia grafica come superfici, pulsanti, immagini, o elementi di layout come colonne, righe e griglie: ogni schermata dell'applicazione è un insieme di _Composable_ innestati. Ogni schermata ha un _ViewModel_ associato che si occupa di gestire la logica di presentazione della schermata e rappresenta il titolare dello stato dell'interfaccia grafica: contiene i dati da mostrare all'interfaccia grafica e scambia i dati con gli altri livelli. Per esempio, per la lista dei luoghi ci sarà un _ViewModel_ associato che carica la lista dei luoghi dalla sorgente dati e li presenta a schermo, inoltre viene gestito l'input utente come la selezione di un filtro per la lista. == Livello dati #figure( image("../resources/images/mad-arch-overview-data.png", width: 60%), caption: [Schema livello dati, da _Guide to app architecture_ @mad.] ) <Livello-dati> Il *livello dati* di un'applicazione _Android_ contiene la logica di business e si occupa ci come l'applicazione crea, archivia e modifica i dati. Per il livello dati ho utilizzato il pattern repository, i *repository* si occupano di esporre i dati agli altri livelli, senza che essi sappiano da dove vengono questi dati, e si occupano della logica di business sui dati. Nel progetto ho creato un repository per ogni tipo di risorsa (luogo, utente ...) e questi repository scambiano dati con due sorgenti dati: - Il *database locale*, cioè il database _Room_, è la fonte di riferimento dei dati in quanto è la più veloce da accedere e permette di avere i dati disponibili anche offline. Il database locale è composto da una classe di database che crea il database locale se non esiste già e, attraverso una classe DAO (_Data Access Object_), permette di prelevare o modificare i dati da esso; la classe DAO consente l'accesso alle tabelle del database locale. Il database locale è relazionale, per vederne la struttura consultare il diagramma ER nell'#link(label("db-scheme"),[appendice]), in sintesi ho cercato di avere una struttura simile alle risposte JSON del back-end remoto; - Il *back-end remoto*, cioè il servizio API REST che fornisce i dati. Il back-end remoto è la sorgente secondaria dei dati, in quanto richiede una connessione a Internet, ma permette di avere i dati sempre aggiornati. Una classe di servizio API viene creata per ogni risorsa. Nel progetto quando l'applicazione carica i dati, prima carica i dati dalla fonte di riferimento e poi sincronizza i dati del database locale con il back-end remoto, salvando i dati nuovi nel database e aggiornando quelli già presenti. In questo modo, l'applicazione può mostrare i dati anche offline e può mostrare i dati più aggiornati quando è connessa ad Internet: questo approccio è detto sincronizzazione basata sul pull ed è quello che ho implementato nel progetto. == Livello di dominio #figure( image("../resources/images/mad-arch-overview-domain.png", width: 60%), caption: [Schema livello di dominio, da _Guide to app architecture_ @mad.] ) <Livello-dominio> Il *livello di dominio* è un livello posto in mezzo tra il livello dati e il livello di presentazione, è responsabile dell'incapsulamento di una logica di business più complessa o di logica che viene riutilizzata su più _ViewModel_. In questo livello si trovano le classi *UseCase* che sono responsabili ciascuna di una singola funzionalità (si occupano di un solo _caso d'uso_). I _ViewModel_ possono utilizzare le classi *UseCase* per ottenere dati complessi che necessitano di combinare dati da più repository o per ottenere dati che necessitano di una elaborazione più complessa. Un esempio può essere l'ottenimento dei dettagli di un luogo con l'autore associato, in questo caso viene creata una classe _UseCase_ che prende i dati del luogo dal repository dei luoghi e i dati dell'autore dal repository degli utenti e li combina in un unico oggetto che viene mandato al _ViewModel_. Questo livello non è necessario se il progetto è abbastanza piccolo, a volte è possibile utilizzare direttamente i repository nei _ViewModel_, nel progetto è stato usato più a scopo educativo. == Dependency injection Il pattern *Dependency Injection* (In breve *DI*) è un pattern che permette di semplificare la gestione delle dipendenze tra le classi. In questo modo, invece di creare le dipendenze all'interno delle classi, le dipendenze vengono create all'esterno e poi passate alle classi che ne necessitano. Questo permette di semplificare la gestione delle dipendenze e di rendere il codice più testabile. Nel progetto è stato utilizzato il framework _Hilt_ per implementare il pattern _DI_. Per esempio, è stato utilizzato per iniettare le classi _UseCase_ e i repository nei _ViewModel_ e le sorgenti dati nei repository.
https://github.com/rlpundit/typst
https://raw.githubusercontent.com/rlpundit/typst/main/Typst/fr-Rapport/Class.typ
typst
MIT License
#let report( title: "", diploma: "", program: "", supervisor: "", author: "", date: none, body, ) = { // --- Set the document's geometric properties. --- set page( paper: "a4", margin: (left: 30mm, right: 30mm, top: 40mm, bottom: 40mm), numbering: "1", number-align: center, ) // --- Save heading and body font families in variables --- let body-font = "Garamond" let sans-font = "Garamond" // --- Body font family --- set text( font: body-font, size: 12pt, lang: "fr" ) show math.equation: set text(weight: 400) // --- Headings --- show heading: set block(below: 0.85em, above: 1.75em) show heading: set text(font: body-font) set heading(numbering: "1.1") /* set page(header: locate(loc => { let elems = query( selector(heading).before(loc), loc, ) if elems == () { align(right, capstone) } else { let body = elems.last().body capstone + h(1fr) + emph(body) } })) */ // --- Paragraphs --- show par: set block(spacing: 1.5em) set par(leading: 1em, justify: true) // --- Figures --- show figure: set text(size: 0.85em) body pagebreak() } // --- Chapter Titles --- #let chap(ref) = { pagebreak() set page(header: none) v(7cm) place( center, rect(height: 50pt,radius: (rest: 2pt))[ #text(3em, weight: 700, ref) ] ) }
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/cartao/0.1.0/cartao.typ
typst
Apache License 2.0
// vim:ts=2:wrap:linebreak:tw=80:nonumber:norelativenumber:expandtab #let cardnumber = counter("cardnumber") #let cardheader = state("header", "init") #let cardfooter = state("footer", "init") #let cardquestion = state("question", "init") #let cardanswer = state("answer", "init") #let card(header, footer, question, answer) = [ #cardnumber.step() #cardheader.update(header) #cardfooter.update(footer) #cardquestion.update(question) #cardanswer.update(answer) <card> ] #let letter8up = { let cardwidth = 8.5in / 2 let cardheight = 11.0in / 4 let normal = 11pt let small = normal * 0.75 let tiny = normal * 0.35 let large = normal * 1.25 let huge = normal * 1.65 let accent = luma(200) locate(loc => { let elements = query(<card>, loc) let questions = () let oddanswers = () let evenanswers = () let answers = () for loc in elements { // get the value of the #card at each <card> let header = cardheader.at( loc.location() ) let footer = cardfooter.at( loc.location() ) let question = cardquestion.at( loc.location() ) let answer = cardanswer.at( loc.location() ) let card = cardnumber.at( loc.location() ).first() let cardlast = cardnumber.final( loc.location() ).first() // Make the questions and answers arrays questions.push( box( width: cardwidth, height: cardheight, { place(top + center, dy: 0.5cm, float: true, box(width: cardwidth - 1cm)[ #text(size: normal)[ #smallcaps[#header] #h(0.5fr) #card/#cardlast ] ] ) place(top + center, dy: 1.5cm, box(inset: (x: 1cm, y: 0.5cm), [ #text(size: large, weight: "bold")[ #question ] ]) ) place( bottom + right, dx: -0.5cm, dy: -0.5cm, float: true, text(size: normal, style: "italic")[#footer], ) } ) ) if calc.odd(card) { oddanswers.push( box( width: cardwidth, height: cardheight, { place( top + right, dx: -0.5cm, dy: 0.5cm, float: true, [ #set align(right) #text(size: normal)[#card/#cardlast] ] ) place(horizon + center, box(inset: (x: 1cm, y: 0.5cm), [ #set align(left) #text(size: large)[#answer] ]) ) } ) ) } else { evenanswers.push( box( width: cardwidth, height: cardheight, { place( top + right, dx: -0.5cm, dy: 0.5cm, float: true, [ #set align(right) #text(size: normal)[#card/#cardlast] ] ) place(horizon + center, box(inset: (x: 1cm, y: 0.5cm), [ #set align(left) #text(size: large)[#answer] ]) ) } ) ) } } if oddanswers.len() > evenanswers.len() { evenanswers.push( [] ) questions.push( [] ) } answers = evenanswers.zip(oddanswers).flatten() // split each array per whole page let questionspp = () let answerspp = () let questionstmp = () let answerstmp = () let count = 0 let pages = calc.floor(questions.len() / 8) for page in range(pages) { for i in range(8) { questionstmp.push(questions.at(i + page*8)) answerstmp.push(answers.at(i + page*8)) } questionspp.push(questionstmp) answerspp.push(answerstmp) questionstmp = () answerstmp = () } // attach non-whole pages if (pages*8) < questions.len() { for i in range(questions.len() - pages*8) { questionstmp.push(questions.at(pages*8 + i)) answerstmp.push(answers.at(pages*8 + i)) } questionspp.push(questionstmp) answerspp.push(answerstmp) questionstmp = () answerstmp = () } // draw the cards in a table for page in range(questionspp.len()) { table( columns: (cardwidth, cardwidth), rows: cardheight, inset: 0pt, stroke: ( thickness: 0.5pt, dash: "dashed", cap: "round", paint: accent.darken(30%).lighten(50%), ), ..questionspp.at(page) ) pagebreak() table( columns: (cardwidth, cardwidth), rows: cardheight, inset: 0pt, stroke: ( thickness: 0.5pt, dash: "dashed", cap: "round", paint: accent.darken(30%).lighten(50%), ), ..answerspp.at(page) ) } }) } #let a48up = { let cardwidth = 210mm / 2 let cardheight = 297mm / 4 let normal = 11pt let small = normal * 0.75 let tiny = normal * 0.35 let large = normal * 1.25 let huge = normal * 1.65 let accent = luma(200) locate(loc => { let elements = query(<card>, loc) let questions = () let oddanswers = () let evenanswers = () let answers = () for loc in elements { // get the value of the #card at each <card> let header = cardheader.at( loc.location() ) let footer = cardfooter.at( loc.location() ) let question = cardquestion.at( loc.location() ) let answer = cardanswer.at( loc.location() ) let card = cardnumber.at( loc.location() ).first() let cardlast = cardnumber.final( loc.location() ).first() // Make the questions and answers arrays questions.push( box( width: cardwidth, height: cardheight, { place(top + center, dy: 0.5cm, float: true, box(width: cardwidth - 1cm)[ #text(size: normal)[ #smallcaps[#header] #h(0.5fr) #card/#cardlast ] ] ) place(top + center, dy: 1.5cm, box(inset: (x: 1cm, y: 0.5cm), [ #text(size: large, weight: "bold")[ #question ] ]) ) place( bottom + right, dx: -0.5cm, dy: -0.5cm, float: true, text(size: normal, style: "italic")[#footer], ) } ) ) if calc.odd(card) { oddanswers.push( box( width: cardwidth, height: cardheight, { place( top + right, dx: -0.5cm, dy: 0.5cm, float: true, [ #set align(right) #text(size: normal)[#card/#cardlast] ] ) place(horizon + center, box(inset: (x: 1cm, y: 0.5cm), [ #set align(left) #text(size: large)[#answer] ]) ) } ) ) } else { evenanswers.push( box( width: cardwidth, height: cardheight, { place( top + right, dx: -0.5cm, dy: 0.5cm, float: true, [ #set align(right) #text(size: normal)[#card/#cardlast] ] ) place(horizon + center, box(inset: (x: 1cm, y: 0.5cm), [ #set align(left) #text(size: large)[#answer] ]) ) } ) ) } } if oddanswers.len() > evenanswers.len() { evenanswers.push( [] ) questions.push( [] ) } answers = evenanswers.zip(oddanswers).flatten() // split each array per whole page let questionspp = () let answerspp = () let questionstmp = () let answerstmp = () let count = 0 let pages = calc.floor(questions.len() / 8) for page in range(pages) { for i in range(8) { questionstmp.push(questions.at(i + page*8)) answerstmp.push(answers.at(i + page*8)) } questionspp.push(questionstmp) answerspp.push(answerstmp) questionstmp = () answerstmp = () } // attach non-whole pages if (pages*8) < questions.len() { for i in range(questions.len() - pages*8) { questionstmp.push(questions.at(pages*8 + i)) answerstmp.push(answers.at(pages*8 + i)) } questionspp.push(questionstmp) answerspp.push(answerstmp) questionstmp = () answerstmp = () } // draw the cards in a table for page in range(questionspp.len()) { table( columns: (cardwidth, cardwidth), rows: cardheight, inset: 0pt, stroke: ( thickness: 0.5pt, dash: "dashed", cap: "round", paint: accent.darken(30%).lighten(50%), ), ..questionspp.at(page) ) pagebreak() table( columns: (cardwidth, cardwidth), rows: cardheight, inset: 0pt, stroke: ( thickness: 0.5pt, dash: "dashed", cap: "round", paint: accent.darken(30%).lighten(50%), ), ..answerspp.at(page) ) } }) } #let present = { let cardwidth = 297mm let cardheight = 167.0625mm // 297.0, 167.0625, "presentation-16-9") // 280.0, 210.0, "presentation-4-3" let normal = 20pt let small = normal * 0.75 let tiny = normal * 0.35 let large = normal * 1.25 let huge = normal * 1.65 let accent = luma(200) locate(loc => { let elements = query(<card>, loc) let questions = () let oddanswers = () let evenanswers = () let answers = () for loc in elements { // get the value of the #card at each <card> let header = cardheader.at( loc.location() ) let footer = cardfooter.at( loc.location() ) let question = cardquestion.at( loc.location() ) let answer = cardanswer.at( loc.location() ) let card = cardnumber.at( loc.location() ).first() let cardlast = cardnumber.final( loc.location() ).first() // Make the questions and answers arrays questions.push( box( width: cardwidth, height: cardheight, { place(top + center, dy: 0.5cm, float: true, box(width: cardwidth - 1cm)[ #text(size: normal)[ #smallcaps[#header] #h(0.5fr) #card/#cardlast ] ] ) place(horizon + center, box(inset: (x: 1cm, y: 0.5cm), [ #text(size: large, weight: "bold")[ #question ] ]) ) place( bottom + right, dx: -0.5cm, dy: -0.5cm, float: true, text(size: normal, style: "italic")[#footer], ) } ) ) answers.push( box( width: cardwidth, height: cardheight, { place(top + center, dy: 0.5cm, float: true, box(width: cardwidth - 1cm)[ #text(size: normal)[ #smallcaps[#header] #h(0.5fr) #card/#cardlast ] ] ) place(horizon + center, box(inset: (x: cardwidth*0.1, y: 0.5cm), [ #set align(left) #text(size: large)[#answer] ]) ) } ) ) } for card in range(questions.len()) { table( inset: 0pt, stroke: none, columns: auto, questions.at(card), answers.at(card) ) } }) }
https://github.com/ParaN3xus/numblex
https://raw.githubusercontent.com/ParaN3xus/numblex/main/README.md
markdown
MIT License
# Numblex How to number the heading like this? - Appendix A. XXXX - A.1. YYY - A.2. ZZZ Or this? - 一、话题 - 1\. 论点 - (1) 证据 You might use a function: ```Typst #set heading(numbering: (..nums) => { if nums.pos().len() == 1 { return "Appendix " + numbering("A.", ..nums) } return numbering("A.1.", ..nums) } ``` Or set up a couple of `set` rules: ```Typst #set heading(numbering: "A.1.") #show heading.where(level: 1): set heading(numbering: (n) => "Appendix " + numbering("A.", n)) // No, you can't use "Appendix A." since Typst would treat the first "A" as a numbering ``` Or simply use Numblex: ```Typst #import "@preview/numblex:0.2.0": numblex #set heading(numbering: numblex("{Appendix [A].:d==1;[A].}{[1].}")) ``` ## Usage ```typst #import "@preview/numblex:0.2.0": numblex #set heading(numbering: numblex("{Section [A].:d==1;[A].}{[1].}{[1])}")) ``` You can read the [Manual](https://github.com/ParaN3xus/numblex/blob/main/manual.pdf) for more information.
https://github.com/drupol/ipc2023
https://raw.githubusercontent.com/drupol/ipc2023/main/src/ipc2023/theme/ipc.typ
typst
#import "@preview/polylux:0.3.1": * // Originally contributed by <NAME> - https://github.com/drupol // Todo: How to get rid of these colors #let ecmain = rgb("#990027") #let ecaccentblue = rgb(75, 197, 222) #let ecaccentyellow = rgb(255, 192, 0) #let ectext = rgb(77, 77, 77) #let ecbackgroundgrey = rgb(234, 234, 234) #let ecbackgroundblue = rgb(219, 243, 248) #let ec-colors = state("ec-colors", (:)) #let ec-short-title = state("ec-short-title", none) #let ec-short-author = state("ec-short-author", none) #let ec-short-date = state("ec-short-date", none) #let ec-progress-bar = state("ec-progress-bar", true) #let ipc-theme( aspect-ratio: "16-9", short-title: none, short-author: none, short-date: none, ecmain: ecmain, ecaccentblue: ecaccentblue, ecaccentyellow: ecaccentyellow, ectext: ectext, ecbackgroundgrey: ecbackgroundgrey, ecbackgroundblue: ecbackgroundblue, progress-bar: true, body, ) = { set page( paper: "presentation-" + aspect-ratio, margin: 0em, header: none, footer: none, ) set text(size: 25pt) show footnote.entry: set text(size: .6em) ec-progress-bar.update(progress-bar) ec-colors.update(( ecmain: ecmain, ecaccentblue: ecaccentblue, ecaccentyellow: ecaccentyellow, ectext: ectext, ecbackgroundgrey: ecbackgroundgrey, ecbackgroundblue: ecbackgroundblue, )) ec-short-title.update(short-title) ec-short-author.update(short-author) ec-short-date.update(short-date) body } #let focus-slide(background-color: none, background-img: none, body) = { let background-color = if background-img == none and background-color == none { ecmain } else { background-color } set page(fill: background-color, margin: 1em) if background-color != none set page( background: { set image(fit: "stretch", width: 100%, height: 100%) background-img }, margin: 1em, ) if background-img != none set text(fill: white, size: 2em) logic.polylux-slide(body) } #let title-slide( title: [], subtitle: none, authors: (), date: none, logo: none, institution: none, ) = { let authors = if type(authors) == "array" { authors } else { (authors,) } let content = locate( loc => { align(center + horizon, { v(8em) show par: set block(spacing: 0.4em) block( inset: 0em, breakable: false, { text(size: 2em, fill: white, strong(title)) if subtitle != none { parbreak() text(size: 1.2em, fill: ecmain.lighten(50%), subtitle) } } ) set text(size: .8em) grid( columns: (1fr,) * calc.min(authors.len(), 3), column-gutter: 1em, row-gutter: .5em, ..authors.map(author => text(fill: ecmain.lighten(50%), author)) ) if institution != none { parbreak() text(fill: ecmain.lighten(50%), size: .9em, institution) } if date != none { parbreak() text(fill: ecmain.lighten(50%), size: .8em, date) } }) }) set image(width: 100%) place(image("../../../resources/images/IPC_MUC23_by_devmio_Templates_Background_GT-1478_v1.png")) logic.polylux-slide(content) } #let slide(title: none, header: none, footer: none, new-section: none, body) = { let body = pad(x: 1em, bottom: 2em, body) let progress-barline = locate( loc => { if ec-progress-bar.at(loc) { let cell = block.with(width: 100%, height: 100%, above: 0pt, below: 0pt, breakable: false) let colors = ec-colors.at(loc) utils.polylux-progress(ratio => { grid( rows: 2pt, columns: (ratio * 100%, 1fr), cell(fill: colors.ecaccentblue), cell(fill: colors.ecaccentyellow), ) }) } else { [] } }, ) let header-text = { if header != none { header } else { if new-section != none { utils.register-section(new-section) } locate(loc => { let colors = ec-colors.at(loc) box(width:100%)[ #set align(right) #box(width: 100%)[ #box(inset: .2em, width: 100%)[ #place(left)[ #{ if title != none { text(size: 1.25em, fill: colors.ecmain, title) } } ] #place(right)[ #{ if title != none { text(size: 1.25em, fill: colors.ecmain.lighten(65%), utils.current-section) } } ] ] ] ] }) } } let header = { set align(top) grid(rows: (auto, auto), row-gutter: 0mm, progress-barline, header-text) } set page( margin: (top: 2em, bottom: 0em, x: 0em), header: header, footer: footer, footer-descent: 0em, header-ascent: .6em, background: place(bottom + left)[ #image("../../../resources/images/IPC_MUC23_by_devmio_Templates_Footer_GT-1478_v1.png", fit: "stretch") ] ) logic.polylux-slide(body) } #let screencast-slide-body(url: none, preview: none, caption: none) = { set align(center + horizon) set text(size: .5em) figure( link(url)[ #image(preview, height: 90%) ], caption: [ #caption ] ) } #let screencast-slide(title: none, new-section: none, url: none, preview: none, caption: none, ..body) = { slide(title: title, new-section: new-section)[ #screencast-slide-body( url: url, preview: preview, caption: caption, ) ] } #let matrix-slide(columns: none, rows: none, ..bodies) = { let bodies = bodies.pos() let columns = if type(columns) == "integer" { (1fr,) * columns } else if columns == none { (1fr,) * bodies.len() } else { columns } let num-cols = columns.len() let rows = if type(rows) == "integer" { (1fr,) * rows } else if rows == none { let quotient = calc.quo(bodies.len(), num-cols) let correction = if calc.rem(bodies.len(), num-cols) == 0 { 0 } else { 1 } (1fr,) * (quotient + correction) } else { rows } let num-rows = rows.len() if num-rows * num-cols < bodies.len() { panic( "number of rows (" + str(num-rows) + ") * number of columns (" + str(num-cols) + ") must at least be number of content arguments (" + str(bodies.len()) + ")", ) } let cart-idx(i) = (calc.quo(i, num-cols), calc.rem(i, num-cols)) let color-body(idx-body) = { let (idx, body) = idx-body let (row, col) = cart-idx(idx) let color = if calc.even(row + col) { white } else { silver } set align(center + horizon) rect(inset: .5em, width: 100%, height: 100%, fill: color, body) } let content = grid( columns: columns, rows: rows, gutter: 0pt, ..bodies.enumerate().map(color-body), ) logic.polylux-slide(content) }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/docs/raw.typ
typst
Apache License 2.0
/// Docs for f. /// /// ```typst /// #show raw: it => it { /// it /// } /// ``` /// #let /* ident after */ f(a) = { show it: it => it; };
https://github.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper
https://raw.githubusercontent.com/BeiyanYunyi/Architectural-Technology-and-Art-Paper/main/README.md
markdown
MIT License
# 南京信息工程大学本科学位论文 nuist-thesis-typst 南京信息工程大学毕业论文(设计)的 Typst 模板,能够简洁、快速、持续生成 PDF 格式的毕业论文。 ![](images/editor.jpg) ## 致谢 本项目 fork 自 `nju-thesis-typst` 南京大学 Typst 学位论文项目。他们的交流群是 943622984 本项目暂时只实现了本科生毕业论文的部分,研究生部分欢迎贡献 PR。 ## 劣势 - Typst 是一门新生的排版标记语言,还做不到像 Word 或 LaTeX 一样成熟稳定。 - 该模板并非官方模板,而是民间模板,**存在不被认可的风险**。 - 仍有部分未能解决的问题(需要等到 Typst 官方支持,可能还需要几个月) - 没有伪粗体,无法给部分字体加粗,例如「楷体」和「仿宋」。 - <del>无法自定义参考文献格式。</del> 现已支持 [自定义 CSL 样式](https://typst.app/docs/reference/meta/bibliography/)。 ## 优势 Typst 是可用于出版的可编程标记语言,拥有变量、函数与包管理等现代编程语言的特性,注重于科学写作 (science writing),定位与 LaTeX 相似。可以阅读我的 [一篇知乎文章](https://zhuanlan.zhihu.com/p/669097092) 进一步了解 Typst 的优势。 - **语法简洁**:上手难度跟 Markdown 相当,文本源码阅读性高,不会像 LaTeX 一样充斥着反斜杠与花括号。 - **编译速度快**:Typst 使用 Rust 语言编写,即 typ(e+ru)st,目标运行平台是 WASM,即浏览器本地离线运行;也可以编译成命令行工具,采用一种 **增量编译** 算法和一种有约束的版面缓存方案,**文档长度基本不会影响编译速度,且编译速度与常见 Markdown 渲染引擎渲染速度相当**。 - **环境搭建简单**:不需要像 LaTeX 一样折腾几个 G 的开发环境,原生支持中日韩等非拉丁语言,无论是官方 Web App 在线编辑,还是使用 VS Code 安装插件本地开发,都是 **即开即用**。 - **现代编程语言**:Typst 是可用于出版的可编程标记语言,拥有 **变量、函数、包管理与错误检查** 等现代编程语言的特性,同时也提供了 **闭包** 等特性,便于进行 **函数式编程**。以及包括了 `[标记模式]`、`{脚本模式}` 与 `$数学模式$` 等多种模式的作用域,并且它们可以不限深度地、交互地嵌套。并且通过 **包管理**,你不再需要像 TexLive 一样在本地安装一大堆并不必要的宏包,而是 **按需自动从云端下载**。 可以参考我参与搭建和翻译的 [Typst 中文文档网站](https://typst-doc-cn.github.io/docs/) 迅速入门。 ## 使用 快速浏览效果: 查看 [thesis.pdf](https://github.com/OrangeX4/nju-thesis-typst/blob/main/thesis.pdf),样例论文源码:查看 [thesis.typ](https://github.com/OrangeX4/nju-thesis-typst/blob/main/thesis.typ) **你只需要修改根目录下的 `thesis.typ` 文件即可,基本可以满足你的所有需求,`nju-thesis` 目录下的代码可以用于参数查阅,但是理论上你不应该对其进行更改。** 如果你认为不能满足你的需求,可以先查阅后面的 [Q&A](#Q%26A) 部分。 ### 本地编辑(推荐) 1. 克隆本项目,或者直接通过 [GitHub Releases](https://github.com/OrangeX4/nju-thesis-typst/releases) 页面下载。 ```sh git clone https://github.com/OrangeX4/nju-thesis-typst.git ``` 2. 在 [VS Code](https://code.visualstudio.com/) 中打开该目录。 3. 在 VS Code 中安装 [Typst LSP](https://marketplace.visualstudio.com/items?itemName=nvarner.typst-lsp) 和 [Typst Preview](https://marketplace.visualstudio.com/items?itemName=mgt19937.typst-preview) 插件。前者负责语法高亮和错误检查,后者负责预览。 - 也推荐下载 [Typst Companion](https://marketplace.visualstudio.com/items?itemName=CalebFiggers.typst-companion) 插件,其提供了例如 `Ctrl + B` 进行加粗等便捷的快捷键。 - 你还可以下载我开发的 [Typst Sync](https://marketplace.visualstudio.com/items?itemName=OrangeX4.vscode-typst-sync) 和 [Typst Sympy Calculator](https://marketplace.visualstudio.com/items?itemName=OrangeX4.vscode-typst-sympy-calculator) 插件,前者提供了本地包的云同步功能,后者提供了基于 Typst 语法的科学计算器功能。 4. 按下 `Shift + Ctrl + P`,然后输入命令 `Typst Preview: Preview current file`,即可 **同步增量渲染与预览**,还提供了 **光标双向定位功能**。 ### 特性 / 路线图 - **说明文档** - [ ] 编写更详细的说明文档,后续考虑使用 [tidy](https://github.com/typst/packages/tree/main/packages/preview/tidy/0.1.0) 编写,你现在可以先参考 [NJUThesis](https://mirror-hk.koddos.net/CTAN/macros/unicodetex/latex/njuthesis/njuthesis.pdf) 的文档,参数大体保持一致,或者直接查阅对应源码函数的参数 - **类型检查** - [ ] 应该对所有函数入参进行类型检查,及时报错 - **全局配置** - [x] 类似 LaTeX 中的 `documentclass` 的全局信息配置 - [x] **盲审模式**,将个人信息替换成小黑条,并且隐藏致谢页面,论文提交阶段使用 - [x] **双面模式**,会加入空白页,便于打印 - [x] **自定义字体配置**,可以配置「宋体」、「黑体」与「楷体」等字体对应的具体字体 - [ ] **字体解耦合**:将字体配置进一步解耦合,让用到字体的地方加上一层字体名称配置项(从「标题(宋体)」-「具体字体」重构为「标题」-「宋体」-「具体字体」) - [x] **数学字体配置**:模板不提供配置,用户可以自己使用 `#show math.equation: set text(font: "Fira Math")` 更改 - **模板** - [x] 本科生模板 - [x] 字体测试页 - [x] 封面 - [x] 声明页 - [x] 中文摘要 - [x] 英文摘要 - [x] 目录页 - [x] 插图目录 - [x] 表格目录 - [x] 符号表 - [x] 致谢 - [ ] 研究生模板 - [ ] 封面 - [ ] 声明页 - [ ] 摘要 - [ ] 页眉 - [ ] 国家图书馆封面 - [ ] 出版授权书 - [ ] 博士后模板 - **编号** - [x] 前言使用罗马数字编号 - [x] 附录使用罗马数字编号 - [x] 表格使用 `1.1` 格式进行编号 - [x] 数学公式使用 `(1.1)` 格式进行编号 - **环境** - [ ] 定理环境(这个也可以自己使用第三方包配置) - **其他文件** - [ ] 本科生开题报告 - [ ] 研究生开题报告 <!-- ## 其他文件 还实现了本科生和研究生的开题报告,只需要预览和编辑 `others` 目录下的文件即可。 ![开题报告](./images/proposal.png) --> ## Q&A ### 我不会 LaTeX,可以用这个模板写论文吗? 可以。 如果你不关注模板的具体实现原理,你可以用 Markdown Like 的语法进行编写,只需要按照模板的结构编写即可。 ### 我不会编程,可以用这个模板写论文吗? 同样可以。 如果仅仅是当成是入门一款类似于 Markdown 的语言,相信使用该模板的体验会比使用 Word 编写更好。 ### 为什么我的字体没有显示出来,而是一个个「豆腐块」? 这是因为本地没有对应的字体,**这种情况经常发生在 MacOS 的「楷体」显示上**。 你应该安装本目录下的 `fonts` 里的所有字体,里面包含了可以免费商用的「方正楷体」和「方正仿宋」,然后再重新渲染测试即可。 你可以使用 `#fonts-display-page()` 显示一个字体渲染测试页面,查看对应的字体是否显示成功。 如果还是不能成功,你可以按照模板里的说明自行配置字体,例如 ```typst #let (...) = documentclass( fonts: (楷体: ("Times New Roman", "FZKai-Z03S")), ) ``` 先是填写英文字体,然后再填写你需要的「楷体」中文字体。 **字体名称可以通过 `typst fonts` 命令查询。** 如果找不到你所需要的字体,可能是因为 **该字体变体(Variants)数量过少**,导致 Typst 无法识别到该中文字体。 ### 为什么楷体无法加粗? 因为一般默认安装的「楷体」只有标准字重的字体,没有加粗版本的字体(华文粗楷等字体并不是免费商用的),而 Typst 又没有实现伪粗体(Fake Bold)算法,所以导致无法正常加粗。 目前我还没找到一个比较好的解决方法。 ### 学习 Typst 需要多久? 一般而言,仅仅进行简单的编写,不关注布局的话,你可以打开模板就开始写了。 如果你想进一步学习 Typst 的语法,例如如何排篇布局,如何设置页脚页眉等,一般只需要几个小时就能学会。 如果你还想学习 Typst 的「[元信息](https://typst-doc-cn.github.io/docs/reference/meta/)」部分,进而能够编写自己的模板,一般而言需要几天的时间阅读文档,以及他人编写的模板代码。 如果你有 Python 或 JavaScript 等脚本语言的编写经验,了解过函数式编程、宏、样式、组件化开发等概念,入门速度会快很多。 ### 我有编写 LaTeX 的经验,如何快速入门? 可以参考 [面向 LaTeX 用户的 Typst 入门指南](https://typst-doc-cn.github.io/docs/guides/guide-for-latex-users/)。 ### 目前 Typst 有哪些第三方包和模板? 可以参考 [第三方包](https://typst-doc-cn.github.io/docs/packages/)、[Awesome Typst Links](https://github.com/qjcg/awesome-typst) 和 [Awesome Typst 列表中文版](https://github.com/typst-doc-cn/awesome-typst-cn)。 ### 为什么只有一个 thesis.typ 文件,没有按章节分多个文件? 因为 Typst **语法足够简洁**、**编译速度足够快**、并且 **拥有光标点击处双向链接功能**。 语法简洁的好处是,即使把所有内容都写在同一个文件,你也可以很简单地分辨出各个部分的内容。 编译速度足够快的好处是,你不再需要像 LaTeX 一样,将内容分散在几个文件,并通过注释的方式提高编译速度。 光标点击处双向链接功能,使得你可以直接拖动预览窗口到你想要的位置,然后用鼠标点击即可到达对应源码所在位置。 还有一个好处是,单个源文件便于同步和分享。 即使你还是想要分成几个章节,也是可以的,Typst 支持你使用 `#import` 和 `#include` 语法将其他文件的内容导入或置入。你可以新建文件夹 `chapters`,然后将各个章节的源文件放进去,然后通过 `#include` 置入 `thesis.typ` 里。 ### 我如何更改页面上的样式?具体的语法是怎么样的? 理论上你并不需要更改 `nju-thesis` 目录下的任何文件,无论是样式还是其他的配置,你都可以在 `thesis.typ` 文件内修改函数参数实现更改。具体的更改方式可以阅读 `nju-thesis` 目录下的文件的函数参数。 例如,想要更改页面边距为 `50pt`,只需要将 ```typst #show: doc ``` 改为 ```typst #show: doc.with(margin: (x: 50pt)) ``` 即可。 后续我也会编写一个更详细的文档,可能会考虑使用 [tidy](https://github.com/typst/packages/tree/main/packages/preview/tidy/0.1.0) 来编写。 如果你阅读了那些函数的参数,仍然不知道如何修改得到你需要的样式,欢迎提出 Issue,只要描述清楚问题即可。 或者也欢迎加群讨论:943622984 ### 该模板和其他现存 Typst 中文论文模板的区别? 其他现存的 Typst 中文论文模板大多都是在 2023 年 7 月份之前(Typst Verison 0.6 之前)开发的,当时 Typst 还不不够成熟,甚至连 **包管理** 功能都还没有,因此当时的 Typst 中文论文模板的开发者基本都是自己从头写了一遍需要的功能/函数,因此造成了 **代码耦合度高**、**意大利面条式代码**、**重复造轮子** 与 **难以自定义样式** 等问题。 该模板是在 2023 年 10 ~ 11 月份(Typst Verison 0.9 时)开发的,此时 Typst 语法基本稳定,并且提供了 **包管理** 功能,因此能够减少很多不必要的代码。 并且我对模板的文件架构进行了解耦,主要分为了 `utils`、`templates` 和 `layouts` 三个目录,这三个目录可以看后文的开发者指南,并且使用 **闭包** 特性实现了类似不可变全局变量的全局配置能力,即模板中的 `documentclass` 函数类。 ### 我不是南京大学本科生,如何迁移该模板? 我在开发的过程中已经对模板的各个模板进行了解耦,理论上你只需要在 `templates` 目录中加入你需要的页面,然后更改少许、或者不需要更改其他目录的代码。 具体目录职责划分可以看下面的开发者指南。 ## 开发者指南 ### 外部目录 - `thesis.typ` 文件: 你的论文源文件,可以随意更改这个文件的名字,甚至你可以将这个文件在同级目录下复制多份,维持多个版本。 - `bibs` 目录: 放置参考文献的目录。 - `nju-thesis` 目录: 模板目录,放置模板的所有内容,**这个目录可以作为一个 Local Package 安装到本地包目录**,因此理论上你不应该修改这个目录下的任何东西。 ### 内部目录 - `utils` 目录: 包含了模板使用到的各种自定义辅助函数,存放没有外部依赖,且 **不会渲染出页面的函数**。 - <del>`i-equation.typ` 文件: 模仿 [i-figured](https://github.com/typst/packages/tree/main/packages/preview/i-figured/0.1.0) 包编写的数学公式编号函数。</del> 已经合并至 [i-figured](https://github.com/typst/packages/tree/main/packages/preview/i-figured/0.2.2). - `templates` 目录: 包含了模板用到的各个 **独立页面**,例如封面页、声明页、摘要等,即 **会渲染出不影响其他页面的独立页面的函数**。 - `layouts` 目录: 布局目录,存放着用于排篇布局的、应用于 `show` 指令的、**横跨多个页面的函数**,例如为了给页脚进行罗马数字编码的前言 `preface` 函数。 - 主要分成了 `doc` 文稿、`preface` 前言、`mainmatter` 正文与 `appendix` 附录/后记。 - `template.typ`: - **职责一**: 作为一个统一的对外接口,暴露出内部的 utils 函数,例如三线表 `tlt` 函数。 - **职责二**: 使用 **函数闭包** 特性,通过 `documentclass` 函数类进行全局信息配置,然后暴露出拥有了全局配置的、具体的 `layouts` 和 `templates` 内部函数。 ## 参与贡献 - 在 Issues 中提出你的想法,如果是新特性,可以加入路线图! - 实现路线图中仍未实现的部分,然后欢迎提出你的 PR。 - 同样欢迎 **将这个模板迁移至你的学校论文模板**,大家一起搭建更好的 Typst 社区和生态吧。 ## 致谢 - 感谢 [@atxy-blip](https://github.com/atxy-blip) 开发的 [NJUThesis](https://github.com/nju-lug/NJUThesis) LaTeX 模板,文档十分详细,本模板大体结构都是参考 NJUThesis 的文档开发的。 - 感谢 [HUST-typst-template](https://github.com/werifu/HUST-typst-template) 与 [sysu-thesis-typst](https://github.com/howardlau1999/sysu-thesis-typst) 等 Typst 中文论文模板。 ## License This project is licensed under the MIT License.
https://github.com/ClazyChen/Table-Tennis-Rankings
https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2005/MS-12.typ
typst
#set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (1 - 32)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [1], [<NAME>], [CHN], [2929], [2], [<NAME>], [GER], [2797], [3], [<NAME>], [CHN], [2758], [4], [<NAME>], [CHN], [2677], [5], [<NAME>], [BLR], [2656], [6], [<NAME>], [CHN], [2578], [7], [<NAME>], [CHN], [2544], [8], [<NAME>un], [KOR], [2510], [9], [<NAME>], [KOR], [2508], [10], [<NAME>], [KOR], [2489], [11], [#text(gray, "<NAME>")], [CHN], [2485], [12], [<NAME>], [DEN], [2465], [13], [<NAME>], [ROU], [2455], [14], [HAO Shuai], [CHN], [2434], [15], [KREANGA Kalinikos], [GRE], [2414], [16], [KEEN Trinko], [NED], [2397], [17], [KONG Linghui], [CHN], [2388], [18], [<NAME>], [BEL], [2372], [19], [BLASZCZYK Lucjan], [POL], [2338], [20], [<NAME>], [AUT], [2338], [21], [<NAME>], [AUT], [2335], [22], [YANG Zi], [SGP], [2330], [23], [CHUANG Chih-Yuan], [TPE], [2317], [24], [<NAME>], [NED], [2314], [25], [<NAME>], [SWE], [2311], [26], [<NAME>], [SWE], [2310], [27], [CHEUNG Yuk], [HKG], [2303], [28], [JOO Saehyuk], [KOR], [2299], [29], [ZHANG Chao], [CHN], [2292], [30], [CHIANG Hung-Chieh], [TPE], [2284], [31], [KORBEL Petr], [CZE], [2274], [32], [HE Zhiwen], [ESP], [2272], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (33 - 64)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [33], [QIU Yike], [CHN], [2264], [34], [LI Ching], [HKG], [2246], [35], [<NAME>], [DEN], [2242], [36], [KARAKASEVIC Aleksandar], [SRB], [2236], [37], [SHMYREV Maxim], [RUS], [2234], [38], [FEJER-KONNERTH Zoltan], [GER], [2227], [39], [KO Lai Chak], [HKG], [2225], [40], [CHIANG Peng-Lung], [TPE], [2221], [41], [<NAME>], [GER], [2215], [42], [ROSSKOPF Jorg], [GER], [2208], [43], [<NAME>], [SRB], [2205], [44], [<NAME>], [CRO], [2203], [45], [<NAME>], [DEN], [2195], [46], [<NAME>], [FRA], [2189], [47], [<NAME>], [SWE], [2182], [48], [<NAME>], [KOR], [2170], [49], [<NAME>], [DOM], [2167], [50], [<NAME>], [CRO], [2161], [51], [<NAME>], [SVK], [2160], [52], [<NAME>], [JPN], [2155], [53], [<NAME>], [FRA], [2153], [54], [<NAME>], [GRE], [2151], [55], [<NAME>], [HKG], [2144], [56], [<NAME>], [BUL], [2142], [57], [<NAME>], [FRA], [2137], [58], [<NAME>], [AUT], [2130], [59], [<NAME>], [CHN], [2121], [60], [<NAME>], [GER], [2115], [61], [<NAME>], [SGP], [2113], [62], [<NAME>], [GER], [2112], [63], [<NAME>], [RUS], [2103], [64], [SMIRNOV Alexey], [RUS], [2101], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (65 - 96)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [65], [<NAME>], [SWE], [2095], [66], [<NAME>], [CZE], [2091], [67], [<NAME>], [BEL], [2089], [68], [<NAME>], [POL], [2086], [69], [<NAME>], [CZE], [2082], [70], [<NAME>], [CZE], [2082], [71], [ERLANDSEN Geir], [NOR], [2075], [72], [<NAME>], [JPN], [2067], [73], [<NAME>], [GER], [2064], [74], [MIZUTANI Jun], [JPN], [2061], [75], [<NAME>], [SLO], [2048], [76], [<NAME>], [SWE], [2045], [77], [<NAME>], [FRA], [2044], [78], [<NAME>], [SVK], [2044], [79], [KUSINSKI Marcin], [POL], [2041], [80], [<NAME>], [KOR], [2037], [81], [<NAME>], [CRO], [2036], [82], [YANG Min], [ITA], [2032], [83], [MAZUNOV Dmitry], [RUS], [2031], [84], [OVTCHAROV Dimitrij], [GER], [2029], [85], [<NAME>], [HKG], [2018], [86], [<NAME>], [GER], [2016], [87], [<NAME>], [NGR], [2016], [88], [<NAME>], [JPN], [2012], [89], [<NAME>], [DEN], [2010], [90], [<NAME>], [HUN], [2007], [91], [<NAME>], [KOR], [2006], [92], [<NAME>], [UKR], [2000], [93], [<NAME>], [FRA], [2000], [94], [<NAME>], [SWE], [1999], [95], [<NAME>], [PRK], [1998], [96], [<NAME>], [PRK], [1994], ) )#pagebreak() #set text(font: ("Courier New", "NSimSun")) #figure( caption: "Men's Singles (97 - 128)", table( columns: 4, [Ranking], [Player], [Country/Region], [Rating], [97], [<NAME>], [KOR], [1993], [98], [CHT<NAME>], [BLR], [1987], [99], [<NAME>], [KOR], [1986], [100], [<NAME>], [CHN], [1986], [101], [<NAME>], [SWE], [1982], [102], [<NAME>], [FRA], [1981], [103], [<NAME>], [KOR], [1976], [104], [XU Hui], [CHN], [1974], [105], [JAKAB Janos], [HUN], [1974], [106], [#text(gray, "<NAME>")], [KOR], [1969], [107], [<NAME>], [CAN], [1966], [108], [#text(gray, "<NAME>")], [ITA], [1963], [109], [<NAME>], [BRA], [1963], [110], [#text(gray, "<NAME>")], [POL], [1961], [111], [<NAME>], [POL], [1953], [112], [<NAME>], [ISL], [1951], [113], [<NAME>], [SWE], [1951], [114], [<NAME>], [CRO], [1947], [115], [<NAME>], [KOR], [1945], [116], [<NAME>], [HUN], [1944], [117], [LIU Song], [ARG], [1943], [118], [<NAME>], [NOR], [1942], [119], [#text(gray, "<NAME>")], [SWE], [1941], [120], [<NAME>], [FRA], [1941], [121], [<NAME>], [CAN], [1940], [122], [<NAME>], [CZE], [1937], [123], [<NAME>], [ROU], [1936], [124], [<NAME>], [BRA], [1934], [125], [<NAME>], [CHN], [1934], [126], [<NAME>], [FRA], [1933], [127], [<NAME>], [FRA], [1928], [128], [<NAME>], [HUN], [1916], ) )
https://github.com/alperari/cyber-physical-systems
https://raw.githubusercontent.com/alperari/cyber-physical-systems/main/week2/solution.typ
typst
#import "@preview/diagraph:0.1.0": * = Exercise 1 - Group 1: a, c, d, g, i, j, k - Group 2: b, e, f, h = Exercise 2 #align( center, raw-render(height: 10em)[```dot digraph { rankdir=LR; start [style = invis, width = 0.01, fixedsize = true]; p0q0 [shape=circle] p0q1 [shape=circle] p0q2 [shape=square, width=0.75] p1q0 [shape=circle] p1q1 [shape=circle] p1q2 [shape=circle] start -> p0q0 p0q0 -> p0q0 [label=b] p0q0 -> p1q0 [label=a] p0q0 -> p1q1 [label=a] p0q1 -> p0q2 [label=b] p0q2 -> p0q2 [label=b] p0q2 -> p1q2 [label=a] p1q0 -> p0q0 [label=a] p1q0 -> p1q0 [label=b] p1q0 -> p0q1 [label=a] p1q1 -> p1q2 [label=b] p1q2 -> p1q2 [label=b] p1q2 -> p0q2 [label=a] } ```], ) = Exercise 3 == Language $L_1$ === Part A $ L_1 = { x_0x_1... | (forall^infinity i in N_0 space . space x_i in sum) and (exists i in N_0 space . space x_i = a) } $ === Part B #align( center, raw-render(height: 10em)[```dot digraph { rankdir=LR; start [style = invis, width = 0.01, fixedsize = true]; q0 [shape=circle] q1 [shape=square] start -> q0 q0 -> q0 [label="a, b"] q0 -> q1 [label=b] q1 -> q1 [label=b] } ```], ) === Part C $ L_1 = (Q_1, sum, delta_1, Q_1^"init", F_1) \ Q_1 = {q_0, q_1} \ sum = {a, b} \ Q_1^"init" = {q_0} \ F_1 = {q_1} \ delta_1 = { (q_0, a, q_0), (q_0, b, q_0), (q_0, b, q_1), (q_1, b, q_1) } $ == Language $L_2$ === Part A $ L_2 = { x_0 x_1 ... | (forall i in N_0 space . space x_i in sum)and (forall^infinity i in N_0 space . space i mod 2 eq 1 space . space x_i = a) } $ === Part B #align( center, raw-render(height: 10em)[```dot digraph { rankdir=LR; start [style = invis, width = 0.01, fixedsize = true]; q0 [shape=square] q1 [shape=circle] start -> q0 q0 -> q1 [label="a, b"] q1 -> q0 [label=a] } ```], ) === Part C $ L_2 = (Q_2, sum, delta_2, Q_2^"init", F_2) \ Q_2 = {q_0, q_1} \ sum = {a, b} \ Q_2^"init" = {q_0} \ F_2 = {q_0} \ delta_2 = { (q_0, a, q_1), (q_0, b, q_1), (q_1, a, q_0) } $
https://github.com/Enter-tainer/typst-preview
https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/docs/dev.typ
typst
MIT License
#import "./book.typ": book-page #import "./templates/gh-page.typ": page-width, is-dark-theme #import "@preview/fontawesome:0.1.0": * #import "@preview/colorful-boxes:1.1.0": * #import "@preview/commute:0.1.0": node, arr, commutative-diagram #show: book-page.with(title: "Set Up Development Environment") #show link: underline = Set Up Development Environment + Install Node.js & Yarn You need to install Node.js and Yarn for your platform first. + Install npm dependencies for `addons/frontend` and `addons/vscode` ```bash cd addons/typst-dom yarn && yarn build cd addons/frontend yarn && yarn build cd ../vscode yarn ``` + Install rust toolchain. The common option is to use #link("https://rustup.rs/")[rustup]. + Build and run: - To build and debug the VSCode extension: press `F5` in VSCode. And a new VSCode window will pop up. Open a typst source file in the new window, and you will see the preview button in the top right corner of the editor. - To build and run the binary only, run `cargo run` in the root directory of the project.
https://github.com/MatheSchool/typst-g-exam
https://raw.githubusercontent.com/MatheSchool/typst-g-exam/develop/examples/exam-big-image.typ
typst
MIT License
#import "../src/lib.typ": * #show: g-exam.with( author: ( name: "<NAME>", email: "<EMAIL>", watermark: "Teacher: Évariste", ), school: ( name: "Sunrise Secondary School", logo: image("./logo.png"), ), exam-info: ( academic-period: "Academic year 2023/2024", academic-level: "1st Secondary Education", academic-subject: "Mathematics", number: "2nd Assessment 1st Exam", content: "Radicals and fractions", model: "Model A" ), language: "en", decimal-separator: ",", date: "November 21, 2023", show-student-data: "first-page", show-grade-table: false, question-points-position: left, clarifications: "Answer the questions in the spaces provided. If you run out of room for an answer, continue on the back of the page." ) #g-question[Given the equation $x^n + y^n = z^n$ for $(x,y,z)$ and $n$ positive integers.] #image("./logo.png"), #g-subquestion[For what values of $n$ is the statement in the previous question true?] #v(1fr) #g-subquestion[For $n=2$ there's a theorem with a special name. What's that name?] #v(1fr) #g-subquestion[What famous mathematician had an elegant proof for this theorem but there was not enough space in the margin to write it down?]. #v(1fr) #g-question[Prove that the real part of all non-trivial zeros of the function $zeta(z) "is" 1/2$]. #v(1fr)
https://github.com/CoderJackZhu/XDUthesis-Typst
https://raw.githubusercontent.com/CoderJackZhu/XDUthesis-Typst/main/README.md
markdown
MIT License
# 西安电子科技大学学位论文 XDUthesis-Typst ## 介绍 Typst是一种新的排版标记语言,由rust编写,比latex性能优异,编译速度快,即使对非常长的文章也是一样,但是稳定性可能比不上Word和LaTeX。 这是西安电子科技大学毕业论文的Typst语言模板, 适用于本科和研究生学位论文,项目基于[modern-nju-thesis](https://github.com/nju-lug/modern-nju-thesis)重构。 ## 使用方法 ### VS Code 本地编辑(推荐) 在 VS Code 中安装 Tinymist Typst 和 Typst Preview 插件。前者负责语法高亮和错误检查等功能,后者负责预览。 也推荐下载 Typst Companion 插件,其提供了例如 Ctrl + B 进行加粗等便捷的快捷键。 你还可以下载我开发的 Typst Sync 和 Typst Sympy Calculator 插件,前者提供了本地包的云同步功能,后者提供了基于 Typst 语法的科学计算器功能。 最后用 VS Code 打开生成的目录,打开 template文件夹下的thesis.typ 文件,并按下 Ctrl + K V 进行实时编辑和预览。 <!-- --> 本科生和研究生的毕业论文都支持,在thesis.typ下按照要求更改选项即可,所有内容都在一个文件下了,语法简洁方便修改。 学习 Typst 需要多久? 一般而言,仅仅进行简单的编写,不关注布局的话,你可以打开模板就开始写了。 如果你想进一步学习 Typst 的语法,例如如何排篇布局,如何设置页脚页眉等,一般只需要几个小时就能学会。 如果你还想学习 Typst 的「元信息」部分,进而能够编写自己的模板,一般而言需要几天的时间阅读文档,以及他人编写的模板代码。 如果你有 Python 或 JavaScript 等脚本语言的编写经验,了解过函数式编程、宏、样式、组件化开发等概念,入门速度会快很多。 我有编写 LaTeX 的经验,如何快速入门? 可以参考 面向 LaTeX 用户的 Typst 入门指南。 目前 Typst 有哪些第三方包和模板? 可以查看 Typst Universe。 目前尚未完成西电毕业论文格式的适配,正在开发中,慎用。 ## 致谢参考仓库 [南京大学毕业论文](https://github.com/nju-lug/modern-nju-thesis) [上海大学本科毕业论文](https://github.com/shuosc/SHU-Bachelor-Thesis-Typst)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/grid-4-02.typ
typst
Other
// Test that all three kinds of rows use the correct bases. #set page(height: 4cm, margin: 0cm) #grid( rows: (1cm, 1fr, 1fr, auto), rect(height: 50%, width: 100%, fill: green), rect(height: 50%, width: 100%, fill: red), rect(height: 50%, width: 100%, fill: green), rect(height: 25%, width: 100%, fill: red), )
https://github.com/LDemetrios/Typst4k
https://raw.githubusercontent.com/LDemetrios/Typst4k/master/src/test/resources/suite/scripting/include.typ
typst
// Test module includes. --- include-file --- #set page(width: 200pt) // Include a file #include "modules/chap1.typ" // Expression as a file name. #let chap2 = include "modu" + "les/chap" + "2.typ" -- _Intermission_ -- #chap2 --- include-file-not-found --- #{ // Error: 19-38 file not found (searched at tests/suite/scripting/modules/chap3.typ) let x = include "modules/chap3.typ" } --- include-no-bindings --- #include "modules/chap1.typ" // The variables of the file should not appear in this scope. // Error: 2-6 unknown variable: name #name --- include-semicolon-or-linebreak --- // Error: 18 expected semicolon or line break #include "hi.typ" Hi
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/list-marker_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test that items are cycled. #set list(marker: ([--], [•])) - A - B - C
https://github.com/EunTilofy/NumComputationalMethods
https://raw.githubusercontent.com/EunTilofy/NumComputationalMethods/main/Chapter5/Chapter5-1.typ
typst
#import "../template.typ": * #show: project.with( course: "Computing Method", title: "Computing Method - Chapter5", date: "2024.4.5", authors: "<NAME>, 3210106357", has_cover: false ) *Problems:1,2(1),5,6* #HWProb(name: "1")[ 试证明: #set enum(numbering: "(1)") + $integral_a^b f(x) dx = (b - a)f(a) + (b-a)^2 / 2 f'(xi), a < xi < b$. + $integral_a^b f(x) dx = (b - a)f(b) - (b-a)^2 / 2 f'(eta), a < eta < b$. + $integral_a^b f(x) dx = (b - a)f((a+b)/2) + (b-a)^3/24 f''(zeta), a < zeta < b$. ] #Proof[ #set enum(numbering: "(1)") + $ integral_a^b f(x) dx = integral_a^b f(a) + (x - a) f'(xi_x) dx = (b - a) f(a) + integral_a^b (x - a) f'(xi_x) dx, $ 根绝 $f'(x)$ 在 $[a, b]$ 有界可设 $m leq f'(x) leq M$,所以 $ integral_a^b m(x - a) dx < integral_a^b (x - a) f'(xi_x) dx < integral_a^b M(x - a) dx \ arrow.double ((b-a)^2)/2 m < integral_a^b (x - a) f'(xi_x) dx < ((b-a)^2)/2 M, $ 所以,有$ m leq (integral_a^b f(x) dx - (b - a)f(a))/(1/2 (b-a)^2) leq M, $ 根据 $f in C^1$ 可知存在 $xi in (a, b)$,满足 $ f'(xi) = (integral_a^b f(x) dx - (b - a)f(a))/(1/2 (b-a)^2), $ 所以 $integral_a^b f(x) dx = (b - a)f(a) + (b-a)^2 / 2 f'(xi)$。 + $ integral_a^b f(x) dx = - integral_b^a f(x) dx, $ 类似(1)的证明,存在 $eta in (a, b)$,$ integral_b^a f(x) dx = (a - b) f(b) + (b-a)^2 / 2 f'(eta), $ 所以 $ integral_a^b f(x) dx = (b - a) f(b) - (b-a)^2 / 2 f'(eta). $ + $forall x in [a, b], f(x) = f((a+b)/2) + (x - (a+b)/2) f'((a+b)/2) + (x - (a+b)/2)/2 f''(xi_x), xi in [min(x, (a+b)/2), max(x, (a+b)/2)]$, $ integral_a^b f(x) dx &= integral_a^b f((a+b)/2) + (x - (a+b)/2) f'((a+b)/2) + (x - (a+b)/2)^2/2 f''(xi_x) dx \ &= (b - a) f((a+b)/2) + integral_a^b (x - (a+b)/2)/2 f''(xi_x) dx. $ 根绝 $f'(x)$ 在 $[a, b]$ 有界可设 $m leq f'(x) leq M$,所以$ integral_a^b m (x - (a+b)/2)^2 / 2 dx < integral_a^b (x - (a+b)/2)^2/2 f''(xi_x) dx < integral_a^b M (x - (a+b)/2)^2 / 2 dx \ arrow.double (b-a)^3/24 m leq integral_a^b (x - (a+b)/2)^2/2 f''(xi_x) dx leq (b-a)^3/24 M. $ 所以,有 $ m leq (integral_a^b f(x) dx - (b-a) f((a+b)/2))/(1/24 (b-a)^3) leq M, $ 根据 $f in C^1$ 可知存在 $zeta in (a, b)$,满足 $ f'(zeta) = (integral_a^b f(x) dx - (b-a) f((a+b)/2))/(1/24 (b-a)^3), $ 所以 $integral_a^b f(x) dx = (b - a)f((a+b)/2) + (b-a)^3/24 f''(zeta)$。 ] #HWProb(name: "2(1)")[ 用梯型公式和抛物线公式计算积分,并比较其结果。 $ integral_0^1 x / (4 + x^2) dx quad quad text("(八等分)"). $ ] #solution[ #set enum(numbering: "(1)") + $1/8 (1/2 f(0) + f(1/8) + dots.c + f(7/8) + 1/2 f(1)) = 0.11140235$ + $1/8 (1/6 f(0) + 2/3 f(1/16) + 1/3 f(1/8) + 2/3 f(3/16) + 1/3 f(2/8) + dots.c + 2/3 f(15/16) + 1/6 f(1)) = 0.11157181$ + 真值 $integral_0^1 x / (4 + x^2) dx = 1/2 ln(5/4) = 0.11157177$,\ 使用梯型公式计算误差为:0.000169,\ 使用抛物线公式计算误差为:3.75e-8,\ 可以发现使用抛物线公式计算效果更好。 ] #HWProb(name: "5")[ 如果 $f''(x) > 0$, 证明用梯型公式计算积分 $integral_a^b f(x) dx$ 所得结果比准确值大,并说明其几何意义。 ] #Proof[ 因为 $f''(x) > 0$,所以 $f$ 是凸函数,所以有$ f(t a + (1-t)b) < t f(a) + (1-t)f(b), forall 0 < t < 1, $ 所以$ integral_a^b f(x) dx &= (b - a)integral_0^1 f(t a + (1- t)b) dt \ &< (b - a) integral_0^1 (t f(a) + (1-t) f(b)) dt \ &= (b-a)/2 (f(a) + f(b)). $ 对于凸函数,因为其任意两点间割线总是位于这两点间曲线的上方,所以使用割线以下梯形的面积作为积分的估计总是比真实值来的大。 ] #HWProb(name: "6")[ 验证当 $f(x) = x^5$ 时,$n = 4$ 的 Newton-Cotes 公式是准确的。 ] #Proof[ 对于 $n = 4$,Newton-Cotes 公式为 $ integral_a^b f(x) dx approx (b-a)/90 (7f(a) + 32 f((3a+b)/4) + 12 f((a+b)/4) + 32 f((a+3b)/4) + 7 f(b)), $ 对于 $f(x) = x^5$, $ (b-a)/90 (7a^5 + 30((3a+b)/4)^5 + 12((a+b)/2)^5 + 32((a+3b)/4)^5 + 7b^5 = (b-a)^6/6. $ 所以公式是准确的。 ]
https://github.com/pedrofp4444/BD
https://raw.githubusercontent.com/pedrofp4444/BD/main/report/content/[1] Definição do sistema/main.typ
typst
#import "contexto.typ": contexto #import "motivacao.typ": motivacao #import "viabilidade.typ": viabilidade #import "recursos.typ": recursos #import "execucao.typ": execucao #let definicao_do_sistema = { [ = Definição do Sistema #contexto #motivacao #viabilidade #recursos #execucao ] }
https://github.com/paugarcia32/CV
https://raw.githubusercontent.com/paugarcia32/CV/main/modules/event.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Events") #cvEvent( title: "HackBCN", date: "2024", url: "https://www.hackbcn.com/en", logo: "../src/logos/hackbcn.png", description: list( [IA based Hackathon], [Teams of 3], ), ) #cvEvent( title: "HackUPC", date: "2024", url: "https://hackupc.com/", logo: "../src/logos/hackupc.jpeg", description: list( [Student Hackathon], [Teams of 4], [Development of a real time monitoring system], ), )
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/116.%20kate.html.typ
typst
kate.html What Kate Saw in Silicon Valley August 2009<NAME> is the architect who designed Y Combinator's office. Recently we managed to recruit her to help us run YC when she's not busy with architectural projects. Though she'd heard a lot about YC since the beginning, the last 9 months have been a total immersion.I've been around the startup world for so long that it seems normal to me, so I was curious to hear what had surprised her most about it. This was her list:1. How many startups fail.Kate knew in principle that startups were very risky, but she was surprised to see how constant the threat of failure was — not just for the minnows, but even for the famous startups whose founders came to speak at YC dinners. 2. How much startups' ideas change.As usual, by Demo Day about half the startups were doing something significantly different than they started with. We encourage that. Starting a startup is like science in that you have to follow the truth wherever it leads. In the rest of the world, people don't start things till they're sure what they want to do, and once started they tend to continue on their initial path even if it's mistaken. 3. How little money it can take to start a startup.In Kate's world, everything is still physical and expensive. You can barely renovate a bathroom for the cost of starting a startup. 4. How scrappy founders are.That was her actual word. I agree with her, but till she mentioned this it never occurred to me how little this quality is appreciated in most of the rest of the world. It wouldn't be a compliment in most organizations to call someone scrappy.What does it mean, exactly? It's basically the diminutive form of belligerent. Someone who's scrappy manages to be both threatening and undignified at the same time. Which seems to me exactly what one would want to be, in any kind of work. If you're not threatening, you're probably not doing anything new, and dignity is merely a sort of plaque. 5. How tech-saturated Silicon Valley is."It seems like everybody here is in the industry." That isn't literally true, but there is a qualitative difference between Silicon Valley and other places. You tend to keep your voice down, because there's a good chance the person at the next table would know some of the people you're talking about. I never felt that in Boston. The good news is, there's also a good chance the person at the next table could help you in some way. 6. That the speakers at YC were so consistent in their advice. Actually, I've noticed this too. I always worry the speakers will put us in an embarrassing position by contradicting what we tell the startups, but it happens surprisingly rarely.When I asked her what specific things she remembered speakers always saying, she mentioned: that the way to succeed was to launch something fast, listen to users, and then iterate; that startups required resilience because they were always an emotional rollercoaster; and that most VCs were sheep.I've been impressed by how consistently the speakers advocate launching fast and iterating. That was contrarian advice 10 years ago, but it's clearly now the established practice. 7. How casual successful startup founders are.Most of the famous founders in Silicon Valley are people you'd overlook on the street. It's not merely that they don't dress up. They don't project any kind of aura of power either. "They're not trying to impress anyone."Interestingly, while Kate said that she could never pick out successful founders, she could recognize VCs, both by the way they dressed and the way they carried themselves. 8. How important it is for founders to have people to ask for advice.(I swear I didn't prompt this one.) Without advice "they'd just be sort of lost." Fortunately, there are a lot of people to help them. There's a strong tradition within YC of helping other YC-funded startups. But we didn't invent that idea: it's just a slightly more concentrated form of existing Valley culture. 9. What a solitary task startups are.Architects are constantly interacting face to face with other people, whereas doing a technology startup, at least, tends to require long stretches of uninterrupted time to work. "You could do it in a box."By inverting this list, we can get a portrait of the "normal" world. It's populated by people who talk a lot with one another as they work slowly but harmoniously on conservative, expensive projects whose destinations are decided in advance, and who carefully adjust their manner to reflect their position in the hierarchy.That's also a fairly accurate description of the past. So startup culture may not merely be different in the way you'd expect any subculture to be, but a leading indicator.Japanese Translation
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/tests/unit/test.typ
typst
MIT License
#import "/src/lib.typ" as scrutinize // the output is not relevant for this test #set page(width: 0pt, height: 0pt) // TODO real tests #assert(true)
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/showybox/1.0.0/showy.typ
typst
Apache License 2.0
/* * ShowyBox - A package for Typst * <NAME> and Showybox Contributors (c) 2023 * * Main Contributors: * - <NAME> (<https://github.com/jneug>) * * showy.typ -- The package's main file containing the * public and (more) useful functions * * This file is under the MIT license. For more * information see LICENSE on the package's main folder. */ /* * Function: showy-inset() * * Description: Helper function to get inset in a specific direction * * Parameters: * + direction * + value */ #let showy-inset( direction, value ) = { direction = repr(direction) // allows use of alignment values if type(value) == "dictionary" { if direction in value { value.at(direction) } else if direction in ("left", "right") and "x" in value { value.x } else if direction in ("top", "bottom") and "y" in value { value.y } else if "rest" in value { value.rest } else { 0pt } } else if value == none { 0pt } else { value } } /* * Function: showy-line() * * Description: Creates a modified `#line()` function * to draw a separator line with start and end points * adjusted to insets. * * Parameters: * + frame: The dictionary with frame settings */ #let showy-line( frame ) = { let inset = frame.at("body-inset", default: frame.at("inset", default:(x:1em, y:0.65em))) let inset = ( left: showy-inset(left, inset), right: showy-inset(right, inset) ) let (start, end) = (0%, 0%) // For relative insets the original width needs to be calculated if type(inset.left) == "ratio" and type(inset.right) == "ratio" { let full = 100% / (1 - float(inset.right) - float(inset.left)) start = -inset.left * full end = full + start } else if type(inset.left) == "ratio" { let full = (100% + inset.right) / (1 - float(inset.left)) (start, end) = (-inset.left * full, 100% + inset.right) } else if type(inset.right) == "ratio" { let full = (100% + inset.left) / (1 - float(inset.right)) (start, end) = (-inset.left, full - inset.left) } else { (start, end) = (-inset.left, 100% + inset.right) } line.with( start: (start, 0%), end: (end, 0%) ) } /* * Function: showy-stroke() * * Description: Creates a stroke or set of strokes * to use as borders. * * Parameters: * + frame: The dictionary with frame settings */ #let showy-stroke( frame, ..overrides ) = { let (paint, dash, width) = ( frame.at("border-color", default: black), frame.at("dash", default: "solid"), frame.at("thickness", default: 1pt) ) let strokes = (:) if type(width) != "dictionary" { // Set all borders at once for side in ("top", "bottom", "left", "right") { strokes.insert(side, (paint: paint, dash: dash, thickness: width)) } } else { // Set each border individually for pair in width { strokes.insert( pair.first(), // key (paint: paint, dash: dash, thickness: pair.last()) ) } } for pair in overrides.named() { strokes.insert( pair.first(), (paint: paint, dash: dash, thickness: pair.last()) ) } return strokes } /* * Function: showybox() * * Description: Creates a showybox * * Parameters: * - frame: * + title-color: Color used as background color where the title goes * + body-color: Color used as background color where the body goes * + border-color: Color used for the showybox's border * + radius: Showybox's radius * + thickness: Border width of the showybox * + dash: Showybox's border style * - title-style: * + color: Text color * + weight: Text weight * + align: Text align * - body-styles: * + color: Text color * + align: Text align * - sep: * + width: Separator's width * + dash: Separator's style (as a 'line' dash style) */ #let showybox( frame: ( title-color: black, body-color: white, border-color: black, footer-color: luma(220), inset: (x:1em, y:.65em), radius: 5pt, thickness: 1pt, dash: "solid" ), title-style: ( color: white, weight: "bold", align: left ), body-style: ( color: black, align: left ), footer-style: ( color: luma(85), weight: "regular", align: left ), sep: ( width: 1pt, dash: "solid", gutter: 0.65em ), shadow: none, width: 100%, breakable: false, // align: none, // collides with align-function title: "", footer: "", ..body ) = { /* * Alignment wrapper */ let alignprops = (:) for prop in ("spacing", "above", "below") { if prop in body.named() { alignprops.insert(prop, body.named().at(prop)) } } let alignwrap( content ) = block( ..alignprops, width: 100%, if "align" in body.named() and body.named().align != none { align(body.named().align, content) } else { content } ) /* * Optionally create a wrapper * function to add a shadow. */ let shadowwrap = (sbox) => sbox if shadow != none { if type(shadow.at("offset", default: 4pt)) != "dictionary" { shadow.offset = ( x: shadow.at("offset", default: 4pt), y: shadow.at("offset", default: 4pt) ) } shadowwrap = (sbox) => block( breakable: breakable, radius: frame.at("radius", default: 5pt), fill: shadow.at("color", default: luma(128)), outset: ( top: -shadow.offset.y, left: -shadow.offset.x, right: shadow.offset.x, bottom: shadow.offset.y ), sbox ) } let showyblock = block( width: width, fill: frame.at("body-color", default: white), radius: frame.at("radius", default: 5pt), inset: 0pt, breakable: breakable, stroke: showy-stroke(frame) )[ /* * Title of the showybox. We'll check if it is * empty. If so, skip its drawing and only put * the body */ #if title != "" { block( inset: if "title-inset" in frame { frame.title-inset } else { frame.at("inset", default:(x:1em, y:0.65em)) }, width: 100%, spacing: 0pt, fill: frame.at("title-color", default: black), stroke: showy-stroke(frame, bottom:1pt), radius: (top: frame.at("radius", default: 5pt)))[ #align( title-style.at("align", default: left), text( title-style.at("color", default: white), weight: title-style.at("weight", default: "bold"), title ) ) ] } /* * Body of the showybox */ #block( width: 100%, spacing: 0pt, inset: if "body-inset" in frame { frame.body-inset } else { frame.at("inset", default:(x:1em, y:0.65em)) }, align( body-style.at("align", default: left), text( body-style.at("color", default: black), body.pos() .map(block.with(spacing:0pt)) .join(block(spacing: sep.at("gutter", default: .65em), align(left, // Avoid alignment errors showy-line(frame)( stroke: ( paint: frame.at("border-color", default: black), dash: sep.at("dash", default: "solid"), thickness: sep.at("thickness", default: 1pt) ) ) )) ) ) ) ) /* * Footer of the showybox */ #if footer != "" { block( inset: if "footer-inset" in frame { frame.footer-inset } else { frame.at("inset", default:(x:1em, y:0.65em)) }, width: 100%, spacing: 0pt, fill: frame.at("footer-color", default: luma(220)), stroke: showy-stroke(frame, top:1pt), radius: (bottom: frame.at("radius", default: 5pt)))[ #align( footer-style.at("align", default: left), text( footer-style.at("color", default: luma(85)), weight: footer-style.at("weight", default: "regular"), footer ) ) ] } ] alignwrap( shadowwrap(showyblock) ) }
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Grand_Oral.typ
typst
#import "template.typ": * // Take a look at the file `template.typ` in the file panel // to customize this template and discover how it works. #show: project.with( title: "Grand Oral", authors: ( "<NAME>", ), date: "16, Mai 2024", ) #set heading(numbering: "1.1.") == Problématique Comment sécurisons-nous nos conversations ? == Plan === 1. Contexte et Introduction - Présentation du contexte : les communications électroniques sont de plus en plus courantes dans notre vie quotidienne, mais cela pose des risques de sécurité - Présentation du sujet : les mathématiques permettent de sécuriser nos conversations en utilisant des algorithmes de cryptographie basés sur des principes mathématiques solides - But de l'exposé : montrer comment les mathématiques permettent de sécuriser nos conversations en utilisant des exemples concrets - Choix du sujet : expliquer les raisons === 2. Les clés asymétriques et symétriques - Définition des clés asymétriques : une paire de clés, l'une publique et l'autre privée, utilisées pour chiffrer et déchiffrer les messages - Explication du principe des clés asymétriques : utilisation de la théorie des nombres, notamment le petit théorème de Fermat - Définition des clés symétriques : une seule clé utilisée à la fois pour chiffrer et déchiffrer les messages Explication du principe des clés symétriques : utilisation de l'algorithme AES (Advanced Encryption Standard) === 3. Exemples d'utilisation concrète - Exemple 1 : le protocole SSL/TLS (Secure Sockets Layer/Transport Layer Security) qui utilise des clés asymétriques pour sécuriser les communications sur internet - Exemple 2 : le chiffrement des données avec l'algorithme AES ( Gestionnaire de mot de passe ) - Exemple 3 : la signature numérique RSA (Rivest-Shamir-Adleman) qui utilise des clés asymétriques pour authentifier et vérifier l'intégrité des données ( Authentification ) === 4. Conclusion Reprendre les idées principales == Elements mathématiques Petit théorème de Fermat: $a^p ≡ a (mod p)$ si $p$ est premier (RSA) Fonction indicatrice d'Euler $C equiv M^e (mod n)$ Chiffrement $ M equiv C^d (mod n)$ Déchiffrement Congruence (RSA) Nombre premier Matrice (AES) == Sources - https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Br2.pdf - https://nvlpubs.nist.gov/nistpubs/fips/nist.fips.197.pdf - https://fr.wikipedia.org/wiki/Cryptographie - https://fr.wikipedia.org/wiki/Advanced_Encryption_Standard - https://fr.wikipedia.org/wiki/Chiffrement_RSA - https://www.di.ens.fr/~nitulesc/files/crypto3.pdf - https://www.youtube.com/playlist?list=PLBlnK6fEyqRgj06MEnp2VebJ8DgMpF0Zj == IA Je me suis aidé d'une IA pour faciliter les itérations du plan et me donner des pistes pour commencer les recherches
https://github.com/matthew-e-brown/assignmatts
https://raw.githubusercontent.com/matthew-e-brown/assignmatts/main/src/templates.typ
typst
MIT License
/// General template for most written assignments. #let assignment( /// The main title of the assignment. If it is not `none`, appears at the top of the first page /// and in the top-right of the page header. title: none, /// The student/author name. Currently, multiple authors are not supported. Underneath the title /// and in the top-left of the page header. author: none, /// The `ABCD-1234H` course code. Appears next to the course name above the title, as well as in /// in the top-right of the page margins before the assignment title. course-code: none, /// The full name of the course. Appears above the title on the first page. course-name: none, /// The title to add to the PDF. pdf-title: none, /// The author(s) to add to the PDF. pdf-author: none, /// Set to `true` to put the title on its own page. title-page: false, /// Extra content to include underneath the title before the rest of the content. If /// `title-page` is `false`, it is placed directly after the title with a bit of extra space /// beneath it. If `title-page` is true, it is placed on the title page. preamble: none, /// What page size to use. page-size: "us-letter", /// How large to make the page margins. page-margins: 1in, /// A font-stack to use for main body text. main-font: ("New Computer Modern", "Linux Libertine"), /// A font-stack to use for equations. math-font: ("New Computer Modern Math"), /// A font-stack to use for `raw` text elements. code-font: ("New Computer Modern Mono", "Cascadia Code", "Consolas", "SF Mono"), /// The colour of the line that should separate footnotes from the rest of the document. footnotes-line-color: blue, /// Whether or not each page should have its own set of numbers/symbols for footnotes. footnotes-per-page: false, doc ) = { // A couple "private" defaults let par-spacing = 1.40em let par-leading = 0.70em // ============================================================================================= // ==== General text styles and spacing // ============================================================================================= // Set fonts set text(size: 11pt, font: main-font, lang: "en") show math.equation: set text(font: math-font) show raw: set text(font: code-font) // Block spacing set block(spacing: par-spacing) // Default spacing for all blocks, can be overridden show heading: set block(above: 1.6em, below: 1.2em) // Leading set par(leading: par-leading, linebreaks: "optimized") set list(indent: 1.25em, spacing: par-spacing) set enum(indent: 1.25em, spacing: par-spacing) // Highlight links blue and underline them, but only if they're hyperlinks show link: it => { if type(it.dest) == str and ( it.dest.starts-with("http://") or it.dest.starts-with("https://") or it.dest.starts-with("mailto:") or it.dest.starts-with("tel:") ) { underline(text(fill: rgb(0, 98, 209), it)) } else { it } } // ============================================================================================= // ==== Page-wide layout // ============================================================================================= set document( title: if pdf-title != auto { pdf-title } else if title != none [ #title ] else { none }, author: if pdf-author != none { pdf-author } else { () }, ) // Creates a block that will extend horizontally outwards by half the page margins. let margin-block(body) = { set text(size: 0.90em) move(dx: -page-margins / 2, block(width: 100% + page-margins, body)) } let header-content = margin-block[ #if footnotes-per-page { counter(footnote).update(0) } #author #h(1fr) #(course-code, title).filter(x => x != none).join[: ] ] let footer-content = margin-block[ #set align(right) #counter(page).display("p. 1/1", both: true) ] set page( paper: page-size, numbering: "1", margin: page-margins, header-ascent: page-margins / 2, footer-descent: page-margins / 2, header: header-content, footer: footer-content, ) // ============================================================================================= // ==== Styles for individual elements // ============================================================================================= set outline(indent: 2.4em) // -- Footnotes // -------------------------------------------------------- set footnote.entry( gap: 0.5em, clearance: 1em, separator: line(length: 100%, stroke: (thickness: 0.75pt, paint: footnotes-line-color, cap: "round")), ) show footnote.entry: it => { set par(justify: true) set text(size: 0.90em) let loc = it.note.location() let num = numbering(it.note.numbering, ..counter(footnote).at(loc)) let space = 0.65em grid( columns: (auto, 1fr), column-gutter: 0pt, block(inset: (right: space, top: 0.2em), width: 1.7em, align(right, strong(num))), block(inset: (left: space, y: 0.2em), stroke: (left: 0.25pt + gray), it.note.body), ) } // -- Figures // -------------------------------------------------------- set figure(gap: par-leading * 1.85) // Un-justify and shrink figure caption text, make supplement and counter bold show figure.caption: it => { set text(0.90em) set par(justify: false) [*#it.supplement #it.counter.display():* #it.body] } // ============================================================================================= // ==== END OF PREAMBLE ==== // ============================================================================================= let title-block = if title != none { set align(center) set par(leading: 1.15em) set text(1.15em) // If there's a title alone on a title page, it doesn't need extra padding below it. let title-padding = if title-page and preamble == none { 0pt } else { 3.25em } block(below: title-padding, [ #(course-code, course-name).filter(x => x != none).join[: ] \ #text(2.00em, weight: 700, title) \ #author ]) } else { none } // If we have a title page, wrap the title block in it its own page with some different spacing // first. Otherwise, just spit it out right away. if title-page { // New footer just for this page let footer = margin-block[ #set align(right) #counter(page).display("i.") ] page(numbering: "i", footer: footer, { v(0.25fr) title-block preamble v(1.00fr) }) counter(page).update(1) } else { // Fix for a "bug?" For some reason, the margin-blocks in the header and footer get shifted // to the side without this. v(0pt, weak: false) title-block if preamble != none { preamble v(par-spacing * 2, weak: true) } } doc }
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/shorthand-00.typ
typst
Other
The non-breaking~space does work.
https://github.com/Mufanc/hnuthss-template
https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/README.md
markdown
## 喵 感谢 [@cyp0633](https://github.com/cyp0633) 提供的 [论文模板](https://github.com/cyp0633/hnu-bachelor-thesis-typst-template) 在原项目基础上改太多了,于是单独开了个仓库( --- 中文字体换成了 Google Fonts 的 Noto 系列,请自行下载 [Noto Sans SC](https://fonts.google.com/noto/specimen/Noto+Sans+SC) 和 [Noto Serif SC](https://fonts.google.com/noto/specimen/Noto+Serif+SC) 这两个字体到 `assets/fonts` 文件夹下 你也可以从 [fonts 分支](https://github.com/Mufanc/bachelor-dissertation-template/tree/fonts) 中下载到我使用的字体(共约 175MB) ```shell make checkout-fonts ``` 如果感觉字体不对劲,也可以直接使用 SimSun 和 SimHei,然后按下面的方式配置假加粗: ```typst // https://github.com/typst/typst/issues/394#issuecomment-2014481869 #show text.where(weight: "bold").or(strong): content => { show regex("\p{script=Han}"): set text(stroke: 1em / 35) content } ```
https://github.com/kotfind/typst_task
https://raw.githubusercontent.com/kotfind/typst_task/master/task.typ
typst
// -------------------- Utils -------------------- // Returns the first argument that is not equal to `none`. // Returns `none` if all arguments are equal to `none`. #let ifnone(..args) = { for arg in args.pos() { if arg != none { arg break } } none } // -------------------- Doc -------------------- #let doc_data = state("doc_data", (:)) #let conf( title: none, short_title: none, show_score_table: true, show_ans_table: true, reset_tour_page_counter: true, body ) = { // Update variables doc_data.update(( title: title, short_title: ifnone(short_title, title), show_score_table: show_score_table, show_ans_table: show_ans_table, reset_tour_page_counter: reset_tour_page_counter, )) // Body body } // -------------------- Tour -------------------- #let tour_counter = counter("tour_counter") #let tour_tasks = state("tour_tasks", ()) #let this_tour_end() = { query(selector(label("tour_end")).after(here())).first().location() } #let tour_score_table() = { let tasks = tour_tasks.at(this_tour_end()) let total_score = tasks.map(task => task.score).sum(default: 0) let score_box = box(width: 0.7cm, height: 0.7cm) let nums_row = range(1, tasks.len() + 1).map(id => str(id)) let max_scores_row = tasks.map(task => $#task.score$) let scores_row = tasks.map(task => score_box) table( columns: tasks.len() + 2, [*Задача:*], ..nums_row, $sum$, [*Макс. балл:*], ..max_scores_row, $#total_score$, [*Балл:*], ..scores_row, score_box, ) } #let tour_ans_table() = { let tasks = tour_tasks.at(this_tour_end()) let row = tasks .enumerate() .map(((id, task)) => ( str(id + 1), task.name, par(justify: true, task.ans) )).flatten() table( columns: (auto, auto, 1fr), [*№*], [*Задача*], [*Ответ*], ..row ) } #let tour( title: none, show_score_table: none, show_ans_table: none, body ) = { // Update variables tour_tasks.update(()) tour_counter.step() context { if doc_data.get().reset_tour_page_counter { counter(page).update(1) } } // Page setup // NOTE Works on the answers page only. Seems to be related to https://github.com/typst/typst/issues/2987 set page( header: align(center, context { let footer = () if doc_data.get().short_title != none { footer.push(doc_data.get().short_title) } footer.push([Тур #tour_counter.display()]) if title != none { footer.push(["#title"]) } footer.join(". ") line(length: 100%, stroke: 0.5pt) }), footer: align(center)[Лист #counter(page).display()], ) // Title pagebreak(weak: true) if title != none { align(center, text(18pt, weight: "bold", context { if doc_data.get().title != none { doc_data.get().title linebreak() } [Тур ] tour_counter.display() if title != none { linebreak() ["#title"] } })) } // Scores table context { if ifnone(show_score_table, doc_data.get().show_score_table, true) { align(center, tour_score_table()) } } // Body body // Answers table context { if ifnone(show_ans_table, doc_data.get().show_ans_table, true) { pagebreak() align(center, { text(18pt, weight: "bold")[Ответы] tour_ans_table() }) } } [#none <tour_end>] } // -------------------- Tasks -------------------- #let score_as_word(score) = { let orig_score = score if score >= 20 { score = calc.rem(score, 10) } let word = if score == 0 [баллов] else if score == 1 [балл] else if score <= 4 [балла] else if score <= 19 [баллов] else { panic("unreachable") } [#orig_score #word] } #let task(score: 1, with_proof: false, name, cond, ans) = box(width: 1fr, { // Update variables tour_tasks.update(t => { t.push(( name: name, score: score, ans: ans, )) t }) // Title v(0.5cm) align(center, text(14pt, weight: "bold", context [ Задача #tour_tasks.get().len(). #name (#score_as_word(score)) ])) // Condition cond // Answer/ proof field if with_proof [ *\ Решение:* #box(width: 1fr, height: 5cm) ] else [ *\ \ Ответ: * #box(width: 5cm, stroke: (bottom: 0.5pt)) ] })
https://github.com/giZoes/justsit-thesis-typst-template
https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/utils/textcricled.typ
typst
MIT License
#import "indent.typ":fake-par #let onum(num) = { set text(size: 0.625em) fake-par num = str(num) box( circle( radius: 0.5em, stroke: 0.5pt, inset: 0pt, outset: 1pt, move( dx: 1pt - 1.5pt * (num.len() - 1), dy: 0.1pt, num, ), ), ) [ ] }
https://github.com/Edubmstr/typst_public
https://raw.githubusercontent.com/Edubmstr/typst_public/main/supercharged-dhbw1/acronyms.typ
typst
#let acronyms = ( API: "Application Programming Interface", HTTP: "Hypertext Transfer Protocol", REST: "Representational State Transfer", )
https://github.com/AntonioSilva03/CurriculumVitae
https://raw.githubusercontent.com/AntonioSilva03/CurriculumVitae/main/Curriculum em Português/template/resume.typ
typst
#import "@preview/modern-cv:0.4.0": * #show: resume.with( author: ( firstname: "António", lastname: "Silva", email: "<EMAIL>", phone: "(+351) 968780666", github: "AntonioSilva03", linkedin: "antónio-silva03", address: "Braga, Braga", positions: ( "Engenheiro Informático", ), ), date: datetime.today().display(), language: "en", colored-headers: true, ) = Educação #resume-entry( title: "Escola EB 2,3 de Gualtar", location: "Braga", date: "2013 - 2018" ) #resume-entry( title: "Escola Secundária Carlos Amarante", location: "Braga", date: "2018 - 2021", description: "Curso de Ciências e Tecnologias Média Final de 18,22 valores", ) #resume-entry( title: "Universidade do Minho", location: "Braga", date: "2021 - 2024", description: "Licenciatura em Engenharia Informática", ) = Certificações #resume-entry( title: "Quadro de Merito Académico (x8)", location: "Braga", date: "2013-2021", description: "Agrupamento de Escolas Carlos Amarante", ) #resume-entry( title: "Certificate in Advanced English (C1)", location: "Braga", date: "dezembro 2020", description: "Cambridge Assessment English", ) = Projetos #resume-entry( title: "Plataforma de leilões online", location: [#github-link("AntonioSilva03/Projeto-LI4")], date: "setembro 2023 - janeiro 2024", description: "Universidade do Minho - Laboratórios de Informática IV", ) #resume-item[ - Plataforma para a criação de leilões contendo skins do jogo Counter-Strike - Plataforma composta em 3 camadas: Base de Dados, Lógica de Negócio e Interface do Utilizador - Autenticação básica com email e password, com a qual cada utilizador pode criar leilões, licitar em leilões e ver o seu histórico de leilões - Dashboard de administrador - Ferramentas - Blazor, Microsoft SQL Server, HTML, CSS ] #resume-entry( title: "Gerador de Sites de UC", location: [#github-link("AntonioSilva03/Projeto-EngWeb")], date: "maio 2024 - junho 2024", description: "Universidade do Minho - Engenharia Web", ) #resume-item[ - Plataforma para gerar páginas web que servem de suporte a unidades curriculares - Três tipos de utilizadores (aluno, docente, admin) - Nesta aplicação, os docentes das UCs podem disponibilizar ficheiros, colocar informação sobre a UC (avaliação, horários, equipa docente). - Todos este conteúdo poderá ser consultado pelos alunos que ingressarem na UC. - Arquitetura dividida 3 camadas: interface, servidor de autenticação, API e base de dados - Autenticação com JWT - Ferramentas - Express, MongoDB, JWT, Docker ] #resume-entry( title: "Engine 3D", location: [#github-link("AntonioSilva03/Projeto-CG")], date: "fevereiro 2024 - junho 2024", description: "Universidade do Minho - Computação Gráfica", ) #resume-item[ - Neste projeto foi desenvolvido um motor 3D baseado em gráficos de mini-figuras 3D. - Foi dividido em quatro fases e, em cada fase, foi fornecido um conjunto de ficheiros XML de configuração para fins de teste e avaliação. - Foi possível a criação de cenas 3D, como por exemplo, a criação de um cubo, um plano, uma esfera, um cone, um cilindro e até mesmo de um sistema solar, com rotação dos planetas realistas. - Foi implementado um sistema de transformações geométricas manualmente, um sistema de câmara e um sistema de iluminação. - Ferramentas - OpenGl, C++. ] #pagebreak() #resume-entry( title: "Serviço de orquestração de tarefas num computador", location: [#github-link("AntonioSilva03/Projeto-SO")], date: "março 2024 - junho 2024", description: "Universidade do Minho - Sistemas Operativos", ) #resume-item[ - O servidor é executado infinitamente, esperando de forma persistente por pedidos de clientes. - O cliente pode pedir por uma execução de uma tarefa, uma pipeline de programas ou por um estado do servidor. - O servidor consegue executar com duas políticas de escalonamento que devem ser passadas como argumento. - É possível testar os tempos de execução das várias políticas com as mesmas tarefas - Ferramentas - C ] #resume-entry( title: "Desenvolvimento de uma interface de sistema", location: [#github-link("AntonioSilva03/Projeto-IPM")], date: "março 2024 - junho 2024", description: "Universidade do Minho - Interface Pessoa-Máquina", ) #resume-item[ - Interface para mecânicos de uma estação de serviço - Vários estados para um serviço - Possibilidade de alterar detalhes - Foi utilizado o pinia para implementar o estado da aplicação - Backend implementada com json-server - Ferramentas - Vue ] #resume-entry( title: "Sistemas de gestão de uma estação de serviço", location: [#github-link("AntonioSilva03/Projeto-DSS")], date: "setembro 2023 - janeiro 2024", description: "Universidade do Minho - Desenvolvimento de Sistemas de Software", ) #resume-item[ - Este sistema auxilia o funcionamento de uma estação da E.S.Ideal. - Vários diagramas para auxiliar a compreensão do sistema - Fornece aos seus clientes vários serviços de marcação e de manutenção automóvel. - Dois tipos de utilizadores: gerente e mecânico - Arquitetura implementada com o uso de uma base de dados. - Ferramentas - Java, SQL Server e Visual Paradigm. ] #resume-entry( title: "Base de Dados de um fictício Hospital", location: [#github-link("AntonioSilva03/Projeto-BD")], date: "fevereiro 2022 - junho 2023", description: "Universidade do Minho - Base de Dados", ) #resume-item[ - Definição do sistema de informação de um hospital e recursos humanos - Levantamento e Análise de Requisitos - Modelação conceptual e lógica da base de dados - Implementação física da base de dados e de um sistema de gestão de base de dados - Sistema de Painéis de Análise de Dados - Ferramentas - SQL, PowerBI, brModelo ] #resume-entry( title: "Serviço de transferência de ficheiros Peer-to-Peer", location: [#github-link("AntonioSilva03/Projeto-CC")], date: "outubro 2023 - dezembro 2023", description: "Universidade do Minho - Comunicações por Computador", ) #resume-item[ - Um serviço peer-to-peer de transferência de ficheiros permite aos clientes transferir dados de forma mais eficiente de vários nós (seeders) transferindo partes diferentes de pacotes em paralelo. - Existe uma entidade central que trata das conecções e controla que ficheiros cada nó tem - É possível também consultar os ficheiros que se encontram a ser partilhados naquele momento diretamente no programa, bem como eliminar ficheiros. - Utilização de TCP e UDP - Ferramentas - Java ] #resume-entry( title: "Modelos de aprendizagem e decisão", location: [#github-link("AntonioSilva03/Projeto-ADI")], date: "março 2024 - junho 2024", description: "Universidade do Minho - Aprendizagem e Decisão Inteligentes", ) #resume-item[ - Este projeto divide-se em duas tarefas separadas. A primeira tarefa consiste na consulta, exploração, análise e preparação de um dataset escolhido por nós. A segunda tarefa consiste na mesma base, mas desta vez sobre um dataset escolhido pelos professores. - Como o dataset escolhido pelos professores demonstrava normalmente um problema de Classificação, o dataset que resolvemos escolher demonstra normalmente um problema de Regressão. - Todos os modelos em detalhe, bem como resultados e análise podem ser encontrados num relatório. - Ferramentas - KNIME ] #pagebreak() #resume-entry( title: "Serviços de troca de mensagens", location: [#github-link("AntonioSilva03/SSI2324")], date: "fevereiro 2024 - junho 2024", description: "Universidade do Minho - Segurança de Sistemas Informáticos", ) #resume-item[ - Repositório com todos os trabalhos práticos realizados na unidade curricular de Segurança de Sistemas Informáticos e guiões de laboratório. - TP1: serviço de troca de mensagens encriptadas que utiliza o protocolo Diffie-Hellman. São ainda utilizados certificados x503 e o protocolo Station-to-Station. - TP2: Aplicação Concordia. Serviço de troca de mensagens que funciona com os utilizadores e grupos do sistema Linux. É possivel enviar mensagens para um utilizador único ou para um grupo constituído por vários utilizadores. - Ferramentas - Python, C ] #resume-entry( title: "Compilador de Forth", location: [#github-link("AntonioSilva03/Projeto-PL")], date: "maio 2024 - junho 2024", description: "Universidade do Minho - Processamento de Linguagens", ) #resume-item[ - Compilador para a linguagem Forth que gera código para uma máquina virtual - Gramática tradutora baseada em PLY-Yacc - Analisador léxico implementado com PLY-Lex - Ferramentas - Python ] = Skills #resume-skill-item( "Linguagens", ( "C++", "C", "C#", "Python", "Java", "JavaScript", "Haskell", "HTML", "CSS", ), ) #resume-skill-item( "Frameworks", ( "Vue", "Blazor", "Express", ), ) #resume-skill-item( "Ferramentas", ( "Git", "Docker", "MongoDB", "SQL Server", ), ) #resume-skill-item("Linguas faladas", ( "Português", "Inglês" )) #resume-skill-item("Soft-skills", ( "Trabalho em equipa", "Comunicação", "Gestão de tempo", "Resolução de problemas", "Adaptabilidade", "Descobrimento de bugs" ))
https://github.com/qjcg/typstry
https://raw.githubusercontent.com/qjcg/typstry/main/templates/tutorial-report/main.typ
typst
MIT License
#set page( paper: "us-letter", margin: (x: 3.0cm, y: 1.5cm), ) #set par( justify: true, leading: 0.52em, ) #set text(font: "ETBembo", size: 30pt) = Title Page #set text(size: 12pt) #pagebreak() #set heading(numbering: "1.") #outline() #pagebreak() = Introduction In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers and how they contribute to the formation and behavior of these natural structures. + The climate + The topography + The geology Glaciers as the one shown in @glaciers will cease to exist if we don't take action soon! #figure( image("../../images/glacier.jpg", width: 70%), caption: [ _Glaciers_ form an important part of the earth's climate system. ], ) <glaciers> == Background #lorem(100) == Methods #lorem(200)
https://github.com/jassielof/typst-templates
https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/capítulos/8.inversiones.typ
typst
MIT License
= Inversiones == Inversiones Durante el Año 0 === Activos Fijos === Activos Diferidos === Capital de Trabajo === Estructura de Inversiones == Plan de Reinversiones === Activos Fijos === Capital de Trabajo
https://github.com/bigskysoftware/hypermedia-systems-book
https://raw.githubusercontent.com/bigskysoftware/hypermedia-systems-book/main/ch04-extending-html-as-hypermedia.typ
typst
Other
#import "lib/definitions.typ": * == Extending HTML As Hypermedia In the previous chapter we introduced a simple Web 1.0-style hypermedia application to manage contacts. Our application supported the normal CRUD operations for contacts, as well as a simple mechanism for searching contacts. Our application was built using nothing but forms and anchor tags, the traditional hypermedia controls used to interact with servers. The application exchanges hypermedia (HTML) with the server over HTTP, issuing `GET` and `POST` HTTP requests and receiving back full HTML documents in response. It is a basic web application, but it is also definitely a Hypermedia-Driven Application. It is robust, it leverages the web’s native technologies, and it is simple to understand. So what’s not to like about the application? Unfortunately, our application has a few issues common to web 1.0 style applications: - From a user experience perspective: there is a noticeable refresh when you move between pages of the application, or when you create, update or delete a contact. This is because every user interaction (link click or form submission) requires a full page refresh, with a whole new HTML document to process after each action. - From a technical perspective, all the updates are done with the `POST` HTTP method. This, despite the fact that more logical actions and HTTP request types like `PUT` and `DELETE` exist and would make more sense for some of the operations we implemented. After all, if we wanted to delete a resource, wouldn’t it make more sense to use an HTTP `DELETE` request to do so? Somewhat ironically, since we have used pure HTML, we are unable to access the full expressive power of HTTP, which was designed specifically _for_ HTML. The first point, in particular, is noticeable in Web 1.0 style applications like ours and is what is responsible for giving them the reputation for being "clunky" when compared with their more sophisticated JavaScript-based Single Page Application cousins. We could address this issue by adopting a Single Page Application framework, and updating our server-side to provide JSON-based responses. Single Page Applications eliminate the clunkiness of web 1.0 applications by updating a web page without refreshing it: they can mutate parts of the Document Object Model (DOM) of the existing page without needing to replace (and re-render) the entire page. #sidebar[The DOM][ #index[Document Object Model (DOM)] The DOM is the internal model that a browser builds up when it processes HTML, forming a tree of "nodes" for the tags and other content in the HTML. The DOM provides a programmatic JavaScript API that allows you to update the nodes in a page directly, without the use of hypermedia. Using this API, JavaScript code can insert new content, or remove or update existing content, entirely outside the normal browser request mechanism. ] There are a few different styles of SPA, but, as we discussed in Chapter 1, the most common approach today is to tie the DOM to a JavaScript model and then let an SPA framework like #link("https://reactjs.org/")[React] or #link("https://vuejs.org/")[Vue] _reactively_ update the DOM when a JavaScript model is updated: you make a change to a JavaScript object that is stored locally in memory in the browser, and the web page "magically" updates its state to reflect the change in the model. In this style of application, communication with the server is typically done via a JSON Data API, with the application sacrificing the advantages of hypermedia in order to provide a better, smoother user experience. Many web developers today would not even consider the hypermedia approach due to the perceived "legacy" feel of these web 1.0 style applications. Now, the second more technical issue we mentioned may strike you as a bit pedantic, and we are the first to admit that conversations around REST and which HTTP Action is right for a given operation can become very tedious. But still, it’s odd that, when using plain HTML, it is impossible to use all the functionality of HTTP! Just seems wrong, doesn’t it? === A Close Look At A Hyperlink <_a_close_look_at_a_hyperlink> It turns out that we can boost the interactivity of our application and address both of these issues _without_ resorting to the SPA approach. We can do so by using a _hypermedia-oriented_ JavaScript library, #link("https://htmx.org")[htmx]. The authors of this book built htmx specifically to extend HTML as a hypermedia and address the issues with legacy HTML applications we mentioned above (as well as a few others.) Before we get into how htmx allows us to improve the UX of our Web 1.0 style application, let’s revisit the hyperlink/anchor tag from Chapter 1. Recall, a hyperlink is what is known as a _hypermedia control_, a mechanism that describes some sort of interaction with a server by encoding information about that interaction directly and completely within the control itself. Consider again this simple #indexed[anchor tag] which, when interpreted by a browser, creates a #indexed[hyperlink] to the website for this book: #figure(caption: [A simple hyperlink, revisited], ```html <a href="https://hypermedia.systems/"> Hypermedia Systems </a> ```) Let’s break down exactly what happens with this link: - The browser will render the text "Hypermedia Systems" to the screen, likely with a decoration indicating it is clickable. - Then, when a user clicks on the text…​ - The browser will issue an HTTP `GET` to `https://hypermedia.systems`…​ - The browser will load the HTML body of the HTTP response into the browser window, replacing the current document. So we have four aspects of a simple hypermedia link like this, with the last three aspects supplying the mechanism that distinguishes a hyperlink from "normal" text and, thus, makes this a hypermedia control. Now, let’s take a moment and think about how we can _generalize_ these last three aspects of a hyperlink. ==== Why Only Anchors & Forms? <_why_only_anchors_forms> Consider: what makes anchor tags (and forms) so special? Why can’t other elements issue HTTP requests as well? For example, why shouldn’t `button` elements be able to issue HTTP requests? It seems arbitrary to have to wrap a form tag around a button just to make deleting contacts work in our application, for example. Maybe: other elements should be able to issue HTTP requests as well. Maybe other elements should be able to act as hypermedia controls on their own. This is our first opportunity to generalize HTML as a hypermedia. #important[Opportunity 1][ HTML could be extended to allow _any_ element to issue a request to the server and act as a hypermedia control. ] ==== Why Only Click & Submit Events? <_why_only_click_submit_events> Next, let’s consider the event that triggers the request to the server on our link: a click event. #index[events][click] #index[events][submit] Well, what’s so special about clicking (in the case of anchors) or submitting (in the case of forms) things? Those are just two of many, many events that are fired by the DOM, after all. Events like mouse down, or key up, or blur are all events you might want to use to issue an HTTP request. Why shouldn’t these other events be able to trigger requests as well? This gives us our second opportunity to expand the expressiveness of HTML: #important[Opportunity 2][ HTML could be extended to allow _any_ event --- not just a click, as in the case of hyperlinks --- to trigger HTTP requests. ] ==== Why Only GET & POST? <_why_only_get_post> #index[HTTP methods] Getting a bit more technical in our thinking leads us to the problem we noted earlier: plain HTML only give us access to the `GET` and `POST` actions of HTTP. HTTP _stands_ for Hypertext Transfer Protocol, and yet the format it was explicitly designed for, HTML, only supports two of the five developer-facing request types. You _have_ to use JavaScript and issue an AJAX request to get at the other three: `DELETE`, `PUT` and `PATCH`. Let’s recall what these different HTTP request types are designed to represent: - `GET` corresponds with "getting" a representation for a resource from a URL: it is a pure read, with no mutation of the resource. - `POST` submits an entity (or data) to the given resource, often creating or mutating the resource and causing a state change. - `PUT` submits an entity (or data) to the given resource for update or replacement, again likely causing a state change. - `PATCH` is similar to `PUT` but implies a partial update and state change rather than a complete replacement of the entity. - `DELETE` deletes the given resource. These operations correspond closely to the CRUD operations we discussed in Chapter 2. By giving us access to only two of the five, HTML hamstrings our ability to take full advantage of HTTP. This gives us our third opportunity to expand the expressiveness of HTML: #important[Opportunity 3][ HTML could be extended so that it allows access to the missing three HTTP methods, `PUT`, `PATCH` and `DELETE`. ] ==== Why Only Replace The Entire Screen? <_why_only_replace_the_entire_screen> #index[transclusion] #index[DOM][partial updates] As a final observation, consider the last aspect of a hyperlink: it replaces the _entire_ screen when a user clicks on it. It turns out that this technical detail is the primary culprit for poor user experience in Web 1.0 Applications. A full page refresh can cause a flash of unstyled content, where content "jumps" on the screen as it transitions from its initial to its styled final form. It also destroys the scroll state of the user by scrolling to the top of the page, removes focus from a focused element and so forth. But, if you think about it, there is no rule saying that hypermedia exchanges _must_ replace the entire document. This gives us our fourth, final and perhaps most important opportunity to generalize HTML: #important[Opportunity 4][ HTML could be extended to allow the responses to requests to replace elements _within_ the current document, rather than requiring that they replace the _entire_ document. ] This is actually a very old concept in hypermedia. <NAME>, in his 1980 book "Literary Machines" coined the term _transclusion_ to capture this idea: the inclusion of content into an existing document via a hypermedia reference. If HTML supported this style of "dynamic transclusion," then Hypermedia-Driven Applications could function much more like a Single Page Application, where only part of the DOM is updated by a given user interaction or network request. === Extending HTML as a Hypermedia with Htmx <_extending_html_as_a_hypermedia_with_htmx> These four opportunities present us a way to extend HTML well beyond its current abilities, but in a way that is _entirely within_ the hypermedia model of the web. The fundamentals of HTML, HTTP, the browser, and so on, won’t be changed dramatically. Rather, these generalizations of _existing functionality_ already found within HTML would simply let us accomplish _more_ using HTML. #index[htmx][about] Htmx is a JavaScript library that extends HTML in exactly this manner, and it will be the focus of the next few chapters of this book. Again, htmx is not the only JavaScript library that takes this hypermedia-oriented approach (other excellent examples are #link("https://unpoly.com")[Unpoly] and #link("https://hotwire.dev")[Hotwire]), but htmx is the purest in its pursuit of extending HTML as a hypermedia. ==== Installing and Using Htmx <_installing_and_using_htmx> From a practical "getting started" perspective, htmx is a simple, dependency-free and stand-alone JavaScript library that can be added to a web application by simply including it via a `script` tag in your `head` element. #index[htmx][installing] Because of this simple installation model, you can take advantage of tools like public CDNs to install the library. Below is an example using the popular #link("https://unpkg.com")[unpkg] Content Delivery Network (CDN) to install version `1.9.2` of the library. We use an integrity hash to ensure that the delivered JavaScript content matches what we expect. This SHA can be found on the htmx website. We also mark the script as `crossorigin="anonymous"` so no credentials will be sent to the CDN. #figure(caption: [Installing htmx], ```html <head> <script src="https://unpkg.com/[email protected]" integrity="<KEY> <KEY>" crossorigin="anonymous"></script> </head> ```) If you are used to modern JavaScript development, with complex build systems and large numbers of dependencies, it may be a pleasant surprise to find that that’s all it takes to install htmx. This is in the spirit of the early web, when you could simply include a script tag and things would "just work." If you don’t want to use a CDN, you can download htmx to your local system and adjust the script tag to point to wherever you keep your static assets. Or, you may have a build system that automatically installs dependencies. In this case you can use the Node Package Manager (npm) name for the library: `htmx.org` and install it in the usual manner that your build system supports. Once htmx has been installed, you can begin using it immediately. ==== No JavaScript Required…​ <_no_javascript_required> And here we get to the interesting part of htmx: htmx does not require you, the user of htmx, to actually write any JavaScript. #index[htmx][attributes] Instead, you will use _attributes_ placed directly on elements in your HTML to drive more dynamic behavior. Htmx extends HTML as a hypermedia, and it is designed to make that extension feel as natural and consistent as possible with existing HTML concepts. Just as an anchor tag uses an `href` attribute to specify the URL to retrieve, and forms use an `action` attribute to specify the URL to submit the form to, htmx uses HTML _attributes_ to specify the URL that an HTTP request should be issued to. === Triggering HTTP Requests <_triggering_http_requests> #index[hx-get][about] #index[hx-post][about] #index[hx-put][about] #index[hx-patch][about] #index[hx-delete][about] Let’s look at the first feature of htmx: the ability for any element in a web page to issue HTTP requests. This is the core functionality provided by htmx, and it consists of five attributes that can be used to issue the five different developer-facing types of HTTP requests: - `hx-get` - issues an HTTP `GET` request. - `hx-post` - issues an HTTP `POST` request. - `hx-put` - issues an HTTP `PUT` request. - `hx-patch` - issues an HTTP `PATCH` request. - `hx-delete` - issues an HTTP `DELETE` request. Each of these attributes, when placed on an element, tells the htmx library: "When a user clicks (or whatever) this element, issue an HTTP request of the specified type." The values of these attributes are similar to the values of both `href` on anchors and `action` on forms: you specify the URL you wish to issue the given HTTP request type to. Typically, this is done via a server-relative path. #index[hx-get][example] For example, if we wanted a button to issue a `GET` request to `/contacts` then we would write the following HTML: #figure(caption: [A simple htmx-powered button], ```html <button hx-get="/contacts"> <1> Get The Contacts </button> ```) 1. A simple button that issues an HTTP `GET` to `/contacts`. The htmx library will see the `hx-get` attribute on this button, and hook up some JavaScript logic to issue an HTTP `GET` AJAX request to the `/contacts` path when the user clicks on it. Very easy to understand and very consistent with the rest of HTML. ==== It’s All Just HTML <_its_all_just_html> #index[htmx][HTML based] With the request issued by the button above, we get to perhaps the most important thing to understand about htmx: it expects the response to this AJAX request _to be HTML_. Htmx is an extension of HTML. A native hypermedia control like an anchor tag will typically get an HTML response to an HTTP request it creates. Similarly, htmx expects the server to respond to the requests that _it_ makes with HTML. This may surprise web developers who are used to responding to an AJAX request with JSON, which is far and away the most common response format for such requests. But AJAX requests are just HTTP requests and there is no rule saying they must use JSON. Recall again that AJAX stands for Asynchronous JavaScript & XML, so JSON is already a step away from the format originally envisioned for this API: XML. Htmx simply goes another direction and expects HTML. ==== Htmx vs. "Plain" HTML Responses <_htmx_vs_plain_html_responses> There is an important difference between the HTTP responses to "normal" anchor or form driven HTTP requests and to htmx-powered requests: in the case of htmx triggered requests, responses can be _partial_ bits of HTML. #index[htmx][transclusion] #index[htmx][partial updates] In htmx-powered interactions, as you will see, we are often not replacing the entire document. Rather we are using "transclusion" to include content _within_ an existing document. Because of this, it is often not necessary or desirable to transfer an entire HTML document from the server to the browser. This fact can be used to save bandwidth as well as resource loading time. Less overall content is transferred from the server to the client, and it isn’t necessary to reprocess a `head` tag with style sheets, script tags, and so forth. When the "Get Contacts" button is clicked, a _partial_ HTML response might look something like this: #figure(caption: [A partial HTML response to an htmx request], ```html <ul> <li><a href="mailto:<EMAIL>">Joe</a></li> <li><a href="mailto:<EMAIL>">Sarah</a></li> <li><a href="mailto:<EMAIL>">Fred</a></li> </ul> ```) This is just an unordered list of contacts with some clickable elements in it. Note that there is no opening `html` tag, no `head` tag, and so forth: it is a _raw_ HTML list, without any decoration around it. A response in a real application might contain more sophisticated HTML than this simple list, but even if it were more complicated it wouldn’t need to be an entire page of HTML: it could just be the "inner" content of the HTML representation for this resource. Now, this simple list response is perfect for htmx. Htmx will simply take the returned content and then swap it in to the DOM in place of some element in the page. (More on exactly where it will be placed in the DOM in a moment.) Swapping in HTML content in this manner is fast and efficient because it leverages the existing native HTML parser in the browser, rather than requiring a significant amount of client-side JavaScript to be executed. This small HTML response shows how htmx stays within the hypermedia paradigm: just like a "normal" hypermedia control in a "normal" web application, we see hypermedia being transferred to the client in a stateless and uniform manner. This button just gives us a slightly more sophisticated mechanism for building a web application using hypermedia. === Targeting Other Elements <_targeting_other_elements> Now, given that htmx has issued a request and gotten back some HTML as a response, and that we are going to swap this content into the existing page (rather than replacing the entire page), the question becomes: where should this new content be placed? It turns out that the default htmx behavior is to simply put the returned content inside the element that triggered the request. That’s _not_ a good thing in the case of our button: we will end up with a list of contacts awkwardly embedded within the button element. That will look pretty silly and is obviously not what we want. #index[hx-target][about] Fortunately htmx provides another attribute, `hx-target` which can be used to specify exactly _where_ in the DOM the new content should be placed. The value of the `hx-target` attribute is a Cascading Style Sheet (CSS) _selector_ that allows you to specify the element to put the new hypermedia content into. Let’s add a `div` tag that encloses the button with the id `main`. We will then target this `div` with the response: #index[hx-target][example] #figure(caption: [A simple htmx-powered button], ```html <div id="main"> <1> <button hx-get="/contacts" hx-target="#main"> <2> Get The Contacts </button> </div> ```) 1. A `div` element that wraps the button. 2. The `hx-target` attribute that specifies the target of the response. We have added `hx-target="#main"` to our button, where `#main` is a CSS selector that says "The thing with the ID 'main'." By using CSS selectors, htmx builds on top of familiar and standard HTML concepts. This keeps the additional conceptual load for working with htmx to a minimum. Given this new configuration, what would the HTML on the client look like after a user clicks on this button and a response has been received and processed? It would look something like this: #figure(caption: [Our HTML after the htmx request finishes], ```html <div id="main"> <ul> <li><a href="mailto:<EMAIL>">Joe</a></li> <li><a href="mailto:<EMAIL>">Sarah</a></li> <li><a href="mailto:<EMAIL>">Fred</a></li> </ul> </div> ```) The response HTML has been swapped into the `div`, replacing the button that triggered the request. Transclusion! And this has happened "in the background" via AJAX, without a clunky page refresh. === Swap Styles <_swap_styles> Now, perhaps we don’t want to load the content from the server response _into_ the div, as child elements. Perhaps, for whatever reason, we wish to _replace_ the entire div with the response. To handle this, htmx provides another attribute, `hx-swap`, that allows you to specify exactly _how_ the content should be swapped into the DOM. #index[htmx][swap model] #index[hx-swap][about] #index[hx-swap][innerHTML] #index[hx-swap][outerHTML] #index[hx-swap][beforebegin] #index[hx-swap][afterbegin] #index[hx-swap][beforeend] #index[hx-swap][afterend] #index[hx-swap][delete] #index[hx-swap][none] The `hx-swap` attribute supports the following values: - `innerHTML` - The default, replace the inner html of the target element. - `outerHTML` - Replace the entire target element with the response. - `beforebegin` - Insert the response before the target element. - `afterbegin` - Insert the response before the first child of the target element. - `beforeend` - Insert the response after the last child of the target element. - `afterend` - Insert the response after the target element. - `delete` - Deletes the target element regardless of the response. - `none` - No swap will be performed. The first two values, `innerHTML` and `outerHTML`, are taken from the standard DOM properties that allow you to replace content within an element or in place of an entire element respectively. The next four values are taken from the `Element.insertAdjacentHTML()` DOM API, which allow you to place an element or elements around a given element in various ways. The last two values, `delete` and `none` are specific to htmx. The first option will remove the target element from the DOM, while the second option will do nothing (you may want to only work with response headers, an advanced technique we will look at later in the book.) Again, you can see htmx stays as close as possible to existing web standards in order to minimize the conceptual load necessary for its use. So let’s consider that case where, rather than replacing the `innerHTML` content of the main div above, we want to replace the _entire div_ with the HTML response. To do so would require only a small change to our button, adding a new `hx-swap` attribute: #figure(caption: [Replacing the entire div])[ ```html <div id="main"> <button hx-get="/contacts" hx-target="#main" hx-swap="outerHTML"> <1> Get The Contacts </button> </div> ``` ] 1. The `hx-swap` attribute specifies how to swap in new content. Now, when a response is received, the _entire_ div will be replaced with the hypermedia content: #figure(caption: [Our HTML after the htmx request finishes], ```html <ul> <li><a href="mailto:<EMAIL>">Joe</a></li> <li><a href="mailto:<EMAIL>">Sarah</a></li> <li><a href="mailto:<EMAIL>">Fred</a></li> </ul> ```) You can see that, with this change, the target div has been entirely removed from the DOM, and the list that was returned as the response has replaced it. Later in the book we will see additional uses for `hx-swap`, for example when we implement infinite scrolling in our contact management application. Note that with the `hx-get`, `hx-post`, `hx-put`, `hx-patch` and `hx-delete` attributes, we have addressed two of the four opportunities for improvement that we enumerated regarding plain HTML: - Opportunity 1: We can now issue an HTTP request with _any_ element (in this case we are using a button). - Opportunity 3: We can issue _any sort_ of HTTP request we want, `PUT`, `PATCH` and `DELETE`, in particular. And, with `hx-target` and `hx-swap` we have addressed a third shortcoming: the requirement that the entire page be replaced. - Opportunity 4: We can now replace any element we want in our page via transclusion, and we can do so in any manner we want. So, with only seven relatively simple additional attributes, we have addressed most of the shortcomings of HTML as a hypermedia that we identified earlier. What’s next? Recall the one other opportunity we noted: the fact that only a `click` event (on an anchor) or a `submit` event (on a form) can trigger an HTTP request. Let’s look at how we can address that limitation. === Using Events <_using_events> Thus far we have been using a button to issue a request with htmx. You have probably intuitively understood that the button would issue its request when you clicked on the button since, well, that’s what you do with buttons: you click on them. And, yes, by default when an `hx-get` or another request-driving annotation from htmx is placed on a button, the request will be issued when the button is clicked. #index[hx-trigger][about] However, htmx generalizes this notion of an event triggering a request by using, you guessed it, another attribute: `hx-trigger`. The `hx-trigger` attribute allows you to specify one or more events that will cause the element to trigger an HTTP request. Often you don’t need to use `hx-trigger` because the default triggering event will be what you want. The default triggering event depends on the element type, and should be fairly intuitive: - Requests on `input`, `textarea` & `select` elements are triggered by the `change` event. - Requests on `form` elements are triggered on the `submit` event. - Requests on all other elements are triggered by the `click` event. To demonstrate how `hx-trigger` works, consider the following situation: we want to trigger the request on our button when the mouse enters it. Now, this is certainly not a _good_ UX pattern, but bear with us: we are just using this as an example. To respond to a mouse entering the button, we would add the following attribute to our button: #figure(caption: [A (bad?) button that triggers on mouse entry], ```html <div id="main"> <button hx-get="/contacts" hx-target="#main" hx-swap="outerHTML" hx-trigger="mouseenter"> <1> Get The Contacts </button> </div> ```) 1. Issue a request on the... `mouseenter` event. Now, with this `hx-trigger` attribute in place, whenever the mouse enters this button, a request will be triggered. Silly, but it works. Let’s try something a bit more realistic and potentially useful: let’s add support for a keyboard shortcut for loading the contacts, `Ctrl-L` (for "Load"). To do this we will need to take advantage of additional syntax that the `hx-trigger` attribute supports: event filters and additional arguments. #index[hx-trigger][event filters] Event filters are a mechanism for determining if a given event should trigger a request or not. They are applied to an event by adding square brackets after it: `someEvent[someFilter]`. The filter itself is a JavaScript expression that will be evaluated when the given event occurs. If the result is truthy, in the JavaScript sense, it will trigger the request. If not, the request will not be triggered. #index[event][keyup] In the case of keyboard shortcuts, we want to catch the `keyup` event in addition to the click event: #figure(caption: [A start, trigger on keyup], ```html <div id="main"> <button hx-get="/contacts" hx-target="#main" hx-swap="outerHTML" hx-trigger="click, keyup"> <1> Get The Contacts </button> </div> ```) 1. A trigger with two events. #index[hx-trigger][multiple events] Note that we have a comma separated list of events that can trigger this element, allowing us to respond to more than one potential triggering event. We still want to respond to the `click` event and load the contacts, in addition to handling the `Ctrl-L` keyboard shortcut. Unfortunately there are two problems with our `keyup` addition: As it stands, it will trigger requests on _any_ keyup event that occurs. And, worse, it will only trigger when a keyup occurs _within_ this button. The user would need to tab onto the button to make it active and then begin typing. Let’s fix these two issues. To fix the first one, we will use a trigger filter to test that Control key and the "L" key are pressed together: #index[event filter][example] #figure(caption: [Getting better with filter on keyup], ```html <div id="main"> <button hx-get="/contacts" hx-target="#main" hx-swap="outerHTML" hx-trigger="click, keyup[ctrlKey && key == 'l']"> <1> Get The Contacts </button> </div> ```) 1. `keyup` now has a filter, so the control key and L must be pressed. The trigger filter in this case is `ctrlKey && key == 'l'`. This can be read as "A key up event, where the ctrlKey property is true and the key property is equal to l." Note that the properties `ctrlKey` and `key` are resolved against the event rather than the global name space, so you can easily filter on the properties of a given event. You can use any expression you like for a filter, however: calling a global JavaScript function, for example, is perfectly acceptable. OK, so this filter limits the keyup events that will trigger the request to only `Ctrl-L` presses. However, we still have the problem that, as it stands, only `keyup` events _within_ the button will trigger the request. #index[event bubbling] If you are not familiar with the JavaScript event bubbling model: events typically "bubble" up to parent elements. So an event like `keyup` will be triggered first on the focused element, and then on its parent (enclosing) element, and so on, until it reaches the top level `document` object that is the root of all other elements. #index[hx-trigger][from:] #index[keyboard shortcut] To support a global keyboard shortcut that works regardless of what element has focus, we will take advantage of event bubbling and a feature that the `hx-trigger` attribute supports: the ability to listen to _other elements_ for events. The syntax for doing this is the `from:` modifier, which is added after an event name and that allows you to specify a specific element to listen for the given event on using a CSS selector. #index[events][listener] In this case, we want to listen to the `body` element, which is the parent element of all visible elements on the page. Here is what our updated `hx-trigger` attribute looks like: #figure(caption: [Even better, listen for keyup on the body], ```html <div id="main"> <button hx-get="/contacts" hx-target="#main" hx-swap="outerHTML" hx-trigger="click, keyup[ctrlKey && key == 'l'] from:body"> <1> Get The Contacts </button> </div> ```) 1. Listen to the 'keyup' event on the `body` tag. Now, in addition to clicks, the button will listen for `keyup` events on the body of the page. So it will issue a request when it is clicked on and also whenever someone hits `Ctrl-L` within the body of the page. And now we have a nice keyboard shortcut for our Hypermedia-Driven Application. #index[hx-trigger][about] The `hx-trigger` attribute supports many more modifiers, and it is more elaborate than other htmx attributes. This is because events, in general, are complicated and require a lot of details to get just right. The default trigger will often suffice, however, and you typically don’t need to reach for complicated `hx-trigger` features when using htmx. Even with more sophisticated trigger specifications like the keyboard shortcut we just added, the overall feel of htmx is _declarative_ rather than _imperative_. That keeps htmx-powered applications "feeling like" standard web 1.0 applications in a way that adding significant amounts of JavaScript does not. === Htmx: HTML eXtended <_htmx_html_extended> And hey, check it out! With `hx-trigger` we have addressed the final opportunity for improvement of HTML that we outlined at the start of this chapter: - Opportunity 2: We can use _any_ event to trigger an HTTP request. That’s a grand total of eight, count 'em, _eight_ attributes that all fall squarely within the same conceptual model as normal HTML and that, by extending HTML as a hypermedia, open up a whole new world of user interaction possibilities within it. #index[HTML][opportunities] Here is a table summarizing those opportunities and which htmx attributes address them: / Any element should be able to make HTTP requests: #[ `hx-get`, `hx-post`, `hx-put`, `hx-patch`, `hx-delete` ] / Any event should be able to trigger an HTTP request: #[ `hx-trigger` ] / Any HTTP Action should be available: #[ `hx-put`, `hx-patch`, `hx-delete` ] / Any place on the page should be replaceable (transclusion): #[ `hx-target`, `hx-swap` ] === Passing Request Parameters <_passing_request_parameters> So far we have just looked at a situation where a button makes a simple `GET` request. This is conceptually very close to what an anchor tag might do. But there is that other native hypermedia control in HTML-based applications: #indexed[forms]. Forms are used to pass additional information beyond just a URL up to the server in a request. This information is captured via input and input-like elements within the form via the various types of input tags available in HTML. Htmx allows you include this additional information in a way that mirrors HTML itself. ==== Enclosing Forms <_enclosing_forms> The simplest way to pass input values with a request in htmx is to enclose the element making a request within a form tag. Let’s take our original #indexed[search] form and convert it to use htmx instead: #figure(caption: [An htmx-powered search button], ```html <form action="/contacts" method="get" class="tool-bar"> <1> <label for="search">Search Term</label> <input id="search" type="search" name="q" value="{{ request.args.get('q') or '' }}" placeholder="Search Contacts"/> <button hx-post="/contacts" hx-target="#main"> <2> Search </button> </form> ```) 1. When an htmx-powered element is withing an ancestor form tag, all input values within that form will be submitted for non-`GET` requests 2. We have switched from an `input` of type `submit` to a `button` and added the `hx-post` attribute #index[htmx][form values] Now, when a user clicks on this button, the value of the input with the id `search` will be included in the request. This is by virtue of the fact that there is a form tag enclosing both the button and the input: when an htmx-driven request is triggered, htmx will look up the DOM hierarchy for an enclosing form, and, if one is found, it will include all values from within that form. (This is sometimes referred to as "serializing" the form.) You might have noticed that the button was switched from a `GET` request to a `POST` request. This is because, by default, htmx does _not_ include the closest enclosing form for `GET` requests, but it _does_ include the form for all other types of requests. This may seem a little strange, but it avoids junking up URLs that are used within forms when dealing with history entries, which we will discuss in a bit. You can always include an enclosing form’s values with an element that uses a `GET` by using the `hx-include` attribute, which we will discuss next. Note also that we could have added the `hx-post` attribute to the form, rather than to the button but that would create a somewhat awkward duplication of the search URL in the `action` and `hx-post` attributes. This can be avoided by using the `hx-boost` attribute, which we discuss in the next chapter. ==== Including Inputs <_including_inputs> #index[form tag][in tables] While enclosing all the inputs you want included in a request within a form is the most common approach for serializing inputs for htmx requests, it isn’t always possible or desirable: form tags can have layout consequences and simply cannot be placed in some spots in HTML documents. A good example of the latter situation is in table row (`tr`) elements: the `form` tag is not a valid child or parent of table rows, so you can’t place a form within or around a row of data in a table. #index[hx-include][about] #index[hx-include][example] To address this issue, htmx provides a mechanism for including input values in requests: the `hx-include` attribute. The `hx-include` attribute allows you to select input values that you wish to include in a request via CSS selectors. Here is the above example reworked to include the input, dropping the form: #figure(caption: [An htmx-powered search button with `hx-include`], ```html <div id="main"> <label for="search">Search Contacts:</label> <input id="search" name="q" type="search" value="{{ request.args.get('q') or '' }}" placeholder="Search Contacts"/> <button hx-post="/contacts" hx-target="#main" hx-include="#search"> <1> Search </button> </div> ```) 1. `hx-include` can be used to include values directly in a request. The `hx-include` attribute takes a CSS selector value and allows you to specify exactly which values to send along with the request. This can be useful if it is difficult to colocate an element issuing a request with all the desired inputs. It is also useful when you do, in fact, want to submit values with a `GET` request and overcome the default behavior of htmx. ===== Relative CSS selectors <_relative_css_selectors> #index[relative CSS selectors][about] The `hx-include` attribute and, in fact, most attributes that take a CSS selector, also support _relative_ CSS selectors. These allow you to specify a CSS selector _relative_ to the element it is declared on. Here are some examples: / `closest`: #index[relative CSS selectors][closest] Find the closest parent element matching the given selector, e.g., `closest form`. / `next`: #index[relative CSS selectors][next] Find the next element (scanning forward) matching the given selector, e.g., `next input`. / `previous`: #index[relative CSS selectors][previous] Find the previous element (scanning backwards) matching the given selector, e.g., `previous input`. / `find`: #index[relative CSS selectors][find] Find the next element within this element matching the given selector, e.g., `find input`. / `this`: #index[relative CSS selectors][this] The current element. Using relative CSS selectors often allows you to avoid generating ids for elements, since you can take advantage of their local structural layout instead. ==== Inline Values <_inline_values> #index[hx-vals][about] A final way to include values in htmx-driven requests is to use the `hx-vals` attribute, which allows you to include "static" values in the request. This can be useful if you have additional information that you want to include in requests, but you don’t want to have this information embedded in, for example, hidden inputs (which would be the standard mechanism for including additional, hidden information in HTML.) #index[hx-vals][example] #index[hx-vals][JSON] #index[query strings] Here is an example of `hx-vals`: #figure(caption: [An htmx-powered button with `hx-vals`], ```html <button hx-get="/contacts" hx-vals='{"state":"MT"}'> <1> Get The Contacts In Montana </button> ```) 1. `hx-vals`, a JSON value to include in the request. The parameter `state` with the value `MT` will be included in the `GET` request, resulting in a path and parameters that looks like this: `/contacts?state=MT`. Note that we switched the `hx-vals` attribute to use single quotes around its value. This is because JSON strictly requires double quotes and, therefore, to avoid escaping we needed to use the single-quote form for the attribute value. #index[hx-vals][js: prefix] You can also prefix `hx-vals` with a `js:` and pass values evaluated at the time of the request, which can be useful for including things like a dynamically maintained variable, or value from a third party JavaScript library. For example, if the `state` variable were maintained dynamically, via some JavaScript, and there existed a JavaScript function, `getCurrentState()`, that returned the currently selected state, it could be included dynamically in htmx requests like so: #figure(caption: [A dynamic value], ```html <button hx-get="/contacts" hx-vals='js:{"state":getCurrentState()}'> <1> Get The Contacts In The Selected State </button> ```) 1. With the `js:` prefix, this expression will evaluate at submit time. These three mechanisms, using `form` tags, using the `hx-include` attribute and using the `hx-vals` attribute, allow you to include values in your hypermedia requests with htmx in a manner that should feel very familiar and in keeping with the spirit of HTML, while also giving you the flexibility to achieve what you want. === History Support <_history_support> We have a final piece of functionality to close out our overview of htmx: browser history support. When you use normal HTML links and forms, your browser will keep track of all the pages that you have visited. You can then use the back button to navigate back to a previous page and, once you have done this, you can use a forward button to go forward to the original page you were on. #index[browser history] This notion of history was one of the killer features of the early web. Unfortunately it turns out that history becomes tricky when you move to the Single Page Application paradigm. An AJAX request does not, by itself, register a web page in your browser’s history, which is a good thing: an AJAX request may have nothing to do with the state of the web page (perhaps it is just recording some activity in the browser), so it wouldn’t be appropriate to create a new history entry for the interaction. However, there are likely to be a lot of AJAX driven interactions in a Single Page Application where it _is_ appropriate to create a history entry. There is a JavaScript API to work with browser history, but this API is deeply annoying and difficult to work with, and thus often ignored by JavaScript developers. If you have ever used a Single Page Application and accidentally clicked the back button, only to lose your entire application state and have to start over, you have seen this problem in action. In htmx, as with Single Page Application frameworks, you will often need to explicitly work with the history API. Fortunately, since htmx sticks so close to the native model of the web and since it is declarative, getting web history right is typically much easier to do in an htmx-based application. Consider the button we have been looking at to load contacts: #figure(caption: [Our trusty button], ```html <button hx-get="/contacts" hx-target="#main"> Get The Contacts </button> ```) As it stands, if you click this button it will retrieve the content from `/contacts` and load it into the element with the id `main`, but it will _not_ create a new history entry. #index[hx-push-url] #index[back button] If we wanted it to create a history entry when this request happened, we would add a new attribute to the button, the `hx-push-url` attribute: #figure(caption: [Our trusty button, now with history!], ```html <button hx-get="/contacts" hx-target="#main" hx-push-url="true"> <1> Get The Contacts </button> ```) 1. `hx-push-url` will create an entry in history when the button is clicked. Now, when the button is clicked, the `/contacts` path will be put into the browser’s navigation bar and a history entry will be created for it. Furthermore, if the user clicks the back button, the original content for the page will be restored, along with the original URL. #index[htmx][browser history] Now, the name `hx-push-url` for this attribute might sound a little obscure, but it is based on the JavaScript API, `history.pushState()`. This notion of "pushing" derives from the fact that history entries are modeled as a stack, and so you are "pushing" new entries onto the top of the stack of history entries. With this relatively simple, declarative mechanism, htmx allows you to integrate with the back button in a way that mimics the "normal" behavior of HTML. Now, there is one additional thing we need to handle to get history "just right": we have "pushed" the `/contacts` path into the browsers location bar successfully, and the back button works. But what if someone refreshes their browser while on the `/contacts` page? In this case, you will need to handle the htmx-based "partial" response as well as the non-htmx "full page" response. You can do this using HTTP headers, a topic we will go into in detail later in the book. === Conclusion <_conclusion> So that’s our whirlwind introduction to htmx. We’ve only seen about ten attributes from the library, but you can see a hint of just how powerful these attributes can be. Htmx enables a much more sophisticated web application than is possible in plain HTML, with minimal additional conceptual load compared to most JavaScript-based approaches. Htmx aims to incrementally improve HTML as a hypermedia in a manner that is conceptually coherent with the underlying markup language. Like any technical choice, this is not without trade-offs: by staying so close to HTML, htmx does not give developers a lot of infrastructure that many might feel should be there "by default". By staying closer to the native model of the web, htmx aims to strike a balance between simplicity and functionality, deferring to other libraries for more elaborate frontend extensions on top of the existing web platform. The good news is that htmx plays well with others, so when these needs arise it is often easy enough to bring in another library to handle them. #html-note[Budgeting For HTML][ The close relationship between content and markup means that good HTML is labor-intensive. Most sites have a separation between the authors, who are rarely familiar with HTML, and the developers, who need to develop a generic system able to handle any content that’s thrown at it --- this separation usually taking the form of a CMS. As a result, having markup tailored to content, which is often necessary for advanced HTML, is rarely feasible. Furthermore, for internationalized sites, content in different languages being injected into the same elements can degrade markup quality as stylistic conventions differ between languages. It’s an expense few organizations can spare. Thus, we don’t expect every site to contain perfectly conformant HTML. What’s most important is to avoid _wrong_ HTML --- it can be better to fall back on a more generic element than to be precisely incorrect. If you have the resources, however, putting more care in your HTML will produce a more polished site. ]
https://github.com/timon-schelling/uni-phi111-essay-2023-12-01
https://raw.githubusercontent.com/timon-schelling/uni-phi111-essay-2023-12-01/main/src/main.typ
typst
#import "template/template.typ": * #let bib-urls = { sys.inputs.at("urls", default: none) != none } #let theme = { sys.inputs.at("theme", default: none) } #set page(fill: rgb("1a1a1a")) if theme == "dark" #set text(fill: rgb("c7c7c7")) if theme == "dark" #show: project.with( title: "Einführung in die Logik am Beispiel politischer Argumente", authors: ( "<NAME>", ), date: "2023-12-01", title-page-infos: [ #table( columns: (8em, auto), inset: (x: 0em, y: 0.6em), stroke: none, [Universität:], [Carl von Ossietzky Universität Oldenburg], [Fakultät:], [Fakultät IV - Human- und Gesellschaftswissenschaften], [Studiengang:], [Philosophie/Werte und Normen Zwei-Fächer-Bachelor], [Semester:], [Wintersemester 2023/2024], [Veranstaltung:], [Tutorium: 4.03.1101f Einführung in die Theoretische Philosophie], [Dozent:], [Svea Reinken], [Mail:], [#link("mailto:<EMAIL>"), #link("mailto:<EMAIL>")] ) ], font: "Times New Roman", bib-urls: bib-urls, ) #let argument(premises, conclusion) = align(left, [ #set text(style: "italic") #table(inset: (x: 0.8em, y: 0em), stroke: none)[ #table( stroke: none, inset: (x: 0.1em, y: 0.4em), columns: 3, ..premises.enumerate(start: 1).map(e => { let (i, premise) = e ([$P_#i$], [$:$], premise) }).flatten(), ..([$K$], [$:$], conclusion) ) ] ]) = Einleitung Menschen werden in der Gesellschaft täglich mit Argumenten konfrontiert, sei es als Teil des politischen Diskurses, in Nachrichten, der Werbung oder im privaten Gespräch mit Freunden und Familie. Von welchen Argumenten sollten wir uns überzeugen lassen und welche sollten wir ablehnen? Es gibt verschiedene Ebenen, auf denen sich Argumente bewerten lassen. Argumente können literarisch wertvoll, originell oder auch rhetorisch geschickt sein. In dieser Arbeit sollen allerdings allein Eigenschaften von Argumenten betrachtet werden, mit denen sich die philosophische Disziplin der Logik beschäftigt, namentlich die Gültigkeit und die Stichhaltigkeit. Im Folgenden wird am Beispiel politischer Argumente eine Einführung in die Logik gegeben. Fokus soll dabei auf der Logik als Werkzeug liegen, mit dem sich politische Argumente bewerten lassen. Im #link(<discussion>, [_letzten Kapitel_]) der Arbeit wird anschließend diskutiert, inwiefern die Logik für politische Bildung im Allgemeinen und Medienkompetenz im Speziellen nützlich ist. = Deduktive gültige Argumente Um die Qualität politischer Argumente zu bewerten, ist es hilfreich, das Konzept der deduktiven Gültigkeit in der Logik zu verstehen. Ein Argument gilt genau dann als deduktiv gültig, wenn die Konklusion aus den Prämissen folgt. @beckermann2011[vgl.&21] Die Wahrheit der Prämissen muss die Wahrheit der Konklusion garantieren. @beckermann2011[vgl.&20] Wenn es sich bei einem Argument also um ein deduktiv gültiges Argument handelt, ist keine Welt denkbar, in der die Prämissen wahr sind, aber die Konklusion falsch. Es ist dabei für die deduktive Gültigkeit egal, ob die Prämissen tatsächlich wahr sind, es geht ausschließlich um den Zusammenhang zwischen den Prämissen und der Konklusion. @beckermann2011[vgl.&21-22] Das folgende Argument könnte benutzt werden, um für Steuersenkungen für Reiche zu argumentieren, wie es beispielsweise die US-Regierung unter Bush getan hat. @bartels2005[vgl.&15] @lupia2007[vgl.&1-2] #argument( ( [Wenn von Steuersenkungen für Reiche die Gesamtwirtschaft profitiert, dann sind Steuersenkungen für Reiche eine gute Maßnahme.], [Von Steuersenkungen für Reiche profitiert die Gesamtwirtschaft.] ), [Steuersenkungen für Reiche sind eine gute Maßnahme.] ) Die erste Prämisse des Arguments ist ein Konditional, sie besteht aus zwei Teilen, dem Antezedens und der Konsequenz. @beckermann2011[vgl.&150-152] @krimphove2012[vgl.&55-58] Das Antezedens ist der erste Halbsatz der Prämisse, er beginnt hier mit "Wenn". Die Konsequenz ist der zweite Halbsatz, er beginnt hier mit "dann". Das Antezedens ist die Bedingung, die erfüllt sein muss, damit die Konsequenz wahr ist. Die Konsequenz ist die Schlussfolgerung, die aus dem Antezedens folgt. Die zweite Prämisse ist eine Aussage, die die Wahrheit der Konsequenz der ersten Prämisse behauptet. Wenn das Konditional der ersten Prämisse wahr ist und die zweite Prämisse wahr ist, dann ist auch die Wahrheit der Konsequenz der ersten Prämisse garantiert. Die Konklusion hat den gleichen Inhalt, wie die Konsequenz der ersten Prämisse. Die Wahrheit der Prämissen garantiert demnach auch die Wahrheit der Konklusion. Das Argument hat sich als deduktiv gültig erwiesen. Ohne viel fachsprachliches Vokabular erklärt, es ist keine Welt denkbar, in der beide Prämissen des Arguments wahr sind, die Konklusion aber falsch, also ist das Argument ein deduktiv gültiges. Zu beachten ist hier wieder, dass bei einem deduktiv gültigen Argument die Wahrheit der Prämissen nicht garantiert ist. @beckermann2011[vgl.&21-22] Gültigkeit kann also nicht die einzige Eigenschaft sein, die ein Argument haben muss, um überzeugend zu sein, dafür ist die Wahrheit der Prämissen ebenso entscheidend. In der Logik wird diese Eigenschaft von Argumenten Stichhaltigkeit genannt. @krimphove2012[vgl.&8] Wenn bei einem deduktiv gültigen Argument die Prämissen wahr sind, so handelt es sich um ein stichhaltiges Argument. @beckermann2011[vgl.&22] Bei dem vorliegenden Argument besteht wissenschaftlich begründeter Zweifel an der Wahrheit der zweiten Prämisse. @hope2022[vgl.&555] Es ist also mindestens fraglich, ob es sich bei diesem Argument um ein stichhaltiges handelt, wodurch seine die Überzeugungskraft deutlich geschmälert wird. = Induktive gültige Argumente Weniger stark, als die deduktive Gültigkeit, ist die induktive Gültigkeit. Ein Argument gilt als induktiv gültig, wenn die Wahrheit der Prämissen die Wahrheit der Konklusion wahrscheinlicher macht, als die ihrer Negation. @beckermann2011[vgl.&30-31] Es ist also eine Welt denkbar, in der die Prämissen wahr sind, die Konklusion aber falsch. Die Konklusion ist also nicht notwendigerweise wahr, wenn die Prämissen wahr sind. Es ist auch möglich, die induktive Gültigkeit ohne die Verwendung von Wahrscheinlichkeiten zu definieren. In einer solchen Definition sind Argumente genau dann induktiv gültig, wenn "es bei diesen Argumenten rational ist, die Konklusion für wahr zu halten, wenn alle Prämissen wahr sind, obwohl die Konklusion nicht logisch aus den Prämissen folgt". @beckermann2011[31] Das folgende Argument könnte benutzt werden, um für die Einführung eines bedingungslosen Grundeinkommens zu argumentieren. #argument( ( [Wenn die Einführung eines bedingungslosen Grundeinkommens die Armut verringert, dann ist die Einführung eines bedingungslosen Grundeinkommens eine gute Maßnahme.], [Die Einführung eines bedingungslosen Grundeinkommens verringert meistens die Armut.] ), [Die Einführung eines bedingungslosen Grundeinkommens ist eine gute Maßnahme.] ) Es handelt sich hier um eine nahezu identische Argumentstruktur, wie beim Beispiel-Argument aus dem Abschnitt zur deduktiven Gültigkeit, mit dem Unterschied, dass die zweite Prämisse den Antezedenz der ersten Prämisse nicht als wahr behauptet, sondern nur partiell bejaht, hier zuerkennen an dem Wort "meistens". Die Konklusion ist also nicht notwendigerweise wahr, wenn die Prämissen wahr sind. Es ist allerdings rational anzunehmen, dass die Konklusion wahr ist, wenn die Prämissen wahr sind. Gleichermaßen ist die Konklusion, bei Wahrheit der Prämissen, wahrscheinlicher als ihre Negation. Das Argument ist demnach induktiv gültig. Ein induktiv gültiges Argument ist folglich weniger stark, als ein deduktiv gültiges Argument, jedoch immer noch stärker als ein ungültiges. @beckermann2011[vgl.&32] Auch bei einem induktiv gültigen Argument ist die Wahrheit der Prämissen nicht garantiert, es ist also auch hier nicht die einzige Eigenschaft, die ein Argument haben muss, um überzeugend zu sein. @beckermann2011[vgl.&32] Die Wahrheit der Prämissen ist auch hier entscheidend. = Logik in politischer Bildung und Medienkompetenz <discussion> Spätestens in den letzten Jahren ist die Bedeutung von Medienkompetenz auch für die breite Bevölkerung deutlich geworden. @mason2018[vgl.&6] Im Englischen als "Fake News" bekannt gewordene Falschinformationen zeigten sich den Demokratien der Welt als einfluss-mächtiges Instrument, um Wahlen im Speziellen und die öffentliche Meinung im Allgemeinen zu beeinflussen. @greifeneder2020[vgl.&1-3] @eleftheriadi-zacharaki2022[vgl.&145-146] Genauere Analysen der Wahlen in Deutschland 2017 und den USA 2016 haben gezeigt, dass die Verbreitung von Falschinformationen, insbesondere über soziale Medien, zu genau diesem Zweck lange nicht mehr nur theoretisch existierten und dass vor allem das Schaffen von Problembewusstsein in der Bevölkerung eine sinnvolle Maßnahme ist, um Einflussnahme von außen einzugrenzen. @kaiser2017[vgl.&446-447] Die Fähigkeit, Falschinformationen zu erkennen und zu entlarven, ist ein relevanter Teil der Medienkompetenz, die in der Schule vermittelt werden sollte. @eikenbusch2018[vgl.&6-9] @kaiser2017[vgl.&59] Es braucht jedoch nicht unbedingt Falschinformationen, um Menschen von Positionen zu überzeugen, die ihren eigenen Interessen oder Werten widersprechen, z.B. auch rhetorisch geschickte Argumente können dies leisten. Sich gegen solche Argumente zu wappnen ist ebenfalls wichtig, um sich nicht von Positionen überzeugen zu lassen, die den eigenen Interessen oder Werten entgegenstehen. Besonders hier kann die Logik als Werkzeug dienen, um Argumente tiefer zu analysieren. In den Abschnitten zur deduktiven und induktiven Gültigkeit wurden bereits einige Beispiele für Argumente gegeben, die in der politischen Debatte vorkommen und wie sich diese bewerten lassen. Ein Argument ist deduktiv gültig, im Anschluss stellt es sich durch weitere Recherche als stichhaltig heraus und ist somit ein sehr gutes Argument, das überzeugen darf. Ist ein Argument induktiv gültig, so sollte es weniger überzeugend sein, als ein stichhaltiges, aber immer noch Überzeugungskraft zugesprochen bekommen. Argumente hingegen, die einen logischen Fehlschluss enthalten oder auf andere Weise nicht gültig und nicht stichhaltig sind, können schnell als fragwürdig entlarvt werden. Die Logik ist also mindestens ein nützliches Werkzeug, um sich im politischen Diskurs zurechtzufinden. Aus diesem Grund hat die Logik auch außerhalb der Philosophie für politischen Bildung eine Bedeutung. #pagebreak() = Fazit Diese Arbeit hat eine grundlegende Einführung in den philosophischen Teilbereich der Logik gegeben. Fokus lag dabei auf der Erläuterung der Begriffe der deduktiven und induktiven Gültigkeit sowie der Stichhaltigkeit von Argumenten. Anhand von politischen Beispiel-Argumenten wurde gezeigt, wie sich Argumente mit Hilfe der Logik bewerten lassen. Es wurde gezeigt, dass stichhaltige Argumente aus dem Blickwinkel der Logik überzeugender sind, als induktiv gültige Argumente mit wahren Prämissen, die wiederum überzeugender sind, als ungültige Argumente mit z.B. einem logischen Fehlschluss. Zum Schluss wurde diskutiert, inwiefern die Logik, mit den vorher eingeführten Begriffen, für politische Bildung, Medienkompetenz und als Werkzeug, um sich im politischen Diskurs zurechtzufinden, nützlich ist. Es hat sich gezeigt, dass die Logik ein mindestens nützliches Werkzeug ist, um sich im politischen Diskurs besser zurechtzufinden. Deshalb ist die Logik nicht nur für die philosophische Forschung, sondern auch darüber hinaus relevant. = Ausblick Wenn also die Logik ein solch nützliches Werkzeug ist, wie in dieser Arbeit gezeigt wurde, stellt sich die Frage, ob es sinnvoll wäre, sie mehr Menschen zu vermitteln. In welchem Umfang, in welcher Form und auf welchem Bildungsniveau könnte dies beispielsweise im Kontext der politischen Bildung Anwendung finden? Sollten Kinder bereits in der Schule mit der Logik in Berührung kommen? Welche didaktischen Mittel wären sinnvoll, um die Logik unterschiedlichen Personengruppen nahezubringen? Diese Fragen liegen außerhalb des Rahmens dieser Arbeit, es ist allerdings klar geworden, dass weitere wissenschaftliche Auseinandersetzungen in dieser Hinsicht sinnvoll sein könnten.
https://github.com/aagumin/cv
https://raw.githubusercontent.com/aagumin/cv/typst/content/community.typ
typst
#import "@preview/grotesk-cv:0.1.2": * #import "@preview/fontawesome:0.2.1": * #let meta = toml("../info.toml") #let language = meta.personal.language == #fa-icon("users") #h(5pt) #if language == "en" [Community] else if language == "es" [Community] #v(5pt) #if language == "en" [ #reference-entry( name: [<NAME>, Resistance Leader], company: [Cyberdyne Systems], telephone: [+1 (555) 654-3210], email: [<EMAIL>], ) #reference-entry( name: [<NAME>, CEO], company: [Tyrell Corporation], telephone: [+1 (555) 987-6543], email: [<EMAIL>], ) ] else if language == "ru" [ #reference-entry( name: [<NAME>, Líder de la Resistencia], company: [Cyberdyne Systems], telephone: [+1 (555) 654-3210], email: [<EMAIL>], ) #reference-entry( name: [<NAME>, CEO], company: [Tyrell Corporation], telephone: [+1 (555) 987-6543], email: [<EMAIL>], ) ]
https://github.com/adam-zhang-lcps/papers
https://raw.githubusercontent.com/adam-zhang-lcps/papers/main/calculus-q1-proofs.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "@preview/equate:0.2.1": equate #set document( title: [Quarter 1 Proofs], author: "<NAME>", date: datetime.today(), ) #set page( paper: "us-letter", margin: 1in, header: [ #grid( columns: (1fr, 1fr), align(left + top)[ #set block(spacing: 0.6em) AET Multivariable Calculus *Quarter 1 Proofs* ], align(right + top)[Adam Zhang], ) ], ) #set text(font: "New Computer Modern") #set enum(numbering: "1.a.") #set math.equation(numbering: "(1.a)") // Allows numbering only referenced equations. #show: equate.with(sub-numbering: true, number-mode: "label") #align(center)[ _On my honor, I will not accept nor provide any unauthorized aid on this assignment._ ] = Proofs + Given an unknown point $P$, and known points $𝐴(3, 2, −1)$ and $𝐵(−3, −1, 5)$, if the distance from $P$ to $A$ is equal to twice the distance from $P$ to $B$. Prove that the set of all points defined by $A$, $𝐵$, and $P$ is a sphere. Find the center and the radius. A sphere centered at the origin can be defined as the set of vectors ${arrow(v) | norm(arrow(v)) = r}$ where $r$ is the radius of the sphere. To translate the center of the sphere to the point defined by the position vector $arrow(P)$, each vector must be defined relative to the new point; thus, the set of vectors becomes ${arrow(v) mid(|) norm(arrow(v) - arrow(P)) = r}$. This can be represented as in @1-sphere-eq. $ r &= norm(arrow(v) - arrow(P)) \ &= sqrt((v_x - P_x)^2 + (v_y - P_y)^2 + (v_z - P_z)^2) \ r^2 &= (v_x - P_x)^2 + (v_y - P_y)^2 + (v_z - P_z)^2 #<1-sphere-eq> $ Let the position vectors $arrow(P)$, $arrow(A)$, and $arrow(B)$ represent the points P, A, and B, respectively. Thus, the given statement can be represented by @1-eq. $ norm(arrow(A) - arrow(P)) = 2 norm(arrow(B) - arrow(P)) $ <1-eq> Via elementary algebra, @1-eq can be rearranged into @1-rearranged, which, as established in @1-sphere-eq, defines a sphere with a radius of six centered at $(-5, -2, 7)$. $ sqrt((A_x - P_x)^2 + (A_y - P_y)^2 + (A_z - P_z)^2) = 2 sqrt((B_x - P_x)^2 + (B_y - P_y)^2 + (B_z - P_z)^2) \ (A_x - P_x)^2 + (A_y - P_y)^2 + (A_z - P_z)^2 = 4 (B_x - P_x)^2 + ( B_y - P_y )^2 + (B_z - P_z)^2 \ (3 - P_x)^2 + (2 - P_y)^2 + (-1 - P_z)^2 = 4 ( (-3 - P_x)^2 + (-1 - P_y)^2 + (5 - P_z)^2 ) \ P_x^2 - 6 P_x - 4 P_y + P_y^2 + P_z^2 + 2 P_z + 14 = 4 P_x^2 + 24 P_x + 4 P_y^2 + 8 P_y - 40 P_z + 4 P_z^2 + 140 \ - 3 P_x^2 - 30 P_x - 3 P_y^2 - 12 P_y - 3 P_z^2 + 42 P_z = 126 \ -3 (P_x^2 + 10 P_x + P_y^2 + 4 P_y + P_z^2 - 14 P_z) = 126 \ -3 ( P_x^2 + 10 P_x + 25 + P_y^2 + 4 P_y + 4 + P_z^2 - 14 P_z + 49 - 78 ) = 126 \ -3 ((P_x + 5)^2 + (P_y + 2)^2 + (P_z - 7)^2) = -108 \ (P_x + 5)^2 + (P_y + 2)^2 + (P_z - 7)^2 = 6^2 #<1-rearranged> $ // This proof… this proof *scares* me. + If the midpoints of any two consecutive sides of any quadrilateral (in $RR^2$ or $RR^3$) are connected by straight lines, prove that the resulting quadrilateral is a parallelogram. A quadrilateral in $RR^3$ can be defined by four points defined by position vectors $arrow(A)$, $arrow(B)$, $arrow(C)$, and $overline(D)$ with edges $overline(A B)$, $overline(B C)$, $overline(C D)$, and $overline(D A)$. The midpoint of each edge can be described as a vector as follows: $ overline(A B) &: (arrow(A) + arrow(B)) / 2 \ overline(B C) &: (arrow(B) + arrow(C)) / 2 \ overline(C D) &: (arrow(C) + arrow(D)) / 2 \ overline(D A) &: (arrow(D) + arrow(A)) / 2 $ Thus, the edges between the midpoints can be described as follows: $ alpha &= (arrow(B) + arrow(C)) / 2 - (arrow(A) + arrow(B)) / 2 = 1 / 2 ( arrow(C) - arrow(A) ) \ beta &= (arrow(C) + arrow(D)) / 2 - (arrow(B) + arrow(C)) / 2 = 1 / 2 ( arrow(D) - arrow(B) ) \ gamma &= (arrow(D) + arrow(A)) / 2 - (arrow(C) + arrow(D)) / 2 = 1 / 2 ( arrow(A) - arrow(C) ) \ lambda &= (arrow(A) + arrow(B)) / 2 - (arrow(D) + arrow(A)) / 2 = 1 / 2 ( arrow(B) - arrow(D) ) $ A quadrilateral is a parallelogram if both opposing edges are parallel. Two vectors are parallel if one is a scalar multiple of the other. $ arrow(u) parallel arrow(v) <=> arrow(u) = k arrow(v) and k in RR $ As $alpha = -gamma and beta = -lambda => alpha parallel gamma and beta parallel lambda$, $alpha$, $beta$, $gamma$, and $lambda$ form a parallelogram. + Prove that if $arrow(u) + arrow(v)$ and $arrow(u) - arrow(v)$ are orthogonal, then the vectors $arrow(u)$ and $arrow(v)$ must have the same magnitude. $ (arrow(u) + arrow(v)) dot (arrow(u) - arrow(v)) = 0 \ (arrow(u) dot arrow(u)) - (arrow(v) dot arrow(v)) = 0 \ arrow(u) dot arrow(u) = arrow(v) dot arrow(v) \ norm(arrow(u))^2 = norm(arrow(v))^2 \ norm(arrow(u)) = norm(arrow(v)) $ + Suppose that $arrow(a) eq.not 0$. + (3 points) If $arrow(a) dot arrow(b) = arrow(a) dot arrow(c)$, does it follow that $arrow(b) = arrow(c)$? Why or why not? Let $arrow(a) = hat(i)$, $arrow(b) = hat(j)$, and $arrow(c) = hat(k)$. $ &arrow(a) dot arrow(b) = arrow(a) dot arrow(c) = 0 and arrow(b) eq.not arrow(c) \ &therefore arrow(a) dot arrow(b) = arrow(a) dot arrow(c) arrow.double.not arrow(b) = arrow(c) #<4a> $ + (3 points) If $arrow(a) times arrow(b) = arrow(a) times arrow(c)$, does it follow that $arrow(b) = arrow(c)$? Why or why not? Let $arrow(a) = hat(i)$, $arrow(b) = cos(pi/3)hat(i) + sin(pi/3)hat(j)$, and $arrow(c) = cos((2pi)/3)hat(i) + sin((2pi)/3)hat(j)$. $ &arrow(a) times arrow(b) = arrow(a) times arrow(c) = vec(0, 0, sqrt(3)/2) \ &therefore arrow(a) times arrow(b) = arrow(a) times arrow(c) arrow.double.not arrow(b) = arrow(c) $ + (2 points) If $arrow(a) dot arrow(b) = arrow(a) dot arrow(c)$ #underline[and] $arrow(a) times arrow(b) = arrow(a) times arrow(c)$, does it follow that $arrow(b) = arrow(c)$? Why or why not? The given equations can be rearranged into @4c-rearranged. For both equations to be true, either $arrow(a) = arrow(0)$ or $arrow(b) - arrow(c) = arrow(0)$. Since the former cannot be true, the latter must be true, indicating that $arrow(b)$ and $arrow(c)$ are equal as per @4c-solution. $ arrow(a) dot arrow(b) - arrow(a) dot arrow(c) = 0 and arrow(a) times arrow(b) - arrow(a) times arrow(b) = arrow(0) \ arrow(a) dot (arrow(b) - arrow(c)) = 0 and arrow(a) times ( arrow(b) - arrow(c) ) = arrow(0) #<4c-rearranged> \ therefore arrow(b) - arrow(c) = arrow(0) \ therefore arrow(b) = arrow(c) #<4c-solution> $ + Prove that if $arrow(a) dot (arrow(b) times arrow(c)) = 0$, then $arrow(a)$, $arrow(b)$, and $arrow(c)$ are coplanar. $ arrow(u) dot arrow(v) = 0 arrow.double arrow(u) perp arrow(v) or arrow(u) = arrow(0) or arrow(v) = arrow(0) $ Consider the two trivial cases where $arrow(a) = arrow(0) or arrow(b) times arrow(c) = 0$. In the former, $arrow(b)$ and $arrow(c)$ must be coplanar, since any two non-zero vectors can define a plane. In the latter, since $arrow(b)$ and $arrow(c)$ are parallel ($arrow(u) times arrow(v) = 0 arrow.double arrow(u) parallel arrow(v)$), they reside upon the same line; thus, along with $arrow(a)$, a plane can be defined. Now consider the non-trivial case where no vector equals $arrow(0)$. A plane can be defined by a normal vector $arrow(n)$ and an origin point $O$. All points $P$ in which a position vector $arrow(P)$ from the origin point $O$ to the point $P$ is orthogonal to the normal vector ($arrow(n) dot arrow(P) = 0$) is contained within the plane. By the definition of the cross product, $(arrow(b) times arrow(c)) perp arrow(b) and (arrow(b) times arrow(c)) perp arrow(c)$. Thus, $arrow(b) times arrow(c)$ defines a plane with origin point $(0, 0, 0)$ containing $arrow(b)$ and $arrow(c)$. Since $arrow(a) dot (arrow(b) times arrow(c)) = 0$, $arrow(a)$ is also contained within the plane, making all three vectors coplanar. + Prove the triangle inequality theorem for vectors: $norm(arrow(a) + arrow(b)) <= norm(arrow(a)) + norm(arrow(b))$. $ norm(arrow(a) + arrow(b)) &= sqrt(norm(arrow(a) + arrow(b))^2) \ &= sqrt((arrow(a) + arrow(b)) dot ( arrow(a) + arrow(b) )) \ &= sqrt(norm(arrow(a))^2 + 2 (arrow(a) dot arrow(b)) + norm(arrow(b))^2) \ &= sqrt(norm(arrow(a))^2 + 2 norm(arrow(a)) norm(arrow(b)) cos(theta) + norm(arrow(b))^2) \ &<= sqrt(norm(arrow(a))^2 + 2 norm(arrow(a)) norm(arrow(b)) + norm(arrow(b))^2) \ &= sqrt((norm(arrow(a)) + norm(arrow(b)))^2) \ &= norm(arrow(a)) + norm(arrow(b)) \ &therefore norm(arrow(a) + arrow(b)) <= norm(arrow(a)) + norm(arrow(b)) $ + If $arrow(A) = A_1 hat(i) + A_2 hat(j) + A_3 hat(k)$, $arrow(B) = B_1 hat(i) + B_2 hat(j) + B_3 hat(k)$, $arrow(C) = C_1 hat(i) + C_2 hat(j) + C_3 hat(k)$, prove that $arrow(A) dot (arrow(B) times arrow(C)) = (arrow(A) times arrow(B)) dot arrow(C)$. $arrow(u) dot (arrow(v) times arrow(w))$ defines the scalar triple product, which is equal to the determinant of the matrix formed by the three vectors' components. $ arrow(u) dot ( arrow(v) times arrow(w) ) = mat(delim: "|", u_1, v_1, w_1; u_2, v_2, w_2; u_3, v_3, w_3 ) $ // Reference isn't processed directly after an opening parenthesis. Thus, finding the determinants of both expressions (#[@7-det-1] and @7-det-2) shows that they are equal (#[@7-solution]). $ arrow(A) dot ( arrow(B) times arrow(C) ) &= mat(delim: "|", A_1, B_1, C_1; A_2, B_2, C_2; A_3, B_3, C_3 ) \ &= A_1(B_2 C_3 - C_2 B_3) - B_1(A_2 C_3 - C_2 A_3) + C_1(A_2 B_3 - B_2 A_3) \ // Would like to highlight matching terms, but unfortunately highlights within math are broken in the current version of the compiler. &= A_1 B_2 C_3 - A_1 C_2 B_3 - B_1 A_2 C_3 + B_1 C_2 A_3 + C_1 A_2 B_3 - C_1 B_2 A_3 #<7-det-1> \ arrow(C) dot ( arrow(A) times arrow(B) ) &= mat(delim: "|", C_1, A_1, B_1; C_2, A_2, B_2; C_3, A_3, B_3 ) \ &= C_1 (A_2 B_3 - B_2 A_3) - A_1 (C_2 B_3 - B_2 C_3) + B_1 ( C_2 A_3 - A_2 C_3 ) \ &= C_1 A_2 B_3 - C_1 B_2 A_3 - A_1 C_2 B_3 + A_1 B_2 C_3 + B_1 C_2 A_3 - B_1 A_2 C_3 #<7-det-2> \ &therefore arrow(A) dot ( arrow(B) times arrow(C) ) = arrow(C) dot ( arrow(A) times arrow(B) ) #<7-solution> $ #pagebreak() = True or False Prove that the given statement is true in $RR^3$ or provide a counterexample to show that it is false. // True 8. Two lines parallel to a third line are parallel. <8> Let the vectors $arrow(v)$ and $arrow(u)$ describe two lines. Two lines are parallel if their direction vectors are parallel. Two vectors are parallel if they are a scalar multiple of each other; thus, if their normalized components are equal or directly opposite one another. $ arrow(v) parallel arrow(u) <=> 1 / norm(arrow(v)) arrow(v) = plus.minus 1 / norm(arrow(u)) arrow(u) $ Let $arrow(b)$ and $arrow(c)$ describe two vectors parallel to vector $arrow(a)$. Via the transitive property, @8-transitive can be derived, showing that $arrow(b) parallel arrow(c)$. $ 1 / norm(arrow(b)) arrow(b) &= plus.minus 1 / norm(arrow(a)) arrow(a) \ 1 / norm(arrow(c)) arrow(c) &= plus.minus 1 / norm(arrow(a)) arrow(a) \ 1 / norm(arrow(b)) arrow(b) &= plus.minus 1 / norm(arrow(c)) arrow(c) #<8-transitive> $ // False + Two lines perpendicular to a third line are parallel. <9> Two lines, described by $arrow(u)$ and $arrow(v)$, are perpendicular if and only if $arrow(u) dot arrow(v) = 0$. Thus, by @8-ik and @8-jk, the unit vectors $hat(i)$ and $hat(j)$ are both perpendicular to $hat(k)$. However, by @8-ij, $hat(i)$ and $hat(j)$ must also be perpendicular to each other, which means they cannot be parallel, disproving the statement by counterexample. $ hat(i) dot hat(k) &= 0 #<8-ik> \ hat(j) dot hat(k) &= 0 #<8-jk> \ hat(i) dot hat(j) &= 0 #<8-ij> $ // False + Two planes perpendicular to a third plane are parallel. Two planes are perpendicular if their normal vectors are perpendicular. Two planes are parallel if their normal vectors are parallel. Two vectors are perpendicular if their dot product is zero ($arrow(a) dot arrow(b) = 0$). Two vectors are parallel if their cross product is zero ($arrow(a) times arrow(b) = 0$). Let $hat(i)$, $hat(j)$, and $hat(k)$ describe three planes. $ hat(i) dot hat(j) = 0 => hat(i) perp hat(j) \ hat(i) dot hat(k) = 0 => hat(i) perp hat(k) \ hat(j) times hat(k) != arrow(0) => not hat(j) parallel hat(k) $ #pagebreak() // False 11. Two lines parallel to a plane are parallel. A line can be defined by a direction vector $arrow(v)$ and origin point $p$. A plane can be defined by a normal vector $arrow(v)$ and origin point $p$. Let $overline(L)$ represent any line and $P$ represent any plane. $ overline(L) parallel P <=> arrow(v)_L dot arrow(v)_P = 0 \ overline(L_1) parallel overline(L_2) <=> exists k in RR_(!= 0) : arrow(v)_L_1 = k arrow(v)_L_2 $ Let $hat(k)$ define a plane with origin point $(0, 0, 0)$. Let $hat(i)$ and $hat(j)$ define two lines with origin point $(0, 1, 0)$. $ hat(k) dot hat(i) = 0 and hat(k) dot hat(j) = 0 => hat(k) parallel hat(i) and hat(k) parallel hat(j) \ exists.not k in RR_(!= 0) : hat(i) = k hat(j) => hat(i) parallel.not arrow(j) \ therefore arrow(v)_"line"_1 parallel arrow(v)_"plane" and arrow(v)_"line"_2 parallel arrow(v)_"plane" arrow.double.not arrow(v)_"line"_1 parallel arrow(v)_"line"_2 $ // True + Two lines perpendicular to a plane are parallel. A line is perpendicular to a plane if the direction vector of the line $arrow(l)$ is parallel to the normal vector of the plane $arrow(n)$. Let $arrow(l_1)$ and $arrow(l_2)$ describe two lines that are perpendicular to the plane described by normal vector $arrow(n)$. $ arrow(l_1) parallel arrow(n) and arrow(l_2) parallel arrow(n) $ Thus, by #link(<8>)[Proof 8], $arrow(l_1) parallel arrow(l_2)$. // False + Two planes parallel to a line are parallel. A plane is parallel to a line if the line's direction vector $arrow(l)$ is perpendicular to the plane's normal vector $arrow(n)$. $ P parallel overline(L) <=> arrow(n) dot arrow(l) = 0 $ Let $arrow(n_1)$ and $arrow(n_2)$ be normal vectors describing two planes parallel to the line described by direction vector $arrow(l)$. $ arrow(n_1) dot arrow(l) = 0 and arrow(n_2) dot arrow(l) = 0 $ By #link(<9>)[Proof 9], two vectors perpendicular to a third does not imply that those vectors are parallel; thus, two planes parallel to a line does not imply that those planes are parallel.
https://github.com/EricWay1024/Homological-Algebra-Notes
https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/d-app.typ
typst
#import "../libs/template.typ": * = Example: $R = ZZ$ // == $R = ZZ$ Let $A in Ab$. Recall that we have the following: - $A$ is projective #iff $A$ is free; - $A$ is injective #iff $A$ is divisible, #iff $A$ is a direct sum of copies of $QQ$ and $ZZ[1/p] over ZZ$, where each $p$ is prime; - $A$ is flat #iff $A$ is torsionfree. We now demonstrate some calculations in the category $Ab$ using tools developed throughout the course. These may serve as exercises or reference materials. == Resolutions #align(center, table(columns: (auto, auto, auto), inset: 7pt, stroke: none, [Type], [Object], [Resolution], table.hline(), [projective], $ZZ over m$, $0->ZZ->^m ZZ -> ZZ over m -> 0$, [injective], $ZZ over m$, $0-> ZZ over m -> QQ over ZZ ->^m QQ over ZZ -> 0$, [injective], $ZZ$, $0 -> ZZ -> QQ -> QQ over ZZ -> 0$, )) == Tensor products #align(center, table(columns: (auto, auto, auto, auto, auto), inset: 7pt, stroke: none, [$tp_ZZ$], table.vline(), $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, table.hline(), $ZZ$, $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, $QQ$, $QQ$, $QQ$, $0$, $0$, $ZZ over n$, $ZZ over n$, $0$, $ZZ over"gcd"(m, n)$, $0$, $QQ over ZZ$, $QQ over ZZ$, $0$, $0$, $0$ )) - $A tp_ZZ B iso B tp_ZZ A$; - $ZZ tp_ZZ A iso A$; - $QQ tp_ZZ T iso 0$ if $T$ is torsion; - $QQ over ZZ tp_ZZ T iso 0$ if $T$ is torsion; - $ZZ over m tp_ZZ A iso A over m A$ (recall that $R over I tp_R M iso M over I M$); - $QQ tp_ZZ QQ iso QQ$. == $Tor$ groups #let tor1z = [$Tor_1^ZZ$] #align(center, table(columns: (auto, auto, auto, auto, auto), inset: 7pt, stroke: none, [$Tor_1^ZZ$], table.vline(), $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, table.hline(), $ZZ$, $0$, $0$, $0$, $0$, $QQ$, $0$, $0$, $0$, $0$, $ZZ over n$, $0$, $0$, $ZZ over"gcd"(m, n)$, $ZZ over n$, $QQ over ZZ$, $0$, $0$, $ZZ over m$, $QQ over ZZ$ )) - $Tor_n^ZZ (A, B) iso Tor_n ^ZZ (B, A)$; - $ZZ$ is free and thus flat, so $Tor_1^ZZ (ZZ , -) = 0$; - $QQ$ is torsionfree and thus flat, so $Tor_1^ZZ (QQ , -) = 0$; - $tor1z (ZZ over m, A) iso {a in A | m a = 0}$; - $tor1z (QQ over ZZ, QQ over ZZ)$ is obtained from the #lest induced by applying $(- tpz QQ over ZZ)$ to $0 -> ZZ -> QQ -> QQ over ZZ -> 0$. == Hom-sets #align(center, table(columns: (auto, auto, auto, auto, auto), inset: 7pt, stroke: none, [$hom_ZZ$], table.vline(), $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, table.hline(), $ZZ$, $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, $QQ$, $0$, $QQ$, $0$, [$?$], $ZZ over n$, $0$, $0$, $ZZ over"gcd"(m, n)$, $ZZ over n$, $QQ over ZZ$, $0$, $0$, $0$, $hat(ZZ)$ )) Each row represents the first argument in $hom$ and each column the second. A question mark indicates that the result is beyond the scope of the course. - $hom_ZZ (ZZ, A) iso A$ (in general, $hom_R (R, M) iso M$); - $hom_ZZ (QQ, QQ) iso QQ$ by establishing a (fairly easy) bijection; - $hom_ZZ (QQ, ZZ) iso 0$ because no integer is arbitrarily divisible, e.g. $f(1) = n f (1/n)$ where $f(1), f(1/n) in ZZ$, so $f(1)$ is divisible by any $n$ which is impossible unless $f(1) = 0$. Similarly $hom_ZZ (QQ, ZZ over m) iso 0$; - $hom_ZZ (ZZ over n, A) iso {a in A | n a = 0}$ (incidentally, this is isomorphic to $tor1z (ZZ over n, A)$); - $hom_ZZ (A, QQ over ZZ)$ is the *Pontryagin duality* of $A$. == $Ext$ groups #align(center, table(columns: (auto, auto, auto, auto, auto), inset: 7pt, stroke: none, [$Ext_1^ZZ$], table.vline(), $ZZ$, $QQ$, $ZZ over m$, $QQ over ZZ$, table.hline(), $ZZ$, $0$, $0$, $0$, $0$, $QQ$, $?$, $0$, $?$, [$0$], $ZZ over n$, $ZZ over n$, $0$, $ZZ over"gcd"(m, n)$, $0$, $QQ over ZZ$, $?$, $0$, $?$, $0$ )) Each row represents the first argument in $Ext$ and each column the second. - $Ext_1^ZZ (ZZ, -) = 0$ as $ZZ$ is projective; - $Ext_1^ZZ (-, QQ) = 0$ as $QQ$ is injective; - $Ext_1^ZZ (-, QQ over ZZ) = 0$ as $QQ over ZZ$ is injective; - $Ext_1^ZZ (ZZ over n, A) iso A over n A$ using the projective resolution of $ZZ over n$. // == $R = k[x]$ // We consider when $R$ is the polynomial ring $k[x]$ for a field $k$. Note that $k[x]$ is a PID. // === Projective, injective, and flat modules // - $k(x)$, the field of fractions, is an injective $k[x]$-module; // - Any quotient of an injective $k[x]$-module is injective; // - $k[x, x^(-1)]$ is a flat $k[x]$-module since it is the localisation of $x$ in $k[x]$; alternatively, it can be constructed as a filtered colimit of flat modules $k[x] ->^(x^(-1)) x^(-1) k[x] -> ^(x^(-2)) x^(-2) k[x] ->...$. // === Resolutions // #align(center, table(columns: (auto, auto, auto), inset: 7pt, stroke: none, // [Type], [Object], [Resolution], // table.hline(), // [projective], $k[x] over (x^m)$, $0->k[x]->^(x^m) k[x] -> k[x] over (x^m) -> 0$, // [injective], $k[x]$, $0-> k[x] -> k(x) -> k(x) over k[x] -> 0$, // [flat], $k[x, x^(-1)] over k[x]$, $0 -> k[x] -> k[x, x^(-1)] -> k[x, x^(-1)] over k[x] -> 0$, // ))
https://github.com/SkytAsul/fletchart
https://raw.githubusercontent.com/SkytAsul/fletchart/main/README.md
markdown
# fletchart `fletchart` (contraction of `fletcher` and `flowchart`) is a Typst package made to easily create flowcharts using the `fletcher` package. ## How to use There are two ways of creating flowcharts with `fletchart`: 1. The "declarative" way, where you create every element and manually setup the links between them. To use it: ```typst #import "src/lib.typ" as fletchart #import fletchart.declarative: fc-declarative #import fletchart.elements: * #fc-declarative({ // your elements here }) ``` 1. The "logical" way, where you declare a logic structure with custom if-else blocks which will be automatically turned to a flowchart. To use it: ```typst #import "src/lib.typ" as fletchart #import fletchart.logical: fc-logical, fc-if, fc-process, fc-begin, fc-end, fc-io, fc-predefined-process #fc-logical({ // your logic here }) ``` ## Examples You can find examples in the [examples](examples) folder.
https://github.com/topdeoo/NENU-Thesis-Typst
https://raw.githubusercontent.com/topdeoo/NENU-Thesis-Typst/master/README.md
markdown
# NENU-Thesis-Typst-Template 东北师范大学毕业论文的 `Typst` 模板,可以在 [`template/thesis.typ`](./template/thesis.typ) 查看使用方法与生成的效果 ![Editor](./images/editor.png) > [!IMPORTANT] > > 此模板是民间模板,有不被学校认可的风险。 > > 本模板虽已尽力尝试复原 LaTex 模板,但可能仍然存在诸多格式问题,详细请看[存在的问题](#存在的问题) > [!NOTE] > > 我们在 `other` 文件夹中放了其他的模板,例如: > > 1. 实验报告模板 > > 这些模板会使用 `assets` 中的图片,因此暂时没有隔离出一个独立的版本 ## 使用方法 > [!NOTE] > > 模板暂时只支持本地编译使用 ### 本地使用 1. 安装一个文本编辑器,这里推荐使用 `VS Code`,并安装 [Tinymist Typst](https://github.com/Myriad-Dreamin/tinymist) 和 [Typst Preview](https://github.com/Enter-tainer/typst-preview) 插件 - 克隆/下载本仓库到本地,并使用 `VS Code` 打开项目文件夹 - 打开 `template/thesis.typ` 文件,开始编写你的论文内容,可以按下 `<C-K> V` (Ctrl+K V) 快捷键在 `VS Code` 中打开预览窗口,实时查看你的论文效果 ## TODO - [x] 学士学位论文模板 - [x] 封面 - [x] 扉页 - [x] 中文摘要 - [x] 英文摘要 - [x] 目录页 - [x] 正文 - [x] 致谢 - [ ] 硕士学位论文模板 - [ ] 博士学位论文模板 - [ ] 更多其它模板 - [ ] 完善使用文档 ## 存在的问题 1. 使用 `subpar` 时,无法正确显示子图的编号,如下图所示: ![subfigure-error](images/subfigure-error.png) 因此暂时不支持使用子图 2. 本科生论文不支持附录功能 3. 扉页中作者签名无法直接插入图片/PDF ## 致谢 - 感谢 [modern-nju-thesis](https://github.com/nju-lug/modern-nju-thesis) 开发的 `Typst` 模板,架构清晰,文档注释详细,本项目在架构上参考良多。 - 感谢 [SEU-Typst-Template](https://github.com/csimide/SEU-Typst-Template/) 开发的 `Typst` 模板
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/show-node-07.typ
typst
Other
// Error: 25-29 content does not contain field "page" and no default value was specified #show heading: it => it.page = Heading
https://github.com/Enter-tainer/typstyle
https://raw.githubusercontent.com/Enter-tainer/typstyle/master/tests/assets/unit/markup/code-inside-content.typ
typst
Apache License 2.0
#[#{ let something = 0; }\ ]
https://github.com/sofianedjerbi/Resume
https://raw.githubusercontent.com/sofianedjerbi/Resume/main/modules_fr/education.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Formation") #cvEntry( title: [Magistère en Mathematiques (Niveau Master)], society: [Université Grenoble Alpes], date: [2022 - 2023], location: [Grenoble, France], ) #cvEntry( title: [Licence en Mathematiques (Niveau Bachelor)], society: [Université Grenoble Alpes], date: [2019 - 2022], location: [Grenoble, France], )
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/content_01.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test tables. $ x := #table(columns: 2)[x][y]/mat(1, 2, 3) = #table[A][B][C] $
https://github.com/hitszosa/universal-hit-thesis
https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/config/constants.typ
typst
MIT License
#let special-chapter-titles = ( 摘要: text(spacing: 1em)[摘 要], Abstract: "Abstract", 目录: text(spacing: 1em)[目 录], 结论: text(spacing: 1em)[结 论], 参考文献: "参考文献", 原创性声明: "原创性声明和使用权限", 致谢: text(spacing: 1em)[致 谢], 成果: "攻读学士学位期间取得创新性成果", ) #let current-date = datetime.today()
https://github.com/Chwiggy/thesis_bachelor
https://raw.githubusercontent.com/Chwiggy/thesis_bachelor/main/src/preamble.typ
typst
#let bib_state = state("bib_state", bibliography("bibliography.bib", style: "american-psychological-association", title: auto))
https://github.com/cadojo/correspondence
https://raw.githubusercontent.com/cadojo/correspondence/main/src/rolo/src/attributes.typ
typst
MIT License
#let attributes( corresponding: false, equal-contributor: false, deceased: false, ) = ( corresponding: corresponding, equal-contributor: equal-contributor, deceased: deceased, )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/while-02.typ
typst
Other
// Condition must be boolean. // Error: 8-14 expected boolean, found content #while [nope] [nope]
https://github.com/topdeoo/Course-Slides
https://raw.githubusercontent.com/topdeoo/Course-Slides/master/Courses/SOTA4CS/main.typ
typst
#import "../../theme/iTalk.typ": * #show: nenu-theme.with( short-title: "PyTorch", short-date: "23-12-20", short-author: "Virgil" ) #title-slide( title: "Make Your Python Faster & Efficient", authors: (name: "Virgil", email: "<EMAIL>"), logo: image("fig/nenu-logo-title.png", width: 30%), institution: "Northeast Normal University", date: "2023-12-20" )
https://github.com/8LWXpg/typst-treet
https://raw.githubusercontent.com/8LWXpg/typst-treet/master/test/demo.typ
typst
MIT License
#import "../lib.typ": * = Tree List == Default #tree-list[ - 1 - 1.1 - 1.1.1 - 1.2 - 1.2.1 - 1.2.2 - 1.2.2.1 - 2 - 3 - 3.1 - 3.1.1 - 3.2 ] == Custom #text( red, tree-list( marker: text(blue)[├── ], last-marker: text(aqua)[└── ], indent: text(teal)[│#h(1.5em)], empty-indent: h(2em), )[ - 1 - 1.1 - 1.1.1 - 1.2 - 1.2.1 - 1.2.2 - 1.2.2.1 - 2 - 3 - 3.1 - 3.1.1 - 3.2 ], ) == Using show rule #show list: tree-list #set text(font: "DejaVu Sans Mono") root_folder\ - sub-folder - 1-1 - 1.1.1 - - 1.2 - 1.2.1 - 1.2.2 - 2
https://github.com/AxiomOfChoices/Typst
https://raw.githubusercontent.com/AxiomOfChoices/Typst/master/Courses/Math%2018_785%20-%20Number%20Theory/Assignments/Assignment%203.typ
typst
#import "/Templates/generic.typ": latex, header #import "@preview/ctheorems:1.1.0": * #import "/Templates/math.typ": * #import "/Templates/assignment.typ": * #show: doc => header(title: "Assignment 3", name: "<NAME>", doc) #show: latex #show: NumberingAfter #show: thmrules #let col(x, clr) = text(fill: clr)[$#x$] #let pb() = { pagebreak(weak: true) } #set page(numbering: "1") #let bar(el) = $overline(#el)$ #set enum(numbering: "(a)") // #show math.equation: set text(font: "Latin Modern Math") *Sources consulted* \ Classmates: <NAME>, <NAME>, <NAME>. We discussed essentially every single problem together.\ Texts: Class Notes, Algebraic Number Theory by Milne, Elementry and Analytic Theory of Algebraic Numbers by Narkiewicz, Number Fields by Marcus. = Question == Statement Follow the following steps to show Lagrange's four-square theorem: Every positive integer is a sum of four squares. + For any positive odd integer $m$, show that there exists $a,b in ZZ$ such that $ a^2 + b^2 + 1 equiv 0 quad (mod m) $ + Let $m$ be a positive odd integer and $a,b$ satisfy the congruence above. Consider $ X &= & m x & & + & a z & + & b w \ Y &= & & m y & - & b z & + & a w \ Z &= & & & & z & & \ W &= & & & & & & w. $ Show that the domain $Omega$ defined by $ abs(X)^2 + abs(Y)^2 + abs(Z)^2 + abs(W)^2 < 2m $ contains a point $(x,y,z,w) in ZZ^4 - {0}$. Show that $m$ is a sum of four squares. + Show that every even integer $m > 0$ is also a sum of four squares (in fact, show that if both $m,n$ are sums of four squares, so is $m n$). == Solution + First we prove this for odd primes, in $ZZ_p$ we know that we have exactly $(p+1)/2$ quadratic residues, so the sets ${a^2 : a in ZZ_p}$ and ${-b^2-1 : b in ZZ_p}$ both have $(p+1)/2$ elements and thus have some non-trivial intersection. That intersection corresponds to a solution of $a^2 + b^2 + 1 = 0 mod p$. Now if instead $m = p^n$, then we can show by induction that such a pair exists, assume it exists for $m = p^(n-1)$, then we have $a^2 + b^2 + 1 = c dot p^(n-1)$ for some integer $c < p$ and integers $a,b <= p^(n-1)$. But we also have $ (a + m p^(n-1))^2 + (b + n p^(n-1))^2 + 1 &= a^2 + b^2 + 2a m p^(n-1) + m^2 p^(2n-2)\ &+ med b^2 + 2 n b p^(n-1) + n^2 p^(2n-2) + 1\ &equiv (c + 2 a m + 2 b n) dot p^(n-1) $ so it is enough to find $m,n$ such that $c + 2a m + 2b n = 0 mod p$ and we know this is possible because at least one of $a,b$ are invertible $mod p$ since if both were divisible by $p$ then $a^2 + b^2 = 0 mod p$ and yet we know $a^2 + b^2 = 1 mod p$. Hence, since $2$ is also invertible (because $p$ is odd) then either $2 a$ or $2 b$ is invertible $mod p$ so we can find such elements $m,n$. Finally if $m$ is a generic product of odd primes, then using Chinese remainder theorem we can reduce to the case of just prime powers. + This domain in $X,Y,W,Z$ coordinate system corresponds to a sphere of radius $sqrt(2 m)$ and so it has volume $pi^2/2 4 m^2 = 2 pi^2 m^2$. The change of basis matrix to the region in coordinates $(x,y,z,w)$ has determinant $m^2$ clearly so the region has volume $2 pi^2 > 16$. So by the Minkowski bound we know that in these coordinates this convex region intersects the integer lattice, which gives us precisely the desired point $(x,y,w,z)$. For such a point we have $ |X|^2 + |Y|^2 + |Z|^2 + |W|^2 &= m(m x^2 + 2a x z + 2 b x w + m y^2 - 2 b y z + 2 a y w) \ &+ med a^2 z^2 + 2 a z b w + b^2 w^2 + b^2 z^2 - 2 a b z w + a^2 w^2 + z^2 + w^2 \ &equiv (a^2 + b^2 + 1) (z^2 + w^2) mod m equiv 0 mod m $ So since this is clearly a positive expression which is smaller than $2 m$ and divisible by $m$, it must be equal to $m$. Hence $m$ is the sum of 4 squares. + Set $m = x_1^2 + y_1^2 + z_1^2 + w_1^2$ and $n = x_2^2 + y_2^2 + z_2^2 + w_2^2$ then we have $ & (x_1 x_2 - y_1 y_2 - z_1 z_2 - w_1 w_2)^2 \ +& (x_1 y_2 + x_2 y_1 + z_1 w_2 - z_2 w_1)^2 \ +& (x_1 z_2 + x_2 z_1 - y_1 w_2 + y_2 w_1)^2 \ +& (x_1 w_2 + x_2 w_1 + y_1 z_2 - y_2 z_1)^2 \ = m n $ so since $m = 2 = 1^2 + 1^2 + 0 + 0$ then all even integers are the sums of 4 squares. = Question == Statement Let $K = QQ(2^(1 slash 3))$. Is $cal(O)_K$ a PID? Justify your answer. == Solution $cal(O)_K$ is indeed a PID. We saw in a previous assignment that the discriminant of $K$ is $-108$ so since $2^(1 slash 3)$ has exactly 2 complex embeddings the Minkowski bound gives us that any class of $K$ has a representative ideal $frak(a)$ with $ NN frak(a) <= sqrt(108) (4/pi)^(1) 3!/3^3 < 3 $ so we have $NN frak(a) <= 2$. Assuming this we get that $cal(O)_k quo frak(a)$ is a $2$ element ring and thus is $FF_2$. Now clearly this means that $frak(a)$ is maximal, next we recall that in this case $cal(O)_k$ is monogenic and is equal to $ZZ[2^(1 slash 3)] = ZZ[x] quo (x^3 - 2)$ so now we can take $mod 2$ to get that $ frak(a) subset ZZ[x] quo (x^3 - 2) => frak(a) quo (2) subset ZZ[x] quo (x^3 - 2, 2) iso ZZ[x] quo (x^3,2) iso FF_2 [x] quo (x^3) $ so $frak(a) quo 2$ is an index 2 subring of $FF_2 [x] quo (x^3)$. But now the only subring of $FF_2 [x] quo (x^3)$ with degree $2$ is $(x)$ so we have that $frak(a)$ is the image of the ideal $(2^(1 slash 3))$ in $cal(O)_K$. But this ideal is clearly principle so the class group of $cal(O)_K$ is trivial so it is a PID. = Question == Statement Let $K$ be a number field. Show that there exists a finite extension $L$ of $K$ such that all the ideals of $K$ become principal ideals in $L$. == Solution Let $frak(a)$ be an ideal of $K$, then some power of $frak(a)$ is principal since it represents a finite order element of the class group. Assume that $frak(a)^m = (a)$ for some minimal $m$, we then have $ (frak(a) K(#h(-3pt) root(m, a)))^m = frak(a^m) K(#h(-3pt) root(m, a)) = (a) K(#h(-3pt) root(m, a)) = ((#h(-3pt) root(m, a)) K(#h(-3pt) root(m, a)))^m $ so since in a number ring prime factorization is unique we get that $ frak(a) K(#h(-3pt) root(m, a)) = (#h(-3pt) root(m, a)) K(#h(-3pt) root(m, a)) $ so $frak(a)$ becomes principal in $L = K(#h(-3pt) root(m, a))$, we then repeat this for every non-trivial class in the class group of $K$. #counter(heading).step() = Question == Statement Let $n in ZZ_(> 0)$ and assume $n^2 - 1$ is square free. Prove that $n + sqrt(n^2 - 1)$ is the fundamental unit of $K = QQ(sqrt(n^2 - 1))$. == Solution Since $n^2 - 1$ is square free then $n^2 - 1 = 3 mod 4$ so $cal(O)_K = ZZ[sqrt(n^2 - 1)]$. Now assume that an element $a + b sqrt(n^2 - 1)$ is the fundamental unit, by negation and conjugation we may assume that $a > 0$ and $b > 0$. The norm of this element is given by $abs(a^2 - (n^2 - 1)b^2)$ which we assume is equal to $1$. Now it is clear that under taking higher powers of this unit, $a$ will only increase in size because if $a,b,c,d > 0$ then $ (a + b sqrt(n^2 - 1))(c + d sqrt(n^2 - 1)) = (a c + (n^2 - 1) b d) + (a d + b c) sqrt(n^2 - 1) $ and $a c + (n^2 - 1) b d > a$. So the fundamental unit must be one for which $a$ is minimal, but $n + sqrt(n^2 - 1)$ has $a = 1$ so it must be minimal, it is thus the fundamental unit. #counter(heading).step() = Question == Statement Let $m > 2$ be an integer and $zeta = zeta_m$ be a primitive $m$-th root of unity. Denote $K = QQ(zeta)$. + Show that $(zeta^k - 1)/(zeta - 1)$ is a unit in $cal(O)_K$ if $(k,m) = 1$. + Show that if $m$ has at least two distinct prime factors, then $1 - zeta$ is a unit in $cal(O)_K$. == Solution + Clearly $(zeta^k - 1)/(zeta - 1)$ is an element of $cal(O)_K$ since #h(1fr) $ (zeta^k - 1)/(zeta - 1) = 1 + zeta + zeta^2 + ... + zeta^(k - 1). $ Now since $(k,m) = 1$ we know that $k$ has a multiplicative inverse $mod m$ so let $ell$ be that inverse, we now have $ 1 + zeta^k + zeta^(2 k) + ... + zeta^((ell - 1) k) = (zeta^(ell k) - 1)/(zeta^k - 1) = (zeta - 1)/(zeta^k - 1) $ is an element of $cal(O)_K$ and clearly the inverse of $(zeta^k - 1)/(zeta - 1)$. + We consider the polynomial $ 1 + x + ... + x^(m-1) = (x^m - 1)/(x - 1) = product_(i = 1)^(m - 1) (x - zeta^i) $ plugging in $x = 1$ gives us $ m = product_(i = 1)^(m - 1) (1 - zeta^i). $ Now write $m = p_1^(r_1) p_2^(r_2) dots.c p_n^(r_n)$ and note that for each $p_j$ we also have $ p_j^(r_j) = product_(i=1)^(p_j^(r_j) - 1) (1 - zeta_(p_j^(r_j))^i) $ so dividing both sides by this expression for every $p_j$ gives us $ 1 = product_(i in S) (1 - zeta^i) $ where $S$ is the set ${i : 1 <= i <= m - 1, gcd(i,n) = 1}$ because these elements are not the powers of any prime power root of unity. Since $gcd(1,n) = 1$ then we can write $ 1 = (1 - zeta) product_(i in S backslash {1}) (1 - zeta^i) $ and hence $1 - zeta$ is a unit.
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/call_info/user.typ
typst
Apache License 2.0
#let f(x, y) = x + y #(/* position after */ f(1, 1))
https://github.com/BeitianMa/typst-lecture-notes
https://raw.githubusercontent.com/BeitianMa/typst-lecture-notes/main/README.md
markdown
## Typst Lecture Notes Template This is a lecture notes template based on [Typst](https://github.com/typst/typst). This template is designed to help students organise their note-taking materials or allow teachers to create more polished handouts. Any advice would be very welcome! You can take a quick look at the [rendered pdf](example.pdf) to determine if it interests you. ### Usage **Page organization:** The template will automatically create a cover and outline page based on the basic information given by the user, and set the header and footer to fit the content of each page. Just use ``` #show: note_page.with(title, author, professor, creater, time, abstract) ``` to complete the global settings. **Text blocks and figures:** You can create blocks to highlight certain text. The template has predefined some classes of blocks. For example, you can create a **Definition** block by ``` #definition[your content] ``` Different classes of blocks are automatically labeled. By making some simple changes to the template, you can also define new block class. This is done by adding a new class name to the global variable `classes` and rewriting the `note_block()` function ``` #let classes = ("Definition", "Lemma", "Theorem", "Corollary", "MyClass") // Choose any color you like! #let myclass(body) = note_block( body, class: "MyClass", fill: rgb("#FFFFFF"), stroke: rgb("#666666") ) #myclass[your content] ``` The `notefig()` function is used similarly to `figure()`, but is more consistent with the numbering rules in this template and supports the quick reference feature described later. **Quick reference:** There are often connections between, for example, theorems and corollaries in lecture notes. Since each block is automatically labeled, you can easily link to any block using the `refto()` function ``` From #refto("Lemma 1.2.1"), we can get #refto("Corollary 1.3.2"). This result is consistent with the pattern in #refto("Figure 1.1.1"). ``` ### Thanks and related links Typst non-official Chinese community provides a convenient communication platform, they are also committed to providing native Chinese speakers with quality learning materials, if you are interested in translating typst documents, please see [Typst Chinese document](https://github.com/typst-doc-cn/typst-doc-cn). More community-created templates please refer to [awesome-typst](https://github.com/qjcg/awesome-typst).
https://github.com/alxsimon/quarto-pci
https://raw.githubusercontent.com/alxsimon/quarto-pci/main/_extensions/pci/typst-show.typ
typst
#import "@preview/superb-pci:0.1.0": * #show: pci.with( $if(title)$ title: [$title$], $endif$ $if(by-author)$ authors: ( $for(by-author)$ ( name: "$it.name.literal$", $if(it.orcid)$ orcid: "$it.orcid$", $endif$ $if(it.affiliations)$ affiliations: [$for(it.affiliations)$$it.id$$sep$,$endfor$], $endif$ ), $endfor$ ), $endif$ $if(by-affiliation)$ affiliations: ( $for(by-affiliation)$ (id: [$it.id$], name: "$it.name$"), $endfor$ ), $endif$ $if(abstract)$ abstract: [$abstract$], $endif$ $if(doi)$ doi: "$doi$", $endif$ $if(keywords)$ keywords: ( $for(keywords)$ "$it$", $endfor$ ), $endif$ $if(correspondence)$ correspondence: "$correspondence$", $endif$ $if(section-numbering)$ numbered_sections: $section-numbering$, $endif$ $if(bibliography)$ bibliography: bibliography("$bibliography$"), $endif$ $if(pcj)$ pcj: $pcj$, $endif$ )
https://github.com/RaphGL/ElectronicsFromBasics
https://raw.githubusercontent.com/RaphGL/ElectronicsFromBasics/main/DC/chap1/3_electric_circuits.typ
typst
Other
#import "../../core/core.typ" === Electric circuits You might have been wondering how electrons can continuously flow in a uniform direction through wires without the benefit of these hypothetical electron Sources and Destinations. In order for the Source-and-Destination scheme to work, both would have to have an infinite capacity for electrons in order to sustain a continuous flow! Using the marble-and-tube analogy, the marble source and marble destination buckets would have to be infinitely large to contain enough marble capacity for a "flow" of marbles to be sustained. The answer to this paradox is found in the concept of a _circuit_: a never-ending looped pathway for electrons. If we take a wire, or many wires joined end-to-end, and loop it around so that it forms a continuous pathway, we have the means to support a uniform flow of electrons without having to resort to infinite Sources and Destinations: #image("static/marble-analogy.png") Each electron advancing clockwise in this circuit pushes on the one in front of it, which pushes on the one in front of it, and so on, and so on, just like a hula-hoop filled with marbles. Now, we have the capability of supporting a continuous flow of electrons indefinitely without the need for infinite electron supplies and dumps. All we need to maintain this flow is a continuous means of motivation for those electrons, which we'll address in the next section of this chapter. It must be realized that continuity is just as important in a circuit as it is in a straight piece of wire. Just as in the example with the straight piece of wire between the electron Source and Destination, any break in this circuit will prevent electrons from flowing through it: #image("static/broken-circuit.png") An important principle to realize here is that _it doesn't matter where the break occurs_. Any discontinuity in the circuit will prevent electron flow throughout the entire circuit. Unless there is a continuous, unbroken loop of conductive material for electrons to flow through, a sustained flow simply cannot be maintained. #image("static/broken-circuit-2.png") #core.review[ - A circuit is an unbroken loop of conductive material that allows electrons to flow through continuously without beginning or end. - If a circuit is "broken," that means its conductive elements no longer form a complete path, and continuous electron flow cannot occur in it. - The location of a break in a circuit is irrelevant to its inability to sustain continuous electron flow. Any break, anywhere in a circuit prevents electron flow throughout the circuit. ]
https://github.com/lyzynec/orr-go-brr
https://raw.githubusercontent.com/lyzynec/orr-go-brr/main/main.typ
typst
#import "lib.typ": * #show: project.with( title: "ORR go BRR", author: "lyzynec", ) #week[#include "01/main.typ"] #pagebreak() #week[#include "02/main.typ"] #pagebreak() #week[#include "03/main.typ"] #pagebreak() #week[#include "04/main.typ"] #pagebreak() #week[#include "05/main.typ"] #pagebreak() #week[#include "06/main.typ"] #pagebreak() #week[#include "07/main.typ"] #pagebreak() #week[#include "08/main.typ"] #pagebreak() #week[#include "09/main.typ"] #pagebreak() #week[#include "10/main.typ"] #pagebreak() #week[#include "11/main.typ"] #pagebreak() #week[#include "12/main.typ"] #pagebreak() #week[#include "13/main.typ"] #pagebreak() #week[#include "14/main.typ"]
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/text/escape-01.typ
typst
Other
// Unicode codepoint does not exist. // Error: 1-11 invalid unicode codepoint: FFFFFF \u{FFFFFF}
https://github.com/jneug/schule-typst
https://raw.githubusercontent.com/jneug/schule-typst/main/src/pt.typ
typst
MIT License
#import "@preview/polylux:0.3.1" as polylux: * #import "@preview/codetastic:0.2.2": qrcode #import "_imports.typ": * #import "util/harbinger.typ": shadow-box #let slide( title: auto, subtitle: none, fill: none, header: auto, footer: auto, section: none, show-progress: auto, align: top + left, body, ) = { let (title, rest) = (title, body) if title == auto { (title, rest) = util.extract-title(body) } let page-args = (:) if fill != auto { page-args.insert("fill", fill) } if header != auto { page-args.insert("header", header) } if footer != auto { page-args.insert("footer", footer) } set page(..page-args) if section != none { polylux.utils.register-section(section) } set typst.align(align) polylux-slide({ context document.use-value( "show-progress", show-progress-doc => if (show-progress == auto and show-progress-doc) or show-progress { polylux.utils.polylux-progress(ratio => { let bar(width, clr) = place( top, dx: -util.inset-at(left, page.margin), dy: -util.inset-at(top, page.margin), rect( fill: clr, width: (100% + util.inset-at(left, page.margin) + util.inset-at(right, page.margin)) * width, height: 6pt, ), ) bar(1.0, theme.bg.primary) bar(ratio, theme.primary) }) }, ) if title != none { heading(depth: 1, title) } if subtitle != none { move(dy: -.33em, text(weight: 600, subtitle)) } rest }) } #let empty-slide = slide.with(header: [], footer: []) #let title-slide(title, subtitle: none) = { empty-slide(title: none, subtitle: none, align: left + horizon, show-progress: false)[ #set text(1.5em) #heading(level: 1, outlined: false, bookmarked: false, title) #if subtitle != none { subtitle } ] } #let praesentation( ..args, body, ) = { let ( doc, page-init, tpl, ) = base-template( type: "PT", type-long: "Präsentation", _tpl: ( options: ( show-progress: t.boolean(default: true), // TODO: Add polylux options and pass to init polylux: t.dictionary( ( theme: t.string(optional: true) ), default: (:) ) ) ), title-block: (doc) => title-slide(doc.title, subtitle: doc.topic), // Some defaults for slides paper: "presentation-16-9", fontsize: 22pt, ..args, body, ) { show: page-init.with( header: (doc, ..) => grid( columns: (1fr, auto), align: (left, right), polylux.utils.current-section, doc.date.display("[day].[month].[year]"), ), footer-right: (doc, body) => { logic.logical-slide.display() " / " polylux.utils.last-slide-number }, ) // TODO: title-block slide ist noch empty .. // title-slide(doc.title, subtitle: doc.topic) show emph: it => text(theme.secondary, weight: 600, it.body) tpl } } #let section-slide(section-name, subtitle: none, level: 1, ..slide-args) = { empty-slide( fill: if level == 1 { theme.bg.primary } else { theme.bg.secondary }, align: center + horizon, ..slide-args, title: none, subtitle: none, section: section-name, heading( depth: 1, { set text( if level == 1 { theme.primary } else { theme.secondary }, 1.5em, ) section-name }, ), ) } #let subsection-slide(body, level: 1, ..slide-args) = { let (title, rest) = util.extract-title(body) empty-slide( fill: theme.bg.muted, align: left + horizon, ..slide-args, { text( 2.5em, if level == 1 { theme.primary } else { theme.secondary }, title, ) linebreak() rest }, ) } #let image-slide(img, align: right, ..slide-args, body) = { slide( ..slide-args, { if align == right { side-by-side(body, img) } else { side-by-side(img, body) } }, ) } #let full-image-slide(img, ..slide-args, overlay: []) = { set page(margin: 0pt) context { let _m = measure(img) let factor = if _m.width > _m.height { page.width / _m.width } else { page.height / _m.height } * 100% + 100% empty-slide( ..slide-args, { set align(center + horizon) scale(img, x: factor, y: factor, origin: center + horizon) }, ) } } #let quote-slide(attribution: none, ..slide-args, body) = { slide( align: center + horizon, ..slide-args, { set text(font: theme.fonts.serif) quote(attribution: attribution, body) }, ) } #let link-slide(target, ..slide-args) = { slide( align: center + horizon, ..slide-args, { set text(2.5em) link(target, target) linebreak() qrcode(target, colors: (white, theme.text.default)) }, ) } #let code-frame(code, light: false) = { let code = code.children.find(it => it.func() == raw) shadow-box( blur: 12, radius: 6pt, dy: 8pt, block( fill: if light { rgb("#f4fafc") } else { rgb("#151718") }, stroke: none, radius: .33em, inset: .5em, { set align(left) block( spacing: 0pt, below: .5em, { for clr in (red, yellow, green) { box( inset: (x: .2em), circle(radius: .33em, fill: clr), ) } }, ) block( spacing: 0pt, inset: 4pt, raw( lang: code.lang, theme: if light { "assets/Eiffel.tmTheme" } else { "assets/Codeacademy.tmTheme" }, code.text, ), ) }, ), ) } #let code-slide(light: false, ..slide-args, body) = { slide( align: center + horizon, ..slide-args, { code-frame(body, light: light) }, ) } #let note = showybox.with( frame: ( body-color: theme.primary, radius: 4pt, inset: .66em, border-color: theme.primary.darken(50%), thickness: .6pt, ), shadow: ( offset: 3pt, color: theme.muted.transparentize(50%), ), body-style: ( color: theme.text.primary, ), ) #let note-secondary = showybox.with( frame: ( body-color: theme.secondary, radius: 4pt, inset: .66em, border-color: theme.secondary.darken(50%), thickness: .6pt, ), shadow: ( offset: 3pt, color: theme.muted.transparentize(50%), ), body-style: ( color: theme.text.secondary, ), )
https://github.com/crd2333/crd2333.github.io
https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Reading/Reconstruction/NeRF.typ
typst
--- order: 3 --- #import "/src/components/TypstTemplate/lib.typ": * #show: project.with( title: "NeRF", lang: "zh", ) #let bo = $bold(o)$ #let bxi = $bold(xi)$ #let bnu = $bold(nu)$ #let bK = $bold(K)$ #let bI = $bold(I)$ #let bT = $bold(T)$ #let bP = $bold(P)$ #let batch_size = math.text("batch_size") #let br = math.bold("r") = NeRF - NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis - 时间:2020.1 - 参考 #link("https://zhuanlan.zhihu.com/p/512538748")[知乎:NeRF 及其发展] == 引言 - 将静态场景表示为:一个连续的 5D 到 4D 的函数,输入为空间中每个点 $(x, y, z)$ 和每个方向 $(th, phi)$,输出是这个方向所发射的辐射,以及该点的 density(作用类似于不透明度,控制穿过光线的累积辐射量)。文章通过 MLP 来表示这个映射,从 $(x,y,z), (x',y',z')$ 回归到 $(R,G,B,si)$ - 说是 5D 是因为 $x, y, z, th, phi$ 的总自由度是 5,但是代码里为了表示方便,把方向编码成 3D 向量 $(x',y',z')$ - 为了渲染从特定角度的神经辐射场,我们: + 前处理:将相机光线穿过场景以生成一组采样的 3D 点 + 模型训练和推理:使用这些点及其对应的 2D 观察方向作为神经网络的输入,以生成一组颜色和密度的输出 + 后处理:使用经典的体渲染技术将这些颜色和密度累积到 2D 图像中 - 实际上模型本身很简单,难点在于前处理和后处理的推导、理解 - 文章发现,对复杂场景的神经辐射场表示,基本的最优化过程无法收敛到足够高分辨率的表示(或者说,高频信息丢失),并且在每个相机光线的采样数量上效率低下。文章分别通过将输入的 5D 坐标做位置编码转换,以及提出一种分层采样方法(两个模型)来解决问题。 - 文章的方法继承了 volumetric representations 的优势:都能表示复杂的现实世界几何形状和外观,并且非常适合使用投影图像进行基于梯度的最优化。但更重要的是,文章的方法在以高分辨率建模复杂场景时克服了高昂的存储成本。总的来说文章主要贡献有: + 把一种复杂的场景表示为 5D 神经辐射场的方法,并参数化为 MLP 网络 + 基于经典体渲染技术的可微渲染过程,从标准 RGB 图像中优化这些表示。包括分层采样策略 + 一种位置编码方法,使神经辐射场能够表示高频场景内容 - 文章证明了 NeRF 成了 SOTA,并且本文是首个能够在 natrual settings 下从 RGB 图像渲染高分辨率且逼真的全新视图的神经场景表示 == Related Work === Neural 3D shape representations - 近年的工作通过优化将 $(x, y, z)$ 坐标映射到 SDF 或 occupancy fields 的深度网络,研究了连续 3D 形状的隐式表示。然而,这些模型需要有 3D 几何形状的 ground truth 作为真值 - 后来的一些工作制定了只需要使用 2D 图像就可以优化神经隐式形状表示的可微渲染函数。 + Niemeyer 等人将物体表面表示为 3D occupancy fields,并使用数值方法找到每条射线的表面交点,然后使用隐式微分计算精确导数。每个光线交点位置都作为神经 3D texture field 的输入,这个 field 预测该点的漫反射颜色 + Sitzmann 等人使用一种更加不直接的神经 3D 表示,在每个连续的 3D 坐标处简单地输出一个特征向量和 RGB 颜色,并提出一个由循环神经网络组成的可微渲染函数,该网络沿着每条射线行进以确定表面的位置 - 虽然这些方法有表示复杂和高分辨率形状的潜力,但是目前仍然只能表达简单的几何形状。 === View synthesis and image-based rendering - 给定密集的采样视角,新视角可以通过 light field sample interpolation 技术得到。但如果是对于更稀疏的采样,就需要从观察到的图像中预测传统的几何和外观表 - 一种流行的方法使用基于 mesh 的场景表示,具有漫反射或与视图相关的外观。 - Differentiable rasterizers 或 path tracers 可以使用梯度下降直接优化网格表示以重现一组输入图像 - 然而,基于图像重投影的基于梯度的 mesh 优化通常很困难,可能是因为局部最小值或缺失的景观部分条件太差了。此外,该策略需要在优化之前提供模板网格作为初始化,这通常不适用于无约束的现实世界场景 - 另一类方法使用 volumetric representations,能表示复杂的形状和材料,非常适合基于梯度的优化,并且比基于 mesh 的方法产生的视觉干扰更少 - 早期的体素方法使用观测到的图像来直接给体素网格上色 - 近期,一些方法使用多个场景的大型数据集来训练深度网络,从一组输入图像中预测采样的体素表示,然后使用 alpha-compositing 或沿光线学习的合成 来在测试时渲染新的视图。其他工作针对每个特定场景优化 CNN 和采样体素网格的组合,使得 CNN 可以补偿来自低分辨率体积网格的离散化 artifacts,或者允许预测的体素网格根据输入时间而变化。虽然这些体积技术在新视图合成方面取得不错的结果,但它们扩展到更高分辨率图像的能力受到了限制,因为离散采样导致时间和空间复杂度高,而渲染更高分辨率的图像需要对 3D 空间进行更精细的采样 - 本文提出的方法通过在 MLP 的参数中编码连续 volume 来规避这个问题,这不仅产生比先前体积方法更高质量的渲染,而且只需要更小的存储成本 - 注:某种程度上,NeRF 建模了视觉成像机理,更接近视觉世界本质 #fig("/public/assets/Reading/Reconstruction/NeRF/2024-10-13-17-11-43.png", width: 70%) == Method - 这里原文分了好多章 Neural Radiance Field Scene Representation, Volume Rendering with Radiance Fields, Optimizing a Neural Radiance Field(Positional encoding & Hierarchical volume sampling),这里将其整合到一起进行理解 - 整个任务的输入和输出 - 输入:给定静止场景下的若干张图片 - 输出:生成新的视角下的图片 - 模型本质是使用神经网络(MLP)来隐式地存储 3D 信息 - 不具有泛化能力,一个模型只能存储一个 3D 信息 - 模型的输入和输出 - 模型输入是粒子的空间位置以及从哪个角度去看它(相机位姿),表示为 5D 向量,$(x, y, z, theta, phi)$,代码里是 6D 向量,$(x, y, z, x', y', z')$ - 模型输出是从这个角度去看它得到的颜色和密度,表示为 4D 向量,$(R, G, B, sigma)$ - 模型是 8 层的 MLP,但有两个 - 整个任务的输入输出和模型的输入输出并不一致,NeRF 的理解难点不在模型本身而在于前后处理,整个流程的 Pipeline 如下: - 前处理: - 将图片中的每个像素,通过相机模型找到对应的射线,共 $#batch_size$ 条射线 - 在每条射线上进行采样,得到 $64$(N_samples) 个粒子 - 对 $#batch_size * 64$ 个粒子进行位置编码 - 位置坐标为 63D 和方向向量为 27D - 模型 1: - $8$ 层 MLP - 输入为 $(#batch_size, 64, 63)$ 和 $(#batch_size, 64, 27)$ - 输出为 $(#batch_size, 64, 4)$ - 后处理1: - 将模型 1 输出通过体渲染,转换为像素 - 对射线进行二次采样,每条射线上总共采样 $192$ 个粒子 - 模型2: - $8$ 层 MLP - 输入为 $(#batch_size, 192, 63)$ 和 $(#batch_size, 192, 27)$ - 输出为 $(#batch_size, 192, 4)$ - 后处理2: - 将模型 2 输出通过体渲染,转换为像素 #fig("/public/assets/Reading/Reconstruction/NeRF/2024-10-12-21-27-35.png") - 下面一个个描述其中的关键步骤 - 输入图片如何得到这些粒子? - 训练时,一张图片(或者多个图片)采样 $#batch_size = 1024$ 个像素 - 从图片和图片对应的相机位姿计算射线,$1024$ 个像素对应 $1024$ 条射线 - $bold(r)(t) = bo + t bd$,从相机位姿得知 $bo$ 和 $bd$ - 从射线上采样粒子 - $t=2 wave 6$ 之间均匀采样(或者如果已知射线上的 CDF,就重要性采样),得到 $"N_samples" = 64$ 个粒子 - 共 $1024*64$ 个粒子,以 batch 形式输入模型 - 每个粒子有自己的空间位置 $bx = (x, y, z)$ 和方向 $bd = (x', y', z')$ - 6D 向量如何进行位置编码? $ ga(p) = (sin(2^0 pi p ), cos(2^0 pi p), dots, sin(2^(L-1) pi p), cos(2^(L-1) pi p), p) $ - 位置编码虽然不可学习,但显著提高了模型表示高频信息的能力 - 模型函数 $F_th$ 现在变为 $F_th compose ga$ - $L = 10 $ for $ga(bx)$, $3 * (2 * 10) + 3 = 63"D"$;and $L = 4$ for $ga(bd)$, $3 * (2 * 4) + 3 = 27"D"$ - 其实 $L$ 的两个数值是超参,体现了作者认为位置比方向更重要 - 模型具体架构? - 图里是 $60, 24$,但代码里是 $63, 27$ - 63D 向量分两次进行输入,倒数第二层输出密度 $si$,同时输入 27D 向量,最后一层输出颜色 $R G B$ - 这里方向输入得很晚,也体现了作者认为位置比方向更重要;另外密度都输出了方向才输入进来,这也是“方向与密度无关,只与颜色有关”的先验 - 模型训练的 ground truth 是图片像素的颜色,因此需要将模型输出通过体渲染公式转换为像素颜色才能算 loss #fig("/public/assets/Reading/Reconstruction/NeRF/2024-10-12-21-56-56.png", width: 70%) - 体渲染如何进行(同时也是模型输出如何得到图片的回答)? - 一个观察(先验):一个点的密度越高,射线通过它之后变得越弱,*密度和透光度呈反比*;同时这个点的颜色反应在像素上的*权重越大*。这就是下面 $T(t)$ 在描述的事情 —— 采样点权重由其*密度*和*与光心距离*共同决定 - 连续体渲染公式(确切地说应该是体渲染中的 Ray-Tracing 方法) - 其中 $c $ 表示颜色, $si$ 表示密度, $r$ 表示 camera ray,$t$ 和 $d$ 分别表示 camera ray 上的距离、方向 $ C(br) = int_(tn)^(tj) T(t) si(br(t)) c(br(t), bd) dif t, "where" T(t) = exp(- int_(t_n)^t si(br(s)) dif s) $ - 实际计算需要将其离散化(掌握其推导:将射线划分为小区间,$delta_i=t_i - t_(i-1)$ 为区间长度,区间内 $si, c$ 为常数) $ hat(C)(br) = sum_(i=1)^N T_i (1 - exp(-si_i delta_i)) c_i, "where" T_i = exp(- sum_(j=1)^(i-1) si_j delta_j) $ - 如果是在推理,通过这个公式从 $c_i, si_i$ 得到像素颜色,从而得到图片 - 如果是在训练,得到像素颜色后与 ground truth 计算 loss,并且该式对于 $c_i, si_i$ 是可导的,可以梯度反传 - 什么是 hierarchical volume sampling? - 根据粗模型 1 输出的密度,进行重要性采样,用更有效的输入训练细模型 2 - 把上面的离散体渲染公式重写一下 $ hat(C)(br) = sum_(i=1)^(N_c) w_i c_i, "where" w_i = T_i (1 - exp(-si_i delta_i)) $ - 将这些权重归一化为 $hat(w)_i = w_i / sum_(j=1)^N w_j$,沿射线生成分段常数概率密度函数(PDF),进而得到 CDF(Cumulative Distribution Function) - 使用逆变换得到 $"CDF"^(-1)$,该分布即为我们想要的重要性分布,采样 $128$ 个粒子,总共 $192$ 个,送入模型 2 == 实验和结论 - NeRF 不具有泛化能力,每个场景训练一次就用一次,在 DeepVoxels 数据集上做了 Synthetic renderings of objects 实验,并且做了 Real images of complex scenes 实验,效果都很好 - 与以往方法的比较 + Neural Volumes (NV) + Scene Representation Networks (SRN) + Local Light Field Fusion (LLFF) - 消融实验,主要考虑以下几个因素 + Positional Encoding + View Dependence(指模型只输入粒子位置而不考虑方向) + Hierarchical + Image number + Frequencies - 作者结论: - 我们证明,将场景表示为 5D 神经辐射场比之前的方法能产生更好的渲染效果,朝着基于真实世界图像的 graphics pipeline 迈出了进步 - 尽管我们提出了一种分层采样策略,以提高渲染的样本效率,但仍有更多进展需要探索 - 未来工作的另一个方向是可解释性:像体素网格这样的采样表示允许对渲染视图的预期质量和失败模式进行推理,但当我们使用深度神经网络的权重编码场景时,如何分析这些问题尚不清楚 - NeRF 的效果非常酷炫,同时也提供了一种 3D 场景建模的新形式(虽然后来被 3DGS 超了),它的主要问题包括 + 速度慢 + 只针对静态场景 + 没有泛化性 + 需要大量视角 == 论文十问 + 论文试图解决什么问题? - 通过稀疏视图集进行 3D 场景的表示,以及新视图的合成 + 这是否是一个新的问题? - 不是,之前已有基于 explicit representation(e.g. volume, mesh)的方法,另外也有基于 implicit representation(e.g. SDF, occupancy field)的方法。但效果算不上好 + 这篇文章要验证一个什么科学假设? + 使用神经网络拟合隐式表达,能在节省储存成本的同时获得高质量的新视图 + 5D 神经辐射场的隐式表达相比显式表达对噪声有更强的包容性和拟合性,能生成细节的几何表达 + MLP 倾向于学习到一些低频的信号,傅里叶特征能使得模型学习到高频特征 + 有哪些相关研究?如何归类?谁是这一课题在领域内值得关注的研究员? - 3D 场景表示的研究,可以分为 explicit 和 implicit 两类,NeRF 属于 implicit 类 + 论文中提到的解决方案之关键是什么? + 使用 5D 神经辐射场的方法来实现复杂场景的隐式表示 + 使用体渲染代替表面渲染完成场景任意光线颜色的渲染 + 使用位置编码让模型学到高频信息,使用 hierarchical volume sampling 提高采样效率 + 论文中的实验是如何设计的? - 在已有数据集和自己合成数据集上实验,对比了以往方法,做了消融实验 + 用于定量评估的数据集是什么?代码有没有开源? - DeepVoxels 数据集,代码开源 #link("https://github.com/yenchenlin/nerf-pytorch")[github.com/yenchenlin/nerf-pytorch] + 论文中的实验及结果有没有很好地支持需要验证的科学假设? - 应该是能支持的 + 这篇论文到底有什么贡献? + 提出了新的神经辐射场的隐式表示 $f_th (x,y,z,th,phi) arrow.r.bar (R,G,B,si) $,并用具体的模型成功拟合 + RGB 的表示自然比 SDF 或 occupancy field 能渲染出更真实的场景 + 密度 $si$ 结合体渲染,使模型表征不仅局限于刚体表面 + 通过位置编码和 hierarchical volume sampling 提高了模型的性能 + 下一步呢?有什么工作可以继续深入? - 速度优化,泛化性,动态场景,可解释性,视角需求数等
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/sweet-graduate-resume/0.1.0/README.md
markdown
Apache License 2.0
# Resume template A basic resume template in typst. To compile/watch, make sure you pass the argument `--font-path ./fonts/` to typst-cli. If you use the helix editor, a configuration has been given in the repository. This auto-compiles your document on saving and you can preview the results in real time using a pdf viewer. Also provides autocomplete, code renaming, and other cool (LSP) features. Make sure you have tinymist and typstyle installed before using the helix config. ## Preview ![basic template](./screenshot.png) ## LICENSE The FontAwesome Free/Brand fonts are licensed under [Font Awesome Free License](https://github.com/FortAwesome/Font-Awesome?tab=License-1-ov-file) The Codeberg SVG in the svg directory are licensed under [Creative Commons CC0](https://codeberg.org/Codeberg/Design/src/commit/ac514aa9aaa2457d4af3c3e13df3ab136d22a49a/LICENSE) For the rest, see [LICENSE](./LICENSE). ## Fonts For fonts, please install the fonts from the repository of the project in codeberg.