repo
stringlengths
26
115
file
stringlengths
54
212
language
stringclasses
2 values
license
stringclasses
16 values
content
stringlengths
19
1.07M
https://github.com/RanolP/resume
https://raw.githubusercontent.com/RanolP/resume/main/modules/util.typ
typst
#let belonging(role, organization) = [#role #text(weight: 400)[\@] #organization] #let enumerate(entries) = grid( columns: entries.len(), rows: (auto, auto), column-gutter: 10pt, row-gutter: 3pt, ..( for (first, _) in entries { (align(center)[#first],) } ), ..( for (_, second) in entries { (align(center)[#second],) } ), ) #let format-thousand(n) = { let len = str(n).len() for (i, c) in str(n).codepoints().enumerate() { if i != 0 and calc.rem((len - i), 3) == 0 { "," } c } }
https://github.com/jomaway/typst-teacher-templates
https://raw.githubusercontent.com/jomaway/typst-teacher-templates/main/ttt-exam/lib/lib.typ
typst
MIT License
#import "template.typ": * #import "points.typ": *
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/touying-aqua/0.5.0/template/main.typ
typst
Apache License 2.0
#import "@preview/touying:0.5.0": * #import themes.aqua: * #show: aqua-theme.with( aspect-ratio: "16-9", config-info( title: [Start Your Writing in Touying], subtitle: [Subtitle], author: [Author], date: datetime.today(), institution: [Institution], ), ) #title-slide() #outline-slide() = The Section == Slide Title Slide content.
https://github.com/DieracDelta/presentations
https://raw.githubusercontent.com/DieracDelta/presentations/master/polylux/polylux.typ
typst
#import "themes/themes.typ" #import "logic.typ" #import "logic.typ": polylux-slide, uncover, only, alternatives, alternatives-match, alternatives-fn, alternatives-cases, one-by-one, line-by-line, list-one-by-one, enum-one-by-one, terms-one-by-one, pause, enable-handout-mode #import "utils/utils.typ" #import "utils/utils.typ": polylux-outline, fit-to-height, side-by-side, pdfpc
https://github.com/kdog3682/typkit
https://raw.githubusercontent.com/kdog3682/typkit/main/0.1.0/src/math.typ
typst
#let slope((x1, y1), (x2, y2)) = { return (x2 - x1) / (y2 - y1) } #let magnitude(s) = { if s > 0 { 1 } else if s == 0 { 0 } else { -1 } }
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/team-organization.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Team Organization", type: "management", date: datetime(year: 2023, month: 5, day: 12), author: "<NAME>", witness: "<NAME>", ) = Design Process As stated in the pre reveal reflection we identified that our largest problem during the last season was our lack of structure and organization. In order to address this issue we decided to have a set of steps for builders to follow while creating a system: - Brainstorm possible designs - Choose best design - Create design in CAD - Have design reviewed by fellow teammates and/or alumni - If the design passed review, build it - Test the system - Iterate again The crucial steps here are the design in CAD and review. CAD by itself cannot verify that the design will work in the real world, but the more eyes we can put on the design before building, the more mistakes we can catch. Overall these two steps will make our designs much more error free, and save us time in the long run. = Schedule We created a schedule to get us a rough timeline of deadlines to help us meet our targets before the first competition of the season. We opted to use a Gantt chart for this because it represents the different overlapping tasks visually. This should help us meet our goal of staying more organized. Our team typically meets twice a week, for 3 hours at a time, so we've organized the chart on a weekly basis. #image("/assets/mermaid/gantt.svg") We decided to dedicate the most time to building the subsystems, as these are easily the hardest part of the robot to build. We've also planned a 4 week cutoff before the first competition to give us time to test the robot thoroughly. Once the first competition happens we will update this schedule further.
https://github.com/KrisjanisP/lu-icpc-notebook
https://raw.githubusercontent.com/KrisjanisP/lu-icpc-notebook/main/6-strings.typ
typst
#block(breakable: false,[ = String Processing == Knuth-Morris-Pratt (KMP) ```cpp char s[N], p[N]; int b[N], n, m; // n = strlen(s), m = strlen(p); void kmppre() { b[0] = -1; for (int i = 0, j = -1; i < m; b[++i] = ++j) while (j >= 0 and p[i] != p[j]) j = b[j]; } void kmp() { for (int i = 0, j = 0; i < n;) { while (j >= 0 and s[i] != p[j]) j=b[j]; i++, j++; if (j == m) {j = b[j];} } } ``` ]) #block( breakable: false,[ == Suffix Array ```cpp vector<int> suffix_array(string &s){ int n = s.size(), alph = 256; vector<int> cnt(max(n, alph)), p(n), c(n); rep(i,0,n) cnt[s[i]]++; rep(i,1,alph) cnt[i]+=cnt[i-1]; rep(i,0,n) p[--cnt[s[i]]] = i; c[p[0]]=0; rep(i,1,n) c[p[i]] = (s[p[i]] != s[p[i-1]]) ? c[p[i-1]] + 1 : c[p[i-1]]; vector<int> p2(n), c2(n); for(int k=0; (1<<k)<n; k++){ rep(i,0,n) p2[i]=(p[i]-(1<<k)+n)%n; fill(cnt.begin(), cnt.begin()+c[p[n-1]]+1, 0); rep(i,0,n) cnt[c[p2[i]]]++; rep(i,1,c[p[n-1]]+1) cnt[i]+=cnt[i-1]; for(int i=n-1;i>=0;i--) p[--cnt[c[p2[i]]]] = p2[i]; c2[p[0]]=0; rep(i,1,n) { pair<int,int> a1 = {c[p[i]], c[(p[i]+(1<<k))%n]}; pair<int,int> a2 = {c[p[i-1]], c[(p[i-1]+(1<<k))%n]}; c2[p[i]] = (a1 != a2) ? c2[p[i-1]] + 1 : c2[p[i-1]]; } c.swap(c2); } return p; } ``` ]) #block( breakable: false,[ == Longest common prefix (LCP) with SA ```cpp vector<int> lcp(string &s, vector<int> &p){ int n = s.size(); vector<int> pi(n), ans(n-1); rep(i,0,n) pi[p[i]] = i; int lst = 0; rep(i,0,n-1){ if(pi[i] == n-1){ lst = 0; continue; } int j = p[pi[i]+1]; while(i+lst<n && j+lst<n && s[i+lst] == s[j+lst]) lst++; ans[pi[i]] = lst; lst = max(lst-1, 0); } return ans; } ``` ]) #block( breakable: false,[ == Rabin-Karp pattern match with hashing ```cpp const int B = 31; const int MOD = 1e9+7, B = 31; void rabin(string s, string p){ int n = s.size(), m = p.size(); if(n<m) return; vector<ull> power(max(n, m), 1); rep(i,1,power.size()) power[i] = (power[i-1]*B)%MOD; ull hp=0, hs=0; rep(i,0,m){ hp=(hp*B + p[i])%MOD; hs=(hs*B + s[i])%MOD; } if(hs == hp) { /* match at 0 */ } rep(i,m,n){ hs = (hs*B + s[i])%MOD; hs = (hs + MOD - (s[i-m]*power[m])%MOD)%MOD; if(hs == hp) { /* match at i-m+1 */ } } } ``` ]) #block( breakable: false,[ == Z-function The Z-function of a string $s$ is an array $z$ where $z_i$ is the length of the longest substring starting from $s_i$ which is also a prefix of $s$. Examples: - "aaaaa": $[0, 4, 3, 2, 1]$ - "aaabaab": $[0,2,1,0,2,1,0]$ - "abacaba": $[0,0,1,0,3,0,1]$ ```cpp vector<int> zfunction(const string& s){ vector<int> z (s.size()); for (int i = 1, l = 0, r = 0, n = s.size(); i < n; i++){ if (i <= r) z[i] = min(z[i-l], r - i + 1); while (i + z[i] < n and s[z[i]] == s[z[i] + i]) z[i]++; if (i + z[i] - 1 > r) l = i, r = i + z[i] - 1; } return z; } ``` ]) #block( breakable: false,[ == Manacher's longest palindromic substring ```cpp int manacher(string s){ int n = s.size(); string p = "^#"; rep(i,0,n) p += string(1, s[i]) + "#"; p += "$"; n = p.size(); vector<int> lps(n, 0); int C=0, R=0, m=0; rep(i,1,n-1){ int mirr = 2*C - i; if(i < R) lps[i] = min(R-i, lps[mirr]); while(p[i + 1 + lps[i]] == p[i - 1 - lps[i]]) lps[i]++; if(i + lps[i] > R){ C = i; R = i + lps[i]; } m = max(m, lps[i]); } return m; } ``` ])
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/post_type_check/text_stroke.typ
typst
Apache License 2.0
#let tmpl2(stroke: ()) = text(stroke: stroke) #tmpl2(stroke: (/* position after */))
https://github.com/RubixDev/typst-i-figured
https://raw.githubusercontent.com/RubixDev/typst-i-figured/main/i-figured.typ
typst
MIT License
#let _prefix = "i-figured-" #let reset-counters(it, level: 1, extra-kinds: (), equations: true, return-orig-heading: true) = { if it.level <= level { for kind in (image, table, raw) + extra-kinds { counter(figure.where(kind: _prefix + repr(kind))).update(0) } if equations { counter(math.equation).update(0) } } if return-orig-heading { it } } #let _typst-numbering = numbering #let _prepare-dict(it, level, zero-fill, leading-zero, numbering) = { let numbers = counter(heading).at(it.location()) // if zero-fill is true add trailing zeros until the level is reached while zero-fill and numbers.len() < level { numbers.push(0) } // only take the first `level` numbers if numbers.len() > level { numbers = numbers.slice(0, level) } // strip a leading zero if requested if not leading-zero and numbers.at(0, default: none) == 0 { numbers = numbers.slice(1) } let dic = it.fields() let _ = if "body" in dic { dic.remove("body") } let _ = if "label" in dic { dic.remove("label") } let _ = if "counter" in dic { dic.remove("counter") } dic + (numbering: n => _typst-numbering(numbering, ..numbers, n)) } #let show-figure( it, level: 1, zero-fill: true, leading-zero: true, numbering: "1.1", extra-prefixes: (:), fallback-prefix: "fig:", ) = { if type(it.kind) == str and it.kind.starts-with(_prefix) { it } else { let figure = figure( it.body, .._prepare-dict(it, level, zero-fill, leading-zero, numbering), kind: _prefix + repr(it.kind), ) if it.has("label") { let prefixes = (table: "tbl:", raw: "lst:") + extra-prefixes let new-label = label(prefixes.at( if type(it.kind) == str { it.kind } else { repr(it.kind) }, default: fallback-prefix, ) + str(it.label)) [#figure #new-label] } else { figure } } } #let show-equation( it, level: 1, zero-fill: true, leading-zero: true, numbering: "(1.1)", prefix: "eqt:", only-labeled: false, unnumbered-label: "-", ) = { if ( only-labeled and not it.has("label") or it.has("label") and ( str(it.label).starts-with(prefix) or str(it.label) == unnumbered-label ) or not it.block ) { it } else { let equation = math.equation( it.body, .._prepare-dict(it, level, zero-fill, leading-zero, numbering), ) if it.has("label") { let new-label = label(prefix + str(it.label)) [#equation #new-label] } else { let new-label = label(prefix + _prefix + "no-label") [#equation #new-label] } } } #let _typst-outline = outline #let outline(target-kind: image, title: [List of Figures], ..args) = { _typst-outline(..args, title: title, target: figure.where(kind: _prefix + repr(target-kind))) }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/editors/vscode/e2e-workspaces/print-state/effect.typ
typst
Apache License 2.0
#let print-state = state("print-effect", ()) #let print(k, end: none) = print-state.update(it => it + (k, end)) #let println = print.with(end: "\n") #let main = content => { context [ #let prints = print-state.final() #metadata(prints.join()) <print-effect> ] content }
https://github.com/frectonz/the-pg-book
https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/152.%20convince.html.typ
typst
convince.html How to Convince Investors Want to start a startup? Get funded by Y Combinator. August 2013When people hurt themselves lifting heavy things, it's usually because they try to lift with their back. The right way to lift heavy things is to let your legs do the work. Inexperienced founders make the same mistake when trying to convince investors. They try to convince with their pitch. Most would be better off if they let their startup do the work — if they started by understanding why their startup is worth investing in, then simply explained this well to investors.Investors are looking for startups that will be very successful. But that test is not as simple as it sounds. In startups, as in a lot of other domains, the distribution of outcomes follows a power law, but in startups the curve is startlingly steep. The big successes are so big they dwarf the rest. And since there are only a handful each year (the conventional wisdom is 15), investors treat "big success" as if it were binary. Most are interested in you if you seem like you have a chance, however small, of being one of the 15 big successes, and otherwise not. [1](There are a handful of angels who'd be interested in a company with a high probability of being moderately successful. But angel investors like big successes too.)How do you seem like you'll be one of the big successes? You need three things: formidable founders, a promising market, and (usually) some evidence of success so far.FormidableThe most important ingredient is formidable founders. Most investors decide in the first few minutes whether you seem like a winner or a loser, and once their opinion is set it's hard to change. [2] Every startup has reasons both to invest and not to invest. If investors think you're a winner they focus on the former, and if not they focus on the latter. For example, it might be a rich market, but with a slow sales cycle. If investors are impressed with you as founders, they say they want to invest because it's a rich market, and if not, they say they can't invest because of the slow sales cycle.They're not necessarily trying to mislead you. Most investors are genuinely unclear in their own minds why they like or dislike startups. If you seem like a winner, they'll like your idea more. But don't be too smug about this weakness of theirs, because you have it too; almost everyone does.There is a role for ideas of course. They're fuel for the fire that starts with liking the founders. Once investors like you, you'll see them reaching for ideas: they'll be saying "yes, and you could also do x." (Whereas when they don't like you, they'll be saying "but what about y?")But the foundation of convincing investors is to seem formidable, and since this isn't a word most people use in conversation much, I should explain what it means. A formidable person is one who seems like they'll get what they want, regardless of whatever obstacles are in the way. Formidable is close to confident, except that someone could be confident and mistaken. Formidable is roughly justifiably confident.There are a handful of people who are really good at seeming formidable — some because they actually are very formidable and just let it show, and others because they are more or less con artists. [3] But most founders, including many who will go on to start very successful companies, are not that good at seeming formidable the first time they try fundraising. What should they do? [4]What they should not do is try to imitate the swagger of more experienced founders. Investors are not always that good at judging technology, but they're good at judging confidence. If you try to act like something you're not, you'll just end up in an uncanny valley. You'll depart from sincere, but never arrive at convincing.TruthThe way to seem most formidable as an inexperienced founder is to stick to the truth. How formidable you seem isn't a constant. It varies depending on what you're saying. Most people can seem confident when they're saying "one plus one is two," because they know it's true. The most diffident person would be puzzled and even slightly contemptuous if they told a VC "one plus one is two" and the VC reacted with skepticism. The magic ability of people who are good at seeming formidable is that they can do this with the sentence "we're going to make a billion dollars a year." But you can do the same, if not with that sentence with some fairly impressive ones, so long as you convince yourself first.That's the secret. Convince yourself that your startup is worth investing in, and then when you explain this to investors they'll believe you. And by convince yourself, I don't mean play mind games with yourself to boost your confidence. I mean truly evaluate whether your startup is worth investing in. If it isn't, don't try to raise money. [5] But if it is, you'll be telling the truth when you tell investors it's worth investing in, and they'll sense that. You don't have to be a smooth presenter if you understand something well and tell the truth about it.To evaluate whether your startup is worth investing in, you have to be a domain expert. If you're not a domain expert, you can be as convinced as you like about your idea, and it will seem to investors no more than an instance of the Dunning-Kruger effect. Which in fact it will usually be. And investors can tell fairly quickly whether you're a domain expert by how well you answer their questions. Know everything about your market. [6]Why do founders persist in trying to convince investors of things they're not convinced of themselves? Partly because we've all been trained to.When my friends <NAME> and <NAME> were in grad school, one of their fellow students was on the receiving end of a question from their faculty advisor that we still quote today. When the unfortunate fellow got to his last slide, the professor burst out: Which one of these conclusions do you actually believe? One of the artifacts of the way schools are organized is that we all get trained to talk even when we have nothing to say. If you have a ten page paper due, then ten pages you must write, even if you only have one page of ideas. Even if you have no ideas. You have to produce something. And all too many startups go into fundraising in the same spirit. When they think it's time to raise money, they try gamely to make the best case they can for their startup. Most never think of pausing beforehand to ask whether what they're saying is actually convincing, because they've all been trained to treat the need to present as a given — as an area of fixed size, over which however much truth they have must needs be spread, however thinly.The time to raise money is not when you need it, or when you reach some artificial deadline like a Demo Day. It's when you can convince investors, and not before. [7]And unless you're a good con artist, you'll never convince investors if you're not convinced yourself. They're far better at detecting bullshit than you are at producing it, even if you're producing it unknowingly. If you try to convince investors before you've convinced yourself, you'll be wasting both your time.But pausing first to convince yourself will do more than save you from wasting your time. It will force you to organize your thoughts. To convince yourself that your startup is worth investing in, you'll have to figure out why it's worth investing in. And if you can do that you'll end up with more than added confidence. You'll also have a provisional roadmap of how to succeed.MarketNotice I've been careful to talk about whether a startup is worth investing in, rather than whether it's going to succeed. No one knows whether a startup is going to succeed. And it's a good thing for investors that this is so, because if you could know in advance whether a startup would succeed, the stock price would already be the future price, and there would be no room for investors to make money. Startup investors know that every investment is a bet, and against pretty long odds.So to prove you're worth investing in, you don't have to prove you're going to succeed, just that you're a sufficiently good bet. What makes a startup a sufficiently good bet? In addition to formidable founders, you need a plausible path to owning a big piece of a big market. Founders think of startups as ideas, but investors think of them as markets. If there are x number of customers who'd pay an average of $y per year for what you're making, then the total addressable market, or TAM, of your company is $xy. Investors don't expect you to collect all that money, but it's an upper bound on how big you can get.Your target market has to be big, and it also has to be capturable by you. But the market doesn't have to be big yet, nor do you necessarily have to be in it yet. Indeed, it's often better to start in a small market that will either turn into a big one or from which you can move into a big one. There just has to be some plausible sequence of hops that leads to dominating a big market a few years down the line.The standard of plausibility varies dramatically depending on the age of the startup. A three month old company at Demo Day only needs to be a promising experiment that's worth funding to see how it turns out. Whereas a two year old company raising a series A round needs to be able to show the experiment worked. [8]But every company that gets really big is "lucky" in the sense that their growth is due mostly to some external wave they're riding, so to make a convincing case for becoming huge, you have to identify some specific trend you'll benefit from. Usually you can find this by asking "why now?" If this is such a great idea, why hasn't someone else already done it? Ideally the answer is that it only recently became a good idea, because something changed, and no one else has noticed yet.Microsoft for example was not going to grow huge selling Basic interpreters. But by starting there they were perfectly poised to expand up the stack of microcomputer software as microcomputers grew powerful enough to support one. And microcomputers turned out to be a really huge wave, bigger than even the most optimistic observers would have predicted in 1975.But while Microsoft did really well and there is thus a temptation to think they would have seemed a great bet a few months in, they probably didn't. Good, but not great. No company, however successful, ever looks more than a pretty good bet a few months in. Microcomputers turned out to be a big deal, and Microsoft both executed well and got lucky. But it was by no means obvious that this was how things would play out. Plenty of companies seem as good a bet a few months in. I don't know about startups in general, but at least half the startups we fund could make as good a case as Microsoft could have for being on a path to dominating a large market. And who can reasonably expect more of a startup than that?RejectionIf you can make as good a case as Microsoft could have, will you convince investors? Not always. A lot of VCs would have rejected Microsoft. [9] Certainly some rejected Google. And getting rejected will put you in a slightly awkward position, because as you'll see when you start fundraising, the most common question you'll get from investors will be "who else is investing?" What do you say if you've been fundraising for a while and no one has committed yet? [10]The people who are really good at acting formidable often solve this problem by giving investors the impression that while no investors have committed yet, several are about to. This is arguably a permissible tactic. It's slightly dickish of investors to care more about who else is investing than any other aspect of your startup, and misleading them about how far along you are with other investors seems the complementary countermove. It's arguably an instance of scamming a scammer. But I don't recommend this approach to most founders, because most founders wouldn't be able to carry it off. This is the single most common lie told to investors, and you have to be really good at lying to tell members of some profession the most common lie they're told.If you're not a master of negotiation (and perhaps even if you are) the best solution is to tackle the problem head-on, and to explain why investors have turned you down and why they're mistaken. If you know you're on the right track, then you also know why investors were wrong to reject you. Experienced investors are well aware that the best ideas are also the scariest. They all know about the VCs who rejected Google. If instead of seeming evasive and ashamed about having been turned down (and thereby implicitly agreeing with the verdict) you talk candidly about what scared investors about you, you'll seem more confident, which they like, and you'll probably also do a better job of presenting that aspect of your startup. At the very least, that worry will now be out in the open instead of being a gotcha left to be discovered by the investors you're currently talking to, who will be proud of and thus attached to their discovery. [11]This strategy will work best with the best investors, who are both hard to bluff and who already believe most other investors are conventional-minded drones doomed always to miss the big outliers. Raising money is not like applying to college, where you can assume that if you can get into MIT, you can also get into Foobar State. Because the best investors are much smarter than the rest, and the best startup ideas look initially like bad ideas, it's not uncommon for a startup to be rejected by all the VCs except the best ones. That's what happened to Dropbox. Y Combinator started in Boston, and for the first 3 years we ran alternating batches in Boston and Silicon Valley. Because Boston investors were so few and so timid, we used to ship Boston batches out for a second Demo Day in Silicon Valley. Dropbox was part of a Boston batch, which means all those Boston investors got the first look at Dropbox, and none of them closed the deal. Yet another backup and syncing thing, they all thought. A couple weeks later, Dropbox raised a series A round from Sequoia. [12]DifferentNot understanding that investors view investments as bets combines with the ten page paper mentality to prevent founders from even considering the possibility of being certain of what they're saying. They think they're trying to convince investors of something very uncertain — that their startup will be huge — and convincing anyone of something like that must obviously entail some wild feat of salesmanship. But in fact when you raise money you're trying to convince investors of something so much less speculative — whether the company has all the elements of a good bet — that you can approach the problem in a qualitatively different way. You can convince yourself, then convince them.And when you convince them, use the same matter-of-fact language you used to convince yourself. You wouldn't use vague, grandiose marketing-speak among yourselves. Don't use it with investors either. It not only doesn't work on them, but seems a mark of incompetence. Just be concise. Many investors explicitly use that as a test, reasoning (correctly) that if you can't explain your plans concisely, you don't really understand them. But even investors who don't have a rule about this will be bored and frustrated by unclear explanations. [13]So here's the recipe for impressing investors when you're not already good at seeming formidable: Make something worth investing in. Understand why it's worth investing in. Explain that clearly to investors. If you're saying something you know is true, you'll seem confident when you're saying it. Conversely, never let pitching draw you into bullshitting. As long as you stay on the territory of truth, you're strong. Make the truth good, then just tell it.Notes[1] There's no reason to believe this number is a constant. In fact it's our explicit goal at Y Combinator to increase it, by encouraging people to start startups who otherwise wouldn't have.[2] Or more precisely, investors decide whether you're a loser or possibly a winner. If you seem like a winner, they may then, depending on how much you're raising, have several more meetings with you to test whether that initial impression holds up.But if you seem like a loser they're done, at least for the next year or so. And when they decide you're a loser they usually decide in way less than the 50 minutes they may have allotted for the first meeting. Which explains the astonished stories one always hears about VC inattentiveness. How could these people make investment decisions well when they're checking their messages during startups' presentations? The solution to that mystery is that they've already made the decision.[3] The two are not mutually exclusive. There are people who are both genuinely formidable, and also really good at acting that way.[4] How can people who will go on to create giant companies not seem formidable early on? I think the main reason is that their experience so far has trained them to keep their wings folded, as it were. Family, school, and jobs encourage cooperation, not conquest. And it's just as well they do, because even being Genghis Khan is probably 99% cooperation. But the result is that most people emerge from the tube of their upbringing in their early twenties compressed into the shape of the tube. Some find they have wings and start to spread them. But this takes a few years. In the beginning even they don't know yet what they're capable of.[5] In fact, change what you're doing. You're investing your own time in your startup. If you're not convinced that what you're working on is a sufficiently good bet, why are you even working on that?[6] When investors ask you a question you don't know the answer to, the best response is neither to bluff nor give up, but instead to explain how you'd figure out the answer. If you can work out a preliminary answer on the spot, so much the better, but explain that's what you're doing.[7] At YC we try to ensure startups are ready to raise money on Demo Day by encouraging them to ignore investors and instead focus on their companies till about a week before. That way most reach the stage where they're sufficiently convincing well before Demo Day. But not all do, so we also give any startup that wants to the option of deferring to a later Demo Day.[8] Founders are often surprised by how much harder it is to raise the next round. There is a qualitative difference in investors' attitudes. It's like the difference between being judged as a kid and as an adult. The next time you raise money, it's not enough to be promising. You have to be delivering results.So although it works well to show growth graphs at either stage, investors treat them differently. At three months, a growth graph is mostly evidence that the founders are effective. At two years, it has to be evidence of a promising market and a company tuned to exploit it.[9] By this I mean that if the present day equivalent of the 3 month old Microsoft presented at a Demo Day, there would be investors who turned them down. Microsoft itself didn't raise outside money, and indeed the venture business barely existed when they got started in 1975.[10] The best investors rarely care who else is investing, but mediocre investors almost all do. So you can use this question as a test of investor quality.[11] To use this technique, you'll have to find out why investors who rejected you did so, or at least what they claim was the reason. That may require asking, because investors don't always volunteer a lot of detail. Make it clear when you ask that you're not trying to dispute their decision — just that if there is some weakness in your plans, you need to know about it. You won't always get a real reason out of them, but you should at least try.[12] Dropbox wasn't rejected by all the East Coast VCs. There was one firm that wanted to invest but tried to lowball them.[13] <NAME> points out that it's doubly important for the explanation of a startup to be clear and concise, because it has to convince at one remove: it has to work not just on the partner you talk to, but when that partner re-tells it to colleagues.We consciously optimize for this at YC. When we work with founders create a Demo Day pitch, the last step is to imagine how an investor would sell it to colleagues. Thanks to <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, and <NAME> for reading drafts of this.
https://github.com/davawen/Cours
https://raw.githubusercontent.com/davawen/Cours/main/typst/physique/0.1.0/utils.typ
typst
#import "@preview/xarrow:0.3.0" #import "@preview/cetz:0.2.2" #import cetz: draw, canvas, vector, plot #let figcan(body, caption: none) = { figure(caption: caption, canvas(body)) } #let point(pos, value: [], anchor: "south", color: black, padding: 5pt, name: none) = { import draw: circle, content circle(pos, radius: 1.5pt, stroke: color, fill: color, name: name) content(pos, value, anchor: anchor, padding: padding) } #let double_arrow(p1, p2, ..params) = { import draw: line line(p1, p2, mark: (start: "straight", end: "straight"), ..params) } #let arrow(p1, p2, ..params) = { import draw: line line(p1, p2, mark: (end: "straight"), ..params) } #let line_through(a, b, box: (none, none), name: none, ..style) = { import draw: * group(name: name, { get-ctx(ctx => { let (cetz, a, b) = cetz.coordinate.resolve(ctx, a, b) let (ax, ay, _) = a let (bx, by, _) = b let dy = by - ay let dx = bx - ax let sx = (ax - 10*dx, ay - 10*dy) let sy = (bx + 10*dx, by + 10*dy) let (boxa, boxb) = box intersections("i", { hide({ line(sx, sy) rect(boxa, boxb) }) }) line("i.0", "i.1", ..style) }) }) }
https://github.com/bpkleer/typst-academicons
https://raw.githubusercontent.com/bpkleer/typst-academicons/main/example.typ
typst
MIT License
#import "lib.typ": * = typst-academicons bpkleer https://github.com/bpkleer/typst-academicons A Typst library for Academicons v1.9.4 icons through the desktop fonts. This is based on the code from `duskmoon314` and the package for #link("https://github.com/duskmoon314/typst-fontawesome")[#text("typst-fontawesome", weight: "bold")]. == Usage === Install the fonts You can download the fonts from the official website: https://jpswalsh.github.io/academicons/ After downloading the zip file, you can install the fonts depending on your OS. ==== Typst web app You can simply upload the `ttf` files to the web app and use them with this package. ==== Mac You can double click the `ttf` files to install them. ==== Windows You can right click the `ttf` files and select `Install`. === Import the library ==== Using the typst packages You can install the library using the typst packages: `#import "@preview/academicons:0.1.0": *` ==== Manually install Copy all files start with `lib` to your project and import the library: `#import "lib.typ": *` There are three files: - `lib.typ`: The main entrypoint of the library. - `lib-impl.typ`: The implementation of `ai-icon`. - `lib-gen.typ`: The generated icons. I recommend renaming these files to avoid conflicts with other libraries. === Use the icons You can use the `ai-icon` function to create an icon with its name: ```typst #ai-icon("lattes")``` #ai-icon("lattes") Or you can use the `ai-` prefix to create an icon with its name: ```typst #ai-lattes()``` #ai-lattes() (This is equivalent to ```typst ai-icon().with("lattes")```) ==== Full list of icons You can find all icons on the #link("https://jpswalsh.github.io/academicons/")[official website]. ==== Customization The `ai-icon` function passes args to `text`, so you can customize the icon by passing parameters to it: ```typst #ai-icon("lattes", fill: blue)``` #ai-icon("lattes", fill: blue) ```typst #ai-lattes(size: 15pt)``` #ai-lattes(size: 15pt) ==== Stacking icons The `ai-stack` function can be used to create stacked icons: ```typst #ai-stack(ai-icon-args: (fill: black), "doi", ("cv", (fill: blue, size: 20pt)))``` #ai-stack(ai-icon-args: (fill: black), "doi", ("cv", (fill: blue, size: 20pt))) Declaration is `ai-stack(box-args: (:), grid-args: (:), ai-icon-args: (:), ..icons)` - The order of the icons is from the bottom to the top. - `ai-icon-args` is used to set the default args for all icons. - You can also control the internal `box` and `grid` by passing the `box-args` and `grid-args` to the `ai-stack` function. - Currently, four types of icons are supported. The first three types leverage the `ai-icon` function, and the last type is just a content you want to put in the stack. - `str`, e.g., `"lattes"` - `array`, e.g., `("lattes", (fill: white, size: 5.5pt))` - `arguments`, e.g. `arguments("lattes", fill: white)` - `content`, e.g. `ai-lattes(fill: white)` == Gallery Here are all the icons in the library. The first column is the icon function you can use, and the second column is what you get with `ai-<iconname>`. The third column is what you get when you use `ai-icon("<iconname>")` with the icon name. #include "gallery.typ"
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/055%20-%20Murders%20at%20Karlov%20Manor/001_Episode%201%3A%20Ghosts%20of%20Our%20Past.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Episode 1: Ghosts of Our Past", set_name: "Murders at Karlov Manor", story_date: datetime(day: 05, month: 12, year: 2023), author: "<NAME>", doc ) The sky over Karlov Manor danced with a dizzying array of colors, brought to life by shimmering cascades of magic. The Orzhov had purchased every Izzet pyrowork in the Tenth District, creating a profligate display of power and plenty. #emph[See? ] it said, even to those not fortunate or favored enough to have obtained an invitation. #emph[See? ] We have so many resources at our command that we can spend them on frivolities. Ravnica is safe now: we do not need to worry and conserve for wartime. It was a calculated expenditure, and every burst of colors or illusionary blossoms falling from the sky reminded the people living in the shadow of the Orzhov Syndicate who their saviors were. The gates stood open, admitting those guests who had chosen fashionable lateness over polite promptness, while lower-ranking guild members checked invitations and identification, making sure no one snuck inside. A few servers in toned-down versions of the more elaborate uniforms worn by those working the interior walked back and forth with trays of equally less elaborate starters, sharing the rare largess of the guild with the less fortunate. Teysa, newest head of the Syndicate, stood on the manor's highest balcony, watching the gathering throng and sipping from a glass of strong coffee laced with bumbat. Soundless as ever, Kaya stepped up next to her, stopping when she reached the rail. Her glance downward was more calculating than Teysa's proprietary appraisal: where Teysa looked like she was measuring the value of the people below them, Kaya looked like she was assessing how long it would take them all to escape should things go wrong. Also, unlike Teysa, her hands were empty. Teysa slanted her a sidelong glance, eyes raking along the length of the barely presentable Planeswalker's form. Kaya had swapped her adventuring clothes for proper Ravnican attire, black and white with golden accents, the symbol of the guild a pale splash across the right side of her chest. If not for the tension in her stance and the way her gaze darted from place to place as she assessed the plaza, she might almost have looked as if she still belonged. "You should have a drink," said Teysa. "You make me look like a miserly host when you walk with empty hands." #figure(image("001_Episode 1: Ghosts of Our Past/01.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "But you #emph[are] a miserly host," Kaya protested without rancor. "Or at least a calculated one. Every zib you spend on this gala will come back to you a golden zino, or you're not the person who outmaneuvered me and seized the reins while my back was turned." Teysa smiled. "I missed you. You've always seen me so clearly." "Clarity gets easier with distance." "Yes, and you were distant when the invasion came to Ravnica." Teysa's smile sharpened like the knife it was. "You owe me this night, Kaya. No matter how far you've traveled, you're Orzhov enough to pay your debts. When Ravnica needed you, you weren't here." "If I'd been here instead of defending the Multiverse, neither of us would be here now!" snapped Kaya. "Don't you dare act like I stopped caring about Ravnica because I couldn't be here. I was"—her voice faltered, turning thick in her throat, and she glanced down at her feet—"I was doing my best." "Yes, and tonight, you do your best for #emph[me] ," said Teysa. "The Agency has helped us to control and contain the chaos that followed the … unpleasantness. Without them, we'd have far more than two useless guilds on our hands. All ten might have been gutted by the invaders, and then what would have become of our plane? So tonight, you smile when I say smile, and you bow when I say bow, and you remember your debts to the Orzhov, if you don't want to remember your debts to me." This time, Kaya's answering look was akin to a snarl, teeth clenched in an expression that seemed like it might actually hurt. But she nodded her acquiescence, and when Teysa touched her wrist, she didn't flinch away. "Come, old friend," said Teysa. "I would be a poor host if I didn't attend to my other guests, and I haven't seen you eat a thing all evening." "I'm not hungry," said Kaya. "Being here unsettles my stomach." "If you faint because you're too stubborn to eat, your debts remain unpaid," said Teysa. "And even if you're too stubborn to enjoy the evening, I oversaw the menu, and I refuse to miss the strudel." She walked past Kaya to the door, leaning heavily on her walking cane. Clearly expecting obedience, she didn't look back. "I pay my debts," Kaya said in a low tone and walked after her. The balcony door led to a well-appointed library, the walls lined with a ransom of rare books and gilded manuscripts. Two lower-ranking guild members flanked the doors, keeping the party guests from "just happening" to wander into a space they had been asked to avoid. Teysa nodded to them as she passed, a small, cool smile on her lips, and they stood at straighter attention, honored by the attention of their Syndicate's leader. Neither of them gave Kaya a second glance, even as she dropped her symbolic coin into the plate held by the one on the left. She matched her pace to Teysa's, looking back at them. "How quickly they forget, huh?" she asked. "The world moves on even when you're not in it," said Teysa, beginning to descend the wide, gently curving stairs toward the ground floor. Revelers dotted the lower steps, goblets and small plates in their hands, jockeying for the sliver of advantage granted by a higher physical position. Teysa nodded to each as she passed, her small, cool smile never wavering. Kaya knew that smile. Teysa called it "number twenty-four: you are honored by my attentions." She had a moment to admire Teysa's unflappability, and then they were at the floor, cutting across the hall to a narrow side door, which opened onto the packed courtyard. The blast of sound and color from the outside wiped the moment away, replacing it with a dazzling array of Ravnica's elite. None were so gauche as to yell or otherwise express delight at Teysa's arrival: nods, smiles, and small lifts of people's glasses were all that she received as she led Kaya out into the cool night air, settling one hand on the taller woman's shoulder in a proprietary fashion. Too quietly for anyone else to hear, she murmured, "Don't embarrass me tonight. Remember why you're here." Together, they moved into the crowd. [hr \/] The people in the courtyard had arranged themselves in almost concentric circles, with each circle made up of people considered slightly less important than those on the next circle in. The outer circle, nearest the doors, consisted of low-ranking guild members, most sticking to the groups they'd come in with, uneasy with the idea of trying to craft alliances in such a public place. No such barriers existed on the next circle in, where the mid-ranked guild members swirled, moving from conversation to conversation with the grace of the socially adept. Not every guild prized social acumen the way the Orzhov or Simic did, but even the Izzet and Gruul had their public speakers, and those had been the members chosen to represent them at what was clearly being treated as the social event of the season. Kaya was abstractly surprised not to see <NAME>, who she would have expected to find representing his guild. Perhaps it was considered unfashionable to invite a Planeswalker, unless you had them properly leashed. No awkwardness or bad manners here: only the dazzling whirl of Ravnican society, their very presence a reminder of everything that made Ravnica worth preserving. #emph[See?] they seemed to say. #emph[We are still here, and we are still glorious, and we deserved salvation.] Through it all, Teysa guided Kaya, pulling her effortlessly through the tiers of society until she reached the innermost ring. It had formed around the great form of Ezrim, the massive archon having occupied the center of the courtyard, where he was apparently deep in conversation with Lavinia, current head of the Azorius Senate. The highest-ranking attendees among the guilds stood at a respectful distance in their own circle, chatting among themselves while they watched with predatory interest to see whether Lavinia was about to escalate their discussion to the level of verbal conflict. "Ezrim has never belonged to any guild, but as an archon with several known associates among the Azorius, Lavinia always assumed he would one day see sense and join the Senate proper," murmured Teysa, her words intended for Kaya's ears alone. "Imagine her displeasure when after the invasion, he took on leadership. Insult to injury, most of those associates followed him. A stroke of luck for the city as a whole if you ask me—he's a brilliant analytical mind, above reproach, and not bound by guild affiliation." Kaya frowned. "If he can't be affiliated with the Senate, why is Lavinia pestering him?" "Who knows? Maybe she's trying to win him back. Oh! Tolsimir!" Teysa turned, suddenly all smiles, her hand slipping from Kaya's shoulder. Kaya seized the opportunity to duck away, moving toward a server with a small tray of bacon-wrapped asparagus spears and neatly plucking one from the assortment. The server, who wore Orzhov colors, looked at her with awe and a small measure of fear. "You're her," he said. "Our former leader. The Planeswalker." "I am," said Kaya. She took a breath, steadying herself. "Teysa asked me to attend the gala." "I didn't #emph[ask] you to attend, dear. You're the next best thing to a guest of honor," Teysa said, looming behind her and whisking her away before the server could swallow his awe enough to say anything else. "There aren't many people here for you to meet—you know them all, of course, from when you actually spent your time at home, with us—but there are many people you need to #emph[see] ." Kaya didn't resist as Teysa pulled her toward Tolsimir and Aurelia, who were apparently deep in a conversation about the absent Dimir. Judith stood nearby, shamelessly eavesdropping as she sipped from a flute of something pale and sparkling, a cruelly amused spark in her eyes. She was dressed in black and red, as always, standing out sharply against the more elegantly attired crowd. As Teysa approached, Tolsimir was saying sharply to Aurelia, "It's naive to think that Lazav is dead. That man will outlive us all. I don't know what he's planning, but he's planning #emph[something] . Teysa, tell her Lazav isn't dead." "As a fellow guild leader, I would be overstepping to attempt to summon his spirit without better cause than my own curiosity," said Teysa smoothly. "I can, however, confirm that I haven't seen him among the departed, although it's been very busy, with all the spirits of the recently dead trying to settle their affairs. So few of them can afford the service." "Is there no way to extend them credit?" asked Tolsimir. "We've extended enough credit toward the resolution of this crisis," said Teysa. "Would you have us bankrupt ourselves for the masses?" A vast topiary panther lumbered by, its leafy tail swishing over their heads as it continued on its vegetable way. Judith laughed. #figure(image("001_Episode 1: Ghosts of Our Past/02.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) "Yes, the risk of bankruptcy is plainly #emph[very] near indeed." She flicked a hand in a dismissive gesture, brushing the topic aside as she inserted herself into the discussion. "But I see you've brought your trophy of the evening. Hello, Kaya. How have you been? Started any invasions recently? Were you aware that whenever you're in the city, all the guilds activate our crisis management divisions?" "We didn't start the invasion, we stopped it," said Kaya. "Ravnica is part of the Multiverse. It always has been, even if it used to be possible to pretend that Ravnica stood alone. What impacts other planes will impact here. We fought as hard and as swiftly as we could." "Ravnicans died," said Judith, levity gone. "So did Planeswalkers," said Kaya. "I lost friends in that fight, same as you did. Not only to death, either. Ravnica doesn't grieve alone." Judith opened her mouth to answer and stopped as Kaya looked at her. There was a wall behind the Planeswalker's eyes that hadn't been there on their last meeting, an unbreachable barrier keeping Kaya in and the rest of the world out. It was as if she had slammed shut at some point during the invasion and had yet to remember how to open. Unsettled, Judith looked away. At the center of their loose circle, Ezrim's mount rose, shaking its great wings to resettle the feathers, and prowled away, Ezrim seated firmly on its back. Teysa returned her hand to Kaya's shoulder. "You'll have to excuse us," she said. "It's almost time for the keystone event of the evening, and it wouldn't do to risk our hero missing the moment." Kaya glanced downward at her feet. "You do keep things ticking away by the numbers," said Tomik, appearing at Teysa's other elbow. Judith's smile returned, more assured now. "Oh, look," she said. "Three leaders of the Syndicate in a line. Which one do you suppose balances the books best? Or—I'm sorry, Tomik. Is it Izzet now, for you?" "My husband's guild is not my own," said Tomik stiffly. "Teysa, we're needed on the grand balcony." "Duty calls," said Teysa, pulling Kaya with her as she turned away. "You owe me for that," murmured Tomik once they were far enough from the other guild leaders to not be overheard. "I didn't need a rescue," said Teysa. "Even if I had, I had a hero at hand. Kaya would have saved me." Kaya said nothing, allowing herself to be pushed along. Out of the corner of her eye, she watched the people they passed reacting to her presence. Some shied away, as if her spark might turn contagious and whisk them off to other planes when they were needed here. Others watched with disdain, or with avarice. None were emotions she was used to seeing on these particular faces, and she found it best not to react, not to let them know she saw. Teysa's hand was an almost comforting constant, guiding her through the crowd, even if she did insist on introducing Kaya as "Orzhov's own hero of the Multiverse" every time the opportunity presented itself. Tomik, at least, seemed to understand Kaya's discomfort: how could he not, when Ral was one of those who grieved the losses Ravnica would never know, the lives lost, the sparks extinguished, all to feed Phyrexia's endless hunger? He walked in silence, not joining Teysa's self-serving introductions, but not stopping her, either. After a journey that felt at least five times longer than it was, they reached the shallow set of steps leading up to the grand balcony. Ezrim was already there, and Kaya felt a pang of envy for how effortlessly he'd passed through the crowd. No one wanted to interrupt an archon on a mission. A guild leader and a so-called hero, however, they felt perfectly comfortable stepping in front of. Teysa began to climb the stairs, leaning more heavily on her cane. Tomik stepped back, unable to assist his superior without it looking like a comment on her fitness, even as her hand on Kaya's shoulder gripped tighter, using the other woman for stability as much as anything else. Kaya glanced at her. "Is it hurting you?" "No," said Teysa. "Stairs just grow more challenging as I get older. Nothing worth fretting about. Here!" As they reached the top of the stairs, Teysa stepped away from Kaya, gesturing her toward a spot in the line of Orzhov lawmages and actuaries who had come to observe. Tomik moved to the line as well, settling to Kaya's left and giving her hand a reassuring squeeze. She shot him a brief smile and thus missed the moment when Teysa stepped up to the balcony rail, casting an unobtrusive enchantment that amplified every word she spoke until it filled the entire courtyard. "Citizens of Ravnica, welcome to <NAME>!" she said. The crowd applauded, some politely, others with more enthusiasm—although none showed more enthusiasm than the goblin in gaudy finery who had stationed himself near the dessert table, forcing anyone who wanted something sweet to subject themselves to his attempts at networking. Teysa's expression hardened for an instant when she saw him, before snapping back to perfect unblemished serenity. "I know I asked a great deal of you all, when I requested you step away from your own guilds and duties for an evening of Orzhov hospitality, and I hope we have lived up to your high expectations. Tonight's purpose is twofold. Tonight, we celebrate Orzhov's own former leader, Kaya, for her role in the salvation of Ravnica and the Multiverse during the Phyrexian invasion, during which she fought with us!" A more restrained wave of applause met this statement. Recognizing her cue, Kaya took a half-step forward and waved, biting the inside of her cheek the whole time. As if that fight were something to be celebrated. Survival, yes, but the battle, no. The applause died down. Kaya stepped back. Teysa smiled at the courtyard once more. "But perhaps even more importantly, tonight we honor the members of the Ravnican Agency of Magicological Investigations." This time, the applause was raucous, and rolled on and on, seemingly without end. Teysa stepped aside, ceding her place to Ezrim, who moved into position with a gravitas that was only tangentially connected to his imposing size. Half-mantling his wings, he looked at the crowd and rumbled, "We are privileged to serve the city of Ravnica in whatever means are open to us. By helping to bring order to the chaos the Phyrexians left in their wake, we have done no less than should be expected of any citizen. "But as we have served the city, the city has also served us, and we have been honored by your support—and yes, your funding." Laughter rippled through the crowd. Teysa, who had acquired a flute of kasarda from a passing server, offered him a smirking salute, taking the ribbing with good spirits. Kaya couldn't help but think Ezrim would pay for that later, behind closed doors. Teysa would absolutely tear strips out of an archon looking for restitution if she thought she had cause. That was why she was so well suited to lead the Syndicate. Better suited than Kaya had ever been. Ezrim was still speaking, but the names he recited meant nothing to Kaya. The first six or so were clearly people not in attendance, as none appeared to accept their honors. The next three stepped out of the crowd and up to his side, standing proudly as he set a heavy hand on their left shoulder and thanked them ceremonially for the part they'd played in the investigation. They looked pleased by the praise, and even more pleased by the small purses handed to them by Teysa, who didn't flinch at the act of giving money away. The guild clearly stood to profit even more from this show of unity than Kaya had been assuming if cash rewards were a part of the proceedings. Ezrim cleared his throat. The sound rolled across the courtyard like the beginning of a storm. "Many of you were present last month, when a Gruul god broke loose of guild control and wreaked havoc across the Ninth District. Anzrag could have continued his rampage for days, had we been reliant on the guilds for immediate support. But the quick thinking and actions of Investigator Kellan and his team brought the rampage to a halt, and the god has been properly contained within an evidence capsule. Kellan, please approach." The crowd applauded again as a slim, dark-haired man in a blue tunic and coat stepped up to Ezrim, clearly uncomfortable with the eyes of the crowd upon him. Kaya could sympathize. "The Agency thanks you, Ravnica thanks you, and I thank you," said Ezrim, placing a hand on Kellan's shoulder. Kellan managed a nervous smile before Ezrim took his hand away and Teysa handed him the purse. Then, with a speed barely shy of impolite, Kellan fled the balcony for the stairs, brushing past Tomik and Kaya. "Wish I could do that," muttered Kaya. Tomik laughed, quick and unamused. "Teysa has you on a tight leash tonight." "I'm her 'hero' for the evening." Kaya sighed. "I don't want to be reminded of the invasion at every turn, but she says I owe the guild for not being here when it happened, and honestly, she's not wrong." "Ral—" "Ral wasn't on New Phyrexia. Ral didn't see how bad it was going to be. Jace …" She shuddered, shaking her head. "For weeks, I saw him every time I closed my eyes. He fought as hard as he could, but he lost. And because of that, we all lost." "It was an impossible fight." "Maybe." Teysa was still distracted talking to Ezrim, having dispelled the enchantment amplifying their voices. Kaya eyed them. "I think this is where I make my escape, at least for a little bit. When Teysa asks where I am, tell her I went to raid the buffet, will you?" "I will," Tomik said. "Thank you." She turned on her heel and slipped into the natural gaps the crowd formed as it eddied. Halfway down the stairs, she passed Kellan, now smiling uncertainly at Zegana and Vannifar as they fixed him with too-sharp eyes, taking his measure. They looked ruffled and unhappy, as if he had interrupted something by coming too close to them. #figure(image("001_Episode 1: Ghosts of Our Past/03.png.jpg", width: 100%), caption: [Art by: <NAME>], supplement: none, numbering: none) Kaya knew the pair had been on poor terms since Vannifar unseated her predecessor. Seeing them here together was odd. "Are you #emph[quite] sure you're not that detective Proft everyone's been talking about?" Zegana asked. "I'm sorry," said Kellan. "I'm not sure precisely who that is." His eyes, darting wildly from side to side, fixed on Kaya. "But I've been meaning to speak with the hero of the hour. If you would excuse me?" He ducked between the pair, not waiting for their reply, and rushed to Kaya's side. Kaya looked at him, bemused. "What did you need to talk to me about?" "Getting out of here," he said. "Forgive me, but I look for clues for a living, and your expression tells me you're as uncomfortable right now as I am." Kaya blinked, startled into laughter. "No wonder they honored you. I was heading for the buffet. Escort me?" Kellan took her arm with visible relief, and the pair descended to ground level, where—somehow, impossibly—Teysa was waiting next to the buffet, her attention fixed on the gaudily dressed goblin as intently as a cat might fixate on a bird. "—payment," she was saying, as the pair approached. The goblin looked nervous. "I acquired my invitation through legitimate means." "I didn't say you hadn't," said Teysa. "Only that there might be better uses of your resources than worming your way into a celebration unrelated to yourself. Think, Krenko. You owe the Karlovs." Not the Orzhov: the Karlovs specifically. Interesting. Kaya focused on Krenko, eavesdropping without shame. "You'll get your money, Karlov," said Krenko, nervousness fading. "In full, and with the agreed-upon interest. For tonight, I'm an invited guest, and this reflects poorly on your hospitality." "I think what you need is #emph[focus] ," said Teysa. "A lack of distractions, perhaps." She would have said more, but a ruckus broke out above them, catching everyone's attention. On the balcony, Ezrim watched impassively as three members of Teysa's security dragged away a shouting centaur dressed in the colors of the Gruul Clans. The centaur was clearly enraged, struggling to break free. "—no right!" he howled. "Anzrag is #emph[our] responsibility, #emph[our] god, and he must be returned to us! He acted only according to his nature!" Kaya turned away from the scene, focusing on a distressed Kellan. "Nothing ever really changes, does it?" she asked. "It puts on a new coat and calls itself remade, but it's all the same under the surface." "I don't quite understand. I'm sorry," said Kellan. She shook her head, with a small, bitter laugh. "It's fine. Just realizing that all that really changes is the faces you don't see anymore. The people who leave you." "You mean Yarus? He's been trying to get us to release his god since we detained him. We've tried explaining that we'll release Anzrag to the Azorius once our investigation is complete, and he should talk to them, but he doesn't seem to care." On the balcony, Yarus's shouting had been replaced by silence. Kaya turned to see him dragged toward the gates, still fighting his captors but no longer howling. Instead, he glared murder at Ezrim, never taking his eyes off the massive archon. Aurelia walked up to the buffet, wings half-mantled, and Kaya had time for one bitter thought about how all the people she most wanted to avoid seemed to be following her before Aurelia was heading for Teysa, saying in a cutting tone, "This investigation should be in the hands of the Boros. We know how to maintain peace without causing unrest within the guilds." Kellan made a sound that could have been interpreted as a scoff. Aurelia wheeled toward him, wings spreading wider, and as Teysa moved to intervene, Kaya saw her chance. She ducked around the buffet and through the door on the other side, passing servers with fresh trays of canapés as she made her escape toward a set of stairs half-concealed behind a marble column. It wasn't until she reached the top of the stairs without anyone stopping her that she paused, took her first unrestrained breath since the party began, and asked herself where she was going. Back to the balcony where she'd been with Teysa, high above all the chaos and the noise, where she could think. Moving faster, she retraced her earlier steps, pausing only to bribe the guards at the door, and stepped back out into the evening air. The sky was beautiful, although the ongoing fireworks blocked the stars. She would have liked to see the stars. She had always liked the Ravnican stars. She leaned against the wall, closing her eyes. She could leave. It would be so #emph[easy] . Unlike some of the people she cared about, her spark still burned as bright as it ever had and would reach across the Blind Eternities to carry her wherever she wanted to go. She could return to Kaldheim, see how Tyvar was adjusting to his new limitations, or head for Dominaria, or Innistrad, or Alara—there were no limits. She didn't have to stay here. She felt herself begin to reach, desire becoming reality, and stopped, opening her eyes and digging her heels into the balcony. Teysa might make her point in the worst possible ways, but she was also right: when Ravnica needed her most, Kaya had allowed her own sense of what mattered to take her away. If she'd stayed, she might have been able to shape the Orzhov into more of a force for good. If she'd refused her position on the strike team so someone else could hold it, maybe they would have been successful. There was no way of knowing, but if she'd stayed here, she might have changed everything. Kaya moved to the edge of the balcony, resting her hands on the rail, and looked down. The conversation by the buffet had escalated to arm and wing waving and raised voices, but Teysa wasn't there. Neither was Judith; no matter how she scanned the crowd, the woman's eye-catching red and black eluded her. Her breathing leveled out as she watched the people move below, safely distant, unable to reach her. She had just started to feel like she might be able to go back downstairs when a footstep from behind her caught her attention, and she turned to see Teysa approaching. The other woman wasn't smirking, for once. Teysa wore an expression of uncharacteristic seriousness. "Kaya, there you are," she said. "I just needed a moment to breathe," said Kaya. "I understand. This is a lot to deal with, even for me, and I know the invasion hurt you as much as it hurt us, but I'm glad I found you." Teysa took a deep, oddly unsteady breath. "There's something I need to tell you. Something important. And I needed to catch you alone." "We were alone before." "Not really." Teysa waved a hand. "Before the gala began, there were people lurking to make sure I didn't need anything. We needed to be #emph[alone] ." "All right. What is it?" Teysa started to reply as a scream rang out from inside the manor, drowning out her words and shattering the moment. Kaya didn't pause to think before running toward the sound. This time, if Ravnica needed her, she wouldn't let them down.
https://github.com/Dherse/typst-glossary
https://raw.githubusercontent.com/Dherse/typst-glossary/main/glossary.typ
typst
#let glossary_entries = state("glossary_entries", (:)) #let gloss(key, suffix: none, short: auto, long: auto) = { locate(loc => { let entries = glossary_entries.at(loc) if entries.keys().contains(key) { let entry = entries.at(key) let long = if (entry.locations.len() <= 0 and short != true) or long == true { [ (#emph(entry.long))] } else { none } link(label(entry.key))[#smallcaps[#entry.short#suffix]#long] glossary_entries.update((x) => { let page = numbering(loc.page-numbering(), ..counter(page).at(loc)); if x.keys().contains(key) and not x.at(key).pages.contains(page) { x.at(key).pages.push(page) x.at(key).locations.push(loc) } x }) } else { text(fill: red)[*Glossary entry not found: #key*] } }) } #let glossary(title: "Glossary", entries, body) = { [ #heading(title) <glossary> ] glossary_entries.update((x) => { for entry in entries { x.insert(entry.key, (key: entry.key, short: entry.short, long: entry.long, locations: (), pages: ())) } x }) let elems = (); for entry in entries.sorted(key: (x) => x.short) { elems.push[ #heading(smallcaps(entry.short), level: 99) #label(entry.key) ] elems.push[ #emph(entry.long) #box(width: 1fr, repeat[.]) #locate(loc => { glossary_entries .final(loc) .at(entry.key) .locations .sorted(key: (x) => x.page()) .map((x) => link(x)[#numbering(x.page-numbering(), ..counter(page).at(x))]) .join(", ") }) ] } table( columns: (auto, 1fr), inset: 5pt, stroke: none, fill: (_, row) => { if calc.odd(row) { luma(240) } else { white } }, align: horizon, ..elems ) show ref: r => { locate(loc => { let term = str(r.target) let res = query(r.target, loc) // If the source exists and is the glossary (heading level 99) if res.len() > 0 and res.first().func() == heading and res.first().level == 99 { gloss(term, suffix: r.citation.supplement) } else { r } }) } body };
https://github.com/saffronner/matrix-alg-notes
https://raw.githubusercontent.com/saffronner/matrix-alg-notes/main/notes.typ
typst
#show: set image(width: 50%); // - $arrow(v)$ #set math.vec(delim: "[") #set math.mat(delim: "[") // #set text(font: "Garamond-Math.otf") #let span = math.op("span") #let col = math.op("col") = Linalg - scalars: real numbers and stuff, $RR$ - vectors: a list of scalars. - we use column vectors: $vec(1,pi) in RR^2$, etc - geometric picture: $RR^2$ is cartesian plane, $RR^3$ is 3d space, etc - operations: - scalar multiplication: $2 dot vec(1,pi) = vec(2, 2pi)$. geometrically: "stretching/shrinking" - vector addition: $vec(1, pi) + vec(2, -pi) = vec(3, 0)$. geometrically: "tail to tip" - standard vectors (think $hat(i), hat(j), hat(k)$ from 3dcalc) - $RR^2$: - $ arrow(e_1) = vec(1, 0) $ - $ arrow(e_2) = vec(0, 1) $ - $RR^3$: - $ arrow(e_1) = vec(1, 0, 0) $ - $ arrow(e_2) = vec(0, 1, 0) $ - $ arrow(e_3) = vec(0, 0, 1) $ - BIG POINT: every vec in $RR^n$ is a linear combination of standard vectors - ie, $vec(1,pi) = vec(1,0) + vec(0, pi) = vec(1,0) + pi vec(0, 1)$ - future language: $arrow(e)_1, arrow(e)_2, dots, arrow(e)_n$ _span_ $RR^n$ - matrices: an array of scalars: $ mat(1,0,7; 0,pi,1/2) $ - variables to use: $A,B,C,U,V$ $ A = mat(a_11, a_12, dots, a_(1n); a_21,a_22,dots,; dots.v,dots.v,,; a_(m 1)) $ - $A_(i*)$ means the $i$th row == Matrix Multiplication - definition: #figure( image("media/multiply_matrices.gif"), caption: "matrix multiplication. use dot products. see gif." ) - matrix mult. can also be viewed row-wise and column-wise (#link("https://ghenshaw-work.medium.com/3-ways-to-understand-matrix-multiplication-fe8a007d7b26")[medium post link]) - let $A B = C$ - a col of $C$ is a linear combination of cols of $A$; weighted by the corresponding col of $B$ - a row of $C$ is a linear combination of rows of $B$, weighted by the corresponding row of $A$ #image("media/matrix_mult_rowcol_forms.png") - matrix-vector mult is just viewing vector as column vector, 1 wide matrix - matrix mult properties: - $m$x$n$ matrix times $n$x$o$ matrix is a $m$x$o$ matrix - Associative property for matrices: $A(B C)=(A B)C$ - Commutative property of scalars: $c(A B)=(c A)B=A(c B)$ - Left distributive property: $A(B+C)=A B+A C$ - Right distributive property: $(B+C)A=B A+C A$ - Identity property: $I_m A = A = A I_n$ - transpose matrix ($A^T$): just leetcode flip 2d array - $arrow(x) dot arrow(y) = arrow(x)^T arrow(y)$ when you view right half as matrix mult. as scalar - TODO something about why $(A B)^T = B^T A^T$? - special matrices - nxn: square - $I_n$: the nxn identity matrix - $A I = A$ and $I A = A$ for any $A$ - permutation matrices: sudoku the 1s - $ mat(0,1,0;0,0,1;1,0,0)mat(A_(1*);A_(2*);A_(3*)) = mat(A_(2*); A_(3*); A_(1*)) $ - diagonal matrices: entries not on diagonal are 0. usually square. - geometrically, they "scale our axes" - jacobian matrices :3 - upper triangular: $A_(i j) = 0 "if" i > j$. i.e. entries _stictly_ lower than diag must be 0. - lower triangular: see above. - swap between lower/upper triang. via transposes - used to solve systems of equations == systems of linear equations - e.g. solve $A arrow(x) = arrow(b)$ where $A$ is a upper triang. matrix $ A = mat(1,-1,2;0,8,-2;0,0,3), arrow(b) = vec(3,4,6) $ - a linear equation is of the form $a_1x_1 + a_2x_2 + ... + a_n x_n = c$ - review: solving systems in general get from system of equations matrix to echelon form matrix to reduced echelon form #image("media/solving_system_1.jpg") #image("media/solving_system_2.jpg") - elementary row operations <elementary_row_operations> - elementary matrices $E$ correspond to these. - use via $E A$. - these are invertible - all reversible - scaling rows: `row *= c` #figure( $ E = mat(1,0,0;0,1,0;0,0,3) $, caption: [scale 3rd row by 3] ) - replace rows: `row += c * other_row` #figure( $ E = mat(1,0,0;0,1,0;3,0,1) $, caption: [add 3R1 to 3rd row] ) - interchange rows - permutation matrices: swap the rows of $I$ you want to swap - two systems are equivalent (have same soln set) if their corresponding augmented matrices are rwo equivalent - a linear system is _consistent_ if it has solutions (1 or inf) and _inconsistent_ otherwise (no solutions) - a system is consistent iff the rightmost column of the augmented matrix is _not_ a pivot column - if system consistent, then (inf. many solutions iff free variables exist) - inconsistent class example: we did the solve path and got an echelon form of $ mat(2,-3,2,1; 0,1,-4,8;0,0,0,15; augment: #3) $ but $0 != 15$. - consistent inf solutions class example: did solve path and got solution set of $ { arrow(x) = vec(x_1,x_2,x_3)=vec(1,4,0)+x_3 vec(5,-1,1) : x_3 in RR} $ - Echelon Form (EF) "easy to solve" definition: - all nonzero rows above zero rows - each leading entry (first nonzero entry) of a row is in a col to the right of the leading entry above - all entries below leading entry are zero #image("media/echelon_form_visualization.jpg") - solving "easy to solve" Echelon Form get Reduced EF (REF) - subset of Echelon form - unique - all leading entries are 1s - each leading entry is the only nonzero in its column #image("media/reduced_echelon_form_visualiztion.png") - A pivot position corresponds to a leading 1 entry in the REF - A pivot column is a column of A that contains a pivot position. == Gaussian Elimination - how we get to the reduced echelon form - eg general solution to: $ mat(1,-2,-1,3,0; -2,4,5,-5,3; 3,-6,-6,8,-3; augment: #4) $ `R2 + 2R1, R3 - 3R1, R3 + R2, R2 / 3, R1 + R2` - let non pivot columns be free variables #figure( image("media/solving_system_full.png"), caption: "full example of solving a system" ) - algorithm: - "forward phase" gets to EF + find leftmost nonzero column. (a pivot pos at top.) use row swaps to move a nonzero entry to pivot pos + use row replacement to get zeros below the pivot. + recurse: ignore top row, repeat prev. 2 steps on rest of matrix - "backward phase" get to REF 4. use rescaling to make all leading entries 1 5. working left/upward, zero entires above pivot positions == Homogeneous Systems - a linear system is _homogeneous_ iff it has the form $A arrow(x) = arrow(0)$ - (non/in homogeneous if that 0 is a nonzero $arrow(b)$) - always consistent: $arrow(x) = arrow(0)$ is always a (trivial) solution - but do they have nontrivial solutions? - just solve it (g. elim.) - if a homogeneous and nonhomogeneous system differs only in their $arrow(0) "vs" arrow(b)$ vector, their solutions sets will only differ by a translation - eg you might get $ arrow(x)_"homogenous" = x_1 vec(1/5, 0, 1) "and" arrow(x)_"inhomogenous"= vec(0,8,-2) + x_1 vec(1/5, 0, 1) $ - i.e., if $A arrow(x) = arrow(b)$ is consistent and $arrow(p)$ is a solution (i.e. $A arrow(p) = arrow(b)$), then the solution set to $A arrow(x)=arrow(b)$ is ${arrow(p) + arrow(v) : A arrow(v) = 0}$ - (note that for $A arrow(x) = 0$, the soln set is ${arrow(x) : A arrow(x) = 0}$) == Matrix inverses - valid for for square matrices #figure( image("media/matrix_inverse_primer.png"), caption: [matrix inverses primer/motivating examples] ) - a matrix $A$ is _invertible_ if there is a matrix $C$ s.t. $C A = I$ and $A C = I$ - in this case, $C = A^(-1)$ - if $A,B$ invertible, then $A B$ invertible and $(A B)^(-1) = B^(-1) A^(-1)$ - imagine $A B arrow(x)$ is B first acting on $arrow(x)$ then $A$ acting on that. to undo, "shoes then socks" stack data structure method, we first $A^(-1)$ to undo the $A$ and then likewise with $B$, getting $B^(-1) A^(-1)$ <TEMPTEMP> - finding inverse not always possible. let $A = mat(1,1;1,1), $ trying to find $A^(-1).$ $ mat(1,1;1,1)mat(a,b;c,d)=mat(1,0;0,1) \ = mat(a+c, b+d; a+c, b+d) $ but $0 != 1$. - non-invertible matrices are called _singular_ - if $A$ invertible, $A arrow(x) = arrow(b)$ has a unique solution $arrow(x) = A^(-1) arrow(b)$ - how to try finding $A^(-1)$ - let $A = mat(a,b;c,d)$ and the determinant $D$ be $a d - b c$. - if $D != 0$, then $A^(-1) = 1/D mat(d,-b;-c,a)$ - if $D = 0, A$ is singular - in general for nxn matrices, find $A^(-1)$ via row reduction - form the matrix $mat(A,I, augment: #1)$ and put it in REF - if $A$ is invertible, we get $mat(I, A^(-1), augment: #1)$ - if $A$ is not invertible, then REF of $A$ is not $I$ #figure( image("media/finding_mat_inverse_ex.png"), caption: [finding matrix inverse example] ) #figure( image("media/finding_mat_inverse_reasoningproof.png"), caption: [proof of why this method works] ) - elementary matrices are invertible (#link(<elementary_row_operations>)[noted above]). #figure( image("media/inverting_elementary_matrices_ex.png"), caption: [inverting elementary matrices] ) - so if REF of $A$ is $I$, there are $E_1, ..., E_m$ s.t. $ (E_m E_(m-1) ... E_2 E_1)A = I $ thus, $A^(-1)$ is simply the product of the elementary matrices. additionally, $ A= E_1^(-1) ... E_(m-1)^(-1) E_m^(-1) $ following from socks/shoes above (#link(<TEMPTEMP>)[link]) === Vector spaces - vector spaces: $RR^n$ - span: if $arrow(v)_1, ..., arrow(v)_n in RR^m$, their span is the set of all linear combinations - i.e. $span{arrow(v)_1, ..., arrow(v)_n} = {c_1 arrow(v)_1+ ...+ c_n arrow(v)_n : c_1, ..., c_n in RR}$ - consider the question: determine if $arrow(b) in span{arrow(v)_1, ..., arrow(v)_n}$. - i.e., are there constants such that $c_1 arrow(v)_1 + ... + c_n arrow(v)_n = arrow(b)$. - if we view each $arrow(v)$ as a column vector of a matrix $A$, we realize we are just asking: solve $A arrow(c) = arrow(b)$ - thus, view columns of a matrix as spanning some linear space (line, plane, hyperplane) - $A arrow(x) = arrow(b)$ is consistent iff $arrow(b) in span{"the cols of" A}$ - theorem: - the columns of $A$ span $RR^n$ ($n$ being "height" of $A$) - iff $forall arrow(b) in RR^n, A arrow(x) = arrow(b)$ is consistent - iff $A$ has a pivot pos in every row - theorem: - the columns of $A$ are _linearly independent_ - iff $A arrow(x) = 0$ has only one solution (the trivial $arrow(x) = arrow(0)$) - iff $A$ has a pivot pos in every column - (intuit: all vecs point in "different directions") - (the column vecs are otherwise _linearly dependent_) - thrm: if $V = {arrow(v)_1, ..., arrow(v)_n}$ are linearly dependent, $exists arrow(v)_j in V, arrow(v)_j in span{V without arrow(v)_j}$ - i.e., if vecs are linearly dependent, one is in the span of the others - thrm: if $arrow(v)_1, ..., arrow(v)_n in RR^m$ and $n > m$, then the vecs are linearly dependent. - informal proof: form the matrix $A$ from col vecs $arrow(v)$. $A$ is $n$ wide, $m$ tall. since $n > m$, this means there _must_ be some pivot column and therefore inf. solutions. - let $B = {arrow(b)_1, ... arrow(b)_m}$. $B$ is a basis for $RR^m$ if $span{B} = RR^m$ and $B$ is linearly independent. - all bases of $RR^m$ have the same size (square! think: why? hints above...) - more generally, let $B = {arrow(b)_1, ... arrow(b)_m}$. $B$ is a basis for a subspace $H$ if $span{B} = H$ and $B$ is linearly independent. - all bases of $H$ have the same size (not necessarily square), calle the dimension of $H$, $dim H$ - a subspace is denoted $H subset.eq RR^m$ - properties: + $0 in H$ + if $arrow(u), arrow(v) in H$, then $arrow(u) + arrow(v) in H$ + if $arrow(u) in H, c in RR$, then $c arrow(u) in H$ - eg plane through $RR^3$'s origin - non-eg a circle in $RR^2$. subspaces don't curve? if we escape the subspace by taking two points and adding them it's not actually a subspace. - subspaces are spans of vectors ($H = span{arrow(v)_1, ..., arrow(v)_k}$) - "spanning set theorem": - let $S = {arrow(v)_1, ..., arrow(v)_k}, H = span S$. if $S$ is linearly dependent ($exists$ redundancy), then $exists arrow(v)_j in S, arrow(v)_j in span{S without arrow(v)_j}$ - (this is basically a duplicate of above) - note that $span{S} = span{S without arrow(v)_j}$ - can keep on "removing" vectors. when you are independent, you get $B$, a basis for $H$ - let the column space of a matrix, $col(A)$, be the span of the columns of a matrix $A$ - notice: this is a subspace! - find a basis for $col(A)$: - suppose matrix is in REF - take the pivot cols of it! - linear dependencies from REF are same as linear dependencies of the original matrix - so the basis is the same exact pivot cols - notice that if a free variable col can be created from some linear combination of pivot cols in the REF, they can be created with the same linear combination of the same pivot cols of the original matrix! - _rank_ is the dimension of the vector space spanned by a matrix's columns /* HOMEWORK TODO: 6d how to format solution set */ /* exam 1: 1.1-1.5 1.7-1.9 2.1-2.3 2.8-2.9 - null space, column space, basis */
https://github.com/chendaohan/bevy_tutorials_typ
https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/21_local_resources/local_resources.typ
typst
#set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3") #set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei") #set raw(theme: "themes/Material-Theme.tmTheme") = 1. 本地资源 本地资源允许你拥有每个系统独立的数据。这些数据不存储在 ECS 世界中,而是与系统一起存储。系统外部无法访问这些数据。该值将在系统的后续运行中保持。 `Local<T>` 是一个系统参数,类似于 `ResMut<T>`,它为你提供对给定数据类型的单个值的完全可变访问,该值独立于实体和组件。 `Res<T>`/`ResMut<T>` 指的是在所有系统之间共享的单个全局实例。另一方面,每个 `Local<T>` 参数是一个独立的实例,仅供该系统使用。 类型必须实现 `Default` 或 `FromWorld`。它会自动初始化,无法指定自定义初始值。 一个系统可以有多个相同类型的 `Local`。 ```rs #[derive(Default)] struct FrameCount(usize); fn info_my_component(mut count: Local<FrameCount>, my_component: Query<&MyComponent>) { if count.0 % 60 == 0 { if let Ok(my_component) = my_component.get_single() { info!("my component: {}", my_component.0); } } count.0 += 1; } ``` = 2. 指定初始值时 `Local<T>` 总是使用类型的默认值自动初始化。如果这不适合你,还有其他方法可以将数据传递到系统中。 如果需要特定数据,可以使用闭包。接受系统参数的 Rust 闭包和独立函数一样,是有效的 Bevy 系统。使用闭包可以“将数据移动到函数中”。 此示例展示了如何初始化一些数据以配置系统,而不使用 `Local<T>`: ```rs fn app_exit(mut frame_count: isize) -> impl FnMut(EventWriter<AppExit>) { move |mut exit_writer| { if frame_count <= 0 { exit_writer.send_default(); } frame_count -= 1; } } ```
https://github.com/ckunte/m-one
https://raw.githubusercontent.com/ckunte/m-one/master/m1.typ
typst
#import "/inc/_template.typ": * #show: book.with( title: [m-one], author: "<NAME>", dedication: [_for my daughters_], publishing-info: [ #include("/inc/_pub.typ") ], ) // preface #include "/inc/_preface.typ" #outline( indent: 1em, depth: 1 ) // #outline( // title: [List of Figures], // target: figure.where(kind: image), // ) // // #outline( // title: [List of Tables], // target: figure.where(kind: table), // ) // abbreviations #include "/inc/abbr.typ" // sea-transport and inertia #include "/inc/tow.typ" #include "/inc/reac.typ" #include "/inc/unconditional.typ" // fatigue #include "/inc/tsa.typ" #include "/inc/sncurves.typ" // wind and wave #include "/inc/wind.typ" #include "/inc/wavelength.typ" #include "/inc/viv.typ" // stability and utilisation #include "/inc/slenderness.typ" #include "/inc/ebs.typ" #include "/inc/cosfunc.typ" // reliability and storm safety #include "/inc/reliability.typ" #include "/inc/stormsafety.typ" // nearshore #include "/inc/fenders.typ" // installation and lifting #include "/inc/jf.typ" #include "/inc/crane.typ" #include "/inc/impact.typ" // model #include "/inc/model.typ" #pagebreak() #bibliography("/inc/ref.bib")
https://github.com/Isaac-Fate/booxtyp
https://raw.githubusercontent.com/Isaac-Fate/booxtyp/master/src/colors.typ
typst
Apache License 2.0
#let color-schema = ( white: rgb(255, 255, 255), gray: (primary: rgb(125, 124, 124)), orange: (primary: rgb(255, 123, 84), light: rgb(255, 178, 107, 10%)), blue: ( primary: rgb(0, 169, 255), light: rgb(137, 207, 240, 10%), dark: rgb(16, 74, 183), ), green: ( primary: rgb(121, 172, 120), light: rgb(176, 217, 177, 10%), dark: rgb(55, 146, 55), ), )
https://github.com/donabe8898/typst-slide
https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/並行prog/03/03.typ
typst
MIT License
// typst compile 02.typ /home/yugo/git/donabe8898/typst-slide/opc/並行prog/02/第2回/{n}.png --format png #import "@preview/polylux:0.3.1": * #import themes.clean: * #show: clean-theme.with( aspect-ratio: "16-9", footer: "Goであそぼう", // short-title: "", logo: image("03素材/gopher.svg"), color: teal ) #show link: set text(blue) #set text(font: "Noto Sans CJK JP",size:18pt) #show heading: set text(font: "Noto Sans CJK JP") #show raw: set text(font: "JetBrains Mono") #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt ) // TODO: 本文 #title-slide( title: "Go言語であそぼう", subtitle: "(第三回) Goの基礎", authors: "<NAME> a.k.a donabe8898", date: none, // watermark: image("01素材/gopher.svg",) ,//透かしの画像 secondlogo: image("03素材/gopher.svg") // 通常ロゴの反対側に映るロゴ ) #slide(title: "本講義のターゲット層")[ - サーバーに興味がある - モダンな言語を習得したい ] #slide(title: "自己紹介")[ = 岡本 悠吾 - <NAME> #v(0.5em) - T学科4回生 - サークル内でLinux関連の講義をやってます = 欲しい物リスト - 車(できればMR) - パソコン(そろそろ買い替えたい) #v(1em) ] // TODO: 本文 #new-section-slide("Section 8. Goとデータ") #slide(title:"型")[ - `int8`/`int16`/`int32`/`int64`: 整数 - `uint8`/`uint16`/`uint32`/`uint64`: 非負整数 - `int`: `int32`か`int64`(システムのbitにより異なる) - `float32`/`float64`: 浮動小数点数 - `complex64`/`complex128`: 虚数 - `byte`: 1バイトデータ(=`uint8`) - `rune`: 1文字(=`int32`) - `uintptr`: ポインタを表現するのに十分な非負整数 - `string`: 文字列 - `bool`: 真偽値 ] #slide(title: "型変換")[ - `型名()`で型変換を行うことができる main.go ```go var hoge uint32 = 8110 fmt.Printf("%T\n", hoge) // uint32 var huga uint64 = uint64(hoge) fmt.Printf("%T\n", huga) // uint64 ``` ] #slide(title: "Printf関数")[ - `fmt.Printf`関数では引数をフォーマットして文字列として出力する. - 個人的によく使う形式は以下の通り ```text %v(デフォルト), %s(文字列), %e(浮動小数点数), %f(小数), %d(整数), %T(型表示), %p(ポインタ) ``` ] #slide(title: "リテラル")[ データの表現方法を色々と工夫できる ```text nil 無しを表す値 true 真 false 偽 1234, 1_064 整数(_は無視されるのでカンマの代わりに) 0b101001, 0B1101 2進数 0777, 0o757, 0O775 8進数 0xFFFF, 0XFF12 16進数 3.14 小数 1.21e5, 3.141E6 浮動小数点数 1.33i 虚数 "Hello" 文字列 'E' 文字(rune型) ``` ] #new-section-slide("Section 9. Goとデータ構造") #slide(title: "配列")[ コンパイル時に個数が決定されるものが*配列* == 写経タイム `Go1.pdf` ```go var arr1 = [3]string{} // 配列宣言 arr1[0] = "りんご" arr1[1] = "バナナ" arr1[2] = "CL7 Honda ACCORD Euro R" arr2 := [3]int{3, 1, 8} // :=での宣言も可能 // 出力 for i := 0; i < 3; i++ { fmt.Printf("%s = %d\n", arr1[i], arr2[i]) } // 宣言時に個数が決まっているのであれば[...]でもOk arr3 := [...]int64{1000, 1500, 1600, 1050, 1150, 1550, 1650, 1100} fmt.Printf("%v\n", arr3) ``` ] #slide(title: "スライス")[ 個数を途中で変更可能なものをスライスと呼ぶ = 配列との違い - メモリ効率や速度が低下する - 配列よりも便利 == 写経タイム `Go2.pdf` // OK: 写経用PDFの作成 ```go arr := []string{} // 個数未決定のスライス arr = append(arr, "Microsoft Window") arr = append(arr, "Apple macOS") arr = append(arr, "GNU/Linux") arr = append(arr, "FreeBSD") fmt.Println("長さ: ", len(arr)) fmt.Println("キャパ: ", cap(arr)) mk := make([]byte, 0, 114514) // make()によるメモリ確保 fmt.Println("長さ: ", len(mk)) fmt.Println("キャパ: ", cap(mk)) ``` ] #slide(title: "マップ")[ - 所謂、連想配列・辞書型 - (key, value)の形で保存されるスライス - keyで検索してvalueを得る == 写経タイム `Go3.pdf` ```go // 今回はコメント書かなくてOKです package main import "fmt" func main() { // 3大都市の連想配列 mp := map[string]bool{ "Tokyo": true, "Osaka": true, "Nagoya": false, } fmt.Printf("%v\n", mp) // 一旦表示してみる mp["Fukuoka"] = false // 福岡を追加 fmt.Printf("%v\n", mp) delete(mp, "Nagoya") // 名古屋は3大都市引退したほうが良いと思う(爆) fmt.Printf("%v\n", mp) fmt.Println("長さ=", len(mp)) // mapの長さを確認 _, ok := mp["Osaka"] // 大阪が存在するかどうか if ok { fmt.Println("ok") } else { fmt.Println("Not found") } for k, v := range mp { fmt.Printf("%s=%t\n", k, v) } } ``` ] #slide(title: "構造体")[ - Goには *classが無い* - structに対してメソッドの実装を行うことはできる(structがclassの一部機能を有している) ] // TODO: マップ // TODO: 構造体
https://github.com/SillyFreak/typst-scrutinize
https://raw.githubusercontent.com/SillyFreak/typst-scrutinize/main/docs/manual.typ
typst
MIT License
#import "template.typ" as template: * #import "/src/lib.typ": grading, task, solution, task-kinds #let package-meta = toml("/typst.toml").package #let date = datetime(year: 2024, month: 10, day: 12) #show: manual( title: "Scrutinize", // subtitle: "...", authors: package-meta.authors.map(a => a.split("<").at(0).trim()), abstract: [ _Scrutinize_ is a library for building exams, tests, etc. with Typst. It provides utilities for common task types and supports creating grading keys and sample solutions. ], url: package-meta.repository, version: package-meta.version, date: date, ) // the scope for evaluating expressions and documentation #let scope = (grading: grading, task: task, solution: solution, task-kinds: task-kinds) #let example(code, lines: none, cheat: none) = { // eval can't access the filesystem, so no imports. // for displaying, we add the imports; for running, we have the imported entries in `scope` let code-to-display = crudo.join( main: -1, crudo.map( ```typ #import "@preview/NAME:VERSION": grading, task, solution, task-kinds ```, line => line.replace("NAME", package-meta.name).replace("VERSION", package-meta.version), ), code, ) if lines != none { code-to-display = crudo.lines(code-to-display, lines) } let code-to-run = if cheat == none { code.text } else { // for when just executing the code as-is doesn't work in the docs cheat.text } set heading(numbering: none, outlined: false) show: task.scope [ #code-to-display #preview-block(eval(code-to-run, mode: "markup", scope: scope)) ] } #let task-example(task, lines: none) = { let cheat = crudo.join( main: 1, ```typ #let q = [ ```, task, ```typ ] #grid( columns: (1fr, 1fr), column-gutter: 1em, solution.with(false, q), solution.with(true, q), ) ```, ) example(task, lines: lines, cheat: cheat) } #(scope.task-example = task-example) = Introduction _Scrutinize_ has three general areas of focus: - It helps with grading information: record the points that can be reached for each task and make them available for creating grading keys. - It provides a selection of task authoring tools, such as multiple choice or true/false questions. - It supports the creation of sample solutions by allowing to switch between the normal and "pre-filled" exam. Right now, providing a styled template is not part of this package's scope. = Tasks and task metadata Let's start with a really basic example that doesn't really show any of the benefits of this library yet: #example(```typ // you usually want to alias this, as you'll need it often #import task: t = Task #t(points: 2) #lorem(20) ```) After importing the library's modules and aliasing an important function, we simply get the same output as if we didn't do anything. The one peculiar thing here is ```typc t(points: 2)```: this adds some metadata to the task. Any metadata can be specified, but `points` is special insofar as it is used by the `grading` module by default. A lot of scrutinize's features revolve around using that metadata, and we'll soon see how. A task's metadata is a dictionary with the following fields: - `data`: the explicitly given metadata of the task, such as ```typc (points: 2)```. - `heading`: the heading that identifies the task, such as ```typ = Task```. - `subtasks`: an array of nested tasks, identified by nested headings. When getting task metadata, you can limit the depth; this is only present as long as the depth is not exceeded. Let's now look at how to retrieve metadata. Let's say we want to show the points in each task's header: #example(lines: "5-8", ```typ // you usually want to alias this, as you'll need it often #import task: t #show heading: it => { // here, we need to access the current task's metadata block[#it.body #h(1fr) / #task.current().data.points P.] } = Task #t(points: 2) #lorem(20) ```) Here we're using the #ref-fn("task.current()") function to access the metadata of the current task. This function requires #link("https://typst.app/docs/reference/context/")[context] to know where in the document it is called, which a show rule already provides. The function documentation contains more details on how task metadata can be retrieved. == Subtasks Often, exams have not just multiple tasks, but those tasks are made up of several subtasks. Scrutinize supports this, and reuses Typst's heading hierarchy for subtask hierarchy. Let's say some task's points come from its subtasks' points. This could be achieved like this: #example(lines: "5-", ```typ // you usually want to alias this, as you'll need it often #import task: t #show heading.where(level: 1): it => { let t = task.current(level: 1, depth: 2) block[#it.body #h(1fr) / #grading.total-points(t.subtasks) P.] } #show heading.where(level: 2): it => { let t = task.current(level: 2) block[#it.body #h(1fr) / #t.data.points P.] } = Task #lorem(20) == Subtask A #t(points: 2) #lorem(20) == Subtask B #t(points: 1) #lorem(20) ```) In this example, #ref-fn("task.current()") is used in conjunction with #ref-fn("grading.total-points()"), which recursively adds all points of a list of tasks and its subtasks. More about this function will be said in the next section, and of course in the function's reference. #pagebreak(weak: true) = Grading The next puzzle piece is grading. There are many different possibilities to grade an exam; Scrutinize tries not to be tied to specific grading strategies, but it does assume that each task gets assigned points and that the grade results from looking at some kinds of sums of these points. If your test does not fit that schema, you can simply ignore the related features. The first step in creating a typical grading scheme is determining how many points can be achieved in total, using #ref-fn("grading.total-points()"). We also need to use #ref-fn("task.all()") (with the `flatten` parameter) to get access to the task metadata distributed throughout the document: #example(lines: "12-", ```typ // you usually want to alias this, as you'll need it often #import task: t // let's show the available points to the right of each // task's title and give the grader a space to put points #show heading: it => { // here, we need to access the current task's metadata block[#it.body #h(1fr) / #task.current().data.points] } #context [ #let ts = task.all(flatten: true) #let total = grading.total-points(ts) #let hard = grading.total-points(ts.filter(t => t.data.points >= 5)) Total points: #total \ Points from hard tasks: #hard ] = Hard Task #t(points: 6) #lorem(20) = Task #t(points: 2) #lorem(20) ```) Once we have the total points of the exam figured out, we need to define the grading key. Let's say the grades are in a three-grade system of "bad", "okay", and "good". We could define these grades like this: #example(lines: "12-19", ```typ // you usually want to alias this, as you'll need it often #import task: t // let's show the available points to the right of each // task's title and give the grader a space to put points #show heading: it => { // here, we need to access the current task's metadata block[#it.body #h(1fr) / #task.current().data.points] } #context [ #let total = grading.total-points(task.all(flatten: true)) #grading.grades( [bad], total * 2/4, [okay], total * 3/4, [good], ) ] = Hard Task #t(points: 6) #lorem(20) = Task #t(points: 2) #lorem(20) ```) Obviously we would not want to render this representation as-is, but #ref-fn("grading.grades()") gives us a convenient way to have all the necessary information, without assuming things like inclusive or exclusive point ranges. The example in the gallery has a more complete demonstration of a grading key. One thing to note is that #ref-fn("grading.grades()") does not process the limits of the grade ranges; they're simply passed through. If you prefer to ignore total points and instead show percentages, or want to use both, that is also possible: #example(lines: "3-", ```typ #let total = 8 #grading.grades( [bad], (points: total * 2/4, percent: 50%), [okay], (points: total * 3/4, percent: 75%), [good], ) ```) #pagebreak(weak: true) = Task templates and sample solutions With the test structure out of the way, the next step is to actually define tasks. There are endless ways of posing tasks, but some recurring formats come up regularly. #pad(x: 5%)[ _Note:_ customizing the styles is currently very limited/not possible. I would be interested in changing this, so if you have ideas on how to achieve this, contact me and/or open a pull request. Until then, feel free to "customize using copy/paste". The MIT license allows you to do this. ] Tasks have a desired response, and producing sample solutions can be made very convenient if they are stored with the task right away. To facilitate this, this package provides - #ref-fn("solution._state"): this boolean state controls whether solutions are currently shown in the document. Some methods have convenience functions on the module level to make accessing them easier: #ref-fn("solution.get()"), #ref-fn("solution.update()"). - #ref-fn("solution.answer()"): this function uses the solution state to conditionally hide the provided answer. - #ref-fn("solution.with()"): this function sets the solution state temporarily, before switching back to the original state. // The `small-example.typ` example in the gallery uses this to show a solved example task at the beginning of the document. Additionally, the solution state can be set using the Typst CLI using `--input solution=true` (or `false`, which is already the default). Within context expressions, a task can use ```typ #solution.get()``` or ```typ #solution.answer()``` to find out whether solutions are shown. This is also used by Scrutinize's task templates. Let's look at a free form question as a simple example: == Free form questions In free form questions, the student simply has some free space in which to put their answer: #task-example(```typ #import task-kinds: free-form // toggle the following comment or pass `--input solution=true` // to produce a sample solution // #solution.update(true) Write an answer. #free-form.plain[An answer] Next question ```) Left is the unanswered version, right the answered one. Note that the answer occupies the same space regardless of whether it is displayed or not, and that the height can also be overridden - see #ref-fn("free-form.plain()"). The content of the answer is of course not limited to text; for example, the task could be to complete a diagram. The `placeholder` parameter is particularly useful for that, and the `stretch` parameter can be used to give students more space to write their solution than a printed version would take: #task-example(lines: "8-", ```typ #import task-kinds: free-form // toggle the following comment or pass `--input solution=true` // to produce a sample solution // #solution.update(true) Connect the nodes. #free-form.plain(stretch: 200%, { stack(dir: ltr, spacing: 1cm, circle(radius: 3mm), circle(radius: 3mm)) place(horizon, dx: 6mm, line(length: 1cm)) }, placeholder: { stack(dir: ltr, spacing: 1cm, circle(radius: 3mm), circle(radius: 3mm)) }) Next question ```) There are also variations of the free-form question that use pre-printed lines or grids: #task-example(lines: "8-", ```typ #import task-kinds: free-form // toggle the following comment or pass `--input solution=true` // to produce a sample solution // #solution.update(true) Do something here. #grid( columns: (1fr, 1fr), column-gutter: 0.5em, // 180% line height, 200% line count free-form.lines(stretch: 180%, count: 200%, lorem(5)), // solution needs four grid lines, six are printed free-form.grid(stretch: 133%, pad(5mm, line(end: (10mm, 10mm)))), ) Next question ```) == fill-in-the-gap questions Related to free form questions are questions where the answer goes into a gap in the text. See #ref-fn("gap.gap()") for details. #task-example(```typ #import task-kinds.gap: gap This question is #gap(stretch: 180%)[easy]. $ sin(0) = #gap(stroke: "box")[$0$] $ ```) == single and multiple choice questions These taks types allow making a mark next to one or multiple choices. See #ref-fn("choice.single()") and #ref-fn("choice.multiple()") for details. #task-example(```typ #import task-kinds: choice Which of these is the fourth answer? #choice.single( range(1, 6).map(i => [Answer #i]), // 0-based indexing 3, ) Which of these answers are even? #choice.multiple( range(1, 6).map(i => ([Answer #i], calc.even(i))), ) ```) #pagebreak(weak: true) = Module reference // #module( // "scrutinize", // read("/src/lib.typ"), // label-prefix: none, // scope: scope, // ) #module( read("/src/task.typ"), name: "scrutinize.task", label-prefix: "task", scope: scope, ) #module( read("/src/grading.typ"), name: "scrutinize.grading", label-prefix: "grading", scope: scope, ) #module( read("/src/solution.typ"), name: "scrutinize.solution", label-prefix: "solution", scope: scope, ) #module( read("/src/task-kinds/choice.typ"), name: "scrutinize.task-kinds.choice", label-prefix: "choice", scope: scope, ) #module( read("/src/task-kinds/free-form.typ"), name: "scrutinize.task-kinds.free-form", label-prefix: "free-form", scope: scope, ) #module( read("/src/task-kinds/gap.typ"), name: "scrutinize.task-kinds.gap", label-prefix: "gap", scope: scope, )
https://github.com/noahjutz/AD
https://raw.githubusercontent.com/noahjutz/AD/main/notizen/sortieralgorithmen/mergesort/merge_input.typ
typst
#import "/components/num_row.typ": single_num_row, arrowed, braced_b #let nums = (12, 23, 34, 34, 45, 7, 17, 18, 38, 43) #let n = nums.len() #let m = calc.div-euclid(n, 2) #single_num_row( nums, labels: ( (0, 1, arrowed[`f`]), (m, m + 1, arrowed[`m`]), (n - 1, n, arrowed(`l`)), ), labels_b: ( (0, m, braced_b[`a1`]), (m, n, braced_b[`a2`]) ), hl_primary: range(m), hl_secondary: range(m, n) )
https://github.com/BackThePortal/typst-plugin-jetbrains
https://raw.githubusercontent.com/BackThePortal/typst-plugin-jetbrains/main/CHANGELOG.md
markdown
<!-- Keep a Changelog guide -> https://keepachangelog.com --> # typst-plugin-jetbrains Changelog ## [Unreleased] ### Added - Initial scaffold created from [IntelliJ Platform Plugin Template](https://github.com/JetBrains/intellij-platform-plugin-template)
https://github.com/tingerrr/masters-thesis
https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/de/thesis.typ
typst
#import "@local/chiral-thesis-fhe:0.1.0" as ctf #import ctf.prelude: * #import "/src/util.typ" #show "C++": util.cpp // convenient smallcaps for simple author names #show regex("![A-Za-z]{2,}\b"): it => smallcaps(it.text.slice(1)) #show: doc( kind: masters-thesis( id: [AI-2024-MA-005], title: [Dynamische Datenstrukturen unter Echtzeitbedingungen], author: "<NAME>. <NAME>", supervisors: ( "Prof. Dr. <NAME>", "Dipl-Ing. <NAME>", ), date: datetime(year: 2024, month: 10, day: 09), field: [Angewandte Informatik], ), draft: false, abstracts: ( (title: [Kurzfassung], body: [ Die Verwendung dynamischer Datenstrukturen unter Echtzeitbedingungen muss genau geprüft werden um sicher zustellen, dass ein Echtzeitsystem dessen vorgegebene Aufgaben in der erwarteten Zeit erfüllen kann. Ein solches Echtzeitsystem ist das Laufzeitsystem der T4gl-Progrmmiersprache, eine Domänenspezifische Sprache für Industrieprüfmaschinen. In dieser Arbeit wird untersucht, auf welche Weise die in T4gl verwendeten Datenstrukturen optimiert oder ausgetauscht werden können, um das Zeitverhalten unter Worst Case Bedingungen zu verbessern. Dabei werden vorallem persistente Datenstrukturen implementiert, getestet und verglichen. ]), (title: [Abstract], body: [ The usage of dynamic data structures under real time constraints must be analyzed precisely in order to ensure that a real time system can execute its tasks in the expected time. Such a real time system is the runtime of the T4gl programming language, a domain-specific language for industrial measurement machines. This thesis is concerned with the analysis, optimization and re-implementation of T4gl's data structures, in order to improve their worst-case time complexity. For this, various, but foremost persistent data structures are implemented, benchmarked and compared. ]), ), outlines: ( (target: image, title: [Abbildungsverzeichnis]), (target: table, title: [Tabellenverzeichnis]), (target: raw, title: [Listingverzeichnis]), ), outlines-position: start, bibliography: bibliography("/src/bib.yaml", title: "Literatur"), acknowledgement: [ Ich bedanke mich bei <NAME> für die wissenschaftliche Genauigkeit seines Feedbacks und die viele Zeit die er trotz vieler andere Pflichten in zahllose Rücksprachetermine investiert hat. Durch sein genaues Hinsehen wurden viele Fehler gefunden, welche gerade bei Änderungen schnell vergessen werden. Gleichermaßen bedanke ich mich bei <NAME> und <NAME> für deren Betreuung von seiten der Firma Brückner und Jarosch Ingeneugesellschaft mbH (BJ-IG). Ihre Unterstüzung, Zeit und Vorschläge haben dann geholfen venn Ergebnisse unrealistisch oder Beweise unmöglich erschienen. Desweiteren bedanke ich mich bei allen Problelesern, welche mir die Fehler gezeigt haben, welche man als Autor nach dem 30. mal Lesen des eigenen Texts nicht mehr sieht. Ohne die Unterstütung meiner Kollegen bei BJ-IG, meine probelesenden Freunde und Betreuer wäre ich nicht so weit gekommen. Ich bedanke mich bei allen Freunden und Familienmitgliedern, welche einfach nur da waren, wenn ich an etwas anderes denken wollte als der herannahende Abgabe Termin. In der Hoffnung, dass ich schon morgen anderen so helfen kann wie sie mir geholfen haben, danke! ], ) #set grid.cell(breakable: false) #show figure.where(kind: "algorithm"): set grid.cell(breakable: true) #show figure.where(kind: "algorithm"): set par(justify: false) #set raw(syntaxes: "/assets/t4gl.sublime-syntax") #chapter(label: <chap:intro>)[Einleitung] #include "chapters/1-intro.typ" #chapter(label: <chap:t4gl>)[T4gl] #include "chapters/2-t4gl.typ" #chapter(label: <chap:non-solutions>)[Lösungsansätze] #include "chapters/3-non-solutions.typ" #chapter(label: <chap:persistence>)[Persistente Datastrukturen] #include "chapters/4-persistent-data-structures.typ" #chapter(label: <chap:impl>)[Implementierung] #include "chapters/5-implementation.typ" #chapter(label: <chap:benchmarks>)[Analyse & Vergleich] #include "chapters/6-benchmarks.typ" #chapter(label: <chap:conclusion>)[Fazit] #include "chapters/7-conclusion.typ"
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/declaration.typ
typst
#let m = yaml("/metadata.yml") = Declaration The group declares that all content presented in this #m.doc_type, as well as the source code, is our original work - with the exception of referenced knowledge and sample source code provided by the manufacturer. We have not copied from any other source. If this declaration is found to be false, the group accepts full responsibility before the Department Chair and the University President. #align(right)[The student group that implements the #m.doc_type]
https://github.com/QuadnucYard/cpp-coursework-template
https://raw.githubusercontent.com/QuadnucYard/cpp-coursework-template/main/docs/cody-doc.typ
typst
#{ import "@preview/tidy:0.2.0" import "../cody.typ" let my-module = tidy.parse-module(read("../cody.typ"), name: "cody", scope: (cody: cody)) tidy.show-module(my-module, sort-functions: none) }
https://github.com/mem-courses/calculus
https://raw.githubusercontent.com/mem-courses/calculus/main/convert-svg-slot-before-body.typ
typst
// #{ set page( width: /* slot: page-width */, height: auto, margin: (left: 0pt, right: 0pt, top: 5pt, bottom: 5pt), numbering: none, header: { }, footer: { }, ) // }
https://github.com/Myriad-Dreamin/tinymist
https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/folding_range/heading-in-multiple-content.typ
typst
Apache License 2.0
#let slides(..args) = args #slides()[ = Heading ][ ]
https://github.com/flavio20002/cyrcuits
https://raw.githubusercontent.com/flavio20002/cyrcuits/main/tests/rc4/test.typ
typst
Other
#import "../../lib.typ": * #set page(width: auto, height: auto, margin: 0.5cm) #show: doc => cyrcuits( scale: 1, doc, ) ```circuitkz \begin{circuitikz} \draw (0,0) to[battery1,l=$E_"Th"$] ++ (0,3) to[R=$R_"Th"$] ++ (3,0) to[C,l_=$C$,v^=$v_C$,f>_=$i_C$] ++ (0,-3) to[short] ++ (-3,0); \end{circuitikz} ```
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/examples/example.typ
typst
Apache License 2.0
#import "../lib.typ": * #set page(width: 500pt, height: auto, margin: 1em) #assert.eq(mitex-convert("\alpha x"), "alpha x ") Write inline equations like #mi("x") or #mi[y]. Also block equations (this case is from #text(blue.lighten(20%), link("https://katex.org/")[katex.org])): #mitex(```latex \newcommand{\f}[2]{#1f(#2)} \f\relax{x} = \int_{-\infty}^\infty \f\hat\xi\,e^{2 \pi i \xi x} \,d\xi ```) We also support text mode (in development): #mitext(```latex \iftypst #set math.equation(numbering: "(1)", supplement: "Equation") \fi \section{Title} A \textbf{strong} text, a \emph{emph} text and inline equation $x + y$. Also block \eqref{eq:pythagoras} and \ref{tab:example}. \begin{equation} a^2 + b^2 = c^2 \label{eq:pythagoras} \end{equation} \begin{table}[ht] \centering \begin{tabular}{|c|c|} \hline \textbf{Name} & \textbf{Age} \\ \hline John & 25 \\ Jane & 22 \\ \hline \end{tabular} \caption{This is an example table.} \label{tab:example} \end{table} ```)
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/layout/par-bidi-03.typ
typst
Other
// Test embedding up to level 4 with isolates. #set text(dir: rtl) א\u{2066}A\u{2067}Bב\u{2069}?
https://github.com/nafkhanzam/typst-common
https://raw.githubusercontent.com/nafkhanzam/typst-common/main/src/templates/drpm/lib.typ
typst
#import "../../common/currency.typ": * #import "../../common/dates.typ": * #let outline-entry-fn(prefix-count, start-level: 1) = ( it => { let loc = it.element.location() let num = numbering(loc.page-numbering(), ..counter(page).at(loc)) let prefixed = it.body.at("children", default: ()).len() > 1 let body = it.body if prefixed { body = it.body.at("children").slice(1 + prefix-count).join() } link( loc, box( grid( columns: 3, gutter: 0pt, { for _ in range(it.level - start-level) { box(width: 1em) } if prefixed { it.body.at("children").slice(0, 1 + prefix-count).join() h(4pt) } }, [#body#box(width: 1fr)[#it.fill]], align(bottom)[#num], ), ), ) } ) #let sym_ = body => { show: text.with(fallback: true) body } #let template(pintorita: false, ref-style: "apa", appendices: none, body) = { set page( paper: "a4", margin: 3cm, number-align: right, ) set par(justify: true, leading: 1em, linebreaks: "optimized") set text( font: "FreeSerif", size: 12pt, fallback: false, hyphenate: false, lang: "id", ) set enum(indent: 1em, spacing: 1.5em, tight: false) set block(below: 1.5em) set heading(numbering: (num1, ..nums) => { if nums.pos().len() == 0 { [BAB #numbering("I", num1)] + "\t" h(10pt, weak: true) } else { numbering("1.1", num1, ..nums) h(7pt, weak: true) } }) set bibliography(style: ref-style) show figure.caption: set text(size: 10pt) if pintorita { import "@preview/pintorita:0.1.0" show raw.where(lang: "pintora"): it => pintorita.render(it.text) } show table: it => { set par(justify: false) set text(size: 10pt) // set align(left) it } set grid(gutter: 1em) show grid: it => { set par(justify: false) set align(left) it } show outline.entry: outline-entry-fn(1) show heading: it => { if it.level == 1 { set align(center) set text(size: 18pt, weight: "bold") it v(1.5em, weak: true) } else { set align(left) set text(size: 12pt, weight: "bold") it v(1.5em, weak: true) } } body if appendices != none { set page(numbering: "1") counter(heading).update(0) set heading( supplement: "Lampiran", numbering: (..nums) => { let arr = nums.pos() if arr.len() == 0 { [] } else if arr.len() == 1 { [LAMPIRAN #numbering("1", ..arr).] + "\t" } else { numbering("1.", ..arr.slice(1)) } }, ) show heading.where(level: 2): set heading(outlined: false) appendices } } #let fig-img(img, caption: none, ..args) = figure( img, kind: "gambar", supplement: "Gambar", caption: caption, ..args, ) #let fig-tab(tab, caption: none, ..args) = figure( tab, kind: "tabel", supplement: "Tabel", caption: figure.caption(position: top, caption), ..args, ) #let budget-template(data, extend: true) = [ #for (i, bd) in data.budget.enumerate() { set text(size: 11pt) let title-i = numbering("A", i + 1) show: block.with(breakable: false) show table.cell: it => { if it.y <= 1 or it.y >= bd.items.len() + 2 { strong(it) } else { it } } table( columns: if extend { (auto, 1fr, 1fr, auto, auto, auto, auto) } else { 7 }, [#title-i], table.cell(colspan: 6)[#bd.title], [No], [Komponen], [Item], [Satuan], [Volume], [Biaya satuan], [Jumlah], ..bd .items .enumerate() .map(((j, item)) => ( [#{ j + 1 }], [#item.component], [#item.item], [#item.unit], [#item.volume], table.cell(breakable: false)[#print-rp(item.price)], table.cell(breakable: false)[#box[#print-rp(item.total)]], )) .flatten(), table.cell(colspan: 6)[#align(center)[SUB TOTAL #title-i]], box[#print-rp(bd.total)], ) } *TOTAL BIAYA #print-rp(data.budget-total)* ] #let timeline-template(data) = { set text(size: 11pt) let (unit, length, ranges) = data.timeline let l = length show table.cell.where(x: 0): strong show table.cell.where(y: 0): strong table( columns: 2 * (auto,) + l * (1fr,), fill: (x, y) => if ranges.enumerate().any(((j, v)) => { let (a, b) = v.range let pos = x - 2 return j == y - 2 and a <= pos and pos <= b }) { blue.lighten(20%) } else { none }, table.cell(rowspan: 2)[No], table.cell(rowspan: 2)[Jenis Kegiatan], table.cell(colspan: l)[#unit ke], ..(() * (l - 1)), ..range(l).map(i => [#{ i + 1 }]), ..ranges .enumerate() .map(((i, v)) => ( [#{ i + 1 }], table.cell(align: left)[#v.title], l * ([],), )) .flatten(), ) } #let cover-solid(data) = [ #let cl-blue = rgb(32, 64, 106) #let cl-yellow = rgb(255, 210, 46) #set text(fill: white) #set page(fill: cl-blue, margin: 0em) #set par(justify: false) #set align(center) #show: pad.with(x: 2em) #v(1fr) #[ #set text(weight: "bold", size: 20pt) PROPOSAL \ PENGABDIAN KEPADA MASYARAKAT \ SKEMA #upper(data.schema) DANA #upper(data.funding-source) #v(1fr) #image("lambang.png", width: 2.33in) #v(1fr) #set text(size: 18pt) #upper[#data.title] Lokasi : #data.partner.address #v(1fr) ] #let write-member-entry(member) = [#member.name (#member.department/#member.faculty)] #[ #set text(size: 14pt) #text(size: 16pt)[*<NAME>:*] \ #for member in data.members [ #write-member-entry(member) \ ] ] #v(1fr) #show: pad.with(x: -2em) #block(fill: cl-yellow, width: 100%, inset: (x: 1em, y: 3em))[ #set text(fill: cl-blue) #set text(weight: "bold", size: 18pt) DIREKTORAT RISET DAN PENGABDIAN KEPADA MASYARAKAT \ INSTITUT TEKNOLOGI SEPULUH NOPEMBER \ SURABAYA #display-year ] ] #let cover-white(data) = [ #set par(justify: false) #set align(center) #let border-width = 12pt #show: body => { set page(margin: 0pt) rect( width: 100%, height: 100%, fill: none, stroke: border-width + rgb(47, 84, 150), pad(3cm - border-width, body), ) } #[ #set text(weight: "bold", size: 14pt) PROPOSAL \ SKEMA PENELITIAN #upper(data.schema) \ SUMBER DANA #upper(data.funding-source) \ TAHUN #display-year #v(1fr) #image("lambang.png", width: 2.33in) #v(1fr) #text(size: 16pt, upper(data.title)) #v(1fr) <NAME>: ] #let write-member-entry(member) = [#member.name / #member.department / #member.faculty / #member.institution] #pad(x: -1cm)[ #grid( columns: (auto, 1fr), [Ketua Peneliti],[: #write-member-entry(data.members.at(0))], [Anggota Peneliti],[: 1. #write-member-entry(data.members.at(1))], ..( data.members.slice(2).enumerate().map(((i, member)) => ( [], [#hide[: ]#{ i + 2 }. #write-member-entry(member)], )).flatten() ) ) ] #v(1fr) #[ #set text(weight: "bold", size: 12pt) DIREKTORAT RISET DAN PENGABDIAN KEPADA MASYARAKAT \ INSTITUT TEKNOLOGI SEPULUH NOPEMBER \ SURABAYA \ #display-year ] ]
https://github.com/Mufanc/hnuthss-template
https://raw.githubusercontent.com/Mufanc/hnuthss-template/main/pages/license.typ
typst
#import "/configs.typ": font, fontsize #import "/components.typ": anchor #let headline(content) = [ #set text(font: font.sans, size: fontsize.L2s) #set align(center) #content ] #let sign(role) = [ #text(role)签名:#h(11em)日期:20#h(1.5em) 年 #h(1.5em) 月 #h(1.5em) 日 ] #let checkbox = [ #box(baseline: 15%, square(size: 1em)) ] #let license = [ #show parbreak: br => v(0em) #anchor[毕业论文(设计)原创性声明和毕业论文(设计)版权使用授权书] #v(1em) #headline[湖 南 大 学] #v(2em) #headline[毕业论文(设计)原创性声明] #v(0.5em) 本人郑重声明:所呈交的论文(设计)是本人在导师的指导下独立进行研究所取得的研究成果。除了文中特别加以标注引用的内容外,本论文不包含任何其他个人或集体已经发表或撰写的成果作品。对本文的研究做出重要贡献的个人和集体,均已在文中以明确方式标明。本人完全意识到本声明的法律后果由本人承担。 #v(1.5em) #sign[学生] #v(3em) #headline[毕业论文(设计)版权使用授权书] #v(0.5em) 本毕业论文(设计)作者完全了解学校有关保留、使用论文(设计)的规定,同意学校保留并向国家有关部门或机构送交论文(设计)的复印件和电子版,允许论文(设计)被查阅和借阅。本人授权湖南大学可以将本论文(设计)的全部或部分内容编入有关数据库进行检索,可以采用影印、缩印或扫描等复制手段保存和汇编本论文(设计)。 本论文(设计)属于 #align(center)[ #box(inset: (left: 4em))[ #set par(first-line-indent: 0em) #set align(left) 1、保#h(1em)密 #checkbox,在 #box(line(length: 3em, stroke: 0.1pt)) 年解密后适用本授权书。 2、不保密 #checkbox。 #h(0.5em)(请在以上相应方框内打“√”) ] ] #v(1.5em) #sign[学生] #sign[导师] ]
https://github.com/polarkac/MTG-Stories
https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/023%20-%20Oath%20of%20the%20Gatewatch/002_Retaliation%20of%20Ob%20Nixilis.typ
typst
#import "@local/mtgstory:0.2.0": conf #show: doc => conf( "Retaliation of Ob Nixilis", set_name: "Oath of the Gatewatch", story_date: datetime(day: 30, month: 12, year: 2015), author: "<NAME> & <NAME>", doc ) #emph[The plan had worked. Together, Nissa, Jace, Gideon, and the army of Zendikari had succeeded in constructing an enormous hedron prison capable of holding an Eldrazi titan. And as of just a moment ago, Nissa had heaved the last hedron into place, trapping Ulamog, the monster that had ravaged her world.] #figure(image("002_Retaliation of Ob Nixilis/01.png", width: 100%), caption: [], supplement: none, numbering: none) #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) Standing on the floating rock next to Gideon, Nissa was at eye level with Ulamog's massive, bony faceplate. The impossibility of what they had just done threatened to send her off balance, but the cheers from the Zendikari below buoyed her up. #figure(image("002_Retaliation of Ob Nixilis/02.jpg", width: 100%), caption: [Aligned Hedron Netwrok | Art by Richard Wright], supplement: none, numbering: none) For too long, her world had been at Ulamog's disposal, careening down an inescapable path toward destruction—Bala Ged, Sejiri. But now, finally and almost inconceivably, it was the other way around. At last, it was Zendikar's turn to do the destroying. And Zendikar would show no mercy. "All right, let's start to pull back! Hold your lines!" Gideon called orders to the Zendikari below as he made his way down a rope ladder toward Sea Gate. "Keep the perimeter secure!" It was good that Gideon was in charge; the people would be safe with him at the helm, which meant Nissa was free to focus on the titan. A surge of anticipation rushed through her. She looked across the battlefield to Jace. As he met her gaze, he opened his mind to her. #emph[He's trapped like you wanted] , she said#emph[. Now it's time to destroy him] . #emph[Yes. How many more hedrons were out there buried in the bluff? ] Jace asked#emph[. ] Nissa could sense the excitement in his voice, even in her head. #emph[We're going to need another one, no, two actually. Nissa, this is going to work! I have a plan.] #emph[So do I. ] Nissa drew her sword. But before she could make her advance, Jace pushed her attention toward the hedron ring. He had recreated his superimposed, life-size illusionary diagram. #emph[With just two more hedrons to redirect the power we're channeling, I believe we'll be able to destroy the titan without ever having to touch it] .#emph[ The risk is minimal—relatively speaking. If we just...] Jace continued talking, but Nissa ceased listening. She didn't want a calculated, clinical strike. She wanted to drive her sword into Ulamog's neck. She wanted to eviscerate him. She wanted to end him, right here and right now. She had promised Jace she would not attempt to destroy the titan until he was trapped; now he was trapped. She turned to face the land, looking to the rocky bluff, and she reached out for the soul of the world. She called, and Ashaya answered. The elemental rose with a determination Nissa had not yet seen in the world. With a hope that she had never before felt. Zendikar emerged ready, finally, for freedom. #figure(image("002_Retaliation of Ob Nixilis/03.jpg", width: 100%), caption: [Ashaya, the Awoken World | Art by Raymond Swanland], supplement: none, numbering: none) Then something broke. Like a twig snapping underfoot, Ashaya cracked and faltered, pieces of her form crumbling away. Confused, Nissa reached out further, pulling harder. But Ashaya did not respond; her branches convulsed and quavered, and with her, all of Zendikar trembled. The floating rock Nissa was standing on swayed, slowly at first and then faster, violently. Nissa stumbled, thrusting her arms out for balance. The bucking and quaking was so severe that it felt as though Zendikar was going to tear itself asunder. Then, just as quickly as the quaking had begun, it stopped. The world calmed, and everything was quiet. But Nissa knew it was a false calm. Something was wrong, she could sense it, something— A ragged gnashing blasted the silence apart. To Nissa's right, the seawall and everything on it swelled like a tidal wave. Nissa watched in horror as Zendikari and Eldrazi alike were sent flailing into the air and came crashing down on the hard stone wall, only to be thrown back up again as the whole thing reared a second time. Wide-eyed and wild, Nissa turned back to Ashaya. Zendikar radiated a flood of pain and terror as the elemental crumbled into a pile of rubble. "Ashaya!" Nissa ran for her friend, but was thrown to her knees as yet another undulation heaved through the world. Out over the sea to her left, the ring of hedrons rocked as violently as the land. The leylines strained to maintain their formation as surge upon surge of rippling tremors tore across the bay. The prison was going to come undone. But it was not the rocking of the world that was putting strain on it. It was the other way around. The unsettled prison was putting a strain on the world. There, above the prison, Nissa saw a stray hedron, a dark power blasting through it, destroying the integrity of the leyline alignment. It was wrong. It shouldn't have been there. Where had it come from? Anxious, she searched out Jace. #emph[Nissa, get out of there! ] Jace's cry filled her mind as soon as he had her attention. With a great, echoing crack, one of the leylines of the prison snapped. The circle was broken. Nissa's heart stopped. #emph[Run, Nissa! Now!] But Nissa didn't run. She launched herself out toward the broken leyline. This couldn't happen. Not now. It was Zendikar's turn. As she landed on a floating rock near the breach, one of the half-freed hedrons tipped, straining its remaining connection until that connection, too, was shattered. For a breath, the great rock teetered, suspended on the last hint of the magical bond that had held it in place, and then it plummeted toward the sea. Nissa was drenched by the massive splash that followed the hedron's impact, but she didn't pause to so much as wipe her eyes. This couldn't happen. She reached out to the dangling leyline, the one that had been connected to the fallen hedron, and she pushed her feeling down into the powerful mana the leyline was made of until she could touch it. The moment she succeeded, an unbelievable surge of power rushed into her. She felt stronger than she had ever felt before. But that wasn't important. What was important was where she channeled that power. She would send it through herself and into the other dangling leyline; she would complete the broken circle using her own body. She would fix this. She reached out for the other leyline, digging down into her own well of strength to stretch herself toward its magic, pouring everything she had into her effort to close the ring. Just a little closer and— She was knocked off her feet. Nissa only saw the thick, pink tentacle after it had struck her. Ulamog. With the integrity of the prison compromised, he had been free to breach its border. #figure(image("002_Retaliation of Ob Nixilis/04.jpg", width: 100%), caption: [Ulamog, the Infinite Gyre | Art by <NAME>], supplement: none, numbering: none) The hedrons of the ring began to sway, off balance. The leylines were whipped out of her reach. Ulamog would not be contained any longer. #emph[No!] Nissa jumped up, springing for the nearest vine, this time with her sword in hand. She set her sights on the titan. This couldn't happen. Trapped or not, she would destroy Ulamog. This was Zendikar's turn. Swinging from a vine, Nissa brought her sword down on one of Ulamog's flailing tentacles. Her blade didn't so much as leave a scratch, but she didn't care. She struck again. And again. And then the rest of the ring gave way. One by one, the other hedrons plummeted into the sea. Wave after wave of salty seawater splashed up at Nissa as a cacophony of terror-laden screams sounded from behind. Ulamog, free of his bonds, was moving toward Sea Gate once more. Nissa cried out in anguish. As impossible as their initial success in trapping Ulamog had been, this end seemed all the more unthinkable. This#emph[ end] ? Was this truly the end? With that thought, a wave of weakness washed through Nissa, draining her. It was all she could do to force her fingers to hold on to the vine. #emph[Nissa, what are you doing? You have to get out of there! ] Jace's voice in her head again. He was as desperate as she had ever heard him, but she couldn't bring herself to move. #emph[Now! ] Jace cried. His anxiety didn't affect her. She stared at the water crashing below. It would be cold if she fell. #emph[The prison is broken, Nissa] , Jace's voice was quieter.#emph[ The demon broke it. There's nothing more to do. Just get out. Please.] The demon...Nissa shook herself. The demon? All at once she felt him, felt the evil of the monster he was. He was here. She looked up. There he was. The demon she had faced back on Bala Ged, the one who had uprooted Khalni Heart, the one who had tried to destroy Zendikar. He had come back. #figure(image("002_Retaliation of Ob Nixilis/05.jpg", width: 100%), caption: [Ob Nixilis Reignited | Art by Chris Rahn], supplement: none, numbering: none) Suddenly it all made sense. His was the darkness she had sensed, he was the thing that had been wrong. It was his hedron that had upset the prison, that had made the land quake. He was the cause of all of this. And now he was casting a spell, a spell so ancient and powerful that Nissa didn't recognize anything more than its vague shape and its complete and consuming darkness. With the casting of this spell, all the land of Zendikar cried out in pain. "Rise!" the demon screamed. And something rose. Nissa turned to see a row of impossibly large, glistening black shards tearing through the ground. Even before the rest of the monster so much as breached the surface, Nissa knew she was looking upon a second titan. Kozilek. The demon had called yet another horror to ravage her world. #figure(image("002_Retaliation of Ob Nixilis/06.jpg", width: 100%), caption: [Art by Lius Lasahido], supplement: none, numbering: none) She looked back up at the demon, and he smiled down at her. Smiled. Nissa shuddered, sickened, and in that moment something inside her was uprooted. Some part of her that she recognized from long ago, a piece of herself that she had tried to temper, had tried to forget. There was power in that part of her, and now it was that power that was coursing through her veins. It was not unlike the sensation of the power of the leylines surging through her, but this time she could keep it all for herself. That felt good. Her strength returned tenfold, and she climbed the vine hand over hand, pulling herself up onto the top of the floating rock above. She stood there staring at the demon. She knew that she should turn away from him. She knew that she should flee—or battle the titans, or help the people, or do anything but what she was about to do. But if she did any of those other things, would it matter? Would her actions make a difference? Was there any hope left, any last shred of hope left to save Zendikar? If she turned away from the demon, Nissa would have to answer that question. So she did not turn away from the demon. Instead, she looked straight at him, the eyeblight that had stolen her world's last chance to survive. For that, and for everything else, she would end him. She leapt down onto the thrashing seawall and raced toward the demon, her blade poised, ready to strike. It had been her mistake not to ensure that she had ended him when last they met; she would not make the same mistake again. As Kozilek rose, the seawall convulsed, the sea swelled, the land shook, and the Zendikari screamed. But that was all happening around Nissa, outside of her sphere of focus, beyond the rage that drove her forward. The only thing could see was the horrid demon, and the only thing she knew was that he was going to die. #figure(image("002_Retaliation of Ob Nixilis/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) As she fought her way past surging spawn and buckling rock toward the winged monster, Nissa was vaguely aware of the influence Kozilek was having on the world around her. She had felt this titan's influence before, back when more of his spawn populated the world. She hadn't much cared for the warping chaos then, and she was not fond of the muddled, snarled effects he was having on the leylines now. The seamless patterns that should have blanketed the world were disrupted and broken. Everything was amiss. Each step she took required a concerted effort to force her foot to contact the land, to overcome the dissection of reality, to compensate for the gravitational distortions. But she pressed forward. Nothing would stop her. And then the land in front of her erupted. Kozilek's flailing arm had smashed into the seawall, his enormous fist crashing through the rock, sending the lighthouse toppling. The impact launched Nissa into the air, along with shrapnel from the seawall and hundreds of other Zendikari. The world was turned on its head as Nissa hung there, momentarily suspended. Time slowed, and black, iridescent corruption crystallized on the shards of pure white rock and the faces of the people around her. It was as though she was trapped in a frozen pond, suffocated by the press of ice around her. Then suddenly time started again and gravity doubled or perhaps even tripled, pulling Nissa back down onto the crumbling wall with such a force that the wind was knocked out of her. She tried to stand, but it felt like she was sinking in quicksand. Everything around her was turning into jagged edges and geometric patterns that spoke of things unnatural. She blinked, but she couldn't clear her vision. It all looked the same; she could no longer distinguish between the wall, the sea, and the demon. She had fallen into Kozilek's field of distortion. She staggered, unsure of where her next step would take her, unsure of where she was or where she was going. Unsure of whether she was even still alive. Had the end come already? No. #emph[No!] It was not the end. It could not be. Not until she had destroyed him. The demon was a blemish on her perfect world. The need to remove him from Zendikar drove her forward. She pushed on, putting one foot in front of the other, breathing one breath after the next, until finally she broke free of the reach of the distortion. Liberated, Nissa raced to the end of the white rock of the seawall and out onto the cliff, straight at the demon. She dove for him, tackling him to the ground, her blade at his neck. "Good for you." He looked up at her, still smiling that revolting smile. "Finally willing to win. Finally willing to do what it takes." "You!" Bile rose in the back of Nissa's throat as she plunged her blade downward. But with one swift movement the demon skirted her sword and dislodged himself, flying up and away, at the same time sending a tide of his essence-draining magic down at Nissa. It struck her before she could get to her feet, sucking the life up out of her veins, drinking in the hatred that was fueling her. She cried out, reaching for the land, and sent a cascade of earth up toward the demon. But it never touched him; the land pivoted in the air and shot back down at her, following an unnaturally knotted and twisted bundle of leylines. Nissa rolled away, tumbling across the ground as the rubble rained on her—black and twisted detritus, unnatural and tormented. Panicked, she watched as four spawn of Kozilek's lineage skittered in between her and the demon. Had he called them? "Alas," the demon said, "my plans must take priority. Zendikar falls." He gave a slight nod, and the spawn closed in on Nissa, driving chunks of rock up around her. "And Zendikar will die." #figure(image("002_Retaliation of Ob Nixilis/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) Searing pain tore through Nissa, and she bellowed in agony. Though she hadn't meant for it to, her cry alerted Ashaya. She could feel Zendikar's concern for her as the land around her began to rise up; the world was coming to her aid. But even as it did, it was being warped, broken, and corrupted. It was being ruined. #emph[No.] Nissa could not allow it. She pushed Zendikar's soul away. Away from this distortion, away from this blight, away from her. #emph[Get back!] Ashaya didn't want to go. The world refused leave her, but Nissa forced it away. There was nothing more either of them could do. As she let go, she felt her last shred of hope contort into fear under the influence of Kozilek's spawn. Her gut wrenched. The earth, the leylines, the life of the world became so contorted and twisted that they no longer existed. As the demon laughed, the last of Nissa's reality unraveled. #v(0.35em) #line(length: 100%, stroke: rgb(90%, 90%, 90%)) #v(0.35em) I laughed at the elf's confused expression, her reality unraveling before her. I couldn't help it. It was funny. Something about the eyes. "Oh, little elf. Would you like to hear something amusing? If you had simply let me finish my work, I would have regained my spark and left your world. I didn't choose you as an enemy, but now I feel obliged to be the enemy you deserve. Kozilek's distortion will allow you to experience the last hours of Zendikar drawn out over the space of a thousand years. Suffering as I did. Normally I don't care for these kinds of theatrics, but you've earned yourself an exception." Kozilek's spawn encircled the Joraga, slicing space in such a way that no leyline could reach her, like spiders weaving a web of broken reality. She was cut off from Zendikar. Powerless. My mind strained to direct the spawn. It was possible, but I knew I was walking the blade's edge. Especially with the titan this close, I risked madness or worse. But as long as I didn't command them to do anything the titan directly opposed, I didn't think it would mind that I was borrowing a few spawn to take care of an insect that was meddling with its work. I leapt back into the sky to survey the rest of the field. It had become a rout. Glorious. Now it was time to leave this place and never return. After I had ensured that no survivors escaped Sea Gate, of course, I would leave this place and never return. Actually, that wasn't important right now. I should just #emph[leave this place and never return.] Interesting. Someone was in my head. Unacceptable. Telepaths are the absolute worst. I've had far too much experience with people trying to put things in my head that don't belong there. I had a vague directional sense pointing me toward the intruder, hidden among the fleeing soldiers below. I hurtled to the ground like a comet and blasted away the Zendikari on impact with the muddy, brine-soaked ground. A blue-robed boy stood tall, unhurt but startled; he reflexively split into dozens of mirror images. Not a bad trick. #figure(image("002_Retaliation of Ob Nixilis/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) I whispered a word: the truest name for pain that I had ever learned. In a crackling sphere around me, agony reigned. I felt it as much as he, but I was less of a stranger to pain than this boy. All of the images doubled over, but only one of them actually #emph[felt ] it. It was trivial to pick out the genuine article. I smirked as I lunged for him but shuddered as he met my gaze. Those eyes hit me like a lance. Discarding subtlety, he assaulted my senses as hard as he could, but that just meant my fist broke his cheekbone instead of taking his head off as I'd intended. He spun to the ground, crumpling into a heap of mud-splattered robes. I stepped forward to snap his neck and be done with it. Something gripped my wing from behind and tossed me back away from him, shredding the wing in the process. I landed painfully and looked up to see my foe. Though he could have followed up with a second blow before I saw it coming, he had waited. Tall, thick, square-jawed, and determined. A good-looking fellow by most standards. I chuckled as I sized him up. He was willing to strike me from behind to save his friend but wasn't willing to #emph[win ] a fight that way. I liked him immediately. A #emph[hero] . I inclined my head to him slightly. "Ob Nixilis. A pleasure. Now, I would ask you to kindly step aside and walk home. You have the look of a general about you, so you must know this war is lost. Was the defense here your doing? Very impressive. I'd love a rematch some time. You pick the world and the terms. But for now..." He interrupted me with a slash from his metal...quadruple...whip thing. Was he actually wielding a #emph[sural] ? Hadn't seen one of those in centuries, and never on Zendikar. Sural specialists tended to be extremely skilled, or entertainingly short-lived. I sidestepped the attack, annoyed. #figure(image("002_Retaliation of Ob Nixilis/10.jpg", width: 100%), caption: [Gideon's Reproach | Art by <NAME>cott], supplement: none, numbering: none) "These people are under my protection, demon. Stand down, or I will #emph[take ] you down." He really sounded like he meant it, too. "Disappointing. Back in my day, if you'll pardon the expression, there was a certain civility to all this. But I guess Planeswalkers aren't what they used to be. For one, they die a lot easier." I raised my palm and let loose a sustained torrent of pure enervation. And this fellow just stood there with a vexing smirk on his face and a golden glow surrounding his body. Invulnerability! This was shaping up to be more interesting than I had expected. "Not that easy," he quipped, and he charged, slashing at me in wide arcs. He charged hard but didn't overcommit on distance—he had a reach advantage, and he wasn't giving me an opening to close to a grapple. I kept him at bay with more blasts of energy; most he evaded, but a few struck home. Each time he managed to brace himself with that golden glow of his. Tactical consideration: his protection required him to focus. He had a fluid expertise with it, though. He was flawlessly weaving the shield into his series of attacks, giving me no real openings. More than once, I caught slashes on my forearms, but the wounds were superficial and healed rapidly. He kept me in a defensive posture, and he didn't bite on any of my feints. We fought back to a neutral position; he had managed to maneuver himself between me and the telepath again. "You fight well, but you can't hurt me, and I won't let you harm any more of these people. I fight for Zendikar, demon." There was plenty of determination in his voice, but I could see the beginnings of doubt edging its way around his face. That's how it always begins. "#emph[Nixilis.] " I corrected. "And you mean...these people?" I casually flicked a beam of energy into a huddle of stragglers and wounded. Six dead. He flinched as if to press the attack again, but he wouldn't leave his position defending the telepath. "Or do you mean #emph[him] ? Oh, my friend. The telepath has gotten to you, hasn't he? This is why you always kill the telepaths first. How sure are you that you're protecting him of your own free will? How sure are you that he hasn't done a little work in that head of yours?" His eyes flicked off to the side—back to the telepath—just for a moment. That brief instant was all it took for doubt to open the crack a little wider. And in that tiny moment in time, I was charging forward, and for that tiny fraction of a second, his weight was on his back foot. There are moments like this in battle, where time stands still. Where the joy of combat overwhelms the senses and the passage of time. He lashed out at me as he dropped into a wrestler's stance, but the strike was high and wide. When our eyes met, I could see that look of joy in his face as well. He loved the fight just as much as I did. Good. I wouldn't have it any other way. He dropped low to meet my charge, but I was ready for it; he tried to sweep my leg, but, with a single beat of my undamaged wing, I vaulted over him and slashed at him with a clawed hand. His shield deflected the blow, but the impact pushed him a foot farther from me than he wanted to be, and he closed with an explosive charge. I had time to brace for it and settle into a low stance. I had the superior weight and strength, but he was quicker, with a lower center of gravity. I didn't know his exact fighting style, but I was familiar enough with the general type to anticipate what was coming next. I gave him a target and he took it. He locked his legs against my knee and started to press—a perfectly executed takedown and joint lock. I was heavier than he was, but he'd still be able to break the knee in just a few seconds. I used those seconds to get control of his right arm, locking it back behind my neck as we grappled close. We splashed in the mud, blood, brine, ichor, and worse, struggling for control—and he was the better wrestler. The knee cracked and a sickening jolt pulsed through my body. The problem for him, however, was that he was expecting that to be the end of the fight, while, in fact, having my knee broken was merely the third worst sensation I had experienced in the last hour. I used my one good leg and my superior weight to pin him. He gritted his teeth, face splattered with the same mud that covered me, that covered all of us, that covered this miserable, doomed world. He channeled his focus to keep his shoulder from breaking. But I had him. I had him and he knew it. #figure(image("002_Retaliation of Ob Nixilis/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none) "You fight for Zendikar? For this broken dung-heap of a world? Well, see how it rewards you!" I pressed his face down hard into the muddy water. He thrashed and flailed, he sputtered and coughed, struggling to get purchase. I could feel the despair and fear as his hands slipped in the mud. As he batted uselessly at me. As he started to drown. Invulnerability proved no match for three inches of dirty water. "This is Zendikar! The suffering and the waste and the filth! #emph[This is Zendikar!] " He convulsed once more, and his body went limp. I held him there for a second more before I released my grip and flipped him onto his back with a splash. "This is Zendikar," I whispered. "And your fight is over."
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/dict-09.typ
typst
Other
// Error: 3-15 cannot mutate a temporary value #((key: "val").other = "some")
https://github.com/extua/nth
https://raw.githubusercontent.com/extua/nth/main/README.md
markdown
MIT No Attribution
# Nth Provides functions `#nth()` and `#nths()` which take a number and return it suffixed by an english ordinal. This package is named after the nth [LaTeX macro](https://ctan.org/pkg/nth) by <NAME>. ## Usage Include this line in your document to import the package. ```typst #import "@preview/nth:1.0.1": * ``` Then, you can use `#nth()` to markup ordinal numbers in your document. For example, `#nth(1)` shows 1st, `#nth(2)` shows 2nd, `#nth(3)` shows 3rd, `#nth(4)` shows 4th, and `#nth(11)` shows 11th. If you want the ordinal to be in superscript, use `#nths` with an 's' at the end. For example, `#nths(1)` shows 1<sup>st</sup>.
https://github.com/DaavidT/CV-2023
https://raw.githubusercontent.com/DaavidT/CV-2023/main/modules/certificates.typ
typst
Apache License 2.0
#import "../brilliant-CV/template.typ": * #cvSection("Certificaciones") #cvHonor( date: [2023], title: [Associate Oracle Cloud Infrastructure Foundations], issuer: [Oracle], ) #cvHonor( date: [2017], title: [CCNAv7: Enterprise Networking, Security, and Automation], issuer: [Cisco] ) #cvHonor( date: [2022], title: [CCNAv7: Switching, Routing, and Wireless Essentials], issuer: [Cisco] ) #cvHonor( date: [2022], title: [CCNAv7: Introduction to Networks], issuer: [Cisco] )
https://github.com/TheOnlyMrCat/tree-sitter-typst
https://raw.githubusercontent.com/TheOnlyMrCat/tree-sitter-typst/master/test.typ
typst
Apache License 2.0
#include "script.typ" #import "script.typ": * #set page( header: block( stroke: (bottom: black), inset: (top: 32pt, bottom: 0.35em), [#grid(columns: (1fr, 1fr, 1fr))[*Three*][#align(center)[*column*]][#align(right)[*header*]]] ), margin: (x: 48pt, y: 56pt) ) #let custom_block = block.with( fill: rgb("#f8f8fc"), stroke: (left: rgb("#0074d9") + 2pt), width: 100%, outset: 5pt, radius: 2pt, ) #custom_block[ Let's put some content in here ] This is my test file. How about some *bold text*. _Emphasised text?_ // A comment, even? /* A multiline block comment, that's even /* nested */ to make sure the parser works */ `Some raw text too`, and a link to https://example.com Escaped \$dollar sign. Also a #"string with an escaped \" quote in it" ```c #include <stdio.h> int main(int argc, char **argv) { puts("Hello, world!"); } ``` ````md This is also legal: ```java class Main { public static void main(String[] args) { System.out.println("Hello, world!"); } } ``` And the raw block *hasn't* terminated yet... ```` Now it has. $ "Oh look, some math" x &= (-b plus.minus sqrt(b^2-4a c))/(2a) \ x &= plus.minus 1 $
https://github.com/Pablo-Gonzalez-Calderon/chic-header-package
https://raw.githubusercontent.com/Pablo-Gonzalez-Calderon/chic-header-package/main/lib/functions.typ
typst
MIT License
/* * Chic-header - A package for Typst * <NAME> (c) 2023 * * functions.typ -- The package's file containing all the * public functions that the user can access. * * This file is under the MIT license. For more * information see LICENSE on the package's main folder. */ #import "layout.typ": * /* * chic-header * * Sets the header content * * Parameters: * - v-center: Whether to vertically align the header content, or not * - side-width: Custom width for sides (can be an array or length) * - left-side: Content that goes at the left side * - center-side: Content that goes at the center * - right-side: Content that goes at the right side */ #let chic-header(v-center: false, side-width: none, left-side: none, center-side: none, right-side: none) = { return ( chic-type: "header", value:[ #chic-grid(v-center: v-center, side-width, left-side, center-side, right-side) ] ) } /* * chic-footer * * Sets the footer content * * Parameters: * - v-center: Whether to vertically align the header content, or not * - side-width: Custom width for sides (can be an array or length) * - left-side: Content that goes at the left side * - center-side: Content that goes at the center * - right-side: Content that goes at the right side */ #let chic-footer(v-center: false, side-width: none, left-side: none, center-side: none, right-side: none) = { return ( chic-type: "footer", value:[ #chic-grid(v-center: v-center, side-width, left-side, center-side, right-side) ] ) } /* * chic-styled-separator * * Returns a styled separator for chic-separator() * * Parameters: * - color: Separator color * - style: Separator to return */ #let chic-styled-separator(color: black, style) = { if style == "double-line" { return block(width: 100%)[ #block(spacing: 0pt, line(length: 100%, stroke: color)) #v(2.5pt) #block(spacing: 0pt, line(length: 100%, stroke: color)) ] } else if style == "bold-center" { return block(width: 100%)[ #line(length: 100%, stroke: color) #place( center, dy: -1.5pt, rect( width: 10%, height: 3pt, radius: 5pt, fill: color ) ) ] } else if style == "center-dot" { return align( center + horizon, stack( dir: ltr, spacing: 3pt, path( fill: color, stroke: color, closed: true, (0pt, 0pt), (50% - 10pt, 1.5pt), ((50% - 8pt, 0pt), (0pt, 1.5pt)), (50% - 10pt, -1.5pt) ), circle(radius: 5pt, fill: color), path( fill: color, stroke: color, closed: true, (50% - 10pt, 0pt), (2pt, 1.5pt), ((0pt, 0pt), (0pt, 1.5pt)), (2pt, -1.5pt) ), ) ) } else if style == "flower-end" { let branch = move( dy: 3.5pt, path( closed: false, fill: color, (50% - 16pt, -1pt), ((13pt, -1pt), (5pt, 0pt)), ((7pt, -7pt), (0pt, 0pt), (-2pt, 2pt)), ((5pt, -2pt), (-1pt, -1pt), (-3pt, 0pt)), (0pt, 0pt), ((5pt, 2pt), (-3pt, 0pt), (-1pt, 1pt)), ((7pt, 7pt), (-2pt, -2pt), (0pt, 0pt)), ((13pt, 1pt), (-5pt, 0pt)), (50% - 16pt, 1pt), ) ) return align( center + horizon, stack( dir: ltr, spacing: 3pt, branch, rect(height: 2pt, width: 2pt, fill: color), rect(height: 2pt, width: 16pt, fill: color), rect(height: 2pt, width: 2pt, fill: color), rotate(180deg, branch) ) ) } else { panic("Invalid styled separator was requested. Possible options are `'double-line'`, `'bold-center'`, `'center-dot'` and `'flower-end'`") } } /* * chic-separator * * Sets the separator for either the header, the footer or both * * Parameters: * - on: Where to apply the separator: "header", "footer" or "both" * - outset: Space around the separator beyond the page margins * - gutter: Space around the separator * - sep: Separator, it can be a stroke or length for creating a line, * or a `line()` element created by the user */ #let chic-separator(on: "both", outset: 0pt, gutter: .65em, sep) = { assert(on in ("both", "header", "footer"), message: "`on` must receive the strings `'both'`, `'header'` or `'footer'`.") if type(sep) == content { // It's a custom separator return ( chic-type: "separator", on: on, value: block(width: 100% + (2 * outset), spacing: gutter, sep) ) } else if type(sep) == stroke or type(sep) == length { // It's a line stroke return ( chic-type: "separator", on: on, value: block(width: 100% + (2 * outset), spacing: gutter, line(length: 100%, stroke: sep)) ) } else { panic("Invalid separator was given in `chic-separator()`") } } /* * chic-height * * Sets the height of either the header, the footer or both * * Parameters: * - on: Where to change the height: "header", "footer" or "both" * - value: New height */ #let chic-height(on: "both", value) = { if type(value) in (length, ratio, relative) { return ( chic-type: "margin", on: on, value: value ) } } /* * chic-offset * * Sets the offset of either the header, the footer or both (relative * to the page content) * * Parameters: * - on: Where to change the offset: "header", "footer" or "both" * - value: New offset */ #let chic-offset(on: "both", value) = { if type(value) in (length, ratio, relative) { return ( chic-type: "offset", on: on, value: value ) } } /* * chic-page-number * * Returns the current page number */ #let chic-page-number() = { return locate(loc => { loc.page() }) } /* * chic-heading-name * * Returns the next heading name in the `dir` direction. The * heading must has a lower or equal level than `level`. If * there're no more headings in that direction, and `fill` is * ``true``, then headings are seek in the other direction. * * Parameters: * - dir: Direction for searching the next heading: "next" (get * the next heading from the current page) or "prev" (get * the previous heading from the current page). * - fill: If there's no headings in the `dir` direction, try to * get a heading in the opposite direction. * - level: Up to what level of headings should this function * search */ #let chic-heading-name(dir: "next", fill: false, level: 2) = locate(loc => { let headings = array(()) // Array for storing headings // Get all the headings in the given direction if dir == "next" { headings = query( selector(heading).after(loc), loc ).rev() } else if dir == "prev" { headings = query( selector(heading).before(loc), loc ) } // If no headings were found, try the other direction if `fill` is true if headings.len() == 0 and fill { if dir == "next" { headings = query( selector(heading).before(loc), loc ) } else if dir == "prev" { headings = query( selector(heading).after(loc), loc ).rev() } } // Now, get the proper heading (i.e. right ``level`` value) // until the headings array is empty let found = false let return-heading = none while not found and headings.len() > 0 { return-heading = headings.pop() // Check the level of the fetched heading if return-heading.level <= level { found = true } } if found { return return-heading.body } else { return } })
https://github.com/Coekjan/parallel-programming-learning
https://raw.githubusercontent.com/Coekjan/parallel-programming-learning/master/ex-2/report.typ
typst
#import "../template.typ": * #import "@preview/cetz:0.2.2" as cetz #import "@preview/codelst:2.0.1" as codelst #show: project.with( title: "并行程序设计第 2 次作业(POSIX Thread 编程)", authors: ( (name: "叶焯仁", email: "<EMAIL>", affiliation: "ACT, SCSE"), ), ) #let data = toml("data.toml") #let lineref = codelst.lineref.with(supplement: "代码行") #let sourcecode = codelst.sourcecode.with( label-regex: regex("//!\s*(line:[\w-]+)$"), highlight-labels: true, highlight-color: lime.lighten(50%), ) #let data-time(raw-data) = raw-data.enumerate().map(data => { let (i, data) = data (i + 1, data.sum() / data.len()) }) #let data-speedup(raw-data) = data-time(raw-data).map(data => { let time = data-time(raw-data) let (i, t) = data (i, time.at(0).at(1) / t) }) #let data-table(raw-data) = table( columns: (auto, 1fr, 1fr, 1fr), table.header([*线程数量*], table.cell([*运行时间(单位:秒)*], colspan: 3)), ..raw-data.enumerate().map(e => { let (i, data) = e (str(i + 1), data.map(str)) }).flatten() ) #let data-chart(raw-data, width, height, time-max, speedup-max) = cetz.canvas({ cetz.chart.columnchart( size: (width, height), data-time(raw-data), y-max: time-max, x-label: [_线程数量_], y-label: [_平均运行时间(单位:秒)_], bar-style: none, ) cetz.plot.plot( size: (width, height), axis-style: "scientific-auto", plot-style: (fill: black), x-tick-step: none, x-min: 0, x-max: 17, y2-min: 1, y2-max: speedup-max, x-label: none, y2-label: [_加速比_], y2-unit: sym.times, cetz.plot.add( axes: ("x", "y2"), data-speedup(raw-data), ), ) }) = 实验:快速排序 == 实验内容与方法 使用 pthread 多线程编程实现快速排序算法的并行加速,并在不同线程数量下进行实验,记录运行时间并进行分析。 - 数组大小:2#super[29] - 线程数量:1 \~ 16 在程序构造过程中,有以下要点: + 为记录排序时间,使用 POSIX 的 ```c gettimeofday()``` 函数; + 依据环境变量 `PTHREAD_NUM` 来决定线程数量; + 排序后检查数组是否有序。 代码如 @code:qsort-code 所示,其中 #lineref(<line:pthread-qsort-create>) 与 #lineref(<line:pthread-qsort-join>) 为 POSIX 线程创建与同步的代码行。 #figure( sourcecode( raw(read("qsort/qsort.c"), lang: "c"), ), caption: "并行快速排序 pthread 实现代码", ) <code:qsort-code> == 实验过程 在如 @chapter:platform-info 所述的实验平台上进行实验,分别使用 1 至 16 个线程进行快速排序实验,记录运行时间,测定 3 次取平均值,原始数据如 @table:qsort-raw-data 所示。 == 实验结果与分析 #let qsort-speedup-max = data-speedup(data.qsort).sorted(key: speedup => speedup.at(1)).last() 快速排序实验测定的运行时间如 @figure:qsort-chart 中的条柱所示,并行加速比如 @figure:qsort-chart 中的折线所示,其中最大加速比在 CPU 数量为 #qsort-speedup-max.at(0) 时达到,最大加速比为 #qsort-speedup-max.at(1)。 可见随着线程数量的增加,运行时间逐渐减少,但在线程数量达到 10 后,运行时间几乎不再减少。这可能有多方面的因素: + 线程数量过多时,线程创建、同步、销毁的开销超过了并行计算的收益,导致运行时间增加。 + 划分快速排序区间时,选择划分点不够均匀,线程负载不一致,导致部分线程空闲。 #figure( data-chart(data.qsort, 12, 8.5, 50, 4.4), caption: "快速排序运行时间", ) <figure:qsort-chart> 快速排序实验中的原始数据如 @table:qsort-raw-data 所示。 #figure( data-table(data.qsort), caption: "快速排序实验原始数据", ) <table:qsort-raw-data> = 附注 == 编译与运行 代码依赖 POSIX 库,若未安装 POSIX 库,需手动安装。在准备好依赖后,可使用以下命令进行编译与运行: - 编译:```sh make```; - 运行:```sh make run```; - 可通过环境变量 ```PTHREAD_NUM``` 来指定线程数量,例如:```sh PTHREAD_NUM=8 make run```; - 清理:```sh make clean```。 == 实验平台信息 <chapter:platform-info> 本实验所处平台的各项信息如 @table:platform-info 所示。 #figure( table( columns: (auto, 1fr), table.header([*项目*], [*信息*]), [CPU], [11th Gen Intel Core i7-11800H \@ 16x 4.6GHz], [内存], [DDR4 32 GB], [操作系统], [Manjaro 23.1.4 Vulcan(Linux 6.6.26)], [编译器], [GCC 13.2.1], ), caption: "实验平台信息", ) <table:platform-info>
https://github.com/7sDream/fonts-and-layout-zhCN
https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/09-layout/layout.typ
typst
Other
#import "/template/template.typ": web-page-template #import "/template/heading.typ": chapter #import "/template/components.typ": note #import "/lib/glossary.typ": tr #show: web-page-template #chapter[ // Layout Challenges in Global Type #tr[global scripts]#tr[layout]中的挑战 ] // The previous chapters have been mainly aimed at font designers, but with some nods to those implementing shaping and layout systems. In this second half of the book, our discussion will be mainly aimed at font *consumers* - shapers, layout engines, and applications - rather than font producers, but with some nods to font designers. 之前的章节我们的关注点主要在字体设计上,附带介绍了一些#tr[shaping]和#tr[layout]系统如何实现的内容。在本书的后半部分,我们将会把焦点从字体的生产者转向字体的*消费者*,也就是#tr[shaper]、#tr[layout]引擎,以及应用程序们。当然其中也会有一些对字体设计师们有用的内容。 // As I may have mentioned once or twice by this point, the historical development of computers and the way that text has been handled has prioritized Latin assumptions about text layout. In the Latin model, things are very simple: a glyph is a square box, you line up each of the square boxes in your string of glyphs next to each other on a horizontal line in left to right order until they more or less fit on a line, you break the line at a space, and then you (possibly) make some adjustments to the line to make it fit nicely, and finally you move onto the next line which is underneath the previous one. 本书中多次提到,在计算机的发展历程中,文本处理的流程一直以拉丁语系的#tr[layout]方式为优先预设。在拉丁文的模型中,各种事情都非常简单。一个#tr[glyph]就是一个方块盒子,从#tr[glyph]序列中一个一个的取出#tr[glyph],然后沿着一条水平的线从左到右逐个排列它们即可。当这些#tr[glyph]差不多占满当前行时,就在一个空格处进行断行。然后为了让这一行看起来更舒服,(可能)会对#tr[glyph]进行一些调整,让间距更加合适。最后在当前行的下方开始新的一行,重复此流程。 // But every single one of those assumptions fails in one or other script around the world. Telugu boxes don't line up next to each other. Hebrew boxes don't go left to right. Japanese boxes sometimes line up on a vertical line, sometimes on a horizontal one. Nastaleeq boxes don't line up on a perpendicular line at all. Thai lines don't break at spaces. The next line in Mongolian is to the right of the previous one, not underneath it; but in Japanese it's to the left. 但在处理世界上的其他#tr[scripts]时,这些预设中的每一条都会有不符合的情况。泰卢固文的#tr[glyph]盒子并不沿着一条线逐个排列;希伯来文不是从左往右写的;日文有时候竖着写有时候又横着写;波斯体#tr[script]甚至是斜着写的;泰语不用空格断行;蒙文的下一行在右边而不是下方;而日文的下一行又在左边…… // What we want to do in this chapter is gain a more sophisticated understanding of the needs of complex scripts as they relate to text layout, and think about how to cater for these needs. 本章的目的是深入理解复杂#tr[scripts]在文本#tr[layout]方面的需求,并思考如何满足这些需求。 #note[ // I'm going to moralize for a moment here, and it's my book, so I can. Once upon a time, a company made a [racist soap dispenser](https://gizmodo.com/why-cant-this-soap-dispenser-identify-dark-skin-1797931773). It looked for skin reflection to see if it needed to dispense soap, and because it didn't see reflection from darker skin, it didn't work for black people. I'm sure they didn't intend to be racist, but that doesn't actually matter because [racism isn't about intention, it's about bias](https://edition.cnn.com/2014/11/26/us/ferguson-racism-or-racial-bias/index.html). 我要在这里要进行一番道德说教。这是我的书,我想写什么就写什么。从前,有一家公司制作了一个“种族歧视的洗手液机”@Fussell.WhyCan.2017。它通过检测皮肤的反射来决定是否需要挤出洗手液,但黑人无法让它工作。我确信这并非是有意的种族歧视,但是否有意并不重要。因为“种族主义不在于意图,而在于偏见”@Blake.NewThreat.2014。 // > Because they didn't think about situations beyond their own experience, and clearly didn't *test* situations beyond their own experience, those involved ended up creating a system that discriminated. What's this got to do with text layout? As it turns out, quite a lot. 他们没有考虑超出自身经验的情况,并且显然也没有在超出自身经验的情境下进行测试,所以相关人员最终设计出了一个具有歧视性的系统。那么这和文本#tr[layout]有什么关系呢?事实证明它们关系匪浅。 // > Now you're reading this book, which is a good start, because it probably means you care about global scripts. But so many programmers coming to layout think "I don't need to use an external library for this. I'll just do it myself. See, it's easy to get something working. We can add the complicated stuff later". So they write some code that works with *their* script (usually Latin), and yes, it is quite easy. They feel very pleased with themselves. Then later a user requires Arabic or Hebrew support, and they look at the problem again, and they realise it's actually not easy. So they put it off, and it never happens. 你现在在读这本书,这是一个好的开始,因为这说明你很可能是关心#tr[global scripts]的。但有太多的开发人员遇到#tr[layout]问题时会想:“这应该不需要引入一个外部库吧,我自己写一个就行。你看,它确实能正常工作。更复杂的东西就以后再说吧。”他们编写了一些能处理自己用的#tr[script](通常是拉丁文)的代码,这确实很简单,写完代码后他们心情愉悦。之后有个用户要求支持阿拉伯文或者希伯来文,这让他们再一次审视这个问题,并意识到实际上它并不简单。结果就是他们决定暂时忽略这个需求,直到永远。 // > What's the moral of this story? 1) It's no more acceptable to write a text layout system that only works for one minority script than it is to make a soap dispenser that only works for white people. 2) Don't write half-assed text layout code until you've read this chapter and realised how big a deal this global scripts stuff is, and then go and use one of the libraries we'll discuss in further chapters instead. 这个故事的寓意是什么呢?一是编写仅适用于少数#tr[scripts]的文本#tr[layout]系统,其不可接受程度不亚于制造仅适用于白人的洗手液机。二是希望在你阅读本章并意识到#tr[global scripts]处理的复杂程度前,不要草率地编写文本#tr[layout]代码。请选择使用我们在后续章节中将介绍的程序库。 ]
https://github.com/An-314/Notes-of-DSA
https://raw.githubusercontent.com/An-314/Notes-of-DSA/main/BST.typ
typst
= 更多BST == 区间树Interval Tree 看这样一个问题: _*Stabbing Query:*给定集合_ $ S = {s_i=[x_i,x'_i] | 1<=i<=n} $ _以及一个待查询的点$q_x$,目标是寻找所有的$s_i$,使得$q_x$在$s_i$的区间内,即_ $ {s_i | q_x in s_i} $ 为解决这个问题,我们引入*区间树*。 为了方便查询,我们需要进行预处理: 先找出区间端点构成的集合$P=diff S$,有$|P|=2n$。令$x_mid$为$P$中的中位数。 #figure( image("fig\BST\11.png" ,width: 70%), caption: "区间树——中位数", ) 这些集合可分成三部分,$S_"left"$是所有在$x_mid$左侧的区间,$S_"right"$是所有在$x_mid$右侧的区间,$S_"mid"$是所有包含$x_mid$的区间。 而$S_"left"$和$S_"right"$又可以分别继续递归地进行划分,直到只剩下一个区间,或者没有区间。 #figure( image("fig\BST\12.png" ,width: 80%), caption: "区间树——划分", ) 这样,我们就得到了一棵二叉搜索树,称为*区间树*。 *平衡性*:区间树的高度为$O(log n)$。 $ max{|S_"left"|,|S_"right"|} <= n/2 $ 为了方便查询,我们还需要组织好区间树的结构。保证所有$S_"mid"$的区间都按照左/右排序。 #figure( image("fig\BST\13.jpg" ,width: 50%), caption: "区间树——排序", ) *空间大小*:是$O(n)$的,因为每个区间只会在节点出现两次。 *构造*:构造的时间是$O(n log n)$的,依次排序即可。 *查询*: ```cpp def queryIntervalTree( v, qx ): if ( ! v ) return; //base if ( qx < xmid(v) ) report all segments of Smid(v) containing qx; queryIntervalTree( lc(v), qx ); else if ( xmid(v) < qx ) report all segments of Smid(v) containing qx; queryIntervalTree( rc(v), qx ); else //with a probability ≈ 0 report all segments of Smid( v ); //both rc(v) & lc(v) can be ignored ``` 在查询时候,每次都从根节点开始,如果$q$在当前节点的区间内,则将当前节点加入结果集,然后递归地查询左右子树。总的查询时间是$O(log n + k)$的,其中$k$是结果集的大小。 == 线段树Segment Tree === 基本区间Elementary Intervals 对于$n$个区间$I = {s_i=[x_i,x'_i] | 1<=i<=n}$,可以将区间端点排序${p_1,p_2,...,p_{m}}$,其中$m<=2n$。将整个区间分成$m+1$个基本区间,$(-oo,p_1],(p_1,p_2],...,(p_m,oo)$。 对于给定的区间,我们就可以实现离散化(Discretization)。在每段基本区间上,他们有一样的性质。 #figure( image("fig\BST\14.png" ,width: 80%), caption: "线段树——基本区间", ) 可以用$O(log n)$二分查找目标区间,然后在$O(k)$的进行输出,其中$k$是结果集的大小。 #figure( image("fig\BST\15.png" ,width: 60%), caption: "线段树——基本区间——最坏情况", ) 但最坏情况需要占用$O(n^2)$的空间。 === 线段树Segment Tree 为了解决上述问题,我们引入线段树。线段树是个完全二叉树,最底层的每个节点都是一个基本区间。 #figure( image("fig\BST\16.png" ,width:70%), caption: "线段树", ) 在存储的时候,先在最底层存满,对有共同祖先的区间向上贪婪合并(greedy merging)。 对于多个区间可以如下储存: #figure( image("fig\BST\17.png" ,width: 70%), caption: "线段树——储存", ) 这些合并的区间被称为*标准子集Canonical Subsets*,占用的空间是$O(n log n)$的。 ```cpp def BuildSegmentTree(I): Sort all endpoints in I before determining all the EI's //O(nlogn) Create T a BBST on all the EI's //O(n) Determine R(v) for each node v //O(n) if done in a bottom-up manner For each s of I InsertSegment( T.root, s ) ``` 每次插入区间贪婪合并,但事实上实现是从顶层摔下去,保留包含在插入标区间内的节点区间。 ```cpp def InsertSegment( v , s ): if ( R(v) is subset of s ) //greedy by top-down store s at v and return; if ( R( lc(v) ) ∩ s != Empty ) //recurse InsertSegment( lc(v), s ); if ( R( rc(v) ) ∩ s != Empty ) //recurse InsertSegment( rc(v), s ); ``` 需要$O(log n)$的时间。 查询也很容易,只需要从根到叶子,逐层报告结果即可。 ```cpp def Query( v , qx ): report all the intervals in Int(v) if ( v is a leaf ) return if ( qx in R( lc(v) ) ) Query( lc(v), qx ) else //qx in R( rc(v) ) Query( rc(v), qx ) ``` 查询的时间是$O(log n + k)$的,其中$k$是结果集的大小。因为每次在标准子集上的时间是$k_i+1$,而从根到叶子的时间是$O(log n)$。 == 高阶搜索树Multi-Level Search Tree === Range Query 考虑Range Query问题 ==== 1D情况 给定$P={p_1,p_2,...,p_n}$是在数轴上排列的$n$个点,给定一个查询区间$I= [x,y]$,目标是找出所有在$I$内的点。 Brute-Force的方法是$O(n)$的。 但是我们可以用二分查找的方法:先补充$P[0] = -oo$,可以二分查找$I$的右端点,之后回退,直到找到左端点。这样可以将时间降低到$O(log n + k)$,其中$k$是结果集的大小。 ```cpp For any interval I = (x1, x2] Find t = search(x2) = max{ i | p[i] <= x2 } //O(logn) Traverse the vector BACKWARD from p[t] and report each point //O(k) until escaping from I at point p[s] return k = t - s //output size ``` 输出敏感度(Output-Sensitivity):如果$k$很小,那么算法的时间就很小。但是如果$k$很大,可能不如两次二分查找。 这个方法也无法拓展到2D情况。 ==== 2D情况 给定$P={p_1,p_2,...,p_n}$是在平面上排列的$n$个点,给定一个查询区间$I= [x_1,x_2] * [y_1,y_2]$,目标是找出所有在$I$内的点。 可以用类似动态规划的记忆法记住从左下角到该点的信息,再用容斥原理,可以得到一个小矩形内的信息。 #figure( image("fig\BST\18.png" ,width: 80%), caption: "Range Query——2D——预处理", ) 这样,我们就可以在$O(log n)$(因为要用二分查找最近的给定点)的时间内得到一个小矩形内的信息。 #figure( image("fig\BST\19.png" ,width: 80%), caption: "Range Query——2D——查询", ) 但要占用$O(n^2)$的空间。 === Multi-Level Search Tree: 1D 结构是一个Complete (Balanced) BST,重构成以下形式: #figure( image("fig\BST\20.png" ,width: 80%), caption: "Multi-Level Search Tree——1D", ) $ forall v , v."key" = min{u."key" | u in v."rTree"} = v."succ.key" $ 则有性质$forall u in v."lTree" , u."key" < v."key"$和$forall u in v."rTree" , u."key" >= v."key"$。令`search(x)`返回最大的$u$,使得$u."key" <= x$。 保证树是完全二叉的,这样可以保证叶节点恰好存满所有给定的数据。这棵树可以在一个完全二叉树的基础上改进得到。原先二叉树最下层的每一个节点的左儿子(如果没有的话)存其前驱,而右节点存自己本身,就可以得到这棵树。 核心想法是寻找最低的公共祖先(Lowest Common Ancestor) #figure( image("fig\BST\21.png" ,width: 80%), caption: "Multi-Level Search Tree——1D——查找", ) 由公共祖先LCA出发,取从左上来的路上节点的右子树,和从右上来的路上节点的左子树,就可以得到结果。 #figure( image("fig\BST\22.png" ,width: 80%), caption: "Multi-Level Search Tree——1D——查找", ) 查询复杂度是$O(log n + k)$,预处理复杂度是$O(n log n)$,空间复杂度是$O(n)$。 #figure( image("fig\BST\23.png" ,width: 80%), caption: "Multi-Level Search Tree——1D——总结", ) 用线段树理解就是上图的样子。 === Multi-Level Search Tree: 2D ==== 2D Range Query = x-Query + y-Query 先对x-Query,再对剩余的候选者做y-Query。 对于最坏的情况,用k-d tree的方法可以做到$O(1 + sqrt(n))$,但是用Multi-Level Search Tree的方法需要做到$O(n)$。 #figure( image("fig\BST\24.png" ,width: 80%), caption: "Multi-Level Search Tree——2D——最坏情况", ) ==== 2D Range Query = x-Query \* y-Query 需要构造一棵树的树: - 为第一个维度的query问题 (x-query)构造一个一维的BBST(x-tree) - 而对于每个x-range tree的节点v,建立一个 y 维度的 BBST(y-tree),其中包含与 v 关联的标准子集(canonical subset) 也就是构造一个x-tree和数个y-tree,称作Multi-Level Search Tree。 #figure( image("fig\BST\25.png" ,width: 50%), caption: "Multi-Level Search Tree——2D——查找", ) 这样的复杂度是$O(log^2 n + k)$,其中$k$是结果集的大小。 #figure( image("fig\BST\26.png" ,width: 30%), caption: "Multi-Level Search Tree——2D——构造", ) ```cpp Query Algorithm: 1. Determine the canonical subsets of points that satisfy the first query // there will be O(logn) such canonical sets, // each of which is just represented as a node in the x-tree 1. Find out from each canonical subset which points lie within the y-range // To do this, // for each canonical subset, // we access the y-tree for the corresponding node // this will be again a 1D range search (on the y-range) ``` 整体的复杂度是: 对于一个2阶搜索树,对于空间中的$n$个点,需要$O(n log n)$的时间构造,$O(n log n)$的空间,$O(log^2 n + k)$的时间查询。 === Multi-Level Search Tree: dD 对于$d$维的情况,整体的复杂度是: 对于一个$d$阶搜索树,对于空间中的$n$个点,需要$O(n log^{d-1} n)$的时间构造,$O(n log^{d-1} n)$的空间,$O(log^d n + k)$的时间查询。 == kD树k Dimentional Tree 我们想把BBST的搜索策略应用到几何范围搜索(Geometric Range Search,GRS)问题中。 从单一区域(整个平面)开始 - 在每个偶/奇数层上 - 垂直/水平划分区域递归划分子区域 为了使其正常工作 - 每个分区应尽可能均匀(中位数) - 每个区域定义为开/封在左下方/右上方 大致划分过程如下: #figure( image("fig\BST\27.png" ,width: 80%), caption: "kD树——划分", ) 有时候对于二维平面,可以用`quadTree`,四叉树,来进行划分。 #figure( image("fig\BST\28.png" ,width: 80%), caption: "quadTree", ) === kD树的构造 ```cpp buildKdTree(P,d) //construct a 2d-tree for point set P at depth d if ( P == {p} ) return createLeaf( p ) //base Root = createKdNode() Root->SplitDirection = even(d) ? VERTICAL : HORIZONTAL Root->SplitLine = findMedian( root->SplitDirection, P ) //O(n)! ( P1, P2 ) = divide( P, Root->SplitDirection, Root->SplitLine ) //DAC Root->LC = buildKdTree( P1, d + 1 ) //recurse Root->RC = buildKdTree( P2, d + 1 ) //recurse return( Root ) ``` #figure( image("fig\BST\29.png" ,width: 80%), caption: "kD树——构造", ) === 标准子集Canonical Subset 每个节点对应 - 平面的一个矩形子区域,以及 - 子区域中包含的点的子集,每一个都被称为典型子集(Canonical Subset) 对于每个有子节点 `L` 和 `R` 的内部节点 `X`,有:`region(X) = region(L) ∪ region(R)` 同一深度的节点子区域互不相交,且它们的并集覆盖整个平面。 每个二维范围查询都可以由多个 CS 的并集来回答。 === kD树的查询 ```cpp def kdSearch(v,R): // 热刀来切千(logn)层巧克力 if ( isLeaf( v ) ) if ( inside( v, R ) ) report(v) return if ( region( v->lc ) ⊆ R ) reportSubtree( v->lc ) else if ( region( v->lc ) ∩ R != Empty ) kdSearch( v->lc, R ) if ( region( v->rc ) ⊆ R ) reportSubtree( v->rc ) else if ( region( v->rc ) ∩ R != Empty ) kdSearch( v->rc, R ) ``` 和BBST的查询类似,不断向两个子树递归。 #figure( image("fig\BST\30.png" ,width: 80%), caption: "kD树——查询", ) #figure( image("fig\BST\31.png" ,width: 80%), caption: "kD树——查询", ) 当然,对于最后得结果,我们会发现最终的目标区域还和一些周围的区域有交集。对于这种相交但不包含的,直接查询叶子是否在其中即可。 如果想避免这种情况,可以适当缩小Bounding Box。 #figure( image("fig\BST\32.png" ,width: 80%), caption: "kD树——查询", ) === kD树的性能 - *Preprocessing*:将平面划分成$n$个区域,满足$T(n) = 2T(n/2) + O(n)$,所以$T(n) = O(n log n)$。 - *Storage*:树的高度是$O(log n)$,所以空间是$O(n)$。 - *Query Time*:$O(sqrt(n) + k)$,其中$k$是结果集的大小。 搜索时间取决于 $Q(n)$ : - 递归调用次数,即 - 与查询区域*相交*的子区域(各级),而在完全在查询区域内的子区域(各级)不会被递归调用。 可以证明:从被分成四块区域开始,每块分别对应一条边。下面的叙述是对于与一条边相交的情况。 每个被递归的节点至多有2个*孙子*(隔层比较)会被递归,即$Q(n) = 2Q(n/4) + O(1)$,所以$Q(n) = O(sqrt(n))$。 更一般地,对于$d$维的情况,整体的复杂度是: - constructed: $O(n log n)$ - size: $O(n)$ - query time: $O(n^{1-1/d} + k)$
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/Metodi%20Algebrici/Strutture/Normale.typ
typst
Creative Commons Zero v1.0 Universal
#import "../Metodi_defs.typ": * Siano $(G, *)$ un gruppo e $(H, *)$ un suo sottogruppo. Siano poi $g_(1)$ e $g_(2)$ due elementi di $G$. Su $G$ é possibile definire due relazioni, $cal(R)_(H)$ e $cal(L)_(H)$, come segue: #grid( columns: (0.5fr, 0.5fr), [$ g_(1) cal(R)_(H) g_(2) space "se e soltanto se" space g_(1) * g_(2)^(-1) in H $], [$ g_(1) cal(L)_(H) g_(2) space "se e soltanto se" space g_(1)^(-1) * g_(2) in H $] ) #theorem[ Siano $(G, *)$ un gruppo e $(H, *)$ un suo sottogruppo. Le relazioni $cal(R)_(H)$ e $cal(L)_(H)$ sono relazioni di equivalenza. ] <Left-right-is-equivalence> #proof[ Per provare che $cal(R)_(H)$ sia una relazione di equivalenza, é necessario provare che sia riflessiva, simmetrica e transitiva: - $cal(R)_(H)$ é riflessiva se, preso un qualsiasi $g in G$, $g * g^(-1) in H$. Questo é vero per definizione, perchè $g * g^(-1) = 1_(*)$ e l'elemento neutro é sempre membro di qualsiasi sottogruppo; - $cal(R)_(H)$ é simmetrica se, presi due $g_(1), g_(2) in G$ qualsiasi, $g_(1) cal(R)_(H) g_(2)$ implica $g_(2) cal(R)_(H) g_(1)$. Se $g_(1) cal(R)_(H) g_(2)$ allora $g_(1) * g_(2)^(-1) in H$, ma allora anche $(g_(1) * g_(2)^(-1))^(-1) in H$. Si noti peró come $(g_(1) * g_(2)^(-1))^(-1) = g_(2) * g_(1)^(-1)$, pertanto anche $g_(2) * g_(1)^(-1) in H$, ovvero $g_(2) cal(R)_(H) g_(1)$; - $cal(R)_(H)$ é transitiva se, presi tre $g_(1), g_(2), g_(3) in G$ qualsiasi, $g_(1) cal(R)_(H) g_(2)$ e $g_(2) cal(R)_(H) g_(3)$ implicano $g_(1) cal(R)_(H) g_(3)$. Se $g_(1) cal(R)_(H) g_(2)$, allora $g_(1) * g_(2)^(-1) in H$. Allo stesso modo, se $g_(2) cal(R)_(H) g_(3)$, allora $g_(2) * g_(3)^(-1) in H$. Ricordando che, per qualsiasi $g in G$, vale $g * g^(-1) = g^(-1) * g = 1_(*)$ Si ha: $ g_(1) * g_(3)^(-1) = g_(1) * (g_(2)^(-1) * g_(2)) * g_(3)^(-1) = g_(1) * g_(2)^(-1) * g_(2) * g_(3)^(-1) = (g_(1) * g_(2)^(-1)) * (g_(2) * g_(3)^(-1)) $ Per definizione di sottogruppo, il risultato dell'applicazione dell'operazione a due membri del sottogruppo é a sua volta membro del sottogruppo. Essendo $g_(1) * g_(2)^(-1) in H$ e $g_(2) * g_(3)^(-1) in H$, il risultato dell'operazione su questi, ovvero $g_(1) * g_(3)^(-1)$, appartiene ad $H$. Avendosi peró che $g_(1) * g_(3)^(-1)$ corrisponde a $g_(1) cal(R)_(H) g_(3)$, é provato che $cal(R)_(H)$ sia transitiva. La prova rispetto a $cal(L)_(H)$ é sostanzialmente analoga. ] Siano $(G, *)$ un gruppo e $(H, *)$ un suo sottogruppo. Essendo $cal(R)_(H)$ e $cal(L)_(H)$ delle relazioni di equivalenza per il @Left-right-is-equivalence, é possibile definire su queste delle classi di equivalenza ed un insieme quoziente per ciascuna. La classe di equivalenza $[g]_(cal(R)_(H))$ prende il nome di *laterale destro* di $H$ in $G$ di rappresentante $g$. Similmente, la classe di equivalenza $[g]_(cal(L)_(H))$ prende il nome di *laterale sinistro* di $H$ in $G$ di rappresentante $g$. Gli insiemi quoziente rispetto a $cal(R)_(H)$ e $cal(L)_(H)$ vengono rispettivamente indicati con $G slash cal(R)_(H)$ e $G slash cal(L)_(H)$. #theorem[ Dato un gruppo $(G, *)$ ed un suo sottogruppo $(H, *)$, le classi di equivalenza $[g]_(cal(R)_(H))$ e $[g]_(cal(L)_(H))$ possono essere scritte come: #grid( columns: (0.5fr, 0.5fr), [$ [g]_(cal(R)_(H)) = H g = {h * g: h in H} $], [$ [g]_(cal(L)_(H)) = g H = {g * h: h in H} $] ) ] #proof[ Sia $g in G$. Si consideri la classe di equivalenza $[g]_(cal(R)_(H))$: $ [g]_(cal(R)_(H)) &= {j in G : j cal(R)_(H) g} = {j in G : j * g^(−1) in H} = {h in G : exists h in H "tale che" j * g^(-1) = h} = \ &= {j in G : exists h in H "tale che" j = h * g} = {h * g : h in H} = H g $ La dimostrazione rispetto a $[g]_(cal(L)_(H))$ é sostanzialmente analoga. ] #lemma[ Siano $(G, *)$ un gruppo e $(H, *)$ un suo sottogruppo. Per un qualsiasi $g in G$, gli insiemi $H$, $H g$ e $g H$ sono equipotenti. ] <Laterals-same-cardinality> #proof[ Per definizione di equipotenza, $H$ e $H g$ sono equipotenti se esiste (almeno) una funzione biettiva con $H$ come dominio e $H g$ come codominio. Si consideri a tal proposito la funzione $f: H |-> H g, f(h) = h * g$. Tale funzione é iniettiva perché se vale $h_(1) * g = h_(2) g$ per certi $h_(1), h_(2) in H$, la legge di cancellazione permette di scrivere $h_(1) = h_(2)$. In altre parole, $h_(1) * g = h_(2) g$ é vera nel solo caso in cui $h_(1) = h_(2)$, e quindi ogni coppia distinta $h_(1), h_(2)$ ha una distinta immagine per $f$. É peró anche suriettiva, perché per ciascun $h * g$ é sempre possibile trovare un $h in H$ tale per cui $f(h) = h * g$. Essendo $f$ sia iniettiva che suriettiva, é biettiva, e quindi $H$ e $H g$ sono equipotenti. In maniera sostanzialmente analoga si prova che $H$ e $g H$ sono equipotenti. Per proprietá transitiva, anche $g H$ e $H g$ sono equipotenti. ] #theorem("Teorema di Lagrange")[ Sia $(G, *)$ un gruppo finito e sia $(H, *)$ un suo sottogruppo. Allora $abs(H)$ é divisore di $abs(G)$. ] <Lagrange-theorem> #proof[ Per la definizione di divisore, $abs(H)$ é divisore di $abs(G)$ se esiste un $k in ZZ$ tale per cui $abs(G) = k abs(H)$. Si consideri l'insieme quoziente $G slash cal(R)_(H)$. Essendo $G$ un insieme finito per ipotesi, anche gli elementi di tale insieme sono in numero finito. Siano questi $H g_(1), H g_(2), ..., H g_(r)$; per il @Laterals-same-cardinality, tutti gli $H g_(i)$ con $i in {1, ..., n}$ sono equipotenti ad $H$. Inoltre, per definizione di insieme quoziente, ciascun $H g_(i)$ con $i in {1, ..., n}$ é disgiunto da tutti gli altri $H g_(j)$ con $j in {{1, ..., n} - i}$. Si ha allora: $ abs(G) = abs(union.big_(i = 1)^(r) H g_(i)) = sum_(i = 1)^(r) abs(H g_(i)) = sum_(i = 1)^(r) abs(H) = r abs(H) $ Essendo $r$ chiaramente un numero intero, si ha che $abs(H)$ é divisore di $abs(G)$. ] Si noti come il @Lagrange-theorem indichi che, dato un gruppo, la cardinalitá di qualsiasi suo sottogruppo é divisore della cardinalitá del gruppo, ma non indica che tali sottogruppi necessariamente esistano. #example[ Sia $(G, *)$ un gruppo di cardinalitá $6$. Il @Lagrange-theorem implica che un qualsiasi sottogruppo di $(G, *)$ debba avere cardinalitá pari ad un divisore di $6$, ovvero $1$, $2$, $3$ oppure $6$, ma non implica che effettivamente esistano dei sottogruppi di $(G, *)$ aventi cardinalitá $1$, $2$, $3$ oppure $6$. Sia peró, ad esempio, $H$ un sottoinsieme di $G$ avente cardinalitá $4$: il @Lagrange-theorem implica che $(H, *)$ non possa essere un sottogruppo di $(G, *)$, perché $4 divides.not 6$. ] Siano $(G, *)$ un gruppo ed $(N, *)$ un suo sottogruppo. $(N, *)$ si dice *sottogruppo normale* di $(G, *)$ se, per qualsiasi $g in G$, i laterali destri e sinistri di $N$ in $G$ di rappresentante $g$ coincidono. Per indicare che $(N, *)$ é un sottogruppo normale di $(G, *)$ si usa la notazione $(N, *) triangle.l (G, *)$. In altre parole: $ (N, *) triangle.l (G, *) space "se" space g N = N g space forall g in G $ #lemma[ Se $(G, *)$ é un gruppo abeliano, allora qualsiasi suo sottogruppo é un sottogruppo normale. ] <Abelian-normal-subgroups> #proof[ Sia $(H, *)$ un sottogruppo di $(G, *)$. Per un qualsiasi $g in G$, i laterali destri e sinistri di $H$ in $G$ di rappresentante $g$ sono, rispettivamente: #grid( columns: (0.5fr, 0.5fr), [$ [g]_(cal(R)_(H)) = H g = {h * g: h in H} $], [$ [g]_(cal(L)_(H)) = g H = {g * h: h in H} $] ) Essendo $(H, *) lt.eq (G, *)$, gli elementi di $H$ sono anche elementi di $G$. Pertanto, per qualsiasi $h in H$, vale $h * g = g * h$, perché $(G, *)$ é abeliano per ipotesi, e quindi $H g = g H$. ] #theorem[ Sia $phi.alt: G |-> K$ un omomorfismo tra i gruppi $(G, *)$ e $(K, diamond.small)$. La struttura algebrica $(ker(phi.alt), *)$ é un sottogruppo normale di $(G, *)$. ] <Kernel-is-normal-subgroup> #proof[ Si osservi innanzitutto come per il @Kernel-is-subgroup, si ha $(ker(phi.alt), *) lt.eq (G, *)$. Per un certo $g in G$, si consideri la classe di equivalenza $[g]_(cal(R)_(ker(phi.alt))) = ker(phi.alt) g = {k * g : k in ker(phi.alt)}$. $ phi.alt((g * k) * g^(-1)) = (phi.alt(g) * phi.alt(k)) diamond.small phi.alt(g^(-1)) = (phi.alt(g) * 1_(*)) diamond.small phi.alt(g^(-1)) = phi.alt(g) diamond.small phi.alt(g^(-1)) = 1_(diamond.small) $ Ovvero, $g * k * g^(-1) in ker(phi.alt)$. Questo significa che esiste $overline(k) in ker(phi.alt)$ per il quale $g k g^(-1) = overline(k)$, e pertanto $g k = overline(k) g in ker(phi.alt)$. Questo implica $ker(phi.alt) g subset.eq g ker(phi.alt)$. In maniera analoga, é possibile provare che $g ker(phi.alt) subset.eq ker(phi.alt) g$. Questo significa che, per qualsiasi $g in G$, $g ker(phi.alt) = ker(phi.alt) g$, e quindi che $(ker(phi.alt), *)$ é un sottogruppo normale di $(G, *)$. ] Siano $(G, *)$ un gruppo ed $(N, *)$ un suo sottogruppo normale. Essendo $cal(R)_(N) = cal(L)_(N)$, i due insiemi quoziente $G slash cal(R)_(H)$ e $G slash cal(L)_(H)$ sono a loro volta coincidenti. L'insieme quoziente dei laterali destri/sinistri di $N$ in $G$ con rappresentante $g$ viene indicato semplicemente con $G slash N$. É possibile definire una operazione prodotto (ben definita) su $G slash N$ in questo modo: $ N g_(1) dot N g_(2) = N (g_(1) * g_(2)) space forall g_(1), g_(2) in G $ #theorem[ Siano $(G, *)$ un gruppo ed $(N, *)$ un suo sottogruppo normale. La struttura algebrica $(G slash N, dot)$ é un gruppo. ] #proof[ Si consideri l'operazione $dot$ della struttura algebrica $(G slash N, dot)$: - Per ogni $N g_(1), N g_(2), N g_(3) in G slash N$, si ha: $ (N g_(1) dot N g_(2)) dot N g_(3) = N (g_(1) * g_(2)) dot N g_(3) = N (g_(1) * (g_(2) * g_(3))) = N g_(1) dot N (g_(2) * g_(3)) = N g_(1) dot (N g_(2) dot N g_(3)) $ Pertanto, $dot$ gode della proprietá associativa, e quindi $(G slash N, dot)$ é un semigruppo; - $N = N 1_(*)$ é l'elemento neutro per $dot$. Infatti, per ogni $N g = g N in N slash G$, vale: $ N dot N g = N 1_(*) dot N g = N (1_(*) * g) = N g = N (g * 1_(*)) = N g dot N 1_(*) = N g dot N $ Esistendo l'elemento neutro per $(G slash N, dot)$, questo é un monoide; - Per ogni elemento $N g in G slash N$, esiste il suo inverso $N g^(-1) in G slash N$, infatti: $ N g dot N g^(−1) = N (g * g^(-1)) = N (g^(-1) * g) = N g^(−1) dot N g = N 1_(*) = N $ Pertanto, $(G slash N, dot)$ é un gruppo. ] Siano $(G, *)$ un gruppo ed $(N, *)$ un suo sottogruppo normale. Il gruppo $(G slash N, dot)$ prende il nome di *gruppo quoziente* di $G$ rispetto a $N$. #theorem("Teorema fondamentale degli omomorfismi")[ Sia $phi.alt: G |-> K$ un omomorfismo tra i gruppi $(G, *)$ e $(K, diamond.small)$. Il gruppo quoziente $(G slash ker(phi.alt), dot)$ é isomorfo a $(Im(phi.alt), dot)$. ] // #proof[ // Dimostrabile, da aggiungere // ]
https://github.com/onomou/typst-examit
https://raw.githubusercontent.com/onomou/typst-examit/main/questionit.typ
typst
MIT License
#import "utilities.typ": * #let pointscounter = counter("totalpoints") #let answerlinelength = 4cm #let showquestion( pointsplacement: "right", number: "", dropboxes: none, question: none, points: none, unnumbered: false, bonus: false, spacing: 1em, answerbox: none, graph: none, numberline: none, choices: none, matching: none, horizontal: none, tf: false, sameline: false, writelines: none, answerline: true, ungraded: false, likert: none, ) = { // add this question's points to total if not bonus and not ungraded { pointscounter.update(t => t + points) } let boxspacing = 12pt let leftedge = -2.6em let scoreboxwidth = 1.7em let theboxes = place( if pointsplacement == "right" { right } else if pointsplacement == "left" { left }, dx: if pointsplacement == "right" { 16mm } else if pointsplacement == "left" { leftedge - boxspacing - scoreboxwidth }, [ #if not unnumbered [ #box(stroke: none, [ #set text(size: 8pt) #align(center + horizon, [#number])]) ] #box( width: 1.2em, [ #align( center + horizon, [ #points#if bonus [\*] ] ) ] ) #box( width: scoreboxwidth, []) ] ) let willdrop = if dropboxes != none { dropboxes } else if answerline { true } else if choices != none or matching != none or answerbox != none { false } else if sameline == false {true} // and answerline and writelines == -1 and answerbox != none if not willdrop and not ungraded [ #set place(dy: -3.5pt) #set box(stroke: black + 0.2mm, height: 1.2em, baseline: -2em,) #theboxes ] [ #if bonus [(Bonus)] #question // offset for answerbox #if answerbox != none [ // #v(-3pt) #writingbox(height: answerbox) #v(-10pt) ] // blank lines for writing #if writelines != none and writelines > 0 [ #v(1em) #for x in range(writelines) [ #writingline()\ \ ] #v(-4em) ] #if sameline { v(-2em) // TODO: this for } // \ // polar or rectangular graph response #if graph != none { h(1fr) if graph == "polar" { align(right, graphpolar()) // } else if graph == "numberline" { // align(right, graphline()) } else { v(-3em) align(right, graphgrid()) v(-4em) } } // multiple choice or true/false #if choices != none { [ #align(right, [ #if horizontal == false { table( stroke: none, align: left, ..for choice in choices { (choicebox(choice),) } ) } else { h(1fr) for choice in choices [ #box([ #h(1em) // #sym.circle.big // #box(width: 1em, height: 1em, stroke: 0.2mm) // // #sym.square.stroked // #h(0.5em) #box([#move(dy: -0.2em, [#choice])]) #choicebox(choice) ]) ] h(1em) } ]) ] } #if matching != none { [ #if horizontal == true { grid( // stroke: black, columns: (auto, )*matching.len(), // column-gutter: 5em, row-gutter: 1em, ..for pair in matching { (choicebox(pair.at(0)), ) }, ..for pair in matching.enumerate() { ( [ #enum( start: pair.at(0)+1, numbering: "A.", pair.at(1).at(1) ) ], ) }, ) } else { grid( columns: (auto, auto), column-gutter: 5em, row-gutter: 1em, ..for pair in matching.enumerate() { ( choicebox(pair.at(1).at(0)), [ #enum( numbering: "A.", start: pair.at(0)+1, [#pair.at(1).at(1)] ) ] ) } ) } ] } #if spacing != none { v(spacing, weak: false) } // answerline and dropped points boxes #if willdrop or answerline or numberline != none [ #place( right + bottom, // dy: spacing, [ #if answerline [ #number. #box([#line(stroke: 0.4pt, length: answerlinelength, start: (4pt, 0pt))]) ] #if numberline != none [ #number. #box(graphline(width: numberline)) ] #if willdrop and not ungraded [ #set place(dy: -10.5pt) #set box(stroke: black + 0.2mm, height: 1.2em, baseline: -2em,) #theboxes ] // #v(1em) ] ) ] ] block(width: 100%) } #let parsequestion( question, pointsplacement: "right", number: "", dropallboxes: none, defaultpoints: none, ) = { let exists(key) = { question.at(key, default: none) != none } if question.at("tf", default: false) { question.insert("choices", ([T],[F],)) } if question.at("choices", default: none) != none and not exists("spacing") { // question.insert("sameline", true) question.insert("spacing", -0.5em) } if question.at("answerbox", default: none) != none and not exists("answerline") { question.insert("answerline", false) question.insert("spacing", 0pt) } // if question.at("numberline", default: none) != none { // question.insert("graph", "numberline") // } let defaults = ( "writelines": none, "tf": false, "sameline": if question.at("choices", default: none) != none and question.at("sameline", default: true) {true} else {false}, "answerline": if question.at("choices", default: none) != none or question.at("graph", default: none) != none or question.at("numberline", default: none) != none or question.at("writelines", default: none) != none {false} else {true}, ) let args = ( question: question.at("question", default: none), points: question.at("points", default: defaultpoints), unnumbered: question.at("unnumbered", default: false), bonus: question.at("bonus", default: false), spacing: question.at("spacing", default: 3em), answerbox: question.at("answerbox", default: none), graph: question.at("graph", default: none), numberline: question.at("numberline", default: none), choices: question.at("choices", default: none), matching: question.at("matching", default: none), horizontal: question.at("horizontal", default: none), writelines: question.at("writelines", default: none), answerline: question.at("answerline", default: defaults.answerline), sameline: question.at("sameline", default: defaults.sameline), ungraded: question.at("ungraded", default: false), dropboxes: question.at("dropboxes", default: dropallboxes), number: number, pointsplacement: pointsplacement, likert: question.at("likert", default: none), ) box(showquestion(..args)) }
https://github.com/coljac/typst-mnras
https://raw.githubusercontent.com/coljac/typst-mnras/main/mnras.typ
typst
MIT License
/* MNRAS template v0.1 By <NAME>, <EMAIL> (Not affiliated with MNRAS!) */ #let affiliations(s) = { let affils = () let auth_to_affils = (:) let affil_to_num = (:) let affils_postal = (:) let names = () for author in s { names.push(author.name.at(0) + ". " + author.name.split( ).at(1)) auth_to_affils.insert(names.at(-1), ()) for val in author.affiliations { if val.name not in affils { affils.push(val.name) affils_postal.insert(val.name, ", " + val.postal) affil_to_num.insert(val.name, affils.len()) } auth_to_affils.at(names.at(-1)).push(str(affil_to_num.at(val.name))) } } // names.at(0) = names.at(0) + footnote(numbering: "*", "<EMAIL>") let emails = s.map(n => { footnote(numbering: "*", n.email) }) let names = names.map(n => { let a = auth_to_affils.at(n) n + super(a.join(",")) if n == names.at(0) { emails.at(0) } }) block(text(weight: 500, 1.3em, names.join(", "))) par(justify: false, leading: 0.2em)[ #text(size: 10pt, for af in affils { let affilnum = affil_to_num.at(af) [#super[#affilnum]#af#affils_postal.at(af)\ ] }) ] } //#set math.equation(numbering: "(1)") #let project( title: "", shorttitle: "", abstract: [], authors: (), keywords: "", date: none, body, ) = { // Set the document's basic properties. set document(author: authors.map(a => a.name), title: title) set page("a4", margin: (left: 25mm, right: 25mm, top: 30mm, bottom: 30mm), numbering: "1", number-align: start, header: locate(loc => { if calc.even(loc.page()) { [#loc.page() ~~~ #authors.at(0).name.at(0). #authors.at(0).name.split(" ").at(-1) et al] //align(center, header) } else { if loc.page() == 1 { grid( columns: (1fr, 1fr, 1fr), rows: 1, gutter: 3pt, [MNRAS 000, 1–2 (#date.split(" ").at(-1))], align(center)[Preprint #date], align(right)[_Compiled with Typst_]) } else { align(right)[#shorttitle ~~ #loc.page()] } } }), footer: locate(loc => { if calc.even(loc.page()) { [MNRAS 000, 1–2 (#date.split(" ").at(-1))] } else { if loc.page() == 1 { [$copyright$ #date.split(" ").at(-1) The Authors] } else { align(right)[MNRAS 000, 1–2 (#date.split(" ").at(-1))] } }}) ) set text(font: "New Computer Modern", lang: "en") show math.equation: set text(weight: 400) set heading(numbering: "1.1") show heading: it => pad(bottom: 0.4em)[#text(size: 0.7em, weight: 800)[*#it*]] show heading.where(level: 1): it => pad(bottom: 0.4em)[#text(size: 1.0em, weight: 800)[*#upper(it)*]] set math.equation(numbering: "(1)") v(2em, weak: false) // Title row. align(left)[ #block(text(weight: "black", 1.75em, title)) #v(1em, weak: true) //#date ] // pad(top: 1em)[#authornames(authors)] affiliations(authors) pad(top: 2em, text(size: 0.85em)[Accepted XXX. Received YYY; in original form ZZZ]) // Abstract. pad( x: 0em, top: 1.5em, bottom: 2.1em, align(left)[ #heading( outlined: false, numbering: none, text(0.85em, [ABSTRACT]), ) #par(justify: true)[#abstract *Key words*: #keywords.split(",").join(" --- ") ] ], ) // Main body. set par(justify: true) show: columns.with(2, gutter: 1.3em) body }
https://github.com/OCamlPro/ppaqse-lang
https://raw.githubusercontent.com/OCamlPro/ppaqse-lang/master/src/étude/mesures.typ
typst
#import "defs.typ": * #import "links.typ": * = Mesures statiques == WCET Le calcul du WCET est important sur les systèmes temps réel pour garantir que les tâches critiques se terminent dans un temps donné. Le WCET est le temps maximal que peut prendre une tâche pour se terminer. Il est calculé en fonction des temps d'exécution des instructions, des branchements et des accès mémoire. Il existe deux méthodes pour calculer le WCET : la méthode _dynamique_ et la méthode _statique_. La méthode dynamique consiste à exécuter le programme dans l'environnement cible et à mesurer le temps d'exécution un nombre de fois jugé suffisant pour établir un WCET statistique. Cette méthode est fiable mais coûteuse en temps et en ressources. La méthode statique consiste à analyser le programme sans l'exécuter et à déduire le WCET à partir de cette analyse. Le problème de cette méthode est qu'il est difficile de calculer un WCET précis du fait des optimisations réalisées par le compilateur et de la complexité des architectures modernes. La prédiction de branchement ou l'utilisation des caches peut faire varier le le temps d'exécution de manière importante et rendre le WCET difficile à calculer sans le majorer excessivement. == Analyse de la pile L'analyse de la pile consiste à calculer la taille maximale de la pile utilisée par un programme. La plupart du temps, cette analyse se fait directement sur le binaire car le langage source ne contient pas forcémement les informations adéquates pour réaliser cette analyse puisqu'elles sont ajoutées durant la compilation. Connaître la taille maximale de la pile utilisée est important pour dimensionner et optimiser les systèmes embarqués qui peuvent être très contraints en mémoire. Cela permet d'éviter les dépassements de pile (_stack overflow_) qui sont des erreurs fatales. L'analyse de la pile peut n'est pas décidable lorsque le programme utilise des pointeurs de fonctions car il n'est pas forcément possible de déterminer la suite d'appels de fonctions à l'avance. Dans ce cas, l'analyse de la pile peut demander à annoter le code source pour avoir plus d'informations.
https://github.com/binhtran432k/ungrammar-docs
https://raw.githubusercontent.com/binhtran432k/ungrammar-docs/main/contents/system-design/user-interface-design.typ
typst
== Online Demonstration Playground User Interface Design This section will delve into the detailed user interface designs for the online demonstration playground, showcasing the visual elements, layout, and interaction patterns that will guide user's interactions with the system. #figure( rect(image("/diagrams/generated/design/dsn-home.svg", width: 80%)), caption: [Home Page] ) #figure( rect(image("/diagrams/generated/design/dsn-popup.svg", width: 80%)), caption: [Pop-up when user click on Documentation or Security] )
https://github.com/tingerrr/typst-test
https://raw.githubusercontent.com/tingerrr/typst-test/main/docs/book/src/quickstart/usage.md
markdown
MIT License
# Usage `typst-test` is a command line program, it can be run by simply invoking it in your favorite shell and passing the appropriate arguments. If you open a shell in the folder `project` and `typst-test` is at `project/bin/typst-test`, then you can run it using `./project/bin/typst-test`. Placing it directly in your project is most likely not what you will do, or want to do. You should install it to a directory which is contained in your `PATH`, allowing you to simply run it using `typst-test` directly. How to add such folders to your `PATH` depends on your operating system, but if you installed `typst-test` using one of the recommended methods in [Installation](.install.md), then such a folder should be chosen for you. <div class="warning"> For the remainder of this document `tt` is used in favor of `typst-test` whenever a command line example is shown. When you see an example such as ```bash tt run -e 'name(~id)' ``` it is meant to be run as ```bash typst-test run -e 'name(~id)' ``` You can also define an alias of the same name to make typing it easier. </div> `typst-test` requires a certain project structure to work, if you want to start testing your project's code, you can create an example test and the required directory structure using the `init` command. ```bash tt init ``` This will create the default example to give you a grasp at where tests are located, and how they are structured. `typs-test` will look for the project root by checking for directories containing a `typst.toml` manifest file. This is because `typst-test` is primarily aimed at developers of packages, if you want to use a different project root, or don't have a `typst-manifest` you can provide the root directory using the `--root` like so. ```bash tt init --root ./path/to/root/ ``` Keep in mind that you must pass this option to every command that operates on a project. Alternatively the `TYPST_ROOT` environment variable can be set to the project root. Further examples assume the existence of a manifest, or the `TYPST_ROOT` variable being set If you're just following along and don't have a package to test this with, you can use an empty project with the following manifest: ```toml [package] name = "foo" description = "A fancy Typst package!" authors = ["<NAME>"] license = "MIT" entrypoint = "src/lib.typ" version = "0.1.0" ``` Once the project is initialized, you can run the example test to see that everything works. ```bash tt run example ``` You should see something along the lines of ```txt Running tests ok example Summary 1 / 1 passed. ``` Let's edit the test to actually do something, the default example test can be found in `<project>/tests/example/` and simply contains `Hello World`. Write something else in there and see what happens ```diff -Hello World +Typst is Great! ``` Once we run `typst-test` again we'll see that the test no longer passes: ```txt Running tests failed example Page 1 had 1292 deviations hint: Diff images have been saved at '<project>/tests/example/diff' Summary 0 / 1 passed. ``` `typst-test` has compared the reference output from the original `Hello World` document to the new document and determined that they don't match. It also told you where you can inspect the difference, the `<project>/test/example` contains a `diff` directory. You can take a look to see what changed, you can also take a look at the `out` and `ref` directories, these contain the output of the current test and the expected reference output respectively. Well, but this wasn't a mistake, this was a deliberate change. So, let's update the references to reflect that and try again. For this we use the appropriately named `update` command: ```bash tt update example ``` You should see output similar to ```txt Updating tests updated example Summary 1 / 1 updated. ``` and the test should once again pass.
https://github.com/Skimmeroni/Appunti
https://raw.githubusercontent.com/Skimmeroni/Appunti/main/C++/Introduzione/Tipi.typ
typst
Creative Commons Zero v1.0 Universal
#import "@preview/showybox:2.0.1": showybox Nel C++ si distinguono i seguenti tipi di dato primitivi: - *booleani*, `bool`; - *caratteri*, `char`; - *numeri interi*, `int`; - *numeri decimali*, `float` (singola precisione) `double` (doppia precisione); - *puntatori*; - *reference*; Possono essere poi aggiunti dei _modificatori_ ai tipi primitivi: - `unsigned`, che rimuove il segno dai tipi numerici; - `long`, che raddoppia il numero di bit usato per rappresentare il valore di una variabile di tipo `int` o `double`. Scrivendo solamente `long` si sottintende `long int`; - `short`, che dimezza il numero di bit usato per rappresentare il valore di una variabile di tipo `int`. Scrivendo solamente `short` si sottintende `short int`; La quantitá di bit effettivamente utilizzata per rappresentare una variabile non é fissata, ma dipende dalle caratteristiche dell'architettura su cui il codice viene compilato e dal sistema operativo. Lo standard fissa comunque dei vincoli di massima: - `char` é la piú piccola entitá che puó essere indirizzata, pertanto non puó avere dimensione inferiore a 8 bit; - `int` non puó avere dimensione inferiore a 16 bit; - `double` non puó avere dimensione inferiore a 32 bit. Le informazioni relative a quanti bit sono allocati per una variabile di ogni tipo si trova in un file della libreria standard chiamato `#limits.h`, che puó eventualmente essere importato per ricavare tali informazioni. In alternativa, la funzione della libreria standard `sizeof()` restituisce la dimensione in multipli di `char` del tipo di dato passato come argomento. #showybox[ ``` std::cout << sizeof(char) << std::endl; // prints, say, 1 std::cout << sizeof(int) << std::endl; // prints, say, 4 std::cout << sizeof(double) << std::endl; // prints, say, 8 ``` ] Un puntatore é un tipo di dato che contiene un riferimento ad un indirizzo di memoria. Esistono tanti tipi di puntatori quanti sono i tipi primitivi; per quanto contengano un indirizzo di memoria (che é un numero), il loro tipo non é un intero, bensí é specificatamente di tipo "puntatore a...". Puntatori a tipi diversi sono incompatibili. Nonostante questo, la dimensione di un puntatore non dipende dal tipo di dato dato che gli indirizzi di memoria hanno tutti la stessa dimensione. Il valore di default per un puntatore é `NULL` oppure (standard C++11) `nullptr`. Un puntatore viene dichiarato come una normale variabile di tale tipo, ma postponendo `*` al tipo #footnote[Tecnicamente, la scrittura `type* v` é equivalente a `type * v` e a `type *v`. Questo perché il token `*` viene riconosciuto dal parser singolarmente, quindi non c'é differenza nella sua posizione. Scegliere uno stile piuttosto che un'altro dipende da preferenze personali.]. Anteponendo `&` al nome di una variabile se ne ottiene l'indirizzo di memoria. Per ricavare il valore della cella di memoria a cui un puntatore é associato si antepone `*` al nome della variabile. L'atto di "risalire" al valore a cui un puntatore é legato é una operazione che prende il nome di *dereferenziazione*. ``` variable_type* pointer_name // declares a pointer variable_type* pointer_name = &variable_to_point // declares and initialises a pointer variable_type variable_name = *pointer_name // dereferences a pointer ``` #showybox[ ``` int* p = nullptr; // initialises a pointer p int s = 10; // initialises an integer s p = &s; // p points to the memory address of s std::cout << *p << std::endl; // retrieves the value to which p is // pointing, and prints it (*p)++; // retrieves the value to which p is // pointing, and increments it by one ``` ] Un puntatore, pur non venendo considerato un intero, puó essere manipolato come tale. In particolare, é possibile sommare un intero ad un puntatore, e l'operando `+` viene reinterpretato non come una somma nel senso stretto del termine ma come lo spostamento di un offset di tante posizioni quante ne viene specificato. Il numero di posizioni dipende dal tipo di puntatore: sommare N ad un puntatore equivale a spostare la cella di memoria a cui si riferisce di N volte la dimensione del tipo di dato a cui il puntatore si riferisce. La scrittura `p[n]` permette di risalire al valore che si trova `n` posizioni in avanti rispetto al puntatore `p` (é uno spostamento unito ad una dereferenziazione). La differenza fra due puntatori restituisce il numero di elementi che si trovano nell'intervallo fra le posizioni in memoria a cui i due si riferiscono. Il confronto (`=`) fra due puntatori viene fatto rispetto ai rispettivi valori, e non a ció a cui puntano. Il fatto che sui puntatori sia possibile fare aritmetica puó presentare un problema, perché significa che é tecnicamente possibile, dall'interno di un programma C++, raggiungere aree di memoria che non sono di competenza del programma stesso, semplicemente incrementando o decrementando il valore di un puntatore. Fortunatamente questo non puó accadere, perché il sistema operativo lo previene emettendo un messaggio di errore `Segmentation Fault` e fermando il programma prima che avvenga l'accesso. Per questo motivo non é consigliabile (a meno di casi eccezionali) inizializzare un puntatore fornendogli direttamente un indirizzo di memoria, perché questo comporta che si chieda al programma di accedere ad una area di memoria specifica senza poter sapere se il programma possa accedervi, dato che gli indirizzi in RAM vengono assegnati in maniera sostanzialmente arbitraria. Cercando di stampare il valore di un puntatore mediante `std::cout` si ottiene effettivamente l'indirizzo di memoria a cui il puntatore é associato (espressa in esadecimale). #showybox[ ``` int d = 1; int* p = &d; int c = p[2]; // A shortand for *(p + 2) p = p + 3; // pointer's location is shifted by one. // A shortand for p = p + 3 * sizeof(int) std::cout << p << std::endl // prints, say, 0xfffff7d7761c ``` ] Essendo un puntatore comunque una variabile, anch'esso si trova in una certa area di memoria, ed é pertanto possibile risalire all'area di memoria di un puntatore. Questo significa che é anche possibile avere dei puntatori a dei puntatori. Inoltre, nulla vieta di avere piú di un puntatore legato alla stessa area di memoria. #showybox[ ``` char s = 's'; // A char char* ss = &s; // A pointer to a char char* sss = &ss; // A pointer to a pointer to a char char** f = &s; // A pointer to a pointer to a char (in one go) ``` ] É possibile sfruttare dei puntatori di tipo `void` per aggirare le limitazioni imposte dal compilatore sui puntatori, in particolare i vincoli di tipo. Infatti, un puntatore di tipo `void` puó riferirsi a qualsiasi tipo di dato, ed é possibile riassegnare un puntatore di tipo `void` a dati diversi. Per operare la dereferenziazione é peró necessario compiere un casting esplicito al tipo di dato a cui il puntatore si riferisce in questo momento. Sebbene nel C vi fosse una certa utilitá nei puntatori `void`, nel C++ é da considerarsi una funzionalitá deprecata. #showybox[ ``` int i; double d; void* pi = &i; void* pd = &d; int* ppd = pd; // NOT Allowed int x = *((int*) (pi)); // Ok int y = *((int*) (pd)); // Allowed, but VERY dangerous ``` ] Le utilitá dei puntatori sono riassunte di seguito: - Permettono di riferirsi a piú dati dello stesso tipo; - Permettono di condividere uno stesso dato in piú parti di codice senza doverlo ricopiare piú volte; - Permettono di accedere ai dati indirettamente, non manipolando il valore della variabile in sé ma bensí accedendo alla memoria su cui tale dato si trova; - Permettono il passaggio per parametri alle funzioni, non passando direttamente il valore ma il puntatore, risparmiando memoria; - Permettono di costruire strutture dati dinamiche, come liste e alberi;
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/utility-components.typ
typst
#import "base-utils.typ": * #let answer-box(x, label: none) = { let math-content = resolve-math-content(x) let expr = [*#label #xequal() #math-content*] let box-attrs = ( inset: 5pt, baseline: 25%, radius: 3pt, stroke: black + 0.5pt, ) h(2pt) box(..box-attrs, expr) } #let answer-key-wrapper(content) = { set text(size: 12pt) let block-attrs = ( inset: 5pt, ) rotate(180deg, block(..block-attrs, content)) } #let code-table(..sink) = { let args = sink.pos() let columns = args.len() let opts = sink.named() table(columns: 1, rows: columns, ..args.map((x) => raw(..opts, x.text))) } #let wde(x) = { let box-attrs = ( stroke: none, inset: 0pt, radius: 0pt, fill: none, outset: 0pt, ) let math-content = resolve-math-content(x) [#h(4pt) *What does #h(2pt) #math-content equal?*] // box(..box-attrs, } #let findx(x, target: "x") = { let math-content = resolve-math-content(x) [*Find $#target$.* #h(4pt) #math-content.] } // #findx("a^1 * a^2 * a^3 = a^(x/2)") #let answerx(x, answer) = { let math-content = resolve-math-content(x) [#math-content. #h(5pt) *$x$ equals #answer.*] } #let give-answer(x, target: "x") = { let math-content = resolve-math-content(x) let box-attrs = ( stroke: black, inset: 5pt, radius: 3pt, fill: none, outset: 0pt, baseline: 25%, ) [The answer is #h(3pt) #box(..box-attrs, [*#target #xequal(h(1pt)) #math-content*])] } // #answerx($1 + 2 + 3 = display(x/2)$, 12) // #give-answer("a^(3x)", target: "b") #let boxed(x) = { let box-attrs = ( stroke: 0.25pt + black, inset: ( x: 5pt, y: 5pt, ), radius: 3pt, baseline: 25%, ) let math-content = resolve-content(x) h(5pt) box(..box-attrs, math-content) h(5pt) } // The only way to make $a^(#xblue($4x$))$ is if $b$ has a base of an exponent of $#xblue($3x$)$. // $ // x + 1 = & 33 && "howdy"\ // x + 1111 = & 33111 && "bowdddddy" // $
https://github.com/liuguangxi/erdos
https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/figures/p224.typ
typst
#import "@preview/cetz:0.2.1" #cetz.canvas(length: 1.5cm, { import cetz.draw: * for x in range(-4, 25) { if calc.rem(x, 5) != 0 { line((x/5, -1.2), (x/5, 5.4), stroke: 0.5pt+luma(220)) } } for y in range(-5, 27) { if calc.rem(y, 5) != 0 { line((-0.9, y/5), (4.9, y/5), stroke: 0.5pt+luma(220)) } } for x in range(-4, 25) { if x != 0 and calc.rem(x, 5) == 0 { line((x/5, -1.2), (x/5, 5.4), stroke: 1pt+luma(180)) } } for y in range(-5, 27) { if y != 0 and calc.rem(y, 5) == 0 { line((-0.9, y/5), (4.9, y/5), stroke: 1pt+luma(180)) } } line((0, -1.2), (0, 5.4), stroke: 1pt+luma(60)) line((-0.9, 0), (4.9, 0), stroke: 1pt+luma(60)) circle((3, -0.1), radius: 1.005, stroke: 1.5pt) circle((2.1, 3), radius: 2.326, stroke: 1.5pt) line((4, 0), (0, 4), stroke: 1.5pt) circle((4, 0), radius: 0.06, stroke: 0.8pt, fill: luma(60)) circle((0, 4), radius: 0.06, stroke: 0.8pt, fill: luma(60)) circle((2, 0), radius: 0.06, stroke: 0.8pt, fill: luma(60)) circle((0, 2), radius: 0.06, stroke: 0.8pt, fill: luma(60)) circle((3.1, 0.9), radius: 0.06, stroke: 0.8pt, fill: blue) circle((2.38, 0.69), radius: 0.06, stroke: 0.8pt, fill: luma(60)) content((4.15, 0.15), $A$) content((0.2, 4.05), $B$) content((2.2, 0.15), $C$) content((0.15, 2.15), $D$) content((3.2, 1.15), $E$) content((2.45, 0.95), $F$) })
https://github.com/The-Notebookinator/notebookinator
https://raw.githubusercontent.com/The-Notebookinator/notebookinator/main/themes/radial/entries.typ
typst
The Unlicense
#import "./colors.typ": * #import "./icons/icons.typ" #import "./components/components.typ" #import "./components/title.typ": * #import "/utils.typ" #import "./metadata.typ": entry-type-metadata // TODO: make an actual cover #let cover = utils.make-cover(ctx =>{ import components: label let label = label.with(size: 4.7em, radius: 6pt) align(center + horizon, text(size: 24pt)[ Radial Theme ]) place(dx: 90pt, dy: -340pt, label("identify")) place(dx: 52pt, dy: -295pt, label("brainstorm")) place(dx: 520pt, dy: 190pt, label("decide")) place(dx: 490pt, dy: 240pt, label("build")) place(dx: 460pt, dy: 290pt, label("test")) place(dx: 150pt, dy: -160pt, rect(width: 50%, height: 300pt, fill: rgb("#eeeeeeff"), radius: (right: 20pt, left: 20pt))) place(dx: 125pt, dy: -180pt, label("management")) place(dx: 425pt, dy: 105pt, label("management")) place(dx: 520pt, dy: -270pt, rect(width: 9%, height: 55pt, fill: rgb("#eeeeeeff"), radius: (right: 5pt, left: 5pt))) place(dx: 455pt, dy: -335pt, rect(width: 9%, height: 55pt, fill: rgb("#eeeeeeff"), radius: (right: 5pt, left: 5pt))) place(dx: 490pt, dy: -300pt, label("program")) place(dx: 55pt, dy: 205pt, rect(width: 9%, height: 55pt, fill: rgb("#eeeeeeff"), radius: (right: 5pt, left: 5pt))) place(dx: 120pt, dy: 275pt, rect(width: 9%, height: 55pt, fill: rgb("#eeeeeeff"), radius: (right: 5pt, left: 5pt))) place(dx: 90pt, dy: 240pt, label("notebook")) place(dx: 165pt, dy: 200pt, line(length: 45%, stroke: 3.5pt + black)) place(dx: 165pt, dy: -215pt, line(length: 45%, stroke: 3.5pt + black)) place(dx: 250pt, dy: -280pt, text(size: 18pt)[ *Radial Theme* ]) place(dx: 225pt, dy: -250pt, text(size: 24pt)[ *[Game Season]* ]) place(dx: 235pt, dy: 165pt, text(size: 24pt)[ *[Team Name]* ]) place(dx: 0pt, dy: -370pt, figure( image("Mediamodifier-Design.svg", width: 118%) )) }) #let frontmatter-entry = utils.make-frontmatter-entry((ctx, body) => { show: page.with( header: title(ctx.title), footer: align(right, context counter(page).display("i")), ) body }) #let body-entry = utils.make-body-entry((ctx, body) => { let metadata = entry-type-metadata.at(ctx.type) show: page.with( header: title( beginning: image.decode( utils.change-icon-color(raw-icon: metadata.icon, fill: white), height: 1em, ), end: ctx.date.display("[year]/[month]/[day]"), color: metadata.color, ctx.title, ), footer: [ #line(length: 100%) #align( left, [ *Designed by:* #ctx.author #h(2pt) \ *Witnessed by:* #ctx.witness #h(1fr) #context counter(page).display() ], ) ], ) body }) #let appendix-entry = utils.make-appendix-entry((ctx, body) => { show: page.with( header: title(ctx.title), footer: align(right, context counter(page).display()), ) body })
https://github.com/LEXUGE/poincare
https://raw.githubusercontent.com/LEXUGE/poincare/main/src/notes/math_essentials/main.typ
typst
MIT License
#import "@preview/physica:0.9.2": * #import "@preview/gentle-clues:0.4.0": * #import "@lexuge/templates:0.1.0": * #import shorthands: * #import pf3: * #show: simple.with( title: "Essential Mathematics", authors: ((name: "<NAME>", email: "<EMAIL>"),), ) #let unproven = text(red)[This is not proven yet.] #let unfinished = text(red)[This is not finished yet.] #pagebreak() = Differential Form and Manifolds We follow the development of @form: start from open subset in $RR^n$ and then extend to manifold. == Differential Forms on $RR^n$. Elements in $RR^n$ can be either seen as points or vectors. And we can assign to each element $p in RR^n$ (when $RR^n$ is seen as a collection of points) a _tangent vector space_ $T_p RR^n$. Unless otherwise stated, we think $T_p RR^n$ and $T_q RR^n$, where $p eq.not q in RR^n$ are different points, as two different vector spaces, and vectors in them may not be added together. We will write indices as $x_1, x_2, x_3, ...$. And in the case of $RR^(n lt.eq 3)$, we use $x,y,z$ and $x_1, x_2, x_3$ interchangeably. Often times, we label a multi-index use a sequence of index or an ordered set. #def[Ordered Set][ An ordered set $I$ is a sequence whose elements are unique. For example, $I=(1,2,1)$ will not be an ordered set. But $I = {1,3,2} eq.not {1,2,3}$ is an ordered set. ]<def-ordered-set> The difference being that indices in a sequence can be repeating#footnote[For example, sequence $I=(1,2,1)$ represents $x_I equiv x_1, x_2, x_1$], whereas an ordered set would have unique indices. #def[Smooth Function][ Given an open $cal(R) subset.eq RR^n$, $f: cal(R) to RR$ is smooth if partial derivatives of all order exists at any point in $cal(R)$. We denote $f in C^oo (cal(R))$. ] <def-smooth-fn> The outline of the basic theory is: 1. Define $k$-form on $cal(R)$ as alternating multi-linear functional on $underbrace(T_p RR^n times dots.c times T_p RR^n, k text("times"))$ 2. Find a elementary "basis"#footnote[They are not really a basis as we cannot use functions as fields for vector spaces.] for these $k$-forms. 3. Define Exterior Product. Those formal definition will just appear as concatenating elementary forms together. And they are linear and distributive, but _anti-commutative_. So doing product with elementary basis is intuitive. 4. Define Exterior Derivative. #pagebreak() #bibliography("./bib.yml", style: "ieee")
https://github.com/OkazakiYumemi/nju-ps-typst-template
https://raw.githubusercontent.com/OkazakiYumemi/nju-ps-typst-template/master/README.md
markdown
# NJU ps typst template for assignment Typst template for the NJU (Nanjing University) specialized course "Problem Solving" Mainly modified from gRox167/typst-assignment-template ## Usage RTFSC ## Todo Many. A list is needed but have no time
https://github.com/TGM-HIT/typst-thesis-workshop
https://raw.githubusercontent.com/TGM-HIT/typst-thesis-workshop/main/slides/assets/mod.typ
typst
#let thesis-thumbnail = image.with("thumbnail.png")
https://github.com/Flower101010/Typst_template
https://raw.githubusercontent.com/Flower101010/Typst_template/main/example.typ
typst
#import "template.typ": * #show: doc => conf( institute: [University of Mars \ Institute of Intergalactic Travel], auther: [Flower], title: [Linear Maps], class: [Linear Algebar], doc, ) #let L(iTem) = $cal(L)(iT em)$ #let F = $bb(F)$ = The Vector Space of Linear Maps #problem(index:"1")[ 假设 $T in cal(L)(#F^n,#F^m)$.证明存在$A_(j,k)in #F$ ,其中 $j=1,dots,m quad k=1,dots,n$, 使得 $ T(x_1,dots,x_n) = (A_(1,1)x_1 + dots + A_(1,n)x_n,dots, A_(m,1)x_1 + dots + A_(m,n)x_n) $ 对于每一个 $(x_1,dots,x_n)in #F^n$都成立. ] #proof[ 对于任意的 $x in #F^n$,我们可以写 $ x = x_1 e_1 + dots + x_n e_n, $ 其中 $e_1,dots,e_n$ 是 $#F^n$ 的标准基. 因为 $T$ 是线性的,我们有 $ T x &= T(x_1 e_1 + dots +x_n e_n) \ &= x_1 T e_1 + dots + x_n T e_n. $ 现在对于 $T e_k in #F^m$, 其中 $k=1,dots, n$, 都存在 $A_(1,k),dots, A_(m,k) in #F$ 使得 $ T e_k &= A_(1,k)e_1 + dots + A_(m,k)e_m\ &= A_(1,k), dots, A_(m,k) $ 因此 $ x_k T e_k = (A_(1,k)x_k, dots, A_(m,k)x_k). $ 所以我们有 $ T x &= sum_(k = 1)^n (A_(1,k)x_k, dots, A_(m,k)x_k)\ &= (sum_(k = 1)^n A_(1,k)x_k, dots, sum_(k = 1)^n A_(m,k)x_k), $ 就证得存在$A_(j,k) in #F$ ,其中 $j=1,dots,m$ 并且 $k=1,dots,n$ 使得等式成立. ] #problem[ 假设 $T in cal(L)(#F^n,#F^m)$. 证明存在$A_(j,k)in #F$ ,其中 $j=1,dots,m quad k=1,dots,n$, 使得 ] #proof[ 对于任意的 $x in #F^n$,我们可以写 $ x = x_1 e_1 + dots + x_n e_n, $ 其中 $e_1,dots,e_n$ 是 $#F^n$ 的标准基. 因为 $T$ 是线性的,我们有 $ T x &= T(x_1 e_1 + dots +x_n e_n) \ &= x_1 T e_1 + dots + x_n T e_n. $ 现在对于 $T e_k in #F^m$, 其中 $k=1,dots, n$, 都存在 $A_(1,k),dots, A_(m,k) in #F$ 使得 $ T e_k &= A_(1,k)e_1 + dots + A_(m,k)e_m\ &= A_(1,k), dots, A_(m,k) $ 因此 $ x_k T e_k = (A_(1,k)x_k, dots, A_(m,k)x_k). $ 所以我们有 $ T x &= sum_(k = 1)^n (A_(1,k)x_k, dots, A_(m,k)x_k)\ &= (sum_(k = 1)^n A_(1,k)x_k, dots, sum_(k = 1)^n A_(m,k)x_k), $ 就证存在$A_(j,k) in #F$ ,其中 $j=1,dots,m$ 并且 $k=1,dots,n$ 使得等式成立. It is't right. ] == The Vector Space of Linear Maps #lorem(100) dadsf #problem(index: "2")[ #lorem(100) ] #proof[ #lorem(100) ] #problem(index: "2")[ Adding `rbx` to `rcx` gives the desired result. What is ```rust fn main()``` in Rust would be ```c int main()``` in C. ```rust fn main() { println!("Hello World!"); } ``` This has ``` `backticks` ``` in it (but the spaces are trimmed). And ``` here``` the leading space is also trimmed. ] #problem(index: "999")[ In this report, we will explore the various factors that influence fluid dynamics in glaciers and how they contribute to the formation and behaviour of these natural structures. ... #align(center + bottom)[ #image("pc.jpg", width: 70%) *Glaciers form an important part of the earth's climate system.* ] ]
https://github.com/donabe8898/typst-slide
https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/並行prog/01/syakyo01.typ
typst
MIT License
#show link: set text(blue) #set text(font: "Noto Sans CJK JP",size:13pt) #show heading: set text(font: "Noto Sans CJK JP") #show raw: set text(font: "0xProto Nerd Font") #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt ) #align(center)[ ```go // AtCoder Beginner Contest 267: Probrem A - Saturday // URL: https://atcoder.jp/contests/abc267/tasks/abc267_a // 少しだけ変更を加えています package main import ( "fmt" ) func main() { var a string // 入力する値を格納する変数 fmt.Scanf("%s", &a) // 標準入力 // 土曜日まで何日あるかを辞書型で持つ var day = map[string]int{ "Monday": 5, "Tuesday": 4, "Wednesday": 3, "Thursday": 2, "Friday": 1, } // 入力から検索 ans, is_found := day[a] // 曜日が見つかった場合 if is_found { fmt.Println(ans) } else { // 曜日が見つからなかった場合 fmt.Printf("Not found \n") } } ``` ]
https://github.com/alimitedgroup/alimitedgroup.github.io
https://raw.githubusercontent.com/alimitedgroup/alimitedgroup.github.io/main/lib.typ
typst
/// Crea un verbale /// /// Parametri: /// - odg: ordine del giorno /// - data: la data della riunione, nella forma YYYY-MM-DD /// - tipo: tipologia di verbale: "interno" o "esterno" /// - presenze: array di nomi e cognomi dei presenti /// - versione: attuale versione del documento /// - stato: attuale stato del documento (approvato oppure no) /// - regmodifiche: lista di modifiche, nella forma /// ```typst /// regmodifiche: ( /// ("0.0.1", "2024-10-15", "Samuele Esposito", "-", "Creazione struttura e template documento"), /// ("0.0.1", "2024-10-15", "Samuele Esposito", "-", "Creazione struttura e template documento"), /// ("0.0.1", "2024-10-15", "Samuele Esposito", "-", "Creazione struttura e template documento"), /// ) /// ``` #set text(lang: "it") #let verbale( data: [], tipo: [interno], odg: [], /*presenze: ( "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "Samuele Esposito", "<NAME>", ),*/ presenze: (), versione: [], stato: [], distribuzione: ([_ALimitedGroup_], "Prof. <NAME>", "Prof. <NAME>"), regmodifiche: (), contenuto, ) = { // Prima pagina set align(center) set text(font: "Times New Roman") image("assets/altd.png", height: 7cm) v(4em) text(24pt, weight: "black", fill: black)[_Verbale_ #tipo #data] v(2.25em) show grid.cell.where(x: 0): cell => align(right, cell) show grid.cell.where(x: 1): cell => align(left, cell) set text(11pt) box( width: 80%, grid( columns: (1fr, 1fr), grid.vline(x: 1), inset: 8pt, [Stato], stato, [Versione], versione, [Presenti], grid(align: left, gutter: 8pt, ..presenze), [Distribuzione], grid(align: left, gutter: 8pt, ..distribuzione), ), ) v(2em) text(14pt, weight: "black", fill: black)[Ordine del giorno] v(0.5em) text(10pt)[#odg] // Setup header, footer, contatore pagina set page( numbering: "1", header: [ #grid( columns: (1fr, 1fr), align(left)[_ALimitedGroup_], align(right)[_Verbale_ #tipo #data], ) #line(length: 100%) ], footer: [ #set align(center) #line(length: 100%) #context [ Pagina #counter(page).display(page.numbering) di #counter(page).final().first() ] ], ) set align(left) set heading(numbering: "1.") counter(page).update(1) pagebreak() // Registro delle modifiche text(16pt, weight: "black", fill: black)[Registro delle Modifiche] table( fill: (x, y) => if (y == 0) { rgb("#800080") } else if (calc.gcd(y, 2) == 2) { rgb("#bf7fbf") } else { rgb("#d8b2d8") }, columns: (auto, auto, 0.5fr, 0.5fr, 1fr), stroke: none, inset: 5pt, align: center, table.header( text(12pt, fill: white)[*Vers.*], text(12pt, fill: white)[*Data*], text(12pt, fill: white)[*Autore*], text(12pt, fill: white)[*Ruolo*], text(12pt, fill: white)[*Descrizione*], ), ..regmodifiche.flatten() ) pagebreak() //Indice show outline.entry.where(level: 1): it => { v(12pt, weak: true) strong(it) } outline(title: [#v(2em) Indice #v(3em)], indent: auto) pagebreak() // Resto del documento contenuto } #let inizio-verbale-interno( modalità, data, inizio, fine, ) = [ Con il seguente documento si attesta che in data #data è stata condotta, in modalità #modalità, una riunione durata dalle ore #inizio alle ore #fine con il seguente ordine del giorno: ] #let inizio-verbale-esterno( modalità, data, inizio, fine, azienda, ) = [ Con il seguente documento si attesta che in data #data è stata condotta, in modalità #modalità, una riunione durata dalle ore #inizio alle ore #fine con l'azienda #azienda riguardante i seguenti argomenti: ]
https://github.com/derekchai/k-mapper
https://raw.githubusercontent.com/derekchai/k-mapper/main/utils.typ
typst
MIT License
// Converts the zero-indexed nth position of the Karnaugh map to its Gray code // coordinate. #let position-to-gray(n, grid-size) = { assert(grid-size == 4 or grid-size == 8 or grid-size == 16, message: "Please enter a grid size of 4, 8, or 16!") let grid-size-4 = (0, 1, 2, 3) let grid-size-8 = (0, 1, 2, 3, 6, 7, 4, 5) let grid-size-16 = ( 0, 1, 3, 2, 4, 5, 7, 6, 12, 13, 15, 14, 8, 9, 11, 10 ) if grid-size == 4 { return grid-size-4.at(n) } else if grid-size == 8 { return grid-size-8.at(n) } else { return grid-size-16.at(n) } } // Converts a Gray code position to its coordinate on the K-map. #let gray-to-coordinate(n, grid-size) = { assert(grid-size == 4 or grid-size == 8 or grid-size == 16, message: "Please enter a grid size of 4, 8, or 16!") let grid-size-4 = ((0, 1), (1,1), (0, 0), (1, 0)) let grid-size-8 = ( (0, 3), (1, 3), (0, 2), (1, 2), (0, 0), (1, 0), (0, 1), (1, 1) ) let grid-size-16 = ( (0, 3), (1, 3), (3, 3), (2, 3), (0, 2), (1, 2), (3, 2), (2, 2), (0, 0), (1, 0), (3, 0), (2, 0), (0, 1), (1, 1), (3, 1), (2, 1) ) if grid-size == 4 { return grid-size-4.at(n) } else if grid-size == 8 { return grid-size-8.at(n) } else { return grid-size-16.at(n) } // TODO: other grid sizes. } // Stacks items in the z-axis. #let zstack( alignment: top + left, ..args ) = style(styles => { let width = 0pt let height = 0pt for item in args.pos() { let size = measure(item.at(0), styles) width = calc.max(width, size.width) height = calc.max(height, size.height) } block(width: width, height: height, { for item in args.pos() { place( alignment, dx: item.at(1), dy: item.at(2), item.at(0) ) } }) })
https://github.com/Origami404/kaoyan-shuxueyi
https://raw.githubusercontent.com/Origami404/kaoyan-shuxueyi/main/README.md
markdown
# 考研数学笔记 如题, 这是一份应试用考研数学一笔记, 面向经历了一定数学训练, 但没有很擅长背诵和考试的人. 更详细地说, 我希望您: - 曾接受过实分析和正经代数课程, 了解诸如戴得金分割等分析基础以及线性代数的直观本质 - 能接受面向试题的, 不完备的数学操作和论断, 明白该资料的应试性 本笔记的使用方式是背诵, 它包含了必背公式和大部分常见情况的应对方法. 它不会尝试给您搭建任何的数学知识体系, 它只会构建一个 考点-方法 体系. 如果把准备考研当作荒野求生, 那么您需要自带一个成熟的本科入门级别的分析和代数方向的数学知识体系作为地图来指导自己的方向, 而该笔记会成为您的瑞士军刀, 帮您解决实际的每一个步骤. ## 编译步骤 ```bash typst compile main.typ ``` 如果您需要即时更新的编辑, 可以运行下面的命令: ```bash typst watch main.typ --root . ``` ## License & Reference 如无特殊说明, 本项目内容遵循 [CC BY-NC-SA](https://creativecommons.org/licenses/by-nc-sa/4.0/) 协议发布. `assets` 中图片可能另有版权要求, 使用前请自行考察. 如侵犯了您的权利, 请新建 issue 告知. 本项目的模版部分 (`template.typ`) 修改自 [jskherman/jsk-lecnotes](https://github.com/jskherman/jsk-lecnotes).
https://github.com/hitszosa/universal-hit-thesis
https://raw.githubusercontent.com/hitszosa/universal-hit-thesis/main/harbin/bachelor/utils/numbering.typ
typst
MIT License
#let heading-numbering(..nums) = { let nums-vec = nums.pos() if nums-vec.len() == 1 [ #numbering("第 1 章", ..nums-vec) #h(0.75em) ] else [ #numbering("1.1", ..nums-vec) #h(0.75em) ] }
https://github.com/KNnut/neoplot
https://raw.githubusercontent.com/KNnut/neoplot/main/README.md
markdown
BSD 3-Clause "New" or "Revised" License
# Neoplot A Typst package to use [gnuplot](http://www.gnuplot.info/) in Typst. ```typ #import "@preview/neoplot:0.0.2" as gp ``` Execute gnuplot commands: ````typ #gp.exec( kind: "command", ```gnuplot reset; set samples 1000; plot sin(x), cos(x) ``` ) ```` Execute a gnuplot script: ````typ #gp.exec( ```gnuplot reset # Can add comments since it is a script set samples 1000 # Use a backslash to extend commands plot sin(x), \ cos(x) ``` ) ```` To read a data file: ``` # datafile.dat # x y 0 0 2 4 4 0 ``` ````typ #gp.exec( ```gnuplot $data <<EOD 0 0 2 4 4 0 EOD plot $data with linespoints ``` ) ```` or ```typ #gp.exec( // Use a datablock since Typst doesn't support WASI "$data <<EOD\n" + // Load "datafile.dat" using Typst read("datafile.dat") + "EOD\n" + "plot $data with linespoints" ) ``` To print `$data`: ```typ #gp.exec("print $data") ```
https://github.com/touying-typ/touying-poster
https://raw.githubusercontent.com/touying-typ/touying-poster/main/poster.typ
typst
#import "@preview/octique:0.1.0": octique-inline #set page("a5", margin: 40pt, height: auto) #set text(font: "Fira Sans") #set par(justify: true) #box(text(font: "PangMenZhengDao-XiXian", size: 85pt)[投], baseline: -4pt) #text(fill: blue, size: 60pt)[*Touy*]#text( fill: rgb("#143345"), size: 60pt, )[*ing*] #v(-4pt) #upper(text(size: 24pt)[*Give a Presentation in Typst*]) #v(-20pt) #text( fill: gray, size: 12pt, )[Touying is a user-friendly, powerful and efficient package for creating presentation slides in Typst.] #set text(size: 10pt) #let cell(title, body) = [ #rect(width: 100%, radius: 4pt, inset: 6pt, stroke: none, fill: blue)[ #set text(fill: white, size: 14pt, weight: "medium") #set align(center + horizon) #title ] #v(-6pt) #rect(width: 100%, radius: 4pt, inset: 14pt, stroke: none, fill: luma(90%))[ #set par(justify: false) #body ] ] #grid( columns: (43%, 1fr), gutter: 6pt, )[ #cell[ 1. Install Simply ][ ```typ 1. Just use the Web App: https://typst.app/ 2. Or use Typst locally: - Install VS Code - Install Tinymist ``` #v(14.5pt) ] ][ #cell[ 2. Split by Headings ][ #grid( columns: 2, gutter: 5pt, )[ ```typ == First Title Text for the first slide. == Second Title Text for the second slide. ``` ][ #v(-2pt) #rect(width: 66pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = First Title #line(length: 100%, stroke: black) Text for the first slide. ] #rect(width: 66pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = Second Title #line(length: 100%, stroke: black) Text for the first slide. ] ] ] ] #show raw.where(block: true): block.with(height: 36pt) #cell[ 3. Math, Layout, Programming and Animation ][ #grid( columns: (1fr,) * 4, gutter: 5pt, )[ ```typ // Math $ E = m c^2 $ ``` #rect(width: 100%, height: 42pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = Math #set text(12pt) $ E = m c^2 $ ] ][ ```typ // Layout #slide( composer: (2fr, 1fr))[A][B] ``` #rect(width: 100%, height: 42pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = Layout #set text(12pt) #table(columns: (2fr, 1fr))[A][B] ] ][ ```typ // Programming $ cos(0) = #calc.cos(0) $ ``` #rect(width: 100%, height: 42pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = Programming #set text(12pt) $ cos(0) = #calc.cos(0) $ ] ][ ```typ // Animation First #pause Second ``` #rect(width: 100%, height: 42pt, fill: white, stroke: blue, radius: 3pt)[ #set text(7pt) = Animation #set text(9.5pt) First #v(-8pt) #line(length: 100%) #v(-8pt) First Second ] ] ] #[ #show raw.where(block: true): block.with(height: 4pt) #show raw: set text(weight: "bold") #show image: block.with(radius: 2pt, stroke: blue, clip: true) #cell[ 4. Beautiful Themes and Simple Customization ][ #grid( columns: (1fr,) * 4, gutter: 5pt, )[ ```typ 1. Aqua ``` #image("images/aqua.png") ][ ```typ 2. Metropolis ``` #image("images/metropolis.png") ][ ```typ 3. University ``` #image("images/university.png") ][ ```typ 4. Stargazer ``` #image("images/stargazer.png") ] ] ] #v(-6pt) #set text(9pt) MIT License #sym.copyright 2024 #h(1fr) #octique-inline("mark-github", baseline: 1pt) https://github.com/touying-typ/touying
https://github.com/AliothCancer/AppuntiUniversity
https://raw.githubusercontent.com/AliothCancer/AppuntiUniversity/main/capitoli_applicazioni/vad.typ
typst
= Vad *V* entricular *A* ssist *D* evice == HearthWare Dispositivo caratterizzato da pompa di tipo centrifugo e levitazione magnetica del rotore combinata con propulsione delle palette (lifting) per il mantenimento della posizione flottante. === Shear Stress $tau$ $ tau = mu dot gamma $ - $mu$ : viscosità dinamica sangue (costante) - $ space space = 3 c P ("centiPoise") = 0.03 g / (c m space s) = 0.003 (N s)/m^2 $\ - $gamma$ : Velocità di deformazione angolare $"rad"/s$ $ gamma = U_t/h_m $ - $U_t$ : velocità di trascimento - $h_m$ : altezza del singolo meato =$(h_"scatola"-h_"rotore")/2$ $ U_t = omega r $ - $omega$ : velocità angolare, di rotazione del rotore. - $r$ : raggio del rotore, ce ne sono 2, interno ed esterno. #v(1.6cm) ==== formula esplicita $ tau_i = mu (omega r_i) / h_m $ - i = r. esterno o raggio interno === Tempo di attraversamento $ t = V_"me" / Q_"me" $ - $V_"me"$: volume del meato - $Q_"me"$: portata del meato === Volume meato $ V_"me" = pi/4 (d_"est."^2 - d_"int."^2) dot h_m $ #align(center)[#image("../immagini/volume_meato.png" , height: 6cm)] === Portata del meato $ Q_"me" = Q_"ematica" dot "Flusso"%_"me" \ \ $
https://github.com/elteammate/typst-compiler
https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/pprint.typ
typst
#import "reflection-ast.typ": is_ast_node #import "typesystem.typ": type_to_string #let pprint(node) = { let ty = if is_ast_node(node) { "ast" } else if type(node) == "dictionary" and "instr" in node { "ir_instr" } else if type(node) == "dictionary" and "code" in node and "labels" in node { "ir" } else { type(node) } if ty == "ast" { [ #text(blue, raw(node.type)) #if "ty" in node [#text(red, raw(type_to_string(node.ty)))] /* @#pprint_span(node.span) */ #h(1em) #pprint(node.fields) ] } else if ty == "ir_instr" { [ #h(1em) #text(red, raw(node.res)) = #text(weight: "extrabold", raw(node.instr)) #text(red, raw(node.ty)) #node.args.map(x => text(blue, raw(repr(x)))).join([ ]) ] } else if ty == "ir" { let labels = range(node.code.len() + 1).map(x => ()) for label, pos in node.labels { labels.at(pos).push(label) } [ \ ] for i, instr in node.code [ #box(align(text(blue, raw(instr.res)), end), width: 5em) = #text(weight: "extrabold", raw(instr.instr)):#text(red, raw(instr.ty)) #h(1em) #instr.args.map(x => [\<#text(blue, raw(repr(x)))\>]).join(h(0.6em)) \ ] [locals: #pprint(node.locals)] [params: #pprint(node.params)] [slots: #pprint(node.slots)] } else if ty in ("dictionary", "array") { let items = () for k, v in node { items.push([#raw(str(k)): #pprint(v)]) } list(..items) } else { text(maroon, raw(repr(node))) } }
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/grid-1_02.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page #set page(height: 3cm, margin: 0pt) #grid( columns: (1fr,), rows: (1fr, auto, 2fr), [], align(center)[A bit more to the top], [], )
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/closure-16.typ
typst
Other
// Error: 13-14 duplicate parameter: a #let f(a, ..a) = none
https://github.com/eduardz1/Bachelor-Thesis
https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/chapters/introduction.typ
typst
#import "../utils/common.typ": * = Introduction The following project was realized as an internship project during my Erasmus semester abroad in Oslo, Norway in collaboration with the #link("https://www.uio.no/")[University of Oslo] and the #link("https://sirius-labs.no/")[Sirius Research Center]. The central focus lies in the development of a digital twin (see @digital-twins) of a greenhouse and the optimization of the environmental conditions for maximum growth potential. Using SMOL, a programming language developed in-house at the research center (see @smol-heading), we can interface with the simulation to predict optimal watering timing and the correct quantity of water to use. #_content( [ == Learning Outcome The internship required several theoretical and practical competencies to be acquired, such as: - Understanding the concept of digital twins. - Learning the syntax and semantics of SMOL to more easily interface with semantic technologies and test it in a real-world scenario. - Learning in depth the concept of semantic technologies (in particular RDF, OWL, SPARQL) and their usage in the context of digital twins. - Learning the basics of the FMI standard. - Learning basic concepts of electronics for the connection of sensors and actuators to a Raspberry Pi. The project also required the usage of several tools such as: - Raspberry Pi and how to work with them on both a software and hardware level. - InfluxDB for efficient data storage of the sensors' readings. - Python, Java, and SMOL as programming languages. By modeling a small-scale model of a digital twin we were able to build the basis for the analysis of a larger-scale problem. Other than the competencies listed above, it was also important to be able to work in a team by dividing tasks and efficiently managing the codebases of the various subprojects (by setting up build tools and CI pipelines in the best way possible, for example). Documentation was also important given that the project is still ongoing and currently being picked up by another student. Electronic prototyping was also a big part of the project. We had to learn how to connect sensors and actuators to a Raspberry Pi (which required the use of breadboards, analog-to-digital converters, and relays for some of them) and how to translate the signal in a way that could be used as data whenever the output was merely a voltage reading. == My Contribution As a team we split our roles evenly and divided the project into sub-tasks but worked together on most of the main ones, my involvement was primarily focused on the following areas: - The hardware side of the project and the setup and configuration of the Linux environment. - The Python side of the codebase, in particular the code for the communication with the sensors. == Results A functioning prototype was built with the potential to be easily scaled both in terms of size and complexity. Adding new shelves with new plants is as easy as adding a new component to the model and connecting the sensors and actuators to the Raspberry Pi. The model is easily extendable to add new components and functionalities such as additional actuators for the control of the temperature and humidity or separate pumps dedicated to the dosage of fertilizer. New sensors can also be easily added (a PH sensor would prove useful for certain plants) #v(600pt) /* FIXME: remove once issue #466 is implemented */ both in the asset model and the code, each sensor and actuator is represented as a class and they are all being read independently from each other. == Thesis Contents The thesis from a theoretical point of view focuses on the concept of digital twins in @digital-twins and the way the SMOL language (in @smol-heading) is closely tied with them. In @tools-and-technologies we will discuss notions regarding semantic technologies in addition to all the tools and technologies we used, such as NoSQL databases and different programming languages and paradigms. In @raspberry-responsabilities-and-physical-setup we will treat the hardware side of the project and how the sensors interface on the software side. In @software-components we will take a deep dive into the codebase and have a closer look at the implementation and structure of the various programs. ] )
https://github.com/JakMobius/courses
https://raw.githubusercontent.com/JakMobius/courses/main/mipt-os-basic-2024/sem07/bubbles.typ
typst
#import "@preview/cetz:0.2.2" #import "@preview/suiji:0.3.0": * #let get-circle-intersections(x1, y1, r1, x2, y2, r2) = { let d = calc.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) let a = (r1 * r1 - r2 * r2 + d * d) / (2 * d) let determinant = r1 * r1 - a * a if determinant < 0 { return () } let h = calc.sqrt(determinant) let x = x1 + a * (x2 - x1) / d let y = y1 + a * (y2 - y1) / d let x3 = x + h * (y2 - y1) / d let y3 = y - h * (x2 - x1) / d let x4 = x - h * (y2 - y1) / d let y4 = y + h * (x2 - x1) / d ((x3, y3), (x4, y4)) } #let draw-small-bubbles(label, count: 4, fill: none, stroke: 3pt + luma(50)) = { cetz.draw.get-ctx(ctx => { let anchor = ctx.nodes.at(label) let distance = cetz.path-util.length(anchor.drawables.at(0).segments) let radius-a = 0.2 let radius-b = 0.8 let total-radius-deltas = (count - 1) * (count - 2) / 2 let radius-delta = (radius-b - radius-a) / count let base-spacing = distance / (count - 1) let rng = gen-rng(42) let t = 0 let res = (); for i in range(0, count) { let radius = radius-a + radius-delta * i cetz.draw.circle((name: label, anchor: t), radius: 1.0cm * radius, fill: fill, stroke: stroke) res.push(i) t += base-spacing // Radius correction t += radius-delta * 2 * i t -= radius-delta * 2 * total-radius-deltas / (count - 1) if t > distance { t = distance } } }) } #let default-bubble-fill = gradient.radial((white, 0%), (luma(240), 100%)) #let bubbles-to-path(random-bubbles) = { let points = () for i in range(0, random-bubbles.len() + 1) { let (x1, y1, r1) = random-bubbles.at(if i == 0 { random-bubbles.len() - 1 } else { i - 1 }) let (x2, y2, r2) = random-bubbles.at(if i == random-bubbles.len() { 0 } else { i }) let intersections = get-circle-intersections(x1, y1, r1, x2, y2, r2) let intersection-modules = intersections.map(((xi, yi)) => { xi * xi + yi * yi }) let smallest-module = intersection-modules.fold(0, calc.max) let smallest-module-index = intersection-modules.position((x) => x == smallest-module) if(smallest-module-index == none) { continue // panic(i) } let (xi, yi) = intersections.at(smallest-module-index) if points.len() != 0 { let last-point = (xi, yi) let prev-point = points.at(points.len() - 1) let (xm, ym) = ((prev-point.at(0) + last-point.at(0)) / 2, (prev-point.at(1) + last-point.at(1)) / 2) xm -= x1; ym -= y1; let mid-length = calc.sqrt(xm * xm + ym * ym) let mid-coef = r1 / mid-length xm = xm * mid-coef + x1 ym = ym * mid-coef + y1 points.push((xm, ym)); } points.push((xi, yi)); } points } #let get-square-angles(points) = { let angles = () let side = int(points / 4) for i in range(0, side) { angles.push(calc.atan2(1, 1 - i / (points / 8)).rad()) } for i in range(0, side) { angles.push(angles.at(i) - calc.pi / 2) } for i in range(0, side) { angles.push(angles.at(i) - calc.pi) } for i in range(0, side) { angles.push(angles.at(i) - calc.pi * 3 / 2) } angles } #let distance-to-unit-square(angle) = { if angle < 0 { return distance-to-unit-square(-angle) } angle = calc.rem(angle, calc.pi / 2) if(angle > calc.pi / 4) { angle = calc.pi / 2 - angle } let tangent1 = 1; let tangent2 = calc.tan(angle); return calc.sqrt(tangent1 * tangent1 + tangent2 * tangent2) } #let generate-bubbles-from-angles(angles) = { let bubbles = angles.len() let radius-variance = 0.3 let bubble-default-radius = (4 / bubbles) * (1 + radius-variance) * 1.3 let rng = gen-rng(42) let random-bubbles = () for angle in angles { let rand-arr = () (rng, rand-arr) = random(rng, size: 3); let square = distance-to-unit-square(angle) let cx = calc.cos(angle) * square let cy = calc.sin(angle) * square let cr = bubble-default-radius * (1 + radius-variance * (rand-arr.at(2) - 0.5) * 2) // cetz.draw.circle(( // cx * width / 2 + x, // -cy * width / 2 + y), // stroke: 3pt + black, // radius: 1cm * cr * width / 2 // ) random-bubbles.push((cx, cy, cr)) } random-bubbles } #let clamp-reduce(value, reduce) = { if value > reduce { value - reduce } else if value < -reduce { value + reduce } else { 0 } } #let generate-bubble-wall(x0, y0, x1, y1, count) = { let distance = calc.sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0)) let dx = (x1 - x0) / count let dy = (y1 - y0) / count let radius-variance = 0.3 let bubble-default-radius = (distance / count / 2) * (1 + radius-variance) * 1.3 let rng = gen-rng(42) let random-bubbles = () for i in range(0, count) { let rand-arr = () (rng, rand-arr) = random(rng, size: 3); let cx = x0 + dx * i let cy = y0 + dy * i let cr = bubble-default-radius * (1 + radius-variance * (rand-arr.at(2) - 0.5) * 2) random-bubbles.push((cx, cy, cr)) } random-bubbles } #let draw-bubble(x0, y0, width, height, fill: default-bubble-fill, stroke: 3pt + luma(50)) = { let x = x0 + width / 2 let y = y0 + height / 2 let bubbles = 16 let dimension-reduce = 0.8 width = clamp-reduce(width, dimension-reduce) height = clamp-reduce(height, dimension-reduce) let angles = get-square-angles(bubbles) let random-bubbles = generate-bubbles-from-angles(angles) let points = bubbles-to-path(random-bubbles) points = points.map(((xp, yp)) => { ((xp / 2) * width + x, (yp / 2) * height + y) }) if points.len() > 2 { cetz.draw.hobby(..points, close: true, fill: fill, stroke: stroke ) } }
https://github.com/RoyalRoppers/stadgar
https://raw.githubusercontent.com/RoyalRoppers/stadgar/master/README.md
markdown
# Statutes of RoyalRoppers The latest version of the statutes are available through a release [here](https://github.com/RoyalRoppers/stadgar/releases/download/latest/royalroppers-statutes.pdf)! ## Changes Whenever a change is approved on one yearly meeting, a pull request with the change should be opened. After the next vote, the pull request should be merged or closed. ## Structure All styling stuff is in `template.typ`, so that `stadgar.typ` as much as possible only contains the statutes themselves. ## Rendering to PDF This project uses [typst](https://github.com/typst/typst) for typesetting and can be rendered to a PDF with: ```sh $ typst c stadgar.typ ``` To get automatic updates as the statutes are changed locally, use `w` instead of `c` and display the PDF using a viewer that supports auto reloading, such as evince (usually called "documents" in gnome). Some editor plugins also support this. ## References To refer to another paragraph, append `<some-descriptive-id>` to it and refer to it with `@some-descriptive-id`. For example: ```typ == En vacker paragraf <vacker> ... == En annan paragraf Någonting någonting enligt @vacker. ``` Would turn into something like: ``` § 2.2 En vacker paragraf ... § 2.3 En annan paragraf Någonting någonting enligt § 2.2. ```
https://github.com/Ngan-Ngoc-Dang-Nguyen/thesis
https://raw.githubusercontent.com/Ngan-Ngoc-Dang-Nguyen/thesis/main/docs/stability%20radius.typ
typst
= BÁN KÍNH ỔN ĐỊNH CỦA ĐIỂM 1-MEDIAN Giả sử $w in RR_+^n$ là một vecto trọng số thỏa mãn điều kiện (1) và $v_1$ là một trung vị tương ứng với $w$. Trong thực tế, vecto trọng số $w$ có thể bị nhiễu thành vecto $tilde(w) in RR_+^n$. Ta giả sử rằng sự khác biệt giữ $w$ và $tilde(w)$ là nhỏ, tức là $norm(tilde(w)-w)_infinity <= epsilon_0$, hoặc tương đương $tilde(w) in [w-epsilon; w+ epsilon] $ với một mức nhiễu nhỏ $epsilon>0$. Trong bối cảnh có nhiễu này, chúng ta nhắm đến việc điều tra sự ổn định của điểm trung vị $v_1$. Cụ thể, chúng ta quan tâm đến mức nhiễu lớn nhất có thể $epsilon$ sao cho $v_1$ vẫn còn tối ưu đối với $tilde(w)$, tức là $ R(w)=sup{epsilon>= 0: v_1 in X_tilde(w)^*, quad forall tilde(w)in [w-epsilon;w+epsilon] sect RR_+^n} $. Ở đây, $R(w)$ được gọi là _bán kính ổn định_ của điểm $v_1$ tương ứng với vecto $w$. Mặc dù $R(w)$ được định nghĩa một cách ngầm định, nó có một cận dưới đơn giản nhưng chặt chẽ. *Định lý...* Ta có $ R(w) >= underline(R)(w) = min_(u in N(v_1)) 1/n (1-2 angle.l w, bb(1)_T_u angle.r). $ (7) Hơn nữa, dấu "=" xảy ra nếu $R(w) < min_(i=1,...,n) w_i$ Trước khi chứng minh *Định lý...* cần lưu ý rằng cận dưới $R(w)$ được đảm bảo không âm do tính tối ưu của $v_1$ (6). Hơn nữa, điều kiện $R(w) < min_(i=1,...,n) w_i$ về cơ bản có nghĩa là $R(w)$ là một mức độ nhiễu sao cho bất kỳ trọng số nào trong khoảng $[w-R(w), w + R(w)]$ vẫn dương, khiến nó trở thành một điều kiện nhẹ nhàng. *Chứng minh.* Đặt $epsilon_u = 1/n (1-2 angle.l w, bb(1)_T_u angle.r)$. Không khó để thấy rằng $epsilon_u$ thỏa mãn phương trình sau: $ angle.l w+ epsilon_u, bb(1)_T_u angle.r = angle.l w- epsilon_u, bb(1)_(T without T_u) angle.r $ Để chứng minh (7), chỉ cần chứng minh rằng với bất kỳ $epsilon$ nào thỏa mãn $epsilon <= min_(u in N(v_1)) epsilon_u$ thì $v_1$ là một điểm trung vị đối với bất kỳ $tilde(w) in [w-epsilon, w+epsilon] sect RR_+^n$. Với tất cả $epsilon <= min_(u in N(v_1) epsilon_u), tilde(w) in [w - epsilon, w+ epsilon] sect RR_+^n$ và $u in N(v_1)$, ta có: $ angle.l tilde(w), bb(1)_T_u angle.r <= angle.l w+ epsilon_u, bb(1)_T_u angle.r = angle.l w - epsilon_u, bb(1)_(T without T_u) angle.r <= angle.l tilde(w), bb(1)_(T without T_u) angle.r. $ Theo *Định lý 2.1* có thể kết luận rằng $v_1 in X_tilde(w)^*$. Giả sử rằng $underline(R)(w) < min_(i=1,...,n) w_i$, mục tiêu của ta là chứng minh rằng $R(w)= underline(R)(w).$ Để đạt được mục tiêu này, chúng tôi chứng minh rằng đối với mức độ nhiễu $epsilon$ lớn hơn $R(w)$, thì sẽ tồn tại một trọng số nhiễu khả thi $tilde(w)$ sao cho $v_1$ không còn là tối ưu đối với $tilde(w)$. Cụ thể, giả sử $epsilon in (R(w), min_(i=1,...,n)w_i)$, sau đó chúng tôi xây dựng một số $tilde(w) in [w-epsilon,w+epsilon] sect RR_n^+$ sao cho $v_1 in.not X_tilde(w)^*$. Vì $epsilon > R(w)$, tồn tại một số $u in N(v_1)$ sao cho $epsilon > epsilon_u$. Do đó $ angle.l w + epsilon, bb(1)_T_u angle.r > angle.l w + epsilon_u, bb(1)_T_u angle.r = angle.l w - epsilon_u, bb(1)_(T without T_u) angle.r > angle.l w- epsilon, bb(1)_(T without T_u) angle.r. $ (9) Đặt $tilde(w)= (w+ epsilon) dot.circle bb(1)_T_u + (w-epsilon) dot.circle bb(1)_(T without T_u)$, trong đó $dot.circle$ là pháp nhân Hadamard giữa hai vecto. Lưu ý rằng $tilde(w) in [w - epsilon, w + epsilon]$ và dương vì $epsilon <= min_(i=1,...,n) w_i$. Quan sát rằng (9) có thể được viết lại dưới dạng $ angle.l tilde(w), bb(1)_T_u angle.r > angle.l tilde(w), bb(1)_(T without T_u) angle.r$. Do đó, $X_tilde(w)^* subset T_u$ theo bổ đề 2.1. Vì $v_1 in.not T_u$, ta có $v_1 in.not X_tilde(w)^*$ Vậy ta hoàn thành chứng minh. *Ví dụ 3.1* Ta xem xét cây có trọng số $T$ trong hình 1. Bán kính ổn định $R(w)$ bị chặn dưới bởi $underline(R)(w) = min{epsilon_v_2, epsilon_v_3, epsilon_v_4}= 0.1/9$, trong đó $epsilon_v_2 = 0.34/9, epsilon_v_3 = 0.76/9, epsilon_v_4 = 0.1/9 $. Bởi vì $0.1/9 < min_(i=1,...,n) w_i = 0.06$, ta thu được $R(w)= 0.1/9 .$
https://github.com/donabe8898/typst-slide
https://raw.githubusercontent.com/donabe8898/typst-slide/main/opc/並行prog/01/01.typ
typst
MIT License
// typst compile 01.typ /home/yugo/git/donabe8898/typst-slide/opc/並行prog/01/第1回/{n}.png --format png #import "@preview/polylux:0.3.1": * #import themes.clean: * #show: clean-theme.with( aspect-ratio: "16-9", footer: "Goであそぼう", // short-title: "", logo: image("01素材/gopher.svg"), color: teal ) #show link: set text(blue) #set text(font: "Noto Sans CJK JP",size:18pt) #show heading: set text(font: "Noto Sans CJK JP") #show raw: set text(font: "JetBrains Mono") #show raw.where(block: true): block.with( fill: luma(240), inset: 10pt, radius: 4pt ) // TODO: 本文 #title-slide( title: "Goの並行処理であそぼう 🐭", subtitle: "(第一回) 並行処理はいいぜ", authors: "<NAME> a.k.a donabe8898", date: none, // watermark: image("01素材/gopher.svg",) ,//透かしの画像 secondlogo: image("01素材/gopher.svg") // 通常ロゴの反対側に映るロゴ ) #slide(title: "本講義のターゲット層")[ - サーバーに興味がある - モダンな言語を習得したい ] #slide(title: "自己紹介")[ = 岡本 悠吾 - <NAME> #v(0.5em) - T学科4回生 - サークル内でLinux関連の講義をやってます - 先日内定もらいました〜 Happy〜♪ #v(1em) #grid( columns: (200pt,auto), text[ == すきなもの - 鉄道 - ガソリン車 - コンピュータ - ゲーム - 蕎麦 ], text[ == きらいなもの - きのこ類 ] ) ] #focus-slide(foreground:white, background: teal)[ みなさんプログラム書いてますか!!!!!! ] // TODO: 1. みなさん何のプログラムを書いてるか #slide(title: "アンケート取ります")[ #v(1em) *Q. 普段どんなプログラムを書いている?* #v(1em) + 競技プログラミング 🚴 + ゲーム開発 🎮 + 自作ソフトウェア 🖳 + 研究用 🧪 + 授業でしかプログラム書かない 🏫 + プログラミング嫌い 🙁 ] #focus-slide(foreground:white, background: teal)[ 何も特別な事をしていない限り単一処理 ] // TODO: 2. プロセスの説明 #new-section-slide("Section 1. プロセス") #slide()[ = プロセス #v(1em) ```text プロセスとは、処理のことである。情報処理においてプログラムの動作中のインスタンスを意味し、プログラムのコードおよび全ての変数やその他の状態を含む。オペレーティングシステム (OS) によっては、プロセスが複数のスレッドで構成される場合があり、命令を同時並行して実行する - Wikipediより ``` #v(1em) - プロセス → プログラム本体 - スレッド → プログラムの処理内容 - プロセス数 $<=$ スレッド数 ] #slide()[ #figure( image("01素材/process.png",width: 60%), caption: [ OS内のプロセスなんとなく図 ] ) ] #slide()[ #align(center)[ = プロセス数の確認 ```bash ps aux | wc -l ``` ] #v(5em) #align(center)[ = スレッド数の確認 ```bash ps -eL | wc -l ``` ] ] // TODO: 3. Golangの説明 #new-section-slide("Section 2. Go言語") #slide()[ #grid( columns: (auto,auto), gutter: 15pt, text[ = Go #v(1em) 2009年Googleが発表したプログラミング言語 == 特徴 - *クセの強い*オブジェクト指向 - コンパイル言語 - メモリ安全かつガベージコレクション - 静的型付け - Python,Rubyに負けない程高い生産性 - オープンソース - マスコットはホリネズミのGopherくん ], text[ #figure( image("01素材/gopher.svg",width: 40%), ) ], ) ] #slide()[ == 対応OS Linux, macOS, FreeBSD, NetBSD, OpenBSD, DragonFly BSD Plan 9 from Bell Labs, Solaris, Microsoft Windows NT iOS, Android, AIX, illumos #v(2em) - *開発者がSuper Hacker* - ケン・トンプソン: オリジナルのUNIX開発者の一人. grep, 正規表現の発案者 - ロブ・パイク: UTF-8, 世界初のUNIX用ウィンドウシステム - <NAME>: V8JavaScriptエンジン, Java HotSpot 仮想マシン ] #slide()[ #grid( columns: (auto,auto), text[ = 何ができるのコレ #v(1em) + サーバーサイドプログラム - API返したり, ミドルウェアを操作したり... - Webサーバーのバックエンドプログラム + オープンソースプロジェクト - 言語使用もコンパイラ、ツール群も一式揃えるのが楽 ], text[ #figure( image("01素材/gopher_brown.png",width: 40%), ) ] ) ] #slide(title: "Goの環境を作ってみよう")[ #v(1em) 構築方法: 私が書いた構築手順書(Linux用だけど他のOSでも大体一緒) #link("https://github.com/donabe8898/BuildEnvironments/blob/donabe8898/Language/Go/Ubuntu.md")[ https://github.com/donabe8898/BuildEnvironments/blob/donabe8898/Language/Go/Ubuntu.md ] #v(4em) == 環境構築がどうしても出来ない人 - The Go Playground - #link("https://go.dev/play/")[https://go.dev/play/] ] #slide(title:"Hello, World")[ #align(center)[ ```go package main import "fmt" func main() { fmt.Println("Hello, World") } ``` ] ] // TODO: 4. 並行処理と並列処理 #new-section-slide("Section 3. 並行処理と並列処理") #slide()[ = 並行と並列 #v(1em) - 並行は*ある範囲で複数の処理を独立に実行できる構成* - 並列は*ある時点で物事の処理が同時に実行* - Golangは*並行処理* ] #slide()[ // 並行と並列の図 #figure( image("01素材/並列と並行.svg",width: 90%) ) ] // TODO: 5. Golangの基礎文法(写経) #new-section-slide("Section 4. Goの基礎") #slide()[ = 写経タイム!!!! #v(1em) - Discordに貼ったPDFのソースコードを写経(丸写し)しましょう。 - なるべく自分でタイピングすることを*強く*おすすめします #v(1em) - 写経できた人はVCステータスを「できた!」にしてください - 質問がある人はテキストチャットかVCでどうぞ ] #new-section-slide("解説") // TODO: 6. 練習問題1 #new-section-slide("Section 5. 練習問題 1") #slide()[ = 次の問題を解きましょう #v(1em) - #link("https://atcoder.jp/contests/abc052/tasks/abc052_a")[https://atcoder.jp/contests/abc052/tasks/abc052_a] #align(left)[ #figure( image("01素材/probrem01.png",width: 50%) ) ] ] // TODO: 7. goルーチン(写経) #new-section-slide("Section 6. goルーチン") #slide()[ = goルーチン #v(1em) - Golangの並行処理を司る仕組み - 関数の前に`go`をつける #v(1em) ```Go go funcA() time.Sleep(3 * time.Second) ``` ] #slide()[ = 写経タイム!!!! #v(1em) - Discordに貼ったPDFのソースコードを写経(丸写し)しましょう。 - なるべく自分でタイピングすることを*強く*おすすめします #v(1em) - 写経できた人はVCステータスを「できた!」にしてください - 質問がある人はテキストチャットかVCでどうぞ ] #slide(title: "解説")[ #figure( image("01素材/並行処理1.svg",width: 50%) ) ] #slide(title: "次回")[ - 次回は並行処理を採用する場合について説明 = 並行処理は必ずしも優秀ではない ]
https://github.com/wj461/operating-system-personal
https://raw.githubusercontent.com/wj461/operating-system-personal/main/HW1/hw1.typ
typst
#import emoji: arrow #align(center, text(17pt)[ *Operating-system homework\#1* ]) #(text(14pt)[ = Written exercises ]) = • Chap.1 - 1.16: Direct memory access is used for high-speed I/O devices in order to avoid increasing the CPU's execution load. - (a) How does the CPU interface with the device to coordinate the transfer? Use DMA controller to coordinate the transfer - (b) How does the CPU know when the memory operations are complete? DMA will send an interrupt to the CPU when the memory operations are complete. - (c) The CPU is allowed to execute other programs while the DMA controller is transferring data. Does this process interfere with the execution of the user programs? If so, describe what forms of interference are caused. Yes.\ If the CPU and the DMA need to share the same memory, it will reduced performance for the user programs because the CPU and the DMA will compete for the memory. = • Chap. 2 - 2.15: What are the two models of interprocess communication? What are the strengths and weakness of the two approaches? the message-passing model and the shared-memory model. - message-passing -> pipes - Strengths: - Easy to manage. - Weakness: - Slow than shared-memory - shared-memory -> shared memory - Strengths: - Fast than message-passing - Weakness: - Not easy to manage because everyone can use the shared memory. - 2.19: What is the main advantage of the microkernel approach to system design? How do user programs and system services interact in a microkernel architecture? What are the disadvantages of using the microkernel approach? - Main advantage: - The main advantage of the microkernel approach to system design is that it is more modular and easier to customize. - How do user programs and system services interact in a microkernel architecture? - They interact through message passing. #figure( image("./image/micokernel.png",width: 50%) ) - Disadvantages: - The modular design can make it more difficult to develop and maintain the operating system = • Chap. 3 - 3.12: Describe the actions taken by a kernel to context-switch between processes. Save the Current Process State to PCB-> Select the Next Process #figure( image("./image/context-switch.png",width: 50%) ) - 3.18: Give an example of a situation in which ordinary pipes are more suitable than named pipes and an example of a situation in which named pipes are more suitable than ordinary pipes. - Ordinary Pipes : one-way communication channel \ - ex. A parent process spawns multiple child processes and needs to implement a pipeline where the output of one child process serves as the input to the next child process. #grid( columns: (0.5fr, 1fr, 0.5fr, 1fr, 0.5fr), align: center + horizon, rect( width: 120%)[Parent], arrow.r.filled, rect( width: 120%)[child], arrow.r.filled, rect( width: 120%)[child] ) - Named Pipes : bi-directional communication channel - ex. Two independent processes running on the same system need to communicate with each other over a persistent, bi-directional channel. #grid( columns: (0.5fr, 1fr, 0.5fr), align: center + horizon, rect( width: 120%)[process], grid( columns: (1fr), align: center + horizon, arrow.r.filled, arrow.r.filled, ), rect( width: 120%)[process], )
https://github.com/SillyFreak/typst-crudo
https://raw.githubusercontent.com/SillyFreak/typst-crudo/main/README.md
markdown
MIT License
# Crudo Crudo allows conveniently working with `raw` blocks in terms of individual lines. It allows you to e.g. - filter lines by content - filter lines by range (slicing) - transform lines - join multiple raw blocks While transforming the content, the original [parameters](https://typst.app/docs/reference/text/raw/#parameters) specified on the given raw block will be preserved. ## Getting Started The full version of this example can be found in [gallery/thumbnail.typ](gallery/thumbnail.typ). `````typ From #let preamble = ```typ #import "@preview/crudo:0.1.1" ``` #preamble and #let example = ````typ #crudo.r2l(```c int main() { return 0; } ```) ```` #example we get #let full-example = crudo.join(preamble, example) #full-example If you execute that, you get #eval(full-example.text, mode: "markup") ````` ![Example](./thumbnail.png) ## Usage See the [manual](docs/manual.pdf) for details.
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024
https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/decide-wedges/entry.typ
typst
Creative Commons Attribution Share Alike 4.0 International
#import "/packages.typ": notebookinator #import notebookinator: * #import themes.radial.components: * #show: create-body-entry.with( title: "Decide: Pushing Robots", type: "decide", date: datetime(year: 2023, month: 9, day: 8), author: "<NAME>", witness: "<NAME>", ) We rated the choices by the following criteria: - Ease Of Build on a scale of 1 to 5. - Widespread Use on a scale of 1 to 5. - Use Of Actuators on a scale of 1 to 5. #decision-matrix(properties: ( (name: "Ease Of Build"), (name: "Widespread Use"), (name: "Use Of Actuators"), ), ("Wedges", 3, 4, 5), ("Plow", 2, 2, 5), ("Arms", 1, 1, 0)) #admonition( type: "decision", )[ The final decision is to use the wedges. Ultimately, they were the easiest and most efficient to use. The wedges are also passive, which means they don't require motors or pistons to be put into use. ] #grid( columns: (1fr, 1fr), gutter: 20pt, figure(image("./iso.png"), caption: "Isometric view"), figure(image("./top.png", height: 25%), caption: "Top view"), figure(image("./front.png", height: 25%), caption: "Front view"), figure(image("./side.png"), caption: "Side view"), ) \ = Final Design #image("./1.png") #image("./2.png")
https://github.com/mitex-rs/mitex
https://raw.githubusercontent.com/mitex-rs/mitex/main/packages/mitex/examples/bench.typ
typst
Apache License 2.0
#import "../lib.typ": * #set page(width: 500pt) #assert.eq(mitex-convert("\alpha x"), "alpha x ") Write inline equations like #mi("x") or #mi[y]. Also block equations: #mitex("\alpha x" * 8000) /* last^1 17000 Benchmark 1: typst compile --root . packages\mitex\examples\bench.typ Time (mean ± σ): 323.1 ms ± 18.0 ms [User: 84.4 ms, System: 14.1 ms] Range (min … max): 302.1 ms … 353.9 ms 10 runs 8000 Benchmark 1: typst compile --root . packages\mitex\examples\bench.typ Time (mean ± σ): 198.3 ms ± 6.5 ms [User: 50.2 ms, System: 24.6 ms] Range (min … max): 188.5 ms … 207.1 ms 14 runs last^2 17000 Benchmark 1: typst compile --root . packages\mitex\examples\bench.typ Time (mean ± σ): 638.8 ms ± 10.4 ms [User: 143.8 ms, System: 32.8 ms] Range (min … max): 616.5 ms … 652.5 ms 10 runs 8000 Benchmark 1: typst compile --root . packages\mitex\examples\bench.typ Time (mean ± σ): 503.2 ms ± 15.1 ms [User: 109.4 ms, System: 28.1 ms] Range (min … max): 485.8 ms … 535.5 ms 10 runs init 17000 Benchmark 1: typst compile --root . typst-package\examples\bench.typ Time (mean ± σ): 972.4 ms ± 28.3 ms [User: 223.4 ms, System: 62.2 ms] Range (min … max): 938.4 ms … 1029.7 ms 10 runs 8000 Benchmark 1: typst compile --root . typst-package\examples\bench.typ Time (mean ± σ): 687.6 ms ± 20.6 ms [User: 154.4 ms, System: 24.8 ms] Range (min … max): 668.2 ms … 731.7 ms 10 runs */
https://github.com/teamdailypractice/pdf-tools
https://raw.githubusercontent.com/teamdailypractice/pdf-tools/main/typst-pdf/examples/example-03.typ
typst
= Introduction In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers and how they contribute to the formation and behaviour of these natural structures. = கடவுள் வாழ்த்து
https://github.com/jgm/typst-hs
https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compute/calc-07.typ
typst
Other
// Error: 11-22 expected integer, float, length, angle, ratio, or fraction, found string #calc.abs("no number")
https://github.com/Myriad-Dreamin/typst.ts
https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_03.typ
typst
Apache License 2.0
#import "/contrib/templates/std-tests/preset.typ": * #show: test-page // Test ligatures. fi vs. #text(ligatures: false)[No fi]
https://github.com/msakuta/latypst
https://raw.githubusercontent.com/msakuta/latypst/master/README.md
markdown
# latypst An experimental tool to convert LaTeX math to Typst math Try it now on your browser! https://msakuta.github.io/latypst/ ## Overview [Typst](https://typst.app/) is a great typesetting software, but they decided to make the math markup not compatible with LaTeX's. It is fine as a brand new typesetting program, but sometimes I would like to convert existing LaTeX documents to Typst, and while most of the document structure is straightforward to convert, math is not so easy. However, the conversion is almost (90%) mechanical replacement, so I thought it should be automated. This project is an attempt to make such an automatic converter and a hope that I can learn about LaTeX and Typst syntax deeper. As this project's scope is so narrow, a complete document-wide conversion is not the goal. If it works for a math between $ symbols, this project would achieve the goal. ## Example Command: ``` echo '$\frac{df}{dx} = \dot{f}$' | cargo r; typst compile out.typ ``` Output: ![Example output](images/example-output.png)
https://github.com/tingerrr/masters-thesis
https://raw.githubusercontent.com/tingerrr/masters-thesis/main/src/de/chapters/2-t4gl.typ
typst
#import "/src/util.typ": * #import "/src/figures.typ" T4gl (_engl._ #strong[T]esting #strong[4]th #strong[G]eneration #strong[L]anguage) ist ein proprietäres Softwareprodukt zur Entwicklung von Testsoftware für Industrieprüfanlagen wie die LUB (#strong[L]ow Speed #strong[U]niformity and #strong[B]alance), HSU (#strong[H]igh #strong[S]peed #strong[U]niformity and Balance) oder vielen Weiteren. T4gl steht bei der Brückner und Jarosch Ingenieurgesellschaft mbH (BJ-IG) unter Entwicklung und umfasst die folgenden Komponenten: - Programmiersprache - Anwendungsspezifische Features - Compiler - Statische Anaylse - Übersetzung in Instruktionen - Laufzeitsystem - Ausführen der Instruktionen - Scheduling von Green Threads - Bereitstellung von maschinen- oder protokollspezifischen Schnittstellen Wird ein T4gl-Script dem Compiler übergeben, startet dieser zunächst mit der statischen Analyse. Bei der Analyse der Skripte werden bestimmte Invarianzen geprüft, wie die statische Länge bestimmter Arrays, die Typsicherheit und die syntaktische Korrektheit des Scripts. Nach der Analyse wird das Script in eine Sequenz von _Microsteps_ (atomare Instruktionen) kompiliert. Im Anschluss führt des Laufzeitsystem die kompilierten _Microsteps_ aus, verwaltet Speicher und Kontextwechsel der _Microsteps_ und stellt die benötigten Systemschnittstellen zur Verfügung. = Echtzeitanforderungen <sec:realtime> Je nach Anwendungsfall werden an das T4gl-Laufzeitsystem Echtzeitanforderungen gestellt. #quote(block: true, attribution: [ <NAME> @bib:sch-05[S. 39] unter Verweis auf DIN 44300 ])[ Unter Echtzeit versteht man den Betrieb eines Rechensystems, bei dem Programme zur Verarbeitung anfallender Daten ständig betriebsbereit sind, derart, dass die Verarbeitungsergebnisse innerhalb einer vorgegebenen Zeitspanne verfügbar sind. Die Daten können je nach Anwendungsfall nach einer zeitlich zufälligen Verteilung oder zu vorherbestimmten Zeitpunkten anfallen. ] Ist ein Echtzeitsystem nicht in der Lage, eine Aufgabe in der vorgegebenen Zeit vollständig abzuarbeiten, spricht man von Verletzung der Echtzeitbedingungen, welche an das System gestellt wurden. Je nach Strenge der Anforderungen lassen sich Echtzeitsysteme in drei verschiedene Stufen einteilen: / Weiches Echtzeitsystem: Die Verletzung der Echtzeitbedinungen führt zu degenerierter, aber nicht zerstörter Leistung des Echtzeitsystems und hat _keine_ katastrophalen Folgen @bib:lo-11[S. 6]. / Festes Echtzeitsystem: Eine geringe Anzahl an Verletzungen der Echtzeitbedingungen hat katastrophale Folgen für das Echtzeitsystem @bib:lo-11[S. 7]. / Hartes Echtzeitsystem: Eine einzige Verletzung der Echtzeitbedingungen hat katastrophale Folgen für das Echtzeitsystem @bib:lo-11[S. 6]. T4gl ist ein weiches Echtzeitsystem. Für Anwendungsfälle, bei denen Echtzeitanforderungen an T4gl gestellt werden, darf die Nichteinhaltung dieser Anforderungen keine katastrophalen Folgen haben (Personensicherheit, Prüfstandssicherheit, Prüflingssicherheit). In diesem Fall sind im schlimmsten Fall nur die Testergebnisse ungültig und müssen verworfen werden. = T4gl-Arrays <sec:t4gl:arrays> Bei T4gl-Arrays handelt es sich um mehrdimensionale assoziative Arrays mit Schlüsseln, welche eine voll definierte Ordnungsrelation haben. Um ein Array in T4gl zu deklarieren, wird mindestens ein Schlüssel- und ein Wertetyp benötigt. Auf den Wertetyp folgt in eckigen Klammern eine komma-separierte Liste von Schlüsseltypen. Die Indizierung erfolgt wie in der Deklaration durch eckige Klammern, es muss aber nicht für alle Schlüssel ein Wert angegeben werden. Bei Angabe von weniger Schlüsseln als in der Deklaration, wird eine Referenz auf einen Teil des Arrays zurückgegben. Sprich, ein Array des Typs `T[U, V, W]` welches mit `[u]` indiziert wird, gibt ein Unter-Array des Typs `T[V, W]` zurück, ein solches Unter-Array kann referenziert, aber nicht gesetzt werden. Wird in der Deklaration des Arrays ein Ganzzahlwert statt eines Typs angegeben (z.B. `T[10]`), wird das Array mit fester Größe und durchlaufenden Indizes (`0` bis `9`) als Schlüssel angelegt und mit Standardwerten befüllt. Für ein solches Array können keine Schlüssel hinzugefügt oder entnommen werden. #figure( figures.t4gl.ex.array1, caption: [ Beispiele für Deklaration und Indizierung von T4gl-Arrays. ], ) <lst:t4gl-ex> Bei den in @lst:t4gl-ex gegebenen Deklarationen werden, je nach den angegebenen Typen, verschiedene Datenstrukturen vom Laufzeitsystem gewählt. Diese ähneln den C++-Varianten in @tbl:t4gl-array-analogies, wobei `T` und `U` Typen sind und `N` eine Zahl aus $NN^+$. Die Deklaration von `staticArray` weist den Compiler an, ein T4gl-Array mit 10 Standardwerten für den `String` Typ (die leere Zeichenkette `""`) für die Schlüssel 0 bis einschließlich 9 anzulegen. Es handelt sich um eine Sonderform des T4gl-Arrays, welches eine dichte festgelegte Schlüsselverteilung hat (es entspricht einem gewöhnlichen Array). #figure( figures.t4gl.analogies, caption: [ Semantische Analogien in C++ zu spezifischen Varianten von T4gl-Arrays. ], ) <tbl:t4gl-array-analogies> Die Datenspeicherung im Laufzeitsystem kann nicht direkt ein statisches Array (`std::array<T, 10>`) verwenden, da T4gl nicht direkt in C++ übersetzt und kompiliert wird. Intern werden, je nach Schlüsseltyp, pro Dimension entweder ein Vektor oder ein geordnetes assoziatives Array angelegt. T4gl-Arrays verhalten sich wie Referenztypen, wird ein Array `a2` durch ein anderes Array `a1` initialisiert, teilen sich diese die gleichen Daten. Schreibzugriffe in einer Instanz sind auch in der anderen lesbar (demonstiert in @lst:t4gl-ref). #figure( figures.t4gl.ex.array2, caption: [Demonstration von Referenzverhalten von T4gl-Arrays.], ) <lst:t4gl-ref> Im Gegensatz zu dem Referenzverhalten der Arrays aus Sicht des T4gl-Programmierers steht die Implementierug durch QMaps. Bei diesen handelt es sich um Copy-On-Write (CoW) Datenstrukturen, mehrere Instanzen teilen sich die gleichen Daten und erlauben zunächst nur Lesezugriffe darauf. Muss eine Instanz einen Schreibzugriff durchführen, wird vorher sichergestellt, dass diese Instanz der einzige Referent der Daten ist, wenn nötig durch eine Kopie der gesamten Daten. Dadurch sind Kopien von QMaps initial sehr effizient, es muss lediglich die Referenzzahl der Daten erhöht werden. Die Kosten der Kopie zeigt sich erst dann, wenn ein Scheibzugriff nötig ist. Damit sich T4gl-Arrays trotzdem wie Referenzdaten verhalten, teilen sie sich nicht direkt die Daten mit CoW-Semantik, sondern QMaps durch eine weitere Indirektionsebene. T4gl-Arrays bestehen aus Komponenten in drei Ebenen: + T4gl: Die Instanzen aus Sicht des T4gl-Programmierers (z.B. die Variable `a1` in @lst:t4gl-ref). + Indirektionsebene: Die Daten aus Sicht des T4gl-Programmierers, die Ebene zwischen T4gl-Array Instanzen und deren Daten. Dabei handelt es sich um Qt-Datentypen wie QMap oder QVector. + Speicherebene: Die Daten aus Sicht des T4gl-Laufzeitsystems. Diese Ebene ist für den T4gl-Programmierer unsichtbar. Zwischen den Ebenen 1 und 2 kommt geteilte Schreibfähigkeit durch Referenzzählung zum Einsatz, mehrere T4gl-Instanzen teilen sich eine Qt-Instanz und können von dieser lesen, als auch in sie schreiben, ungeachtet der Anzahl der Referenten. Zwischen den Ebenen 2 und 3 kommt CoW + Referenzzählung zum Einsatz, mehrere Qt-Instanz teilen sich die gleichen Daten, Schreibzugriffe auf die Daten sorgen vorher dafür, dass die Qt-Instanz der einzige Referent ist, wenn nötig durch eine Kopie. Wir definieren je nach Tiefe drei Typen von Kopien: / Typ-1 (flache Kopie): Eine Kopie der T4gl-Instanz erstellt lediglich eine neue Instanz, welche auf die gleiche Qt-Instanz zeigt. Dies wird in T4gl durch Initialisierung von Arrays durch existierende Instanzen oder die Übergabe von Arrays an normale Funktionen hervorgerufen. Eine flache Kopie ist immer eine $Theta(1)$-Operation. / Typ-2: Eine Kopie der T4gl-Instanz *und* der Qt-Instanz, welche beide auf die gleichen Daten zeigen. Wird eine tiefe Kopie durch das Laufzeitsystem selbst hervorgerufen, erfolgt die Kopie der Daten verspätet beim nächten Schreibzugriff auf eine der Qt-Instanzen. Halbtiefe Kopien sind Operationen konstanter Zeitkomplexität $Theta(1)$. Aus einer halbtiefen Kopie und einem Schreibzugriff folgt eine volltiefe Kopie. / Typ-3 (tiefe Kopie): Eine Kopie der T4gl-Instanz, der Qt-Instanz *und* der Daten. Beim expliziten Aufruf der Methode `clone` durch den T4gl Programmierer werden die Daten ohne Verzögerung kopiert. Tiefe Kopien sind Operationen linearer Zeitkomplexität $Theta(n)$. Bei einer Typ-1-Kopie der Instanz `a` in @fig:t4gl-indirection:new ergibt sich die Instanz `b` in @fig:t4gl-indirection:shallow. Eine Typ-2-Kopie hingegen führt zur Instanz `c` in @fig:t4gl-indirection:deep. Obwohl eine tiefe Kopie zunächst nur auf Ebene 1 und 2 Instanzen kopiert, erfolgt die Typ-3-Kopie der Daten auf Ebene 3 beim ersten Schreibzugriff einer der Instanzen (@fig:t4gl-indirection:mut). In seltenen Fällen kann es dazu führen, dass wie in @fig:t4gl-indirection:deep eine Typ-2-Kopie angelegt wurde, aber nie ein Schreibzugriff auf `a` oder `c` durchgeführt wird, während beide Instanzen existieren. Sprich, es kommt zur Typ-2-Kopie, aber nicht zur Typ-3-Kopie. Diese Fälle sind nicht nur selten, sondern meist auch Fehler der Implementierung. Bei korrektem Betrieb des Laufzeitsystems sind Typ-2-Kopien kurzlebig und immer von Typ-3-Kopien gefolgt, daher betrachten wir im folgenden auch Typ-2-Kopien als Operationen linearer Zeitkomplexität $Theta(n)$, da diese bei korrektem Betrieb fast immer zu Typ-3 Kopien führen. #subpar.grid( figure(figures.t4gl.layers.new, caption: [ Ein T4gl Array nach Initalisierung. \ \ ]), <fig:t4gl-indirection:new>, figure(figures.t4gl.layers.shallow, caption: [ Zwei T4gl-Arrays teilen sich eine C++ Instanz nach Typ-1 Kopie. ]), <fig:t4gl-indirection:shallow>, figure(figures.t4gl.layers.deep-new, caption: [ Zwei T4gl-Arrays teilen sich die gleichen Daten nach Typ-2 Kopie. \ \ ]), <fig:t4gl-indirection:deep>, figure(figures.t4gl.layers.deep-mut, caption: [ Zwei T4gl-Arrays teilen sich keine Daten nach Typ-2 Kopie und Schreibzugriff. ]), <fig:t4gl-indirection:mut>, columns: 2, caption: [Die drei Ebenen von T4gl-Arrays in verschiedenen Stadien der Datenteilung.], label: <fig:t4gl-indirection>, ) Ein kritischer Anwendungsfall für T4gl-Arrays ist die Übergabe einer rollenden Historie von Werten einer Variable. Wenn diese vom Laufzeitsystem erfassten Werte an den T4gl-Programmierer übergeben werden, wird eine Typ-2-Kopie erstellt. Die T4gl-Instanz, welche an den Programmierer übergeben wird, sowie die interne Qt-Instanz teilen sich Daten, welche vom Laufzeitsystem zwangsläufig beim nächsten Schreibzugriff kopiert werden müssen. Es kommt zur Typ-3-Kopie, und, daraus folgend, zu einem nicht-trivialem zeitlichem Aufwand von $Theta(n)$. Das gilt für jeden ersten Schreibzugriff, welcher nach einer Übergabe der Daten an den T4gl-Programmierer erfolgt.
https://github.com/Toniolo-Marco/git-for-dummies
https://raw.githubusercontent.com/Toniolo-Marco/git-for-dummies/main/book/main.typ
typst
#import "@preview/diagraph:0.3.0": * #import "@preview/minitoc:0.1.0": * #import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge, shapes #import "./components/code-blocks.typ": code-block, window-titlebar #import "./components/utils.typ": n_pagebreak #set heading(numbering: "1.") #set page(numbering: "1") #set page(margin: ( top: 1.5cm, bottom: 1.5cm, x: 1.5cm, )) #set document( title: [Git for Dummies], author: ("<NAME>, <NAME>"), keywords: ("git", "guide", "GitHub"), date: (auto) ) // Code-blocks Rule #show raw.where(block: true): it => code-block( stack( dir:ttb, window-titlebar, block.with( fill: rgb("#1d2433"), inset: 8pt, radius: 5pt, )( text(fill: rgb("#a2aabc"), it) ) ) ) // Inline Code Rule #show raw.where(block: false): it => box( fill: rgb("#1d2433"), inset: 5pt, baseline: 25%, radius:2pt, text(fill: rgb("#a2aabc"), it ) ) #set quote(block: true) #show quote: set align(center) #show link: underline #include "cover.typ" // Table of contents #n_pagebreak(n: 2) // Avoid starting behind the cover #show outline.entry.where( level: 1 ): it => { v(12pt, weak: true) strong(it) } #outline(depth: 2, title: "Indice", indent: auto) #pagebreak() #include "git-basics-theory.typ" #include "git-basics-practice.typ" #include "git-advanced.typ" #n_pagebreak(n: 1) #include "roles-duties.typ" #include "organization.typ" #include "inviter.typ" #include "actions.typ" #n_pagebreak(n:2) #bibliography("refs.yaml", style: "institute-of-electrical-and-electronics-engineers", title: "Bibliografia")
https://github.com/azduha/typst-templates
https://raw.githubusercontent.com/azduha/typst-templates/main/template.typ
typst
MIT License
#let lineThickness = 0.7pt #let fillColor = rgb(50,50,150) #let fillSize = 0.9em #let duha( title: "", subtitle: "", author: "", body, ) = { // Set the document's basic properties. set document(author: author, title: title) // Set body font family. set text(lang: "cs", 12pt) show heading: it => { if (it.level == 1) { v(0.3em) text(upper(it.body), weight: "bold", size: 12pt) v(-0.2em) } if (it.level == 2) { text(it.body, weight: "bold", size: 12pt) v(0.2em) } } // Set link style show link: it => underline(text(fill: rgb("#114499"), it)) // no pagebreak before heading show heading.where(level:1): it => it + v(0.5em) set page( margin: ( top: 2cm, bottom: 2cm, left: 2.4cm, right: 2cm ), header: [ #place(top + left, dx: -2.4cm, dy: 0cm, rect(width: 0.2cm, height: 297mm, fill: rgb("#f80304"))) #place(top + left, dx: -2.2cm, dy: 0cm, rect(width: 0.2cm, height: 297mm, fill: rgb("#f1d405"))) #place(top + left, dx: -2.0cm, dy: 0cm, rect(width: 0.2cm, height: 297mm, fill: rgb("#67a601"))) #place(top + left, dx: -1.8cm, dy: 0cm, rect(width: 0.2cm, height: 297mm, fill: rgb("#0c5e73"))) #place(top + right, dx: 0.8cm, dy: 1.4cm, image(width: 4cm, height: 1.5cm, fit: "stretch", "media/logo.png")) ] ) set par(justify: false) body } #let title(title, subtitle: "") = { upper(text(weight: "bold", size: 18pt, title)) v(-1em) upper(text(weight: "bold", subtitle)) v(0.6em) } #let field(title, to: 100%, lines: 1, lastLineTo: -1%, newline: false, content: "") = { if (type(title) == str) { title = title.trim() } if (content == none) { content = "" } if (lastLineTo < 0% or lastLineTo > to) { lastLineTo = to } context { let x = here().position().x if ((not type(title) == str) or title.len() > 0) { box(title, height: 0.6em) h(0.5em) x += 0.5em x += measure(title).width } else { text(".", size: 0pt) } if (not newline) { box( height: 0.8em, { v(1em) box( box( par( leading: 0.85em, { h((x - page.margin.left).length) text(".", size: 0pt) text(str(content), size: fillSize, fill: fillColor) } ), width: (page.width - page.margin.left - page.margin.right) * to, height: 1.4em * lines - (1.4em - 0.8em), clip: true ), inset: (top: -0.8em, left: -(x - page.margin.left).length), width: calc.max(((page.width - page.margin.left - page.margin.right) * to - (x - page.margin.left)).length.to-absolute(), 1em.to-absolute()), height: lineThickness, fill: black ) }, ) } let i = 1 if (newline) { i = 0 } while i < lines { let w = to if (i == lines - 1) { w = lastLineTo } let cont = "" if (newline) { cont = box( par( leading: 0.85em, { text(".", size: 0pt) text(str(content), size: fillSize, fill: fillColor) } ), width: (page.width - page.margin.left - page.margin.right) * to, height: 1.4em * lines - (1.4em - 0.8em), clip: true ) } box( height: 0.8em, { v(1em) box( cont, inset: (top: -0.8em, left: 0.2em, right: 0.2em), width: w, height: lineThickness, fill: black, ) }, ) i += 1 } } if (to < 100% or (lines > 1 and lastLineTo < 100%)) { h(0.3em) } } #let options(title, options: (), selected: "") = { title = title.trim() context { let x = here().position().x if (title.len() > 0) { box(title, height: 0.6em) h(0.5em) x += 0.5em x += measure(title).width } else { text(".", size: 0pt) } for (key, value) in options { let content = { box( { if (selected == key) { place( line( start: (0%, 0%), end: (100%, 100%), stroke: ( paint: fillColor, thickness: 0.8pt ) ) ) place( line( start: (100%, 0%), end: (0%, 100%), stroke: ( paint: fillColor, thickness: 0.8pt ) ) ) } }, width: 0.7em, height: 0.7em, stroke: (paint: black, thickness: lineThickness), ) h(0.4em) key } place(content, dx: value - measure(content).width, dy: -1.5em) } } } #let separator() = { line( stroke: ( paint: black, thickness: lineThickness, dash: "loosely-dotted" ), length: 100% ) } #let form(content) = { show par: it => { it v(-0.3em) } content } #let credentials(fields: ()) = { table( columns: (30%, auto), align: top, inset: 0pt, row-gutter: 1em, stroke: none, ..fields.pairs().map(pair => (text(upper(pair.at(0)), weight: "bold"), pair.at(1))).flatten() ) } #let signature(content, length: 30%) = { align(center + top, [ #v(2em) #line(start: (0pt, 0em), end: (length, 0em), stroke: (paint: black, thickness: lineThickness)) #v(-0.8em) #text(content, size: 0.9em) ]) } #let format-datetime(time) = { if (time.len() >= 10) { datetime( year: int(time.split("-").at(0)), month: int(time.split("-").at(1)), day: int(time.split("-").at(2).slice(0, 2)) ).display("[day]. [month]. [year]") } } #let format-phone(phone) = { let s = str(phone) if (s.len() == 9) { s.slice(0, count: 3) + " " + s.slice(3, count: 3) + " " + s.slice(6, count: 3) } } #let optional(object, value) = { object.at(value, default: "") }
https://github.com/lucifer1004/leetcode.typ
https://raw.githubusercontent.com/lucifer1004/leetcode.typ/main/solutions/s0003.typ
typst
#import "../helpers.typ": * #let longest-substring-without-repeating-charaters-ref(s) = { let s = s.clusters() let n = s.len() let ans = 1 let l = 0 let d = (:) for r in range(n) { let c = s.at(r) while c in d { let cl = s.at(l) let _ = d.remove(cl) l += 1 } d.insert(c, 1) ans = calc.max(ans, r - l + 1) } ans }
https://github.com/NorfairKing/typst.nix
https://raw.githubusercontent.com/NorfairKing/typst.nix/master/README.md
markdown
# Building Typst documents with Nix ## Using this repository ``` nix let typstNixRepo = builtins.fetchGit { url = "https://github.com/NorfairKing/typst.nix"; rev = "0000000000000000000000000000000000000000"; # Use a recent typst.nix commit }; makeTypstDocument = pkgs.callPackage (typstNixRepo + "/makeTypstDocument.nix") {}; in makeTypstDocument { name = "presentation.pdf"; main = "presentation.typ"; src = ./presentation; packagesRepo = builtins.fetchGit { url = "https://github.com/typst/packages"; rev = "0000000000000000000000000000000000000000"; # Use a recent typst packages commit }; # Fill in all typst dependencies that you import in your .typ files typstDependencies = [ { name = "polylux"; version = "0.3.1"; } ]; } ``` ## `makeTypstDocument` See [`./makeTypstDocument.nix`](./makeTypstDocument.nix)
https://github.com/kdog3682/2024-typst
https://raw.githubusercontent.com/kdog3682/2024-typst/main/src/dialogue.problemset.typ
typst
#let problemset(..sink) = { [hiowdy] }
https://github.com/curvenote/tex-to-typst
https://raw.githubusercontent.com/curvenote/tex-to-typst/main/README.md
markdown
MIT License
# tex-to-typst [![tex-to-typst on npm](https://img.shields.io/npm/v/tex-to-typst.svg)](https://www.npmjs.com/package/tex-to-typst) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/curvenote/tex-to-typst/blob/main/LICENSE) ![CI](https://github.com/curvenote/tex-to-typst/workflows/CI/badge.svg) A utility for translating LaTeX math to typst. > **Note**: The library is in alpha, it will likely not work for the majority of math at the moment! More updates to come soon! ```shell npm install tex-to-typst ``` The library uses `@unified-latex` for the LaTeX parsing. ## Overview & Usage ```ts import { texToTypst } from 'tex-to-typst'; const typst = texToTypst( '\\frac{1}{4} \\sum_{i=1}^4 \\mathbf{P}_i^\\top \\sqrt{v} \\mathbf{\\Sigma}^{-1} \\sqrt{v} \\mathbf{P}_i \\mathbf{j} = \\mathbf{D}^\\top v \\phi', ); console.log(typst.value); // frac(1, 4) sum_(i = 1)^4 bold(P)_i^top sqrt(v) bold(Sigma)^(-1) sqrt(v) bold(P)_i bold(j) = bold(D)^top v phi ``` ## Included Utilities - `texToTypst` - translates tex markup to an equivalent typst string --- This package is [ESM only](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). --- <p style="text-align: center; color: #aaa; padding-top: 50px"> Made with love by <a href="https://curvenote.com" target="_blank" style="color: #aaa"> <img src="https://cdn.curvenote.com/brand/logo-blue-icon.png" style="height: 1em" /> Curvenote </a> </p>
https://github.com/TideDra/seu-thesis-typst
https://raw.githubusercontent.com/TideDra/seu-thesis-typst/main/bachelor_thesis.typ
typst
#import "template.typ": acknowledgment, appendix, bachelor_conf, seu_bibliography #import "utils.typ": paragraph, set_doc_footnote, subfigure #import "@preview/funarray:0.3.0": cycle #import "@preview/tablex:0.0.8": tablex, vlinex, hlinex, colspanx, rowspanx // 由于Typst目前的缺陷,footnote必须在开头设置。未来可能会改进 #show: doc => set_doc_footnote(doc) #let info = ( title: [基于四十二号混凝土的意大利面配料方案研究],//手动换行请传入列表,一个元素为一行:("基于四十二号混凝土的意大利面配料方","案研究") student_id: [12345678], name: [张三], college: [霍格沃兹学院], major: [母猪产后护理], supervisor: [李四], duration: "2023.1.1~2024.1.1", sign_date:("2024","1","1"), //论文声明页日期 zh_abstract: [ 摘要内容独立于正文而存在,是论文内容高度概括的简要陈述,应准确、具体、完整地概括论文的主要信息,内容包括研究目的、方法、过程、成果、结论及主要创新之处等,不含图表,不加注释, 具有独立性和完整性,一般为400字左右。 “摘要”用三号黑体加粗居中,“摘”与“要”之间空4个半角空格。摘要正文内容用小四号宋体,固定1.5倍行距。 论文的关键词是反映毕业设计(论文)主题内容的名词,一般为3-5个,排在摘要正文部分下方。关键词与摘要之间空一行。关键词之间用逗号分开,最后一个关键词后不加标点符号。 ], zh_key_words: ("关键词1", "关键词2", "关键词3", "关键词4"), en_abstract: [ 英文摘要应与中文摘相对应,250 个实词左右。采用第三人称介绍该学位论文内容,叙述的基本时态为一般现在时,确实需要强调过去的事情或者已经完成的行为才使用过去时、完成时等其他时态。 ABSTRACT 为三号 Times New Roman 加粗居中。 英文摘要正文为小四号 Times New Roman,固定 1.5 倍行距。英文关键词“KEY WORDS”大写,其后的关键词第一个字母大写,关键词之间用半角逗号隔开。 #lorem(250) ], en_key_words: ("Keywords1", "Keywords2", "Keywords3", "Keywords4"), ) // 对以下文本应用模板 #show: doc => bachelor_conf(doc, ..info) = 绪论 <chap:introduction> == 课题背景和意义 绪论部分主要论述选题的意义、国内外研究现状以及本文主要研究的内容、研究思路以及内容安排等~@calandra2015learning@luketina2019survey。 章标题为三号黑体加粗居中;一级节标题(如,2.1 本文研究内容):四号黑体居左;二级节标题(如,2.1.1 实验方法):小四号宋体居左。 正文部分为小四号宋体,行间距1.5倍行距,首行缩进2个字符。正文一般不少于15000字。 == 研究现状 ...... == 本文研究内容 ...... = 第二章标题 <chap:chap2> 具体研究内容每一章应另起页书写书写,层次要清楚,内容要有逻辑性,每一章标题需要按论文实际研究内容进行填写,不可直接写成第二章 正文。研究内容因学科、选题特点可有差异,但必须言之成理,论据可靠,严格遵循本学科国际通行的学术规范。 中文为小四号宋体,英文及数字为小四号Times New Roman,首行缩进2个字符,行间距为1.5倍。 == 插图格式要求 插图力求精炼,且每个插图均应有图序和图名。图序与图名位于插图下方,图序默认按章节编排,如@fig:rain_dist(#ref(<chap:chap2>)第1个图),在插图较少时可以全文连续编序,如图10。设置 ```typ bachelor_conf(continuous_index: true, ...)``` 启用连续编序。 如一个插图由两个及以上的分图组成,分图用(a)、(b)、(c)等标出,并标出分图名,如@subfig:v_set。 简单文字图可用Typst直接绘制(如CeTZ包),复杂的图考虑使用相应的图形绘制软件完成,以提高图形表达质量~@sanh2021multitask。目前Typst不支持插入PDF图像,矢量图请转为SVG格式。 插图居中排列,与上文文本之间空一行。图序图名设置为五号宋体居中,图序与图名之间空一格。 #figure( image("figures/Picture1.png", width: 50%), caption: [每小时降水量24小时均值分布图], ) <fig:rain_dist> // kind:image figure会自动识别kind,无需手动指定 #figure( grid( columns: (1fr, 1fr), // 两列,列宽1:1 [ #subfigure(image("figures/Picture2.png", height: 6cm), caption: [速度障碍集合]) <subfig:v_set> // label必须在content块里。 ], subfigure(image("figures/Picture3.png", height: 6cm), caption: [避免碰撞集合]), ), caption: [速度障碍法速度选择], ) == 表格格式要求 表格的结构应简洁,一律采用三线表,应有表序和表名,且表序和表名位于表格上方。表格可以逐章单独编序(如:@tab:rain_rate),也可以统一编序(如:表10),采用哪种方式应和插图及公式的编序方式统一。表序必须连续,不得重复或跳跃。 表格无法在同一页排版时,可以用续表的形式另页书写,续表需在表格右上角表序前加“续”字,如“续表2.1”,并重复表头。 表格居中,边框为黑色直线1磅,中文为五号宋体,英文及数字为五号Times New Roman字体,表序与表名之间空一格,表格与下文之间空一行。 // @typstyle off #figure( table( columns: cycle((1fr, ), 3), // 三列,等宽 rows: 1.8em, // 行高 stroke: none, // 线宽 align: center + horizon, table.hline(), [降水率(mm/h)分级], [该等级所占比例(%)], [降水等级描述], table.hline(), [$0 lt.eq x lt 0.5$], [90.36], [没有雨或雨很小], [$0.5 lt.eq x lt 2.0$], [6.41], [小雨], [$2.0 lt.eq x lt 5.0$], [2.04], [中雨], [$5.0 lt.eq x lt 10.0$], [0.10], [大雨], [$10.0 lt.eq x lt 30.0$], [0.73], [大雨到暴雨], [$30.0 lt.eq x lt 100.0$], [0.16], [暴雨], table.hline() ), caption: [降水率分级统计], ) <tab:rain_rate> // @typstyle off #figure( table( columns: cycle((1fr, ), 13), // 13列,等宽 rows: 2em, stroke: none, align: center + horizon, table.hline(), [], table.cell(colspan: 4, [Stage 1 (>7.1 μm)]), table.cell(colspan: 4, [Stage 2 (4.8-7.1 μm)]), table.cell(colspan: 4, [Stage 3 (3.2-4.7 μm)]), table.hline(), [], [Con], [Low], [Medium], [High], [Con], [Low], [Medium], [High], [Con], [Low], [Medium], [High], table.hline(), [H], [2.52], [2.58], [2.57], [2.24], [2.48], [2.21], [2.21], [2.36], [2.66], [2.65], [2.64], [2.53], [E], [2.52], [2.58], [2.57], [2.24], [2.48], [2.21], [2.21], [2.36], [2.66], [2.65], [2.64], [2.53], table.hline() ), kind: table, caption: [室外细菌气溶胶香农-维纳指数(H)和均匀性指数(E)], ) // @typstyle off #figure( table( columns: cycle((2.4cm, ), 5), // 五列,列宽2.4cm rows: 2em, stroke: none, align: center + horizon, table.hline(), [产品], [产量], [销量], [产值], [比重], table.hline(), [手机], [11000], [10000], [500], [50%], [手机], [11000], [10000], [500], [50%], [手机], [11000], [10000], [500], [50%], table.hline(), [合计], [33000], [30000], [1500], [150%], table.hline() ), caption: [统计表], ) // @typstyle off #figure( table( columns: cycle((2.4cm, ), 5), rows: 2em, stroke: none, align: center + horizon, table.hline(), [年度], [产品], [产量], [销量], [产值], table.hline(), table.cell(rowspan: 2, [2004]), [手机], [11000], [10000], [500], [计算机], [1100], [1000], [280], table.hline(), table.cell(rowspan: 2, [2004]), [手机], [11000], [10000], [500], [计算机], [1100], [1000], [280], table.hline(), ), kind: table, caption: [统计表], ) == 表达式 论文中的公式应注序号并加圆括号,序号一律用阿拉伯数字连续编序(如(28))或逐章编序(如@eq:1),编号方式应与插图、表格方式一致。序号排在版面右侧,且距右边距离相等。公式与序号之间不加虚线。 长公式在一行无法写完的情况下,原则上应在等号(或数学符号,如“+”、“-”号)处换行,数学符号在换行的行首。 公式及文字中的一般变量(或一般函数)(如坐标 $X$、$Y$,电压 $V$,频率 $f$)宜用斜体,矢量用粗斜体如 $bold(S)$(```typ $bold(S)$```)或白斜体上加单箭头 $arrow(S)$(```typ $arrow(S)$```),常用函数(如三角函数 $cos$、对数函数 $ln$ 等)、数字运算符、化学元素符号及分子式、单位符号、产品代号、人名地名的外文字母等用正体。 公式排版时使用 ```typ $ equation $```,在 `eqaution` 和 `$` 之间留一个空格进入单行公式模式。公式中插入 `&` 作为对齐符,使用 `\` 换行。 $ V_"cell" = E_"OCV" - V_"act" - V_"ohm" - V_"conc" $ <eq:1> $ E_"OCV" = & 1.229 - 0.85 times 10^(-3) (T_(s t) - T_0) \ & + 4.3085 times 10^(-5) T_(s t) [ln(P_(H_2) / 1.01325) + 1 / 2 ln(P_(O_2) / 1.01325)] $ == 注释 正文中有个别名词或情况需要解释时,可加注说明,注释采用页末注(将注文放在加注页的下端)。在引文的右上角标注序号①、②、……,如“马尔可夫链#footnote[马尔可夫链表示……]”。若在同一页中有两个以上的注时,按各注出现的先后,顺序编号。引文序号,以页为单位,且注释只限于写在注释符号出现的同页,不得隔页。 注释采用小五号宋体,英文及数字为小五号 Times New Roman 字体,利用 ```typ #footnote[]``` 插入。 = 总结与展望 <chap:conclusion> == 工作总结 上述标题第三章仅为示例,实际论文报告可根据研究内容按序编排章节,最后一章结论与展望着重总结论文的创新点或新见解及研究展望或建议。 结论是对论文主要研究结果、论点的提炼与概括,应准确、简明、完整、有条理,使人看后就能全面了解论文的意义、目的和工作内容。主要阐述自己的创造性工作及所取得的研究成果在本学术领域中的地位、作用和意义。 结论要严格区分自己取得的成果与导师及他人的科研工作成果。在评价自己的研究工作成果时,要实事求是,除非有足够的证据表明自己的研究是“首次”的、“领先”的、“填补空白”的,否则应避免使用这些或类似词语。 == 工作展望 展望或建议,是在总结研究工作和现有结论的基础上,对该领域今后的发展方向及重要研究内容进行预测,同时对所获研究结果的应用前景和社会影响加以评价,从而对今后的研究有所启发。 #seu_bibliography(bib_file: "reference.bib") #appendix[ = 附录名称 对于一些不宜放入正文中、但作为毕业设计(论文)又不可残缺的组成部分或具有重要参考价值的内容,可编入毕业设计(论文)的附录中,例如,正文内过于冗长的公式推导、方便他人阅读所需的辅助性数学工具或表格、重复性数据和图表、非常必要的程序说明和程序全文、关键调查问卷或方案等。 附录的格式与正文相同,如有多个附录需依顺序用大写字母 A,B,C,……编序号,如附录 A,附录 B,附录 C,……。只有一个附录时也要编序号,即附录 A。每个附录应有标题,如:“附录 A 参考文献著录规则及注意事项”。 附录一般与论文全文装订在一起,与正文一起编页码。 ] #acknowledgment[ 学位论文正文和附录之后,一般应放置致谢(后记或说明),主要感谢指导老师和对论文工作有直接贡献和帮助的人士和单位。致谢言语应谦虚诚恳,实事求是。字数一般不超过 1000 个汉字。 “致谢”用三号黑体加粗居中,两字之间空 4 个半角空格。致谢内容为小四号宋体,1.5倍行距。 ]
https://github.com/Namacha411/typst-template
https://raw.githubusercontent.com/Namacha411/typst-template/master/README.md
markdown
Apache License 2.0
# Typst-template [Typst](https://github.com/typst/typst)で日本語のレポートを書く時用のテンプレート。フォント設定は游明朝。 [template.typ](template.typ)をインポートし、 ```typ #import "template.typ": * #show: project.with( title: "タイトル", authors: ( "<NAME>", ), date: "2024/01/06" ) ``` のように使う このフォルダをダウンロードして`main.typ`を書き換えて使うのが楽 ## 例 - [サンプルコード](main.typ) - [出力例](main.pdf)
https://github.com/ludwig-austermann/typst-idwtet
https://raw.githubusercontent.com/ludwig-austermann/typst-idwtet/main/idwtet.typ
typst
MIT License
#let init( body, bcolor: luma(210), inset: 5pt, border: 2pt, radius: 2pt, content-font: "linux libertine", code-font-size: 9pt, content-font-size: 11pt, code-return-box: true, wrap-code: false, eval-scope: (:), escape-bracket: "%" ) = { let eval-scope-values = (:) let eval-scope-codes = (:) for (k, v) in eval-scope.pairs() { if type(v) == dictionary { if v.keys().contains("value") { eval-scope-values.insert(k, v.value) } if v.keys().contains("code") { eval-scope-codes.insert(k, v.code) } } else { panic("Argument `eval-scope` accepts only a (value?: ..., code?: ...) dictionary for each variable!") } } /// returns two modified versions of text: /// - substitute: text without the hidden text by `%ENDHIDDEN%` AND with the replacements given by eval-scope-codes /// produces the code to be displayed /// - remove: text with hidden text BUT without the replacements /// produces the code to be evaluated let substitute-remove-code(text) = { let splitted-text = text.split(escape-bracket + "ENDHIDDEN" + escape-bracket) let (hidden-text, shown-text) = if splitted-text.len() == 1 { ("", splitted-text.at(0)) } else { splitted-text.slice(0, 2) } eval-scope-codes.pairs().fold( (shown-text, hidden-text + shown-text), (s, a) => ( s.at(0).replace( escape-bracket + a.at(0) + escape-bracket, a.at(1) ), s.at(1).replace( escape-bracket + a.at(0) + escape-bracket, "" ) ) ) } show raw.where(block: true, lang: "typst-ex"): it => { let (substituted-text, removed-text) = substitute-remove-code(it.text) set text(code-font-size) let code = block( width: 100%, fill: bcolor, stroke: border + bcolor, inset: inset, radius: (top: 4pt), raw(lang: "typst", substituted-text) ) let result = eval( removed-text, mode: "markup", scope: eval-scope-values ) let result-content = block( width: 100%, stroke: border + bcolor, inset: inset, radius: (bottom: radius), text(font: content-font, content-font-size, result) ) grid( code, result-content ) } show raw.where(block: true, lang: "typst-ex-code"): it => { let (substituted-text, removed-text) = substitute-remove-code(it.text) set text(code-font-size) let code = block( width: 100%, fill: bcolor, stroke: border + bcolor, inset: inset, radius: (top: 4pt), if wrap-code { raw(lang: "typst", "#{\n" + substituted-text + "\n}") } else { raw(lang: "typc", substituted-text) } ) let result = eval(removed-text, scope: eval-scope-values) let type-box = box(inset: 2pt, radius: 1pt, fill: white, text(code-font-size, "return type: " + raw(str(type(result))))) let result-content = block( width: 100%, stroke: border + bcolor, inset: inset, radius: (bottom: radius), text(font: content-font, content-font-size, { if code-return-box { style(sty => place( type-box, dx: inset - 1pt, dy: - inset - measure(type-box, sty).height - 1pt, right )) } [ #result ] }) ) grid( code, result-content ) } show raw.where(block: true, lang: "typst"): it => block( width: 100%, fill: bcolor, stroke: border + bcolor, inset: inset, radius: radius, text(code-font-size, raw(lang: "typst", it.text)) ) show raw.where(block: true, lang: "typst-code"): it => block( width: 100%, fill: bcolor, stroke: border + bcolor, inset: inset, radius: radius, text(code-font-size, raw(lang: "typc", it.text)) ) body }
https://github.com/heloineto/utfpr-tcc-template
https://raw.githubusercontent.com/heloineto/utfpr-tcc-template/main/template/template.typ
typst
#import "cover-page.typ": cover-page #import "title-page.typ": title-page #import "approval-page.typ": approval-page #import "abstract-page.typ": abstract-page #import "acknowledgment-page.typ": acknowledgment-page #let base( weight: "regular", style: "normal", body ) = { text( 12pt, weight: weight, style: style, body ) } #let levelToStyle = ( it => base(weight: "bold", upper(it)), it => base(weight: "bold", it), it => base(it), it => base(underline(it)), it => base(style: "italic", it), ) #let headings(it) = { let index = it.level - 1 let styleFn = levelToStyle.at( index, default: it => it ) styleFn(it) } #let project( institution: "", title: "", authors: (), city: "", year: "", english-title: "", goal: [], advisor: "", keywords: (), abstract: [], english-keywords: (), english-abstract: [], approval-date: datetime.today(), approvers: (), acknowledgment: [], body, ) = { set document(author: authors, title: title) set page( paper: "a4", margin: ( top: 3cm, right: 2cm, bottom: 2cm, left: 3cm ), ) set text( size: 12pt, lang: "pt", font: "Arial", ) set cite(style: "chicago-author-date"); set heading(numbering: "1.1") show heading: it => [ #block( width: 100%, below: 20pt, above: 20pt, headings(it) ) #par()[#text(size: 0pt)[#h(0.0em)]] ] cover-page( title: title, authors: authors, institution: institution, city: city, year: year, ) title-page( title: title, authors: authors, english-title: english-title, city: city, year: year, goal: goal, advisor: advisor, ) approval-page( title: title, authors: authors, city: city, year: year, goal: goal, approval-date: approval-date, approvers: approvers, ) acknowledgment-page(acknowledgment) abstract-page(lang: "pt", keywords: keywords, abstract) abstract-page(lang: "en", keywords: english-keywords, english-abstract) show outline.entry: it => { let fields = it.fields() if it.body.at("children", default: false) == false { return [#box(width: 55pt) #it] } let (number, ..rest) = it.body.children // Stops recursion if number.func() == box { return it } let body = ((box(width: 55pt,number),) + rest).join() fields.at("body") = body outline.entry(..fields.values()) } show outline.entry: it => [ #box(headings(it), height: 1.25em) ] outline( depth: 5, title: [ #set align(center) #block(width: 100%, "SUMÁRIO") #v(30pt) ] ) pagebreak() outline( title: [ #set align(center) #block(width: 100%, "LISTA DE FIGURAS") #v(30pt) ], target: figure.where(kind: image), ) pagebreak() outline( title: [ #set align(center) #block(width: 100%, "LISTA DE QUADROS") #v(30pt) ], target: figure.where(kind: "board"), ) pagebreak() set page(numbering: "1", number-align: top + right) set par( justify: true, first-line-indent: 1.5cm, leading: 1em ) show list: it => pad(x: 1.5cm + 0.75cm, it) show enum: it => pad(x: 1.5cm + 0.75cm, it) body pagebreak() show bibliography: it => [ #show heading: it => align(center, text(size: 12pt, weight: "bold", it)) #it ] bibliography( "../main.bib", style: "chicago-author-date", title: "REFERÊNCIAS" ) } #let original-figure = figure; #let figure = ( content, placement: none, source: "", label: none, ..rest ) => [ #set align(center) #set text(weight: "bold", size: 10pt) #set figure.caption(position: top, separator: " – ") #original-figure( content, ..rest ) #label Fonte: #source ]
https://github.com/typst/packages
https://raw.githubusercontent.com/typst/packages/main/packages/preview/scholarly-tauthesis/0.4.1/template/images/README.md
markdown
Apache License 2.0
# images/ Place the images related to your project here. You can then include the images into your thesis with the [`image`][image] function: ```typst #image("path/to/images/filename.svg", width:100%) ``` If you place the `image` call into a [`figure`][figure], you will get a numbered picture that you can reference. [image]: https://typst.app/docs/reference/visualize/image/ [figure]: https://typst.app/docs/reference/model/figure/
https://github.com/RakuJa/Formula_SAE_Report
https://raw.githubusercontent.com/RakuJa/Formula_SAE_Report/main/main.typ
typst
MIT License
#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: "Formula SAE report", subtitle: "", subject: "Project report", guide: ( name: "<NAME>", designation: "Professor & Chair of the M.Sc. in Cybersecurity", department: "Computer Science" ), authors: ( ( name: "<NAME>", department: "Department of Information Engineering", rollno: "647820" ), ( name: "<NAME>", department: "Department of Information Engineering", rollno: "578245", ), ), department: "Department of Information Engineering", institute: "Università degli studi di Pisa", degree: "Master of Science", year: "2023-2024", logo: "images/logo-unipi.png", ) = Introduction Formula SAE is a student design competition, started in 1980 by the SAE student branch at the University of Texas at Austin after a prior asphalt racing competition proved to be unsustainable. The concept behind Formula SAE is that a fictional manufacturing company has contracted a student design team to develop a small Formula-style race car. Each student team designs, builds and tests a prototype based on a series of rules, whose purpose is both ensuring on-track safety and promoting clever problem solving. There are combustion and electric divisions of the competition, primarily only differing in their rules for powertrain. In 2017, the Formula Student Driverless was inaugurated, and in 2022 The Pisa Formula SAE's team started the transition to full electric and the development of the driverless software. == Project goal The goal of the project was to allow the Formula SAE team to pursue an increase in the security and reliability of the code base, mainly targeting the development, test and build phases of the software. The problem was not only technical, but one born from a culture of "if it works, it works." that led to the development of error prone and difficult to maintain software. = Documentation The first task was the creation of a "code guide", aimed at guiding both new and experienced developers. The document follows a simple structure: - General explanation and rules of the topic; - Python specific rules and examples; - C specific rules and examples. The main topic tackled are: - Project setup: How to correctly initialize a repository, the naming convention, how to enable CI, how to enable pre-commit; - Project structure: Physical structure of the project, how the folders and file should be organized and what should be omitted; - Documentation: How the code should be documented, what tools to use to generate documentation from comments; - Testing: How to configure pre-commit, how to integrate static analysis tools and guidelines on how to write unit tests; - Git branching strategy and Code reviews: What strategy should be used to create and manage branches and how to merge the developed code in the stable code base. = GitLab migration #label("GitLab migration") A considerable challenge was encountered during the development of the documentation. The hosting service used to serve our code base to the developer (A hosted GitLab instance using Aruba), was in need of a renewal and for economic reasons the team decided to migrate to a free solution. This is a considerable challenge, even more if we need to consider the security aspect of the endeavour. The research was conducted on two possible solution: 1. Self host the GitLab instance; 2. Find a remote hosting service, possibly free. An in-depth research on possible remote hosts for the team official site was also requested but, after having completed it, the team decided to scrap it in favour of simple (and insecure) WordPress hosting. == Self hosted GitLab Self hosting GitLab was problematic from the start. - University firewall: the workshop's network is the same as the university one, and as such it has strict rules imposed on every computer. We tried asking the university for an exception to the rule, making the specific computer reachable on a specific port from outside the network but it was not granted; - Secure the computer: there is only one computer at our disposal in the workshop. This means that we would need to have the computer accessible by everyone, but at the same time we need to guarantee the security and availability of the code stored in the machine; - Guarantee instance availability: in specific times of the year, mainly when the other departments are rushing to meet specific deadlines, there are many power outages caused by the tools used. This issue could be solved using an uninterruptible power supply (UPS), that would kick in during power outages and guarantee a steady supply of power to the computer. The downside of this solution is cost, the entire computer setup is estimated to require from the power supply unit (PSU) ~1000W, meaning that a good UPS that could last for at least 15 minutes would cost at the very least 100€. To summarize, the downside would be having to buy specific hardware and having a complex setup to avoid users accessing the code base from the shared computer in the workshop. On the upside, by having the service behind the University network, we could delegate a lot of security rules and architecture to the network. This option was abandoned in the end, because the university declined our request to make our service available and as such rendered impossible (or at the very least useless) the self host option. == Remote hosting There was a lot of talk regarding the direction in which we wanted to steer the code base hosting. The chosen service was GitHub, thanks to its perks like: 1. Ease of use: we have a lot of developers inexperienced with version control systems (VCS), and the easy to use GitHub graphic interface helps a lot; 2. Free tier: while we are aiming at a "team" license to have some needed extra security, we want to have the option in the future to swap easily from a paid version to a free version without having to migrate to a different service; 3. CI: GitHub offers free runners to execute the CI configuration that the developer desires; There are obviously some cons, the majors being AI training with hosted code and the impossibility to protect branch on private repositories with a free account. == Migration process The final choice, taken by management after presenting all the pros and cons of each option, was to migrate to GitHub. There were 80 repositories to migrate, maintaining the commit history and, if possible, the issues. To approach this challenge, a quick research was made to schedule a date in which no code would be committed to "freeze" the repositories. Code would stop being uploaded on the 25th of February 2024 and migration would take place on the 26th. GitHub offers a migration tool to import repositories keeping the commit history and also the authors as well. Knowing this, the decision was to import all the repositories manually using a profile token with only the minimum permissions required for the operation. Another decision was dividing each repository between the teams, ETDV and Electronics, to have more modular access control and permissions. A new user that is not in a team will not be able to access any repository by default, while the user of one team will not be able to write on repositories of another team by default. The process took around 8 hours, checking that each repository would correctly import everything and assigning them to the correct team. This process was also slowed down by various malfunction of the GitHub service, that would make the import fail. When an import fails it will still create a repository without any code inside of it, making it hard to retry (cannot import the same repository twice without deleting it first). On the morning of February 27th the process was completed successfully, only having to manually fix two repositories in the month after. = CI/CD CI/CD falls under DevOps (the joining of development and operations teams) and combines the practices of continuous integration and continuous delivery. CI/CD automates much or all of the manual human intervention traditionally needed to get new code from a commit into production, encompassing the build, test (including integration tests, unit tests, and regression tests), and deploy phases, as well as infrastructure provisioning. With a CI/CD pipeline, development teams can make changes to code that are then automatically tested and pushed out for delivery and deployment. CI is the practice of integrating all your code changes into the main branch of a shared source code repository early and often, automatically testing each change when you commit or merge them, and automatically kicking off a build. With continuous integration, errors and security issues can be identified and fixed more easily, and much earlier in the development process. CD covers everything from provisioning the infrastructure to deploying the application to the testing or production environment. == GitLab To develop the CI/CD infrastructure the first step was to study how the GitLab runner works. This study was necessary to understand if we could work behind the University firewall or if we had to request again special permissions to the IT administrators. #figure( image("images/GitLab_runner.png", width: 75%), caption: [GitLab pipeline] )<gitlab_runners> The process is often wrongly explained, saying that the GitLab server notifies each and every registered GitLab runner and then the runner starts the desired job. From our tests and some #link("https://forum.gitlab.com/t/how-does-communicate-gitlab-runners/7553/8")[forum discussions] we managed to understand the process: - A GitLab runner is installed in the desired machine, either through Docker (recommended for #link("https://docs.gitlab.com/runner/security/")[security hardening]) or installing it directly in the system; - The GitLab runner is registered though a guided process using a unique token; - The GitLab runner starts to periodically poll the GitLab server for jobs; - New code is pushed, the GitLab server checks if it triggers a job and then queues it; - The GitLab runner fetches the job, it clones the project locally and then sends the results, logs, and status to the GitLab server. This whole process does not require any inbound connection, the GitLab runner is responsible of contacting the GitLab server on port 443 (HTTPS). A bare bone CI/CD pipeline was developed and tested successfully but was scrapped because of the #link("GitLab migration")[migration to GitHub]. == GitHub GitHub CI/CD approach is pretty different from GitLab. It offers free (up to a certain usage) online runners, and it also has a different convention for the configuration files. The old GitLab files were thus deleted and we approached this part of the migration process tailoring our solution specifically for GitHub. === GitHub-hosted runners GitHub offers hosted virtual machines to run workflows. The virtual machine contains an environment of tools, packages, and settings available for GitHub Actions to use. Each GitHub-hosted runner is a new virtual machine (VM) hosted by GitHub with the runner application and other tools preinstalled, and is available with Ubuntu Linux, Windows, or macOS operating systems. This is all leveraged automatically by activating the GitHub-hosted runners from the repository settings, no further configuration was required on our part. === GitHub Actions The CI/CD configuration files, thanks to the _uses_ keyword, let us leverage the "GitHub Actions" functionality. An Action is a configuration written by other developers and freely shared on GitHub, allowing us to use CI/CD that is tested and supported by the community, minimizing the burden of maintaining the configuration. This marketplace helped us find ROS2 specific actions and examples to provide a better build process to our developers. Unfortunately, due to time constraints and the sheer amount of work in other projects, the CI/CD pipeline was not fully integrated. In the future we would like to integrate simulators to have complex test in which the whole stack could be tested at once in different tracks. To achieve that result we need to add a GitHub local runner with all the docker images installed (simulator, perception, etc) in the same system. This process cannot reasonably be done though remote runners since the whole stack is nearly 60GBs in size, and a remote runner needs to pull each dependency at every run of the CI/CD. = Development Environment #figure( image("images/ETDV-Deps.png", width: 75%), caption: [Dependencies graph] )<Dependencies_graph> The “Driverless” project builds are complicated to say the least. Every developer needs to install in its own machine all of the dependencies that the current project has, as shown in @Dependencies_graph. This led to builds error such as clashing libraries versions and in the production environment there were runtime dependencies missing. To solve this problem we had to create an environment containing all of the libraries required, so that it can be easily installed, replicated and in which development and builds can be done without issues. #pagebreak() == Inherited dockerfile analysis We started the process by analyzing the old dockerfiles structure. #figure( image("images/old_dockerfile.png", width: 75%), caption: [Old dockerfile list] )<old_dockerfile_list> The resulting docker image size was \~50GB, with compile times of hours at a time depending on the hardware resources and no clear instruction on the build process to follow. Looking at all the dockerfiles we managed to track down where the issues originated: - Build size: there was no clear distinction on the dockerfiles between build phases and final image, so libraries used to compile and build needed dependencies were kept on the final build image; - Build time: the nvidia base image is the main issue in this regard. It needs to be compiled with regards to the target GPU architecture making a "generic" image useless; - Instructions: there was some documentation in the README.MD, but knowledge was mainly shared vocally and held by very few people in the team. == Dockerfile improvements Initially moving to Virtual Machines was proposed and successfully tested. The rationale was that docker containers were already used as VMs and switching to them they could lead to true virtualized environment with all the needed tools and library already installed. Unfortunately this approach was not approved citing the increased hardware requirements. To solve the problems listed previously, we adopted different strategies: - Divided the dockerfiles in many cacheable images making the build more modular and with the possibility to resume it later on; - Created a "minimal" version, that does not contain the perception layer, since not all the projects require it and saving tens of GB in the process; - Deleted unused libraries and iteratively slim the images, checking for regressions at each step; #figure( image("images/new_dockerfile_structure.png", width: 72%), caption: [New dockerfile list] )<new_dockerfile_list> == Docker infrastructure With the goal of helping old PCs and low end hardware such as Raspberry PI, infamous for slow compile times, we decided to create a self hosted Docker Hub in which we would store all the versioned images. In the future this choice would allow us to integrate those docker images in the CI/CD stages, to implement and execute tests in the same environment used by the developers. #figure( image("images/new_dockerfile.png", width: 100%), caption: [Repository structure] )<repository_structure> To improve the user experience and avoid misalignment in each developer environment, a script that would guide the user in the creation of the images was created. The script exposes a Command Line Interface (CLI) that acts as a wizard for the image creation process. Following the goal of building scalable and modular software, this build process could also be used as base for the automatic creation of images at each major release, using the previously mentioned CI/CD pipeline. #figure( image("images/build_helper.png", width: 100%), caption: [Image build wizard] )<image_build_wizard> = Personnel training At the end of March, three new members joined the team earlier than usual in order to slowly train and adapt them to the projects. Firstly they got invited in the GitHub organization with minimum permissions to avoid confusion and mistakes. Then, shortly after, two main courses were held. Both courses were recorded and slides created, in order to have them available even for future use in the next years. The first lesson was on Git, touching all the following topics: - Definition, use cases; - Main commands like clone, add, commit, push, fetch, pull; - GUI interfaces; - Branches; - Merge conflicts; - Merge strategies. - Our GitHub structure; - Tour of the repositories. The second lesson, much more in-depth, was on programming with a strong focus on safe programming: - Difference between interpreted and compiled languages; - Difference between Strong, weak, static and dynamic typing, with example of languages and code snippet for each one; - Concept of scope; - Concept of shadowing; - Boolean algebra; - Functions, signature and usage; - Memory management; - Garbage collection; - Manual memory allocation and deallocation in C/C++; - Pointers; - Pointer arithmetic; - Double free, use after free, dangling pointers, memory leaks; - Basic rules to write memory safe code in C/C++; - Rust and the borrow checker; - Object oriented programming; - What are objects and classes; - Inheritance, Polymorphism, Abstraction, Encapsulation; - Side effects, Shallow & Deep copies; - How to avoid undesired side effects; = Optimal lap trajectory #label("Optimal lap trajectory") == The project A new ETDV project, "ETDV optimal lap trajectory", was greenlighted with the goal of finding the optimal lap knowing the track beforehand. This is done by having the car drive as best as it can for the first lap, and then from the second lap onward the optimal lap trajectory will be used. The project will translate MATLAB code in a more efficient solution. This means that the result *must* be readily available at the beginning of the second lap and as such it has strict requirements in terms of: - Small memory footprint; - Memory safety; - Reliability. === Memory footprint Memory footprint refers to the amount of memory used by a program during its execution. Since the program will run in systems with very limited memory capabilities, the lower the memory consumption, the better. This requirement already excludes a lot of garbage collected languages, such as Java and Python. === Memory safety To summarize a broad field of study, in our context memory safety means that all references point to valid memory. There are various programming languages that offer memory safety, mainly garbage collected ones. We care about memory safety for two reasons: - Remove unexpected behaviours that could cause crashes like use after free; - Security: bugs caused by lack of memory safety could range from simple crashes or, in the case of an attack, code injection. === Reliability Software reliability is the probability of failure-free operation of a computer program for a specified period in a specified environment. This requirement is not as stringent as the others, because usually reliability issues appear in software after a long uptime. This last requirement is more related to good programming techniques than technologies or programming languages. === The choice of language So, we need to find a programming language that offers the same safety guarantees of a garbage collected language together with the small memory footprint of manual memory management. Java, thanks to the JVM, is one of the fastest programming languages in the GC group while C/C++ are the de facto standard in the embedded programming scene. Even so, those languages lack at least one requirement each. Rust is the solution to all of these problems thanks to its runtime efficiency and borrow checker static analysis. == Some theory We can assume to know the *n* central point of the track, *p#sub[i]*. Knowing that, we can calculate the coordinates of the points *r#sub[i]* thanks to the equation $ r#sub[i]= p#sub[i]+d#sub[i]*n#sub[i]$, where *n#sub[i]* is the unit normal vector to the tangent line at point *p#sub[i]*. $ t = frac(x#sub[i+1] - x#sub[i], root(2, (x#sub[i+1]-x#sub[i])^2+(y#sub[i+1]-y#sub[i])^2)), frac(y#sub[i+1] - y#sub[i], root(2, (x#sub[i+1]-x#sub[i])^2+(y#sub[i+1]-y#sub[i])^2)) $ Considering the unit normal vector with regards to the plan $k = [0, 0, 1]$, $n#sub[i] = t * k$ To calculate the distance function to minimize: $ sum_(i=1)^n (r#sub[i+1]-r#sub[i])^2 $ Now, we need an iterative process to minimize the distance function. == Libraries Since this is the first project ever made in the team with Rust, the choice of libraries was fundamental as it would pave the road and create an example to follow in future projects. #figure( image("images/libraries.png", width: 79%), caption: [Cargo.toml dependencies file] )<libraries> === Nalgebra Nalgebra is meant to be a general-purpose, low-dimensional, linear algebra library, with an optimized set of tools for computer graphics and physics. Initially #link("")[ndarray], the de facto standard for linear algebra operations in machine learning, was chosen for the high performances offered but later on it was replaced by Nalgebra due to the slow release schedule and difficulty implementing with the ecosystem chosen. As seen with #link("https://github.com/rust-ndarray/ndarray/issues/794")[this issue], ndarray development is currently fragmented and the maintainers themselves #link("https://github.com/rust-ndarray/ndarray/issues/1272")[do not know what to do]. A good alternative that could be introduced in the future is #link("https://github.com/sarah-ek/faer-rs")[faer-rs], an open source linear algebra library that offers very high performances even with high dimensional matrices. \ Various benchmark can be found #link("https://github.com/sarah-ek/faer-rs?tab=readme-ov-file#benchmarks")[online], for our usage the speed critical operations are multiplication and inverse. The benchmark reported in this document compares the main three rust libraries with eigen, the c++ linear algebra library. At the time of writing, multiplication is mostly the same with ndarray being the fastest while faer-rs and nalgebra are similar. For the inverse operation we have ndarray still on top followed by faer-rs. All three libraries have valid speed, and as such only when dealing with optimization issues with high dimensional matrices Nalgebra should be swapped in favour of faer-rs. It's also worth noting that Rust libraries have similar or even better performances than the C++ library. #figure( image("images/linear_algebra_comparison.PNG", width: 100%), caption: [Example of benchmarks between libraries] )<linear_algebra_comparison> === Argmin Argmin is a numerical optimization library written entirely in Rust. Its goal is to offer a wide range of optimization algorithms with a consistent interface. It is type-agnostic by design, meaning that any type and/or math backend, such as Nalgebra or ndarray can be used – even your own. An optional checkpointing mechanism helps to mitigate the negative effects of crashes in unstable computing environments. Due to Rust's powerful generics and traits, most features can be exchanged by your own tailored implementations. Argmin is designed to simplify the implementation of optimization algorithms and as such can also be used as a toolbox for the development of new algorithms. One can focus on the algorithm itself, while the handling of termination, parameter vectors, populations, gradients, Jacobians and Hessians is taken care of by the library. === Zenoh Zenoh is a pub/sub/query protocol unifying data in motion, data at rest and computations. It elegantly blends traditional pub/sub with geo distributed storage, queries and computations, while retaining a level of time and space efficiency that is well beyond any of the mainstream stacks. All the software components of the ETDV suite communicate using network messages over tr the ROS2 infrastructure. ROS2 has some Rust support, mainly C wrappers, but the solution was not elegant and caused all the ROS2 problems to be introduced to the Rust technology stack. To justify choosing zenoh we need to understand the underlying mechanism of ROS2. ==== What is ROS2? The Robot Operating System 2 (ROS2) is NOT an Operating System. It’s an open source robotics middleware, a set of software frameworks for software and robot development. This means that ROS2 offers us a set of tools to develop and make software communicate. ROS2 is used in the majority of the car projects, and has complete binding in Python, C, C++. We will use Rust, where the ROS2 ecosystem is still immature, and as such we need to find alternative ways to interface with the ROS2 communication schema. ==== How does ROS2 communicate? ROS2 processes are represented as nodes in a graph structure, connected by edges called topics. ROS2 nodes can pass messages to one another through topics, make service calls to other nodes or provide a service for other nodes. ROS2 has a peer to peer structure with decentralized discovery mechanism, while ROS has a ROS master that is used to setup the connections between nodes. #figure( image("images/ROS2_nodes_topic_service.gif", width: 100%), caption: [Nodes, topic and services in ROS2] )<ROS2_nodes_topic_service> - Nodes: A node represents one process running the ROS graph. Every node has a name, which it registers before it can take any other actions. Nodes are at the center of ROS programming, as most ROS client code is in the form of a ROS node which takes actions based on information received from other nodes, sends information to other nodes, or sends and receives requests for actions to and from other nodes; - Topics: Topics are named buses over which nodes send and receive messages. To send messages to a topic, a node must publish to said topic, while to receive messages it must subscribe. The publish/subscribe model is anonymous: no node knows which nodes are sending or receiving on a topic, only that it is sending/receiving on that topic. The types of messages passed on a topic vary widely and can be user-defined. The content of these messages can be sensor data, motor control commands, state information, actuator commands, or anything else; - Service: A node may also advertise services. A service represents an action that a node can take which will have a single result. As such, services are often used for actions which have a defined start and end, such as capturing a one-frame image, rather than processing velocity commands to a wheel motor or odometer data from a wheel encoder. Nodes advertise services and call services from one another. ==== Connect to ROS2 without using ROS2 ROS2 uses the Data Distributed Service (DDS) as its middleware and zenoh offers a bridge to communicate using DDS. What zenoh does is search for DDS readers and writers declared by ROS2 and after that is as simple as encoding messages using the same encoder as ROS2 and decoding them accordingly. Knowing this, we can setup zenoh to be able to communicating correctly with ROS2 nodes. More information can be found #link("https://zenoh.io/blog/2021-04-28-ros2-integration/")[in this official zenoh article]. It's worth noting that this technology stack will become more and more relevant as ROS2 development progresses because, at the end of 2023, the ROS2 community decided to officially move to zenoh as the next middleware. The decision can be found #link("https://discourse.ros.org/t/ros-2-alternative-middleware-report/33771")[here]. #pagebreak() == Minimize the distance function Function optimization is a foundational area of study and the techniques are used in almost every quantitative field. Importantly, function optimization is central to almost all machine learning algorithms, and predictive modeling projects. As such, it is critical to understand what function optimization is, the terminology used in the field, and the elements that constitute a function optimization problem. Function optimization is a subfielld of mathematics, and in modern times is addressed using numerical computing methods. Function Optimization involves three elements: the input to the function (e.g. x), the objective function itself (e.g. f()) and the output from the function (e.g. cost). - Input (x): The input to the function to be evaluated, e.g. a candidate solution; - Function (f()): The objective function or target function that evaluates inputs; - Cost: The result of evaluating a candidate solution with the objective function, minimized or maximized. In our case, the function is converted from MATLAB to pure Rust and the argmin library offers lightweight abstraction that help us define and handle the input and cost. The best performing iterative algorithms usually present a gradient to help them calculate in which direction the minimum or maximum is, but in our case the gradient was not possible to calculate for computational complexity reason. For this reason we had to move to derivative-free constrained optimization. The MATLAB code unfortunately did not delve in the algorithm to use, and simply used the provided fmincon function, that automatically chooses the most generic and often time inefficient algorithm. === Cobyla The name COBYLA is an acronym for Constrained Optimization by Linear Approximation. It is an iterative method for derivative-free constrained optimization. The method maintains and updates linear approximations to both the objective function and to each constraint. The approximations are based on objective and constraint values computed at the vertices of a well-formed simplex. Each iteration solves a linear programming problem inside a trust region whose radius decreases as the method progresses toward a constrained optimum. This algorithm is used in famous libraries like Scipy, and wrappers are found also for #link("https://github.com/relf/cobyla/")[Rust] with the main problem being that the underlying logic is written in Fortran and contains some pretty complicated bugs as highlighted by Dr. <NAME> in #link("https://github.com/relf/cobyla/issues/11")[this issue]. Nevertheless, it was the first approach tested mainly for the ease of use. There are still some problems, like an incompatibility with more recent argmin versions but overall it worked, finding valid solutions with low costs on low dimensional problems. The problems started to become impossible to solve with 200 dimensions, where COBYLA would struggle to converge. #figure( grid( columns: (auto, auto), rows: (auto, auto), gutter: 1em, [ #image("images/cobyla50.jpg", width: 100%) ], [ #image("images/cobyla200.jpg", width: 100%) ], ), caption: [COBYLA algorithm comparison between 50 and 200 dimensions] ) <cobyla_algorithm> === Particle Swarm Particle swarm optimization (PSO) methods iteratively solve problems by moving a swarm of designs (“particles”) around the design space until convergence is reached. As these points move through the design space, they have some notion of velocity and momentum that govern how the designs vary iteration by iteration. A real-world analogy is a swarm of mosquitoes moving in space trying to find a meal. They each individually exist in a point and as a group in a swarm, have some velocities, and are on the hunt for the best meal. PSOs are metaheuristic and make few assumptions about the type of problem being solved. This is useful to explore the design space when you know nothing beforehand. Testing this algorithm was fundamental to the introduction of parallel computation in the code base, that proved crucial in order to run the code faster with high dimensional matrices. === Simulated Annealing Simulated Annealing (SA) is a stochastic optimization method which imitates annealing in metallurgy. Parameter vectors are randomly modified in each iteration, where the degree of modification depends on the current temperature. The algorithm starts with a high temperature (a lot of modification and hence movement in parameter space) and continuously cools down as the iterations progress, hence narrowing down in the search. Under certain conditions, reannealing (increasing the temperature) can be performed. Solutions which are better than the previous one are always accepted and solutions which are worse are accepted with a probability proportional to the cost function value difference of previous to current parameter vector. These measures allow the algorithm to explore the parameter space in a large and a small scale and hence it is able to overcome local minima. This was the algorithm that we decided to implement in the code base, easier to read and modify internally thanks to the Anneal functionality and also outperformed all the other algorithms in benchmarks with high dimensions (300). #figure( grid( columns: (auto, auto), rows: (auto, auto), gutter: 0.3em, [ #image("images/cobyla.jpg", width: 100%) ], [ #image("images/particle_swarm.jpg", width: 100%) ], ), caption: [Comparison between cobyla and particle swarm with 300 dimensions] ) <cobyla_particleswarm_comparison> #figure( image("images/simulated_annealing.jpg", width: 60%), caption: [Simulated annealing with 300 dimensions] )<simulated_annealing> = Conclusions == Achievement of the objectives The main achievements of the experience were: - Code base migration: completed successfully, with only a few GitLab issues lost in the process; - Personnel training: completed successfully, with recording and slides available for the years to come; - CI/CD pipeline: created the structure but did not implement much of the desired functionality; - Lap optimization project: the code base is mature and working as desired, there are further improvements such as swapping the linear algebra library to increase matrix computational speed but these changes are not in priority. == Knowledge gained The #link("Optimal lap trajectory") project was personally the most interesting of the year. The original code was written in MATLAB as a proof of work, without any consideration for performances or reliability. In order to port in a more robust language, I had to work with an engineering student that knew almost nothing about programming and as such it led me to discover part of the project that were not explored. One such part was the simulated annealing algorithm that we had to implement and benchmark. Another project that made me understand the compromises that a cybersecurity expert must make, was the migration of the code base. No regards were given to the security and even enforcing the implementation of 2FA was not approved. As a cybersecurity student I think that I did my best with what I had. == Personal considerations I consider the overall experience a positive one. Almost all the objectives set out at the start of the year have been completed and all the projects I've worked on have been developed with the goal of easily adding pieces or modifications. I think that I've also managed to raise awareness on many security related topics.
https://github.com/mariunaise/HDA-Thesis
https://raw.githubusercontent.com/mariunaise/HDA-Thesis/master/graphics/plots/errorrates_temp_enroll.typ
typst
#import "@preview/cetz:0.2.2": canvas, plot #let data25 = csv("../../data/errorrates/2bit_temp/reconstruction/errorrates_left_25_25.csv") #let ndata25 = data25.map(value => value.map(v => float(v)))// fucking hell is that cursed #let data5 = csv("../../data/errorrates/2bit_temp/reconstruction/errorrates_left_25_5.csv") #let ndata5 = data5.map(value => value.map(v => float(v))) #let data35 = csv("../../data/errorrates/2bit_temp/reconstruction/errorrates_left_25_35.csv") #let ndata35 = data35.map(value => value.map(v => float(v))) #let data55 = csv("../../data/errorrates/2bit_temp/reconstruction/errorrates_left_25_55.csv") #let ndata55 = data55.map(value => value.map(v => float(v))) #let dashed = (stroke: (dash: "dashed")) #canvas({ plot.plot(size: (10,1), x-tick-step: none, y-label: $E(1)$, x-label: $m$, y-tick-step: none, axis-style: "left", x-min: 0, { plot.add((ndata25), mark: "o", mark-size: 0.001) plot.add((ndata5), mark: "o", mark-size: 0.001) plot.add((ndata35), mark: "o", mark-size: 0.001) plot.add((ndata55), mark: "o", mark-size: 0.001) }) })
https://github.com/JarKz/math_analysis_with_typst
https://raw.githubusercontent.com/JarKz/math_analysis_with_typst/main/groups/first.typ
typst
MIT License
= Первая группа вопросов 1. *Понятие множества, отношения включения, основные операции над множествами, их свойства.* *Определение 1*. _Множеством_ называется произвольный набор (совокупность, класс, семейство) каких-либо объектов. Объекты, входящие во множество, называются его _элементами_. Если объект $x$ является элементом множества $A$, то говорят, что $x$ _принадлежит_ $A$, и пишут $x in A$. *Определение 2*. Множество $A$ является _подмножеством_ множества $B$, если любой элемент множества $A$ также принадлежит множеству $B$. Обозначение: $A subset B$. Множества $A$ и $B$ равны, если одновременно $A subset B$ и $B subset A$. Обозначение: $A = B$. *Утверждение 3.* _Имеют место следующие свойства_: - _Рефлексивность $subset$: для любого множества $A$ выполнено $A subset A$_; - _Антисимметричность $subset$: если $A subset B$ и $B subset A$, то $A = B$_; - _Транзитивность $subset$: если $A subset B$ и $B subset C$, то $A subset C$_; - _Рефлексивность $=$: для любого множества $A$ выполнено $A = A$_; - _Симметричность $=$: если $A = B$, то $B = A$_; - _Транзитивность $=$: если $A = B$ и $B = C$, то $A = C$_; *Определение 4.* _Пустым множеством_ $emptyset.rev$ называется множество, не содержащее ни одного элемента. *Утверждение 5.* _Для любого множества $A$ выполнено $emptyset.rev subset A$_. === Операции над множествами *Определение 6.* Пусть заданы множества $A$ и $B$, лежащие в некотором универсуме U. Тогда: - _Объединением_ $A$ и $B$ называется множество $A union B = {x | x in A " или " x in B}$. - _Пересечением_ $A$ и $B$ называется множество $A sect B = {x | x in A " и " x in B}$. - _Разностью_ множеств $A$ и $B$ называется множество $A backslash B = {x | x in A " и " x in.not B}$. - _Симметрической разностью_ множеств $A$ и $B$ называется множество $A Delta B = {x | x in A " и " x in.not B, " или " x in B " и " x in.not A}$. - _Дополнением_ множества $A$ называется множество $ overline(A) = {x | x in.not A} = U backslash A$. *Утверждение 7.* _Для операций над множествами выполнены следующие тоджества:_ - _Коммутативность_: $A union B = B union A, A sect B = B sect A$; - _Ассоциативность_: $(A union B) union C = A union (B union C), (A sect B) sect C = A sect (B sect C)$; - _Дистрибутивность_: $A union (B sect C) = (A union B) sect (A union C), A sect (B union C) = (A sect B) union (A sect C)$; - _Законы де Моргана_: $ overline((A union B)) = overline(A) sect overline(B), overline((A sect B)) = overline(A) union overline(B)$. === Дополнительно: Пары и кортежи. Декартово произведение. *Определение 8.* _Кортежем_ длины 0 называется пустое множество. Если $T = (a_1,..., a_n)$ – кортеж длины $n$, то $(a, a_1,...,a_n) = {a,{a,T}}$ есть кортеж $n + 1$. Кортеж длины 2 называется _упорядоченной парой_. Таким образом, упорядоченная пара $(a, b)$ – это множество ${a,{a,{b,{b,emptyset.rev}}}}$. Можно определять упорядоченную пару и другими способами. Например: - Определение Винера: $(a, b) = {{{a}, emptyset.rev},{{b}}}$; - Определение Хаусдорфа: $(a, b) = {{a, 1}, {b, 2}}$, где 1 и 2 суть объекты, отличные от $a, b$ и друг от друга; - Определение Куратовского: $(a, b) = {{a}, {a,b}};$ - Упрощённое определение Куратовского: $(a, b) = {a, {a, b}}$. *Определение 9.* _Декартовым произведением_ множеств $A$ и $B$ называется множество упорядоченных пар $A times B = {(a, b) | a in A, b in B}$. _Декартовой степенью_ $A^n$ множества $A$ называется множество кортежей длины $n$ элементов $A$. *Утверждение 10.* _При всех $A, B, C, n, m$ выполнены равенства:_ - $A times (B times C) = (A times B) times C$; - $A^n = A times A times dot dot dot times A (n "раз")$; - $A^n times A^m = A^(n + m)$; - $(A^n)^m = A^(n m)$. *Замечание 11.* Формально наше отождествление кортежей задаёт _отношение эквивалентности_, а равенство множеств надо понимать так, что для каждого элемента $x$ одного множества найдётся ровно один элемент другого множества, эквивалентный $x$. 2. *Понятие отображения. Примеры. Область определения и область значений. Образы и прообразы множеств при отображениях.* *Определение 1.* _Соответствием_ между множествами $A$ и $B$ называют произвольное подмножество декартова произведения $F subset A times B$. *Определение 2.* _Отображением_ из множества $A$ в множество $B$ называется однозначное соответствие между $A$ и $B$, т.е. такое соответствие, что для любого $a in A$ найдётся ровно одно $b in B$, соответствющее $a$. *Определение 3.* _Областью определения_ соответствия $F: A arrow.r B$ называетсям множество $"Dom" F = F^(-1)(B)$. Иными словами, область определения – множество тех элементов $A$, которым соответствует хотя бы один элемент $B$. *Определение 4.* _Областью значений_ соответствия $F: A arrow.r B$ называется множество $"Ran" F = F(A)$. Иными словами, область определения – множество тех элементов $B$, которые соответствуют хотя бы одному элементу $A$. *Определение 5.* Пусть $F: A arrow.r B$ – соответствие, а $S subset A$. Тогда _образом_ множества $S$ называется множество всех элементов $B$, соответствующих какому-то элементу $S$. Формально можно записать так: $F(S) = union_(s in S) F(s) subset B$. *Определение 6.* Пусть $F: A arrow.r B$ – соответствие, а $T subset B$. Тогда _прообразом_ множества $T$ называется множество элементов $A$, которым соответствует хотя бы один элемент $T$. Формально $F^(-1)(T) = {a: F(a) sect T eq.not emptyset.rev} subset A$. *Утверждение 7.* _Образ пересечения любых двух множеств равняется пересечению образов тех же множеств тогда и только тогда, когда соответствие инъективно._ 3. *Инъективные, сюръективные и биективные отображения. Композиции отображений. Обратные отображения.* *Определение 1.* _Инъективным_ соответствием называется соответствие, при котором для любых $a_1 eq.not a_2$ множества $F(a_1)$ и $F(a_2)$ не пересекаются. Инъективное отображение называется инъекцией. *Определение 2.* _Сюръективным_ соответствием называется соответствие, при котором любой элемент $B$ соответствует хотя бы одному элементу $A$, т.е. любой $b in B$ лежит в $F(a)$ для некоторого $a in A$. Сюръективное отображение называется _сюръекцией_. *Определение 3.* _Биекцией_ называется отображение, являющееся одновременно инъекцией и сюръекцией. *Утверждение 4.* _Соответствие является биекцией тогда и только тогда, когда каждому элементу $A$ соответствует ровно один элемент $B$, а также каждый элемент $B$ соответствует родно одному элементу $A$_. *Определение 5.* Пусть $F: A arrow.r B$ и $G: B arrow.r C$ – соответствия. Тогда их композицией $G circle.small F$ называется соответствие $H: A arrow.r C$, определённое правилом: $c in H(a)$ тогда и только тогда, когда найдётся $b$, такое что одновременно $c in G(b)$ и $b in F(a)$. *Определение 6.* Пусть $F: A arrow.r B$ – соответствие. _Обратным соответствием_ называется соответствие $F^(-1): B arrow.r A$, определяемое правилом $ a in F^(-1)(b) <=> b in F(a)$. 4. *Вещественные числа и их основные свойства, связанные с арифметическими операциями и неравенствами.* Множество вещественных чисел состоит из рациональных и иррациональных чисел. _Рациональным_ называется число вида $p/q$, где $p$ и $q$ – целые числа. Всякое вещественное число, не являющееся рациональным, называется _иррациональным_. Всякое рациональное число либо является целым, либо предствляет собой конечную или периодическую бесконечную десятичную дробь. Например, рациональное число $1/9$ можно представить в виде $0,1111...$. Иррациональное число представляет собой бесконечную непериодическую десятичную дробь; примеры иррациональных чисел: $ sqrt(2) = 1,411421356...; pi = 3.14159265.... $ *Свойства вещественных чисел.* Для любой пары вещественных чисел $a$ и $b$ определены единственным образом два вещественных числа $a + b$ и $a dot b$, называемые соответственно их _суммой_ и _произведением_. Для любых чисел $a, b$ и $c$ имеют место следующие свойства. + $a + b = b + a, a dot b = b dot a$ (коммутативность); + $a + (b+ c) = (a + b) + c, a dot (b dot c) = (a dot b) dot c$ (ассоциативность); + $(a + b) dot c = a dot c + b dot c$ (дистрибутивность); + _Существует единственное число $0$, такое, что $a + 0 = a$ для $forall a$_; + _Для любого числа $a$ существует такое число $(-a)$, что $a + (-a) = 0$_; + _Существует единственное число $1 eq.not 0$, такое, что для любого числа $a$ имеет место равенство $a dot 1 = a$_; + _Для любого числа $a eq.not 0$ существует такое число $a^(-1)$, что $a dot a^(-1) = 1$. Число $a^(-1)$ обозначается также символом $1/a$_. Для любых двух вещественных чисел имеет место одно из трех соотношений: $a = b$ ($a$ равно $b$), $a gt b$ ($a$ больше $b$) или $a lt b$ ($a$ меньше $b$). Отношение равенства обладает свойством _транзитивности_: если $a = b$ и $b = c$, то $a = c$. Отношение "больше" обладает следующими свойствами: + Если $a > b$ и $b > c$, то $a > c$; + Если $a > b$, то $a + c > b + c$; + Если $a > 0$ и $b > 0$, то $a b > 0$. Вместо соотношения $a > b$ употребляют также $b < a$. Запись $a gt.eq b space (b lt.eq a)$ означает, что либо $a = b$, либо $a > b$. Соотношения со знаками $>, <, gt.eq "и" lt.eq$ называются неравенствами, причем соотношения типа $8 < 10$ – строгими неравенствами. - _Любое вещественное число можно приблизить рациональными числами с произвольной точностью._ 5. *Свойства непрерывности (полноты) множества $RR$ – действительных чисел.* Пусть $X$ и $Y$ – два множества вещественных чисел. Тогда, если для любых чисел $x in X$ и $y in Y$ выполняется неравенство $x lt.eq y$, то существует хотя бы одно число $c$, такое, что для всех $x$ и $y$ выполняются неравенства $x lt.eq c lt.eq y$. Отметим здесь, что свойством непрерывности обладает множество всех вещественных (действительных) чисел, но не обладает множество, состоящее только из рациональных чисел. - Верхняя (нижняя) грань числового множества; Говорят, что множество $X subset RR$ _ограничено сверху_ (_снизу_), если существует число $c in RR$ такое, что $x lt.eq X$. Число $c$ в этом случае называют _верхней_ (соответственно _нижней_) _границей_ множества $X$ или также _мажорантой_ (_минорантой_) множества $X$. Множество, ограниченное и сверху, и снизу, называется _ограниченным_. 6. *Точные границы (грани) числовых множеств, их существование и свойства.* Наименьшее из чисел, ограничивающих множество $X subset RR$ сверху, называется _верхней гранью_ или _точной верхней границей_ множества $X$ и обозначается $sup X$ (читается "супремум $X$"). Формальная запись этого определения: $ (s = sup X) := forall x in X space ((x lt.eq s) and (forall s prime < s space exists x prime in X (s prime < x prime))). $ (Знак $:=$ или $=:$ используется для равенства по определению; в нем двоеточие ставится со стороны определяемого объекта.) Аналогично вводится понятие _нижней грани_ (_точной нижней границы_) множества $X$ как наибольшей из нижних границ множества $ X: (i = inf X) := forall x in X space ((i lt.eq x) and (forall i prime > i space exists x prime in X (x prime < i prime))). $ *Лемма.* (принцип верхней грани) _Всякое непустое ограниченное сверху подмножество множества действительных чисел имеет и притом единственную верхнюю грань_. Аналогично с принципом нижней грани у ограниченного снизу числового множества: _Всякое неупустое ограниченное сверху подмножество множества действительных чисел имеет и притом единственную нижнюю грань_. Некоторые следствия. - _Множество $NN$ натуральных чисел неограничено сверху_. - _В множестве $RR$ действительных чисел справедлив принцип Архимеда_. - _Для любого положительного числа $epsilon$ найдется натуральное число $n$, такое что $0 < 1/n < epsilon$_. - _В любом, отличном от точки, промежутке действительных чисел имеются рациональные числа_. 7. *Леммы: о вложенных отрезках, о покрытиях, о предельной точке.* *Лемма.* (принцип вложенных отрезков) _Для любой последовательности $I_1 supset I_2 supset ... supset I_n supset ...$ вложенных отрезков найдется точка $c in RR$, принадлежащая всем этим отрезкам._ _Если, кроме того, известно, что для любого $epsilon > 0$ в последовательности можно найти отрезок $I_k$, длина которого $|I_k| < epsilon$, то c – единственная общая точка всех отрезков._ *Лемма.* (принцип выделения конечного покрытия) _В любой системе интервалов, покрывающей отрезок, имеется конечноая подсистема, покрывающая этот отрезок._ Точка $p in RR$ называется _предельной точкой_ множества $X subset RR$, если любая окрестность этой точки содержит бесконечное подномжество множеств $X$. Это условие, очевидно, равносильно тому, что в любой окрестности точки $p$ есть, по крайней мере одна не совпадающая с $p$ точка множества $X$. *Лемма.* (принцип предельной точки) _Всякое бесконечное ограниченное числовое множество имеет по крайней мере одну предельную точку_. 8. *Понятие предела последовательности. Общие свойства пределов.* *Определение.* Пусть $A$ – произвольное множество и пусть каждому $n in NN$ поставлен в соответствие некоторый элемент $a in A$. Тогда говорят, что задана _последовательность_ $ a_1, a_2, a_3, ..., $ которая обозначается также символами ${a_n}, {a_n}_(n=1)^oo, {a_n}_(n in NN).$ *Определение.* Число $a in RR$ называется _пределом последовательности_ ${a_n}$, если для $ forall epsilon > 0 space exists n_epsilon in NN: |a - a_n| < epsilon space forall n >= n_epsilon $ При этом пишут $lim_(n -> oo) a_n = a$. Например, $lim_(n -> oo) 1/n = 0$. Основные свойства: - Точка $a$ является пределом последовательности ${x_n}$ тогда и только тогда, когда за пределами любой окрестности этой точки находится *конечное число элементов* последовательности или пустое множество. - Если число $a$ не является пределом последовательности ${x_n}$, то существует такая окрестность точки $a$, за пределами которой находится *бесконечное число элементов последовательности*. - *Теорема единственности предела числовой последовательности*. Если последовательность имеет предел, то он единственный. - Если последовательность имеет конечный предел, то она *ограничена*. - Если каждый элемент последовательности ${x_n}$ *равен одному и томуу же числу* $C$: $x_n = C$, то эта последовательность имеет предел, равный числу $C$. - Если у последовательности *добавить, отбросить или изменить первые _m_ элементов*, то это не повлияет на её сходимость. 9. *Теоремы о предельном переходе и арифметических операциях над последовальностями.* *Теорема о предельном переходе.* _Если две варианты $x_n$ и $y_n$ при всех их изменениях равны: $x_n = y_n$, причём каждая из них имеет конечный предел:_ $ lim x_n = a, space lim y_n = b, $ _то равны и эти пределы: $a = b$._ *Арифметические операции над переменными:* + _Если варианты $x_n$ и $y_n$ имеют конечные пределы:_ $ lim x_n = a, space lim y_n = b, $ _то и сумма (разность) их также имеет конечный предел, причем_ $ lim(x_n plus.minus y_n) = a plus.minus b. $ + _Если варианты $x_n$ и $y_n$ имеют конечные пределы_: $ lim x_n = a, space lim y_n = b, $ _то и произведение их также имеет конечный предел, и_ $ lim x_n y_n = a b. $ + _Если варианты $x_n$ и $y_n$ имеют конечные пределы_: $ lim x_n = a, space lim y_n = b, $ _причём $b$ отлично от $0$, то и отношение их также имеет конечный предел, а именно,_ $ lim x_n/y_n = a/b. $ 10. *Теоремы о предельном переходе в неравенствах для последовательностей.* *Теорема о предельном переходе в неравенстве.* _Если для двух вариант $x_n$, $y_n$ всегда выполняется неравенство $x_n >= y_n$, причём каждая из них имеет конечный предел:_ $ lim x_n = a, space lim y_n = b, $ _то равны и $a >= b$._ 11. *<NAME> существования конечного предела последовательности.* *Теорема.* (<NAME>) Для того, чтобы последовательность имела конечный предел, необходимо и достаточно, чтобы она удовлетворяла условию: $ forall epsilon > 0 space exists n_epsilon in NN | forall n > n_epsilon, forall m > n_epsilon |x_n - x_m| < epsilon. $ 12. *Теорема о пределе монотонной последовательности. Существование числа $e$.* *Теорема.* _Пусть дана монотонно возрастающая варианта $x_n$. Если она ограничена сверху_: $ x_n <= M (M = "const"; n = 1,2,3,...), $ _то необходимо имеет *конечный* предел, в противном же случае – она стремится к $+infinity$_. _Точно так же, всегда имеет предел и монотонно убывающая варианта $x_n$. Ее предел конечен, если она ограничена снизу_: $ x_n >= m (m = "const"; n = 1,2,3,...), $ _в противном же случае ее пределом служит $-infinity$_. Рассмотрим варианту $x_n = (1 + 1/n)^n$ и попытаемся применить к ней вышенаписанную теорему. Сначала докажем её монотонность с помощью разложения по формуле бинома: $ x_n = (1 + 1/n)^n = 1 + n dot 1/n + (n(n-1))/(1 dot 2) dot 1/n^2 + (n(n - 1)(n - 2))/(1 dot 2 dot 3) dot 1/n^3 + $ $ + ... + (n(n - 1)...(n - k + 1))/(1 dot 2...k) dot 1/n^k + ... + (n(n - 1)...(n - n + 1))/(1 dot 2...n) dot 1/n^n = $ $ = 1 + 1 + 1/2!(1 - 1/n) + 1/3!(1 - 1/n)(1 - 2/n) + ... + 1/k!(1 - 1/n)...(1 - (k - 1)/n) $ $ + ... + 1/n!(1 - 1/n)...(1 - (n - 1)/n). (1) $ Если от $x_n$ перейти теперь к $x_(n + 1)$, т.е. увеличить $n$ на единицу, то, прежде всего, добавится новый, $(n + 2)$-й (*положительный*) член, каждый же из написанных $n + 1$ членов *увеличится*, ибо любой множитель в скобках вида $1 - s/n$ заменится *бОльшим* множителем $1 - s/(n + 1)$. Отсюда и следует, что $ x_(n + 1) > x_n, $ т.е. варианта $x_n$ оказывается возрастающей. Теперь покажем, что она к тому же *ограничена сверху*. Опустив в выражении (1) все множители в скобках, мы этим увеличим его, так что $ x_n < 2 + 1/2! + 1/3! + ... + 1/n! = y_n. $ Заменив, далее, каждый множитель в знаменателях дробей (начиная с 3) числом 2, мы ещё *увеличим* полученное выражение, так что, в свою очередь, $ y_n < 2 + 1/2 + 1/2^2 + ... + 1/(2^(n - 1)). $ Но прогрессия (начинающаяся членом $1/2$) имеет сумму $< 1$, поэтому $y_n < 3$, а значит и подавно $x_n < 3$. Отсюда уже следует, по теореме, что варианта $x_n$ имеет конечный предел. По примеру Эйлера (L. Euler), его обозначают всегда буквой $e$. Это число $ e = lim(1 + 1/n)^n $ имеет исключительную важность как для самого анализа, так и для его приложений. 13. *Понятие предела функции при $x -> a$. различные формы определения этого понятия.* Рассмотрим числовое множество $X = {x}$. Окрестность точки $a$ – любой открытый промежуток $(a - delta, a + delta)$ с центром в точке $a$. *Определение.* Точка $a$ называется *точкой сгущения* этого множества, если в каждой её окрестности содержатся значения $x$ из $X$. *Определение.* (предел функции) функция $f(x)$ имеет пределом число $A$ при стремлении $x$ к $a$ (или в точке $a$), если для каждого число $epsilon > 0$ найдётся такое число $delta > 0$, что $ |f(x) - A| < epsilon, "лишь только" |x - a| < delta $ где ($x$ взято из $X$ и *отлично* от а). обозначают этот факт так: $ lim_(x -> a) f(x) = A. $ Строгая запись предела функции по Коши: $ A = lim_(x -> a) f(x) <=> [forall epsilon > 0 space exists delta > 0 | forall x in X : 0 < |x - a| < delta => |f(x) - A| < epsilon]. $ *Определение.* (предел функции по Гейне) предел функции $f(x)$ в точке $x = a$ равен числу $A$, если для любой последовательности ${x_n}$, стремящейся к $a$, все члены которой не равны $a$, выполняется утверждение: последовательность значений функции $f(x)$ в точках $x_n$ стремится к $A$: $f(x_n) -> A$ при $n -> oo$. Строгая запись предела функции по Гейне: $ forall {x_n} : ((forall n : x_n eq.not a) and (lim_(n -> oo) x_n = a)) => lim_(n -> oo) f(x_n) = A $ 14. *Общие свойства предела функции.* - Предел постоянной равен самой постоянной: $lim_(x -> a) c = c.$ - Если при стремлении $x$ к $a$ функция $f(x)$ имеет конечный предел $A$, и $A > p space (A < p)$, то для достаточно близких к $a$ значений $x$ (отличных от $a$) и сама функция удовлетворяет неравенству $ f(x) > p space (f(x) < q). $ - Если при $x -> a$ функциЯ $f(x)$ имеет конечный положительный (отрицательный) предел, то и сама функция положительна (отрицательна), по крайней мере, для значений $x$, достаточно близких к $a$, но отличных от $a$. - Если при стремлении $x$ к $a$ функция $f(x)$ имеет конечный предел $A$, то *для значений $x$, достаточно близких к $a$*, функция будет ограниченной: $ |f(x)| <= M prime space (M prime = "const", space |x - a| < delta). $ - Функция не может иметь двух различных пределов в одной точке. - Если функции $f(x), g(x)$ и $h(x)$ определены в некоторой окрестности точки $a$, исключая, может быть, саму точку $a$, и для всех $x$ из этой окрестности выполняется неравенство $f(x) <= h(x) <= g(x)$, при этом $lim_(x -> a) f(x) = lim_(x -> a) g(x) = a$, где $a$ – некоторое число, то $ lim_(x -> a) h(x) = lim_(x -> a) f(x) = lim_(x -> a) g(x) = a. $ 15. *Предельный переход и арифметические операции для функций.* *Теорема.* (о предельном переходе в равенстве). Если две функции принимают одинаковые значения в окрестности некоторой точки, что их пределы в этой точке совпадают: $ f(x) = g(x) => lim_(x -> a) f(x) = lim_(x -> a) g(x) $ Свойства пределов, свазанные с арифметическими операциями функций: - Если каждое слагаемое алгебраической суммы функций имеет предел при $x -> a$, то и алгебраическая сумма имеет предел при $x -> a$, причем предл алгебраической суммы равен алгебраической сумме пределов: $ lim_(x -> a) (f(x) + g(x) - h(x)) = lim_(x -> a) f(x) + lim_(x -> a) g(x) - lim_(x -> a) h(x). $ - Если каждый из сомножителей произведения конечного числа функций имеет предел при $x -> a$, то и произведение имеет предел при $x -> a$, причем предел произведения равен произведению пределов: $ lim_(x -> a) (f(x) dot (g(x)) = lim_(x -> a) f(x) dot lim_(x -> a) g(x). $ Следствие. Постоянный множитель можно выносить за знак предела: $ lim_(x -> a) c dot f(x) = c dot lim_(x -> a) f(x). $ - Если функции $f(x)$ и $g(x)$ имеют предел при $x -> a$, причем $lim_(x -> a) g(x) eq.not 0$, то и их частное имеет предел при $x -> a$, причем предел частного равен частному пределов: $ lim_(x -> a) f(x)/g(x) = (lim_(x->a) f(x))/(lim_(x -> a) g(x)), lim_(x -> a) g(x) eq.not 0. $ 16. *Предельный переход и неравенства для функций. Предел $lim_(x->0)(sin x)/x$.* *Теорема.* (о предельном переходе в неравенстве). Если значения функции $f(x)$ в окрестности некоторой точки не превосходят соответствующих значений функции $g(x)$, то предел фукнции $f(x)$ в этой точке не превосходит предела функции $g(x)$: $ f(x) < g(x) => lim_(x -> a) f(x) <= lim_(x -> a) g(x). $ Доказательство $lim_(x -> 0)(sin x)/x = 1$: #figure(image("../images/Prove that limit sin(x) x = 1.gif", width: 80%), caption: [Сектор круга.]) <sector> Изобразим круг, радиус которого равен 1 (@sector). Через $x$ обозначим *радианную меру* угла $angle.arc"AOB"$. Как мы видим на @sector, площадь треугольника $Delta"ABC"$ меньше площади сектора $"ABC"$, который, в свою очередь, меньше площади треугольника $Delta"ABD"$. В итоге имеем неравенство: $ Delta"ABC" < "сектор ABC" < Delta"ABD" $ Площадь треугольника $Delta"ABC"$ равна $1/2"AB"sin x = 1/2 sin x$. Площадь сектора равна произведению длины дуги сектора на половину радиуса: $1/2 R dot display(limits("AB")^paren.b) = 1/2 R * R * x = 1/2 x.$ Площадь треугольника $Delta"ABD"$ равна $1/2"AB" dot "DB" = 1/2 tan x$. Таким образом, имеем неравенство: $ 1/2 sin x < 1/2 x < 1/2 tan x. $ Отсюда – по сокращении на $1/2$ приходим к неравенству: $ sin x < x < tan x space (0 < sin x < pi/2). $ В предположении, что $0 < x < pi/2$, разделим $sin x$ на каждый из членов неравенства. Мы получим: $ 1 < x/(sin x) < 1/(cos x) => 1 > (sin x)/x > cos x. $ Так как $(sin x)/x$ и $cos x$ являются чётными функциями, предыдущоее неравенство является верным для всех ненулевых $x$ между $-pi/2$ и $pi/2$. Более того, при стремлении $x$ к $0$ $cos x$ принимает значение равное $1$: $ cos 0 = 1. $ Таким образом, $(sin x)/x$ окажется заключённым между $1$ и $1$, отчего его предел обязательно должен быть равен $1$: $ lim_(x -> 0) (sin x)/x = 1. $ Что и требовалось доказать. 17. *Теорема о пределе композиции функций.* *Теорема.* Пусть функция $f$ задана на множестве $X$, функция $g$ - на множестве $Y$ и $f(X) subset Y$. Если существуют конечные или бесконечные пределы $ lim_(x -> x_0) f(x) = y_0, lim_(y -> y_0) = g(y) = z_0, $ то при $x -> x_0$ существует предел (конечный или бесконечный) сложной функции $g[f(x)]$, причем $ lim_(x -> x_0) g[f(x)] = lim_(y -> y_0) g(y). $ 18. *Критерий Коши существования конечного предела функции.* *Теорема.* Для того, чтобы функция $f, x in X$ имела в (конечной или бесконечно удаленной) точке $a$ конечный предел, необходимо и достаточно, чтобы для любого $epsilon > 0$ существовала такая окрестность $U(a)$ точки $a$, что для любых $x prime in X sect U(a)$ и $x prime.double in X sect U(a)$ выполнялось бы неравенство $ f(x prime.double) - f(x prime) < epsilon $ *Замечание.* Сформулируем критерий Коши существования конечного предела функции в терминах неравенств для случая, когда $a$ - действительное число: функция $f$, $x in X$, имеет в точке $a in RR$ конечный предел тогда и только тогда, когда для любого $epsilon > 0$ существует такое $delta > 0$, что для всех точек $x prime in X$, $x prime.double in X$, $|x prime - a| < delta, |x prime.double - a| < delta$ , выполняется неравенство $|f(x prime.double) - f(x prime)| < epsilon$. 19. *Сравнение асимптотического поведения функций. Символы $o, O, ~$. Примеры.* *Определение 1.* Пусть функции $f(x)$ и $g(x)$ заданы на некотором множестве $D subset RR$. Говорят, что _на множестве_ $G subset D$ $ f(x) = O(g(x)), x in G $ (читается: "о-большое от $g(x)$"), если существует такая постоянная $M$, что при $x in G$ выполнено неравенство $ |f(x)| <= M|g(x)|. $ *Определение 2.* Пусть функции $f(x)$ и $g(x)$ заданы на некотором множестве $D$, а $a$ - предельная точка этого множества. Говорят, что $ f(x) = o(g(x)), "при" x -> a, $ (читается: "о-малое от $g(x)$"), если существует такая бесконечно малая при $x -> a$ функция $alpha(x)$, что $ f(x) = alpha(x) dot g(x) $ для всех $x$ из некоторой проколотой окрестности $U$ точки $a$, $U subset D$. *Определение 3.* Пусть функции $f(x)$ и $g(x)$ заданы на некотором множестве $D$, а $a$ - предельная точка этого множества. Эти функции _эквивалентны при_ $x -> a$, если в некоторой проколотой окрестности точки $a$ $ f(x) = g(x) + o(g(x)). $ Данное соотношение кратно записывается следующим образом: $ f(x) space ~ space g(x), x -> a (x in D). $ Утверждения: $ "Если" exists lim_(x -> a) f(x)/g(x) = A, A eq.not infinity => f(x) = O(g(x)), x -> a. $ $ "Если" exists lim_(x -> a) f(x)/g(x) = 0 => f(x) = o(g(x)), x -> a. $ $ "Если" exists lim_(x -> a) f(x)/g(x) = 1 => f(x) space ~ space g(x), x -> a. $ Примеры: - $sin x space ~ space x, x -> 0 <=> lim_(x -> 0) (sin x)/x = 1.$ - $sin x = o(x), x -> oo <=> lim_(x -> oo) (sin x)/x = 0.$ - $sin x = O(x), x in RR <=> |sin x| <= |x| forall x.$ По определению 1 следует $sin x = O(x), x in RR.$ 20. *Понятие непрерывности функции в точке. Различные формы определения этого понятия.* *Определение.* Функция $f(x)$ *непрерывна* при значении $x = x_0$ (или в точке $x = x_0$), если выполняется соотношение: $ lim_(x -> x_0) f(x) = f(x_0). $ Если же оно нарушено, то говорят, что при этом значении (или в этой точке) функция имеет *разрыв*. *Определение.* (на языке $epsilon-delta$). Фукнция $f(x)$ называется *непрерывной в точке $x_0$* если $forall epsilon > 0 space exists delta > 0$ такое, что $ "если" x in U(x_0, delta) space ("т.е." |x - x_0| < delta), $ $ "то" f(x) in U(f(x_0), epsilon) space ("т.е." |f(x) - f(x_0)| < epsilon). $ *Определение.* (геометрическое). Функция $f(x)$ называется *непрерывной в точке $x_0$* если в этой точке бесконечно малому приращению аргумента соответствует бесконечно малое приращение функции, т.е. $ lim_(Delta x -> 0) Delta f(x_0) = 0. $ *Определение.* Функция $f(x)$ называется *непрерывной в точке $x_0$ справа (слева)*, если справедливо равенство $ lim_(x -> x_0 + 0) f(x) = f(x_0) space (lim_(x -> x_0 - 0) f(x) = f(x_0)). $ *Определение.* (непрерывность на интервале) Функция $f(x)$ называется *непрерывной на интервале $(a; b)$*, если она непрерывна в каждой точке этого интервала. *Определение.* (непрерывность на отрезке) Функция $f(x)$ называется *непрерывной на отрезке $[a; b]$*, если она непрерывна на интервале $(a; b)$ и имеет одностороннюю непрерывность в граничных точках (т.е. непрерывна в точке $a$ справа, в точке $b$ – слева). 21. *Точки разрыва, их классификация. Примеры разравных функций.* *Определение.* Если функция $f(x)$ определена в некоторой окрестности точки $x_0$, но не является непрерывной в этой точке, то *$f(x)$ называют разрывной в точке $x_0$*, а саму точку *$x_0$ называют точкой разрыва* функции $f(x)$. Пусть $x_0$ – точка разрыва функции $f(x)$. *Определение.* (точка разрыва первого рода). Точка $x_0$ называется *точкой разрыва I рода*, если функция $f(x)$ имеет в этой точке конечные пределы слева и справа. Если при этом эти пределы равны, то точка $x_0$ называется *точкой устранимого разрыва*, в противном случае – *точкой скачка*. Для примера возьмём функцию знака $f(x) = "sign"(x)$. Данная функция терпит разрыв в точке $x_0 = 0$. Пределы справа и слева относительно этой точки определены: $ lim_(x -> 0 + 0) "sign"(x) = 1 $ $ lim_(x -> 0 - 0) "sign"(x) = -1. $ В таком случае, по определению, функция $f(x) = "sign"(x)$ терпит разрыв I рода в точке $x_0 = 0$. Скачок в ней равен: $ lim_(x -> 0+0) "sign"(x) - lim_(x -> 0 - 0) "sign"(x) = 1 - (-1) = 2. $ Однако, если рассматривать функцию $f(x) = |"sign"(x)|$, то точка $x_0 = 0$ является точкой устранимого разрыва, ибо скачок в ней: $ lim_(x -> 0 + 0) "sign"(x) - lim_(x -> 0 - 0) "sign"(x) = 1 - 1 = 0. $ *Определение.* (точка разрыва второго рода). Точка $x_0$ называется *точкой разрыва II рода*, если хотя бы один из односторонних пределов функции $f(x)$ в этой точке равен $infinity$ или не существует. В качестве примера возьмём функцию $f(x) = 1/x$. Очевидно, что она имеет разрыв в точке $x = 0$, так как не определена в этой точке. Пределы справа и слева относительно этой точки не определены: $ lim_(x -> 0 + 0) 1/x = infinity $ $ lim_(x -> 0 - 0) 1/x = -infinity. $ Из этого следует, по определению, что данная функция терпит разрыв II рода в точке $x = 0$. 22. *Локальные свойства непрерывных функций.* Пусть $X = {x_0}$ или $X = (a; b)$ или $X = [a; b]$. - Сумма, разность и произведение конечного числа непрерывных на множестве $X$ функций является функцией непрерывной на $X$. - Если функции $f(x)$ и $g(x)$ непрерывны на $X$ и $g(x) eq.not 0, forall x in X$, то частное $f(x)/g(x)$ – непрерывная на множестве $X$ функция. - Пусть $f: X -> Y$, $phi: Y -> Z$. Если $f(x)$ непрерывна на $X$, $phi(x)$ - непрерывна на $Y$, то сложная функция $phi(f(x))$ непрерывна на $X$. - Основные элементарные функции нерерывны всюду в своей области определения. 23. *Теорема Больцано – Коши. Теорема о промежуточных значениях.* *Теорема Больцано – Коши* (о промежуточных значениях). Пусть функция $f(x)$ непрерывна на отрезке $[a; b]$ и $gamma$ - число, заключенное между $f(a)$ и $f(b)$. Тогда существует хотя бы одна точка $x_0 in [a; b]$ такая, что $f(x_0) = gamma$. *Следствие.* Если функция $f(x)$ непрерывна на отрезке $[a; b]$и на его концах принимает значения разных знаков, то на $(a; b)$ существует хотя бы она точка, в которой функция обращается в ноль. 24. *Т<NAME> о максимуме и минимуме.* *Теорема.* Пусть функция $f(x)$ непрерывна на отрезке $[a; b]$. Тогда + $f(x)$ – ограничена на [a; b]; + $f(x)$ принимает на $[a; b]$ свое наибольшее и наименьшее значения (максимумы и минимумы). *Определение.* Значение функции $m = f(x_1)$ называется *наименьшим* (или минимумом), если $m <= f(x), forall x in D(f)$. Значение функции $M = f(x_2)$ называется *наибольшим* (или максимумом), если $M >= f(x), forall x in D(f)$. *Замечание.* Наименьшее (наибольшее) значение фукнция может принимать в нескольких точках отрезка. *Следствие (теорем Больцано–Коши и Вейерштрасса).* Если функция $f(x)$ непрерывна на отрезке $[a; b]$, то множеством ее значений является отрезок $[m; M]$, где $m$ и $M$ – соответственно наименьшее и наибольшее значения функций $f(x)$ на отрезке $[a; b]$. 25. *Понятие равномерной непрерывности. Теорема Кантора о равномерной непрерывности.* *Определение.* Функция $f: E -> RR$ называется равномерно непрерывной на множестве $D subset E$, если $ forall epsilon > 0 space exists delta > 0 : forall x_1, x_2 in D : |x_1 - x_2| < delta => |f(x_1) - f(x_2)| < epsilon. $ *Теорема (Кантора).* Функция, непрерывная на отрезке $[a; b]$, равномерно непрерывна на нем. 26. *Теорема о непрерывности обратной функции.* *Теорема.* Пусть функция $y = f(x)$ определена, монотонно возрастает (убывает) в строгом смысле слова и непрерывна в некотором промежутке $X$. Тогда в соответствующем промежутке $Y$ значений этой функции существует *однозначная* обратная функция $x = f^-1(y)$, также монотонно возрастающая (убывающая) в строгом смысле слова и непрерывная. 27. *Непрерывность некоторых элементарных функций.* 1. *Целая* и *дробная рацоинальные функции*. Функция $f(x) = x$, очевидно, непрерывна во всем промежутке $(-infinity, +infinity)$: если $x_n -> x_0$, то $f(x_n) = x_n -> x_0 = f(x_0)$. Точно так же непрерывна и функция, сводящаяся тоджественно к постоянной. 2. *Показательная функция*. Докажем непрерывность показательной функции $a^x$ при любом значении $x = x_0$, иными словами, установим, что $ lim_(x -> x_0) a^x = a^(x_0). $ (при этом достаточно ограничиться предположением: $a > 1$.) Проверим непрерывность показательной функции в точке $x_0 = 0$: $ lim_(x -> 0) a^x = 1. $ Отсюда уже легко перейти к любой точке; действительно, $ a^x - a^(x_0) = a^(x_0) (a^(x - x_0) - 1), $ но при $x -> x_0$, очевидно, $x - x_0 -> 1$, так что – по доказанному – $ a^(x - x_0) -> 1 space "и" space a^x -> a^(x_0), $ чтд. 3. *Гиберболические функции*. Их непрерывность непосредственно вытекает из доказанной непрерывности показательной ункции, ибо все они рацоинально выражаются через функцию $e^x$. 4. *Тригонометрические функции*. Остановимся сначала на функции $sin x$. Она также непрерывна при любом значении $x = x_0$, т.е. имеет место равенство $ lim_(x -> x_0) sin x = sin x_0. $ Для доказательства заметим, что из неравенства $ sin x < x, $ установленного при доказательстве предела $lim_(x -> 0) (sin x)/x = 1$, для $0 < x < pi/2$, легко вывести, что неравенство $ |sin x| <= |x| $ справедливо уже для всех значений $x$ (для $|x| >= pi/2 > 1$ это следует из того, что $|sin x| <= 1$). Далее, имеем $ sin x - sin x_0 = 2 sin (x - x_0)/2 dot cos (x + x_0)/2, $ так что $ |sin x - sin x_0| = 2 dot |sin (x - x_0)/2| dot |cos (x + x_0)/2| <= 2 dot |sin (x - x_0)/2| <= 2 dot (|x - x_0|)/2 $ и, окончательно, $ |sin x - sin x_0| <= |x - x_0|, $ каковы бы ни были значения $x$ и $x_0$. Если задано любое $epsilon > 0$, то положим $delta = epsilon$; при $|x - x_0| < delta$ будет $ |sin x - sin x_0| < epsilon, $что и доказывает непрерывность $sin x$. Аналогично устанавливается и непрерывность функции $cos x$ также при любом значении $x$. Отсюда вытекает уже непрерывность функций $ tg x = (sin x)/(cos x), space sec x = 1/(cos x), space ctg x = (cos x)/(sin x), space csc x = 1/(sin x). $ Исключение представляют для первых двух – значения вида $(2k + 1) pi/2$, обращающие $cos x$ в $0$, для последних двух – значения вида $k pi$, обращающие $sin x$ в $0$. 5. *Логарифмическая функция*: $y = log_a x space (a > 0, a eq.not 1)$. Ограничиваясь случаем $a > 1$, видим, что эта функция возрастает при изменении $x$ в промежутке $X = (0, +infinity)$. К тому же она, очевидно, принимает любое значение $y$ из промежутка $Y = (-infinity, +infinity)$, именно, для всех $x = a^y$. Отсюда – ее непрерывность. 6. *Степенная функция*: $y = x^mu (mu gt.lt 0)$, при возрастании $x$ от $0$ до $+infinity$ возрастает, если $mu > 0$, и убывает, если $mu < 0$. При этом она принимает *любое* положительное значение $y$ (для $x = y^(1/mu)$), следовательно, и она непрерывна. 7. *Обратные тригонометрические функции*: $ y = arcsin x, space y = arccos x, space y = "arctg" x , space y = "arcctg" x. $ Первые две непрерывны в промежутке $[-1, + 1]$, а последние – в промежутке $(-infinity, +infinity)$. 28. *Дифференцируемые функции. Понятие дифференциала и производной. Связь между ними.* Определение производной: Пусть функция $y = f(x)$ определена в промежутке $X$. Исходя из некоторого значения $x = x_0$ независимой переменной, придадим ему приращение $Delta x gt.lt 0$, не выводящее его из промежутка $X$, так что и новое значение $x_0 + Delta x$ принадлежит этому промежутку. Тогда значение $y = f(x_0)$ функции заменится новым значением $y + Delta y = f(x_0 + Delta x)$, т.е. получит приращение $ Delta y = Delta f(x_0) = f(x_0 + Delta x) - f(x_0). $ _Предел отношения приращения функции $Delta y$ к вызвавшему его приращению независимой переменной $Delta x$, при стремлении $Delta x$ к $0$, т.е._ $ lim_(Delta x -> 0) (Delta y)/(Delta x) = lim_(Delta x -> 0) (f(x_0 + Delta x) - f(x_0))/(Delta x). $ Определение дифференциала: Пусть имеем функцию $y = f(x)$, определенную в некотором промежутке $X$ и непрерывную в рассматриваемой точке $x_0$. Тогда приращению $Delta x$ аргумента отвечает приращение $ Delta y = Delta f(x_0) = f(x_0 + Delta x) - f(x_0), $ бесконечно малое вместе с $Delta x$. Большую важность имеет вопрос: _существует ли для $Delta y$ такая линейная относительно $Delta x$ бесконечно малая $A dot Delta x space (A = "const")$, что их разность оказывается, по сравнению с $Delta x$, бесконечно малой высшего порядка_: $ Delta y = A dot Delta x + o(Delta x). space (1) $ _Если это равенство выполняется, то функция $y = f(x)$ называется *дифференцируемой* (при данном значении $x = x_0$), само же выражение $A dot Delta x$ называется *дифференциалом* функции_ и обозначается символом $d y$ или $d f(x_0)$. Связь между дифференциалом и производной: _Для того, чтобы функция $y = f(x)$ в точке $x_0$ была дифференцируема, необходимо и достаточно, чтобы для нее в этой точке существовала конечная производная $y prime = f prime (x_0)$. При выполнении этого условия, равенство $(1)$ имеет место при значении постоянной $A$, равном именно этой производной_: $ Delta y = y_x prime Delta x + o(Delta x). $ *Необходимость*. Если выполняется $(1)$, то отсюда $ (Delta y)/(Delta x) = A + (o(Delta x))/(Delta x), $ так что, устремляя $Delta x$ к $0$, действительно, получаем $ A = lim (Delta y)/(Delta x) = y_x prime. $ *Достаточность* сразу вытекает из $ Delta y = y_x prime dot Delta x + o(Delta x). $ 29. *Гоеметрический и физический смысл производной.* *Геометрический смысл производной*: #figure(image("../images/Geometrical sense of derivative.png", width: 70%), caption: [Кривая и касательная.]) <geom_sense_of_derivative> Обратимся к вышеприведённому схематическому рисунку. На нём изображён график функции $y = f(x)$. Обозначим через $P$ точку, которой соответствует значение функции в точке $x_0$. Проведём некоторкую секущую через точки $P$ и $P_1$. Угол наклона между положительным направлением оси $X$ и этой секущей обозначим через $beta$. В результате получится прямоугольный треугольник с катетами $Delta x$ и $Delta y$. Здесь $Delta x$ – это приращение аргумента функции, а $Delta y$ – приращение самой функции. Отношение приращения функции к приращению аргумента есть тангенс угла между секущей и положительным направлением оси абцисс: $ (Delta y)/(Delta x) = tg beta. $ Если устремить $Delta x -> 0$, то точка $P_1$ на графике будет приближаться к точке $P$, а секущая – менять своё положение относительно графика. Предельным положением секущей при стремящемся к нулю приращению будет прямая, в которой точки $P$ и $P_1$ совпадут друг с другом. Такая прямая называется *касательной* к графику в точке $P$. $ tg beta -> tg alpha "при" Delta x -> 0. $ Геометрический смысл производной заключается в том, что значение производной функции в точке численно равно тангенсу угла наклона касательной к функции в этой точке. Известно, что уравнение любой прямой имеет такой общий вид: $y = k dot x + b$. Так вот, в уравнении касательной к функции в точке $P$ коэффициент $k$ как раз равен значению производной в точке $x_0$: $ lim_(Delta x -> 0) (Delta y)/(Delta x) = tg alpha = k. $ *Физический смысл производной*: Рассмотрим движение точки в пространстве. Представим, что точка движется по какой-то траектории на плоскости и пройденное расстояние, конечно же, зависит от времени $S = S(t)$. При этом средняя скорость за определённый отрезок времени будет равняться растоянию, пройденному точкой за это время, делённому на время: $ V_"ср" = S/t.$ Зафиксируем некоторый момент времени $t_0$ и рассмотрим следующий за ним бесконечно малый временной интервал длительностью $Delta t$. По сути, мы опять рассматриваем положение точки в два момента времени: $S(t_0)$ и $S(t_0 + Delta t)$. Устремим $Delta t -> 0$. В результате мы получим ни что иное как значение скорости точки в момент времени $t_0$. Другими словами, это мгновенная скорость точки в конкретный момент времени $t_0$: $V(t_0) = S prime (t_0) = lim_(Delta t -> 0) (S(t_0 + Delta t) - S(t_0))/(Delta t). $ Таким образом, физический смысл производной заключается в следующем: если положение точки при её движении по числовой прямой задаётся функцией $S = S(t)$, где $t$ – время движения, то производная функции $S$ – это мгновенная скорость движения в момент времени $t$. Другими словами, физический смысл производной заключается в определении *скорости изменения* функции. 30. *Производная суммы, произведения, частного функций.* 1. _Пусть функция $u = phi(x)$ имеет (в определенной точке $x$) производную_ $u prime$. Докажем, что и _функция $ y = c u space (c = "const".)$ также имеет производную (в той же точке)_, и вычислим её. Если независимая переменная $x$ получит приращение $Delta x$, то функция $u$ получит приращение $Delta u$, перейдя от исходного значения $u$ к значению $u + Delta u$. Новое значение функции $y$ будет $y + Delta y = c (u + Delta u).$ Отсюда $Delta y = c dot Delta u$ и $ lim_(Delta x -> 0) (Delta y)/(Delta x) = c dot lim_(Delta x -> 0) (Delta u)/(Delta x) = c dot u prime. $ Итак, производная существует и равна $y prime = (c dot u) prime = c dot u prime. $ Эта формула выражает такое правило: *постоянный множитель может быть вынесен за знак производной*. 2. _Пусть функция $u = phi(x), v = psi(x)$ имеют (в определеной точке) производные_ $u prime, v prime$. Докажем, что _функция $y = u plus.minus v$ также имеет производную (в той же точке)_, и вычислим ее. Придадим $x$ приращение $Delta x$; тогда $u, v$ и $y$ получат, соответственно, приращения $Delta u, Delta v$ и $Delta y$. Их новые значения $u + Delta u, v + Delta v$ и $y + Delta y$ связаны тем же соотношением: $ y + Delta y = (u + Delta u) plus.minus (v + Delta v). $ Отсюда $ Delta y = Delta u plus.minus Delta v, space (Delta y)/(Delta x) = (Delta u)/(Delta x) plus.minus (Delta v)/(Delta x) $ \ и $ lim_(Delta x -> 0) (Delta y)/(Delta x) = lim_(Delta x -> 0) (Delta u)/(Delta x) plus.minus lim_(Delta x -> 0) (Delta v)/(Delta x) = u prime plus.minus v prime, $ \ так что производная $y prime$ существует и равна $ y prime = (u plus.minus v) prime = u prime plus.minus v prime. $ Этот результат легко может быть распространен на любое число слагаемых (и притом – тем же методом). 3. _При тех же предположениях относительно функций_ $u, v$, докажем, что _функция $y = u dot v$ тоже имеет производную_, и найдем её. Приращению $Delta x$ отвучают, как и выше, приращения $Delta u, Delta v$ и $Delta y$; при этом $y + Delta y = (u + Delta u) (v + Delta v)$, так что $ Delta y = Delta u dot v + u dot Delta v + Delta u dot Delta v $ \ и $ (Delta y)/(Delta x) = (Delta u)/(Delta x) dot v + u dot (Delta v)/(Delta x) + (Delta u)/(Delta x) dot Delta v. $ Так как при $Delta x -> 0$, в силу непрерывности производной, и $Delta v -> 0$, то $ lim_(Delta x -> 0) (Delta y)/(Delta x) = lim_(Delta x -> 0) (Delta u)/(Delta x) dot v + u dot lim_(Delta x -> 0) (Delta v)/(Delta x) = u prime dot v + u dot v prime, $ \ т.е. существует производная $y prime$ и равна $ y prime = (u dot v) prime = u prime dot v + u dot v prime. $ Если $ y = u v w$, причём $u prime, v prime, w prime$ существуют, то $ y prime = [(u v) dot w] prime = (u v) prime dot w + (u v) dot w prime = u prime v w + u v prime w + u v w prime. $ Легко сообразить, что для случая $n$ сомножителей будем иметь аналогично: $ [overbrace(u v w ... s, n)] prime = u prime v w...s + u v prime w ... s + ... + u v w ... s prime. space (1) $ Для того, чтобы доказать это, воспользуемся методом математической индукции. Предположим, что формула $(1)$ верна для некоторого числа $n$ сомножителей, и установим ее справедливость для $n + 1$ сомножителей: $ [overbrace(u v w...s t, n + 1)] prime = [(overbrace(u v w...s, n)) dot t] prime = (u v w...s) prime dot t + (u v w...s) dot t prime; $ \ если производную $(u v w...s) prime$ развернуть по формуле $(1)$, то придем к формуле $ [u v w...s t ] prime = u prime v w...s t + u v prime w...s t + u v w...s prime t + u v w...s t prime, $ \ совершенно аналогичной $(1)$. Так как в верности формулы $(1)$ при $n = 2$ и $3$ мы убедились непосредственно, то это формула верна при любом $n$. 4. Наконец, _если $u, v$ удовлетворяют прежним предположениям и, кроме того, $v$ отлично от нуля, то_ мы докажем, что _функция $y = u/v$ также имеет производную_, и найдем её. При тех же обозначениях, что и выше, имеем $ y + Delta y = (u + Delta u)/(v + Delta v), $\ так что $ Delta y = (Delta u dot v - u dot Delta v)/(v dot (v + Delta v)) $\ и $ (Delta y)/(Delta x) = ((Delta u)/(Delta x) dot v - u dot (Delta v)/(Delta x))/(v dot (v + Delta v)). $ Устремляя здесь $Delta x$ к нулю (причем одновременно и $Delta v -> 0$), убеждаемся в существовании производной $ y prime = (u/v) prime = (u prime dot v - u dot v prime)/v^2. $ 31. *Производная композиции функций. Инвариантность формы дифференциала.* *Производная композиции функций*: _Пусть 1) функция $u = phi(x)$ имеет в некоторой точке $x_0$, производную $u_x prime = phi prime (x_0)$, 2) функция $y = f(u)$ имеет в соответствующей точке $u_0 = phi (x_0)$ производную $y_u prime = f prime (u_0)$. Тогда сложная функция (или композиция функций) $y = f(phi(x))$ в упомянутой точке $x_0$ также будет иметь производную, равную произведению производных функций $f(u)$ и $phi(x)$_: $ [f(phi(x))] prime = f_u prime (phi(x_0)) dot phi prime (x_0), $\ _или, короче,_ $ y_x prime = y_u prime dot u_x prime. $ Для доказательства придадим $x_0$ приозвольной приращение $Delta x$; пусть $Delta u$ – соответствующее приращение функции $u = phi(x)$ и, наконец, $Delta y$ – приращение функции $y = f(u)$, вызванное приращением $Delta u$. Воспользуемся соотношением $ Delta y = y_x prime dot Delta x + alpha dot Delta x, $ которое, заменяя $x$ на $u$, перепишем в виде $ Delta y = y_u prime dot Delta u + alpha dot Delta u $\ ($alpha$ зависит от $Delta u$ и вместе с ним стремится к нулю). Разделив его почленно на $Delta x$, получим $ (Delta y)/(Delta x) = y_u prime dot (Delta u)/(Delta x) + alpha dot (Delta u)/(Delta x). $ Если $Delta x$ устремить к нулю, то будет стремиться к нулю и $Delta u$ (в силу непрерывности производной), а тогда, как мы знаем, будет также стремиться к нулю зависящая от $Delta u$ величина $alpha$. Следовательно, существует предел $ lim_(Delta x -> 0) (Delta y)/(Delta x) = y_u prime dot lim_(Delta x -> 0) (Delta u)/(Delta x) = y_u prime dot u_x prime, $\ который и представляет собой искомую производную $y_x prime$. *Замечание.* Здесь сказывается полезность замечания "в силу непрерывности функции" относительно величины $alpha$ при $Delta x = 0$: покуда $Delta x$ есть приращение *независимой переменной*, мы могли предполагать его отличным от нуля, но когда $Delta x$ заменено приращением *функции* $u = phi(x)$, то даже при $Delta x eq.not 0$ мы уже не вправе считать, что $Delta u eq.not 0$. *Инвариантность формы дифференциала*: Пусть функции $y = f(x)$ и $x = phi(t)$ таковы, что из них может быть составлена сложная функция: $y = f(phi(t))$. Если существуют производные $y_x prime$ и $x_t prime$, то – по правилу "производной композиции функции" – существует и производная $ y_t prime = y_x prime dot x_t prime. $ Дифференциал $d y$, если $x$ считать независимой переменной, выразится по формуле $d y = y_x prime d x$. Перейдем теперь к независимой переменной $t$; в этом предположении имеем другое выражение для дифференциала: $ d y = y_t prime d t. $ \ Заменяя, однако, производную $y_t prime$ её выражением и замечая, что $x_t prime dot d t$ есть дифференциал $x$ как функции от $t$, окончательно получим: $ d y = y_x prime dot x_t prime d t = y_x prime d x, $\ т. е. вернемся к *прежней* форме дифференциала! Таким образом, мы видим, что *форма дифференциала* _может быть сохранена даже в том случае, если прежняя независимая переменная заменена новой_. Это свойство и называют *инвариантностью формы дифференциала*. 32. *Производная обратной функции.* *Теорема.* Пусть 1) функция $f(x)$ удовлетворяет условиям теоремы "о существовании обратной функции", 2) в точке $x_0$ имеет *конечную и отличную от нуля* производную $f prime (x_0)$. Тогда для обратной функции $g(y)$ в соответствующей точке $y_0 = f(x_0)$ также существует производная, равная $1/(f prime (x_0))$. *Доказательство.* Придадим значению $y = y_0$ произвольное приращение $Delta y$, тогда соответственное приращение $Delta x$ получит и функция $x = g(y)$. Заметим, что при $Delta y eq.not 0$, ввиду однозначности самой функции $y = f(x)$, и $Delta x eq.not 0$. Имеем $ (Delta x)/(Delta y) = 1/((Delta y)/(Delta x)). $ Если теперь $Delta y -> 0$ по любому закону, то – в силу непрерывности функции $x = g(y)$ – и приращение $Delta x -> 0$. Но тогда знаменатель правой части написанного равенства стремится к пределу $f(x_0) eq.not 0$, следовательно, существует предел для левой части, равный обратной величине $1/(f prime (x_0))$; он и представляет собой производную $g prime (y_0)$. Итак, имеем простую формулу: $x_y prime = 1/(y_x prime)$. 33. *Вычисление табличных производных.* 1. Отметим, прежде всего, очевидные результаты: если $y = c = "const."$, то $Delta y = 0$, каково бы ни было $Delta x$, так что $y prime = 0$; если же $y = x$, то $Delta y = Delta x$ и $y prime = 1$. 2. Пусть теперь $y = x^n$, где $n$ – натуральное число. Придадим $x$ приращение $Delta x$; тогда новое значение $y$ будет $ y + Delta y = (x + Delta x)^n = x^n + n x^(n - 1) dot Delta x + (n(n - 1))/(1 dot 2) x^(n - 2) dot Delta x^2 + ..., $\ так что $ Delta y = n dot x^(n - 1) dot Delta x + (n (n - 1))/(1 dot 2) x^(n - 2) dot Delta x^2 + ..., $\ и $ (Delta y)/(Delta x) = n x^(n - 1) + (n (n - 1))/(1 dot 2) x^(n - 2) dot Delta x+ ... $ Так как при $Delta x -> 0$ все слагаемые, проме первого, стремятся к нулю, то $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = n x^(n - 1). $ 3. Если $y = 1/x$, то $y + Delta y = 1/(x + Delta x)$, так что $ Delta y = 1/(x + Delta x) - 1/x = (-Delta x)/(x(x + Delta x)), $ и $ (Delta y)/(Delta x) = 1/(x (x + Delta x)). $ Отсюда $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = -1/(x^2). $ При этом предполагается, конечно, $x eq.not 0.$ 4. Рассмотрим функцию $y = sqrt(x)$ (при $x > 0$). Имеем: $ y + Delta y = sqrt(x + Delta x), $ $ Delta y = sqrt(x + Delta x) - sqrt(x) = (Delta x)/(sqrt(x + Delta x) + sqrt(x)), $ $ (Delta y)/(Delta x) = 1/(sqrt(x + Delta x) + sqrt(x)); $\ наконец, пользуясь непрерывностью корня, получим $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = 1/(2 sqrt(x)). $ Все эти результаты содержатся как частные случаи в следующем. 5. *Степенная функция*: $y = x^mu$ (где $mu$ – любое вещественное число). Область изменения $x$ зависит от $mu$. имеем (при $x eq.not 0$) $ (Delta y)/(Delta x) = ((x + Delta x)^mu - x^mu)/(Delta x) = x^(mu - 1) dot ((1 + (Delta x)/x)^mu - 1)/((Delta x)/x). $ Если воспользоваться пределом $ lim_(alpha -> 0) ((1 + alpha)^mu - 1)/alpha = mu, $\ то получим $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = mu x^(mu - 1). $ В частности $ "если" space y = 1/x = x^(-1), "то" space y prime = (-1) x^(-2) = - 1/x^2, $ $ "если" space y = sqrt(x) = x^(1/2), "то" space y prime = 1/2 x^(-1/2) = 1/(2 sqrt(x)). $ 6. *Показательная функция*: $y = a^x space (a > 0, -infinity < x < +infinity)$. Здесь $ (Delta y)/(Delta x) = (a^(x + Delta x) - a^x)/(Delta x) = a^x dot (a^(Delta x) - 1)/(Delta x). $ Воспользовавшись пределом $ lim_(alpha -> 0) (a^alpha - 1)/alpha = ln a, $ найдём: $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = a^x dot ln a. $ В частности, $ "если" space y = e^x, "то и" space y prime = e^x. $ 7. *Логарифмическая функция*: $y = log_a x space (0 < a eq.not 1, 0 < x < +infinity)$. В этом случае $ (Delta y)/(Delta x) = (log_a (x + Delta x) - log_a x)/(Delta x) = 1/x dot (log_a (1 + (Delta x)/x))/((Delta x)/x). $. Воспользуемся пределом $ lim_(alpha -> 0) (log_a (1 + alpha))/alpha = log_a e, $ найдём: $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = (log_a e)/x. $. В частности, для *натурального* логарифма получается исключительно простой результат: $ "при" space y = ln x space "имеем" space y prime = 1/x. $ 8. *Тригонометрические функции*: Пусть $y = sin x$, тогда $ (Delta y)/(Delta x) = (sin(x + Delta x) - sin x)/(Delta x) = (sin((Delta x)/2))/((Delta x)/2) dot cos(x + (Delta x)/2). $ Пользуясь непрерывностью функции $cos x$ и известным пределом $lim_(alpha -> 0) (sin alpha)/(alpha) = 1$, получим $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = cos x. $ Аналогично найдём: $ "если" space y = cos x, space "то" space y prime = -sin x. $ В случае $y = tg x$ имеем $ (Delta y)/(Delta x) = (tg(x + Delta x) - tg x)/(Delta x) = (sin(x + Delta x)/cos(x + Delta x) - (sin x)/(cos x))/(Delta x) = $ $ = (sin(x + Delta x) dot cos x - cos(x + Delta x) dot sin x)/(Delta x dot cos x dot cos(x + Delta x)) = $ $ = (sin Delta x)/(Delta x) dot 1/(cos x dot cos(x + Delta x)). $ Отсюда, как и выше, $ y prime = lim_(Delta x -> 0) (Delta y)/(Delta x) = 1/(cos^2 x) = sec^2 x. $ Аналогично, $ "если" space y = ctg x, space "то" space y prime = - 1/(sin^2 x) = -csc^2 x. $ 9. *Обратные тригонометрические функции*. Рассмотрим функцию $y = "arcsin" x space (-1 < x < 1)$, причем $-pi/2 < y < pi/2$. Она является обратной для функции $x = sin y$, имеющей для указанных значений $y$ *положительную* производную $x_y prime = cos y$. В таком случае существует также производная $y_x prime$ и равна, по нашей формуле, $ y_x prime = 1/(x_y prime) = 1/(cos y) = 1/sqrt(1 - sin^2 y) = 1/sqrt(1 - x^2); $ корень мы берем со знаком плюс, так как $cos y > 0$. Мы исключили значения $x = plus.minus 1$, ибо для соответствующих значений $y = plus.minus pi/2$ производная $x_y prime = cos y = 0$. Функция $y = "arctg" x space (-infinity < x < +infinity)$ служит обратной для функции $x = tg y$. По формуле $ y_x prime = 1/(x_y prime) = 1/(sec^2 y) = 1/(1 + tg^2 y) = 1/(1 + x^2). $ Аналогично можно получить: $ "для" space y = "arccos" x space space space y prime = - 1/sqrt(1 - x^2) space (-1 < x < 1), $ $ "для" space y = "arcctg" x space space space y prime = - 1/(1 + x^2) space (-infinity < x < +infinity). $ 34. *Вычисление производных от функций, заданных параметрически и неявно.* *Вычислении производных от функций, заданных параметрически:* Если $x$ и $y$ заданы в функции от параметра $t$: $ x = phi(t), y = psi(t), $\ то при известных условиях этим определяется и $y$ как функция от $x$: $y = f(x)$. при наличии последовательных производных от $x$ и $y$ по $t$ существуют соответствующие производные от $y$ по $x$ и выражаются выведенными выше формулами. Их легко получить из дифференциальных выражений, разделив числитель и знаменатель, соответственно, на $d t, d t^3, d t^5, ...$ Таким путем придем к формулам: $ y_x prime = ((d y)/(d t))/((d x)/(d t)) = (y_t prime)/(x_t prime), y_(x^2) prime.double = ((d x)/(d t) dot (d^2 y)/(d t^2) - (d^2 x)/(d t^2) dot (d y)/(d t))/((d x)/(d t))^3 = (x_t prime y_(t^2) prime.double - x_(t^2) prime.double y_t prime)/(x_t prime)^3; $\ аналогично: $ y_(x^3) prime.triple = (x_t prime (x_t prime y_(t^3) prime.triple - x_(t^3) prime.triple y_t prime) - 3 x_(t^2) prime.double (x_t prime y_(t^2) prime.double - x_(t^2) prime.double y_t prime))/(x_t prime)^5, $ и т.д. *Вычислении производных от функций, заданной неявно:* *Определение.* Если независимая переменная $x$ и функция $y$ связаны уравнение вида $F(x, y) = 0$, которое не разрешено относительно $y$, то функция $y$ называется *неявной функцией переменной* $x$. Пример неявно заданной функции: $x^2 sin y + x y - 1 = 0.$ Несмотря на то, что уравнение $F(x, y) = 0$ не разрешимо относительно $y$ (иначе говоря, никак не выразить $y$), оказывается возможным найти производную от $y$ по $x$. В этом случае необходимо продифференцировать обе части заданного уравнения, рассматривая функцию $y$ как функцию от $x$, а затем из полученного уравнения найти производную $y prime$. Пример: Найти производную $y prime$ неявной функции $x^2 + x y^2 = 1$. $ (x^2 + x y^2) prime = (1) prime $ $ (x^2) prime + (x y^2) prime = 0 $ $ 2x + x prime dot y^2 + x dot (y^2) prime = 0 $ $ 2x + 1 dot y^2 + x dot 2 y^2 dot y prime = 0 => 2x + y^2 + 2 x y dot y prime = 0 $ Из полученного равенства выражаем $y prime$: $ 2 x y dot y prime = -(2x + y^2) => y prime = - (2x + y^2)/(2x y) $ 35. *Производные высших порядков.* Если функция $y = f(x)$ имеет конечную производную $y prime = f prime (x)$ в некотором промежутке $X$, так что эта последняя сама прдеставляет новую функцию от $x$, то может случиться, что эта функция в некоторой точке $x_0$ из $X$, в свою очредь, имеет производную, конечную или нет. Ее называют *производной второго порядка* или *второй производной* функции $y = f(x)$ в упомянутой точке, и обозначают одним из символов $ (d^2 y)/(d x^2), y prime.double, D^2 y; (d^2 f(x_0))/(d x^2), f prime.double (x_0), D^2 f(x_0). $ Вспоминая про физический смысл производной, где через путь можно было найти скорость. Однако, если скорость, по прежнему, зависит от времени, то его производная является ускорением. Другими словами, ускорение является *второй производной* от пути по времени: $a = (d^2 S)/(d t^2)$. Аналогично, если функция $y = f(x)$ имеет конечную вторую производную в целом промежутке $X$, то ее производная, конечная или нет, в какой-либо точке $x_0 in X$ называется производной *третьего порядка*. Подобным же образом от третьей производной переходим к четвертой и т.д. Если предположить, что понятие $(n - 1)$-й производной уже определено и что $(n - 1)$-я производная существует и конечна в промежутке $X$, то ее производная в некоторой точке $x_0$ этого промежутка называется *производной $n$-го порядка* от исходной функции $y = f(x)$; для обозначения ее применяются символы: $ (d^n y)/(d x^n), y^((n)), D^n y; (d^n f(x_0))/(d x^n), f^((n)) (x_0), D^n f(x_0). $ Иной раз – при ипользовании обозначениями Лагранжа или Коши – может возникнуть надобность в указании переменной, по которой берется производная; тогда ее пишут в виде значка внизу: $ y_(x^2) prime.double, D_(x^3)^3 y, f_(x^n)^((n)) (x_0), space "и т. п.", $ причем, $x^2, x^3, ...$ есть условная сокращенная запись вместо $x x, x x x, ...$ Таким образом, определили понятие $n$-ой производной, как говорят, *индуктивно*, переходя по порядку от первой производной к последующим. Соотношение, определяющее $n$-ю производную: $ y^((n)) = [y^(n - 1)] prime, $ называют также рекуррентным (или "возвратным"), поскольку оно "возвращает" нас от $n$-й к $(n - 1)$-й производной. 36. *Формула Лейбница и ее применение.* Предположим, что функции $u, v$ от $x$ имеют каждая в отдельности производные до $n$-го порядка включительно: докажем, что тогда их произведение $y = u v$ также имеет $n$-ю производную, и найдём её выражение. Станем последовательно дифференцировать это произведение; мы найдём: $ y prime = u prime v + u v prime, space y prime.double = u prime.double v + 2 u prime v prime + u v prime.double, $ $ y prime.triple = u prime.triple v + 3 u prime.double v prime + 3 u prime v prime.double + u v prime.triple, ... $ Легко подметить закон, по которому построены все эти формулы: правые части их напоминают разложение степеней бинома: $u + v, (u + v)^2, (u + v)^3, ...$ лишь вместо степеней $u, v$ стоят производные соответствующих порядков. Сходство станет более полным, если в полученных формулах вместо $u, v$ писать $u^((0)), v^((0))$. Распространяя этот закон на случай любого $n$, придем к общей формуле: $ y^((n)) = (u v)^((n)) = sum_(i = 0)^n (C_n)^i u^((n - i)) v^((i)) = $ $ = u^((n)) v + n u^((n - 1)) v prime + (n(n - 1))/(1 dot 2) n^((n - 2)) v prime.double + ... $ $ ... + (n (n - 1)...(n - i + 1))/(1 dot 2 ... i) n^((n - i)) v^((i)) + ... + n v^((n)). $ Установленная формула носит название *формулы Лейбница*. Она часто бывает полезна при выводе общих выражений для $n$-й производной. 37. *Понятие локального экстремума функции. Теоремы Ферма, Ролля и их геометрический смысл.* *Определение 1.* Точка $x_0$ называется *точкой локального максимума* функции $f(x)$, если существует такая окрестность этой точки, что для всех $x$ из этой окрестности выполняется неравенство: $f(x) <= f(x_0)$. *Определение 2.* Точка $x_0$ называется *точкой локального минимума* функции $f(x)$, если существует такая окрестность этой точки, что для всех $x$ из этой окрестности $f(x) >= f(x_0)$. *Замечание.* Точка $x_0$ называется *строго локального максимума (минимума)* функции $y = f(x)$, если для всех $x$ из окрестности $f(x) < f(x_0)$ ($f(x) > f(x_0)$). *Теорема (необходимое условие экстремума).* Если фукнцияд $y = f(x)$ имеет экстремум в точке $x_0$, то ее производная $f prime (x_0)$ либо равна нулю, либо не существует. *Теорема (первое достаточное условие экстремума).* Пусть для функции $y = f(x)$ выполнены следующие условия: 1. функция непрерывна в окрестности точки $x_0$; 2. $f prime (x_0) = 0$ или $f prime (x_0)$ не существует; 3. производная $f prime (x)$ при переходе через точку $x_0$ меняет свой знак. Тогда в точке $x = x_0$ функция $y = f(x)$ имеет экстремум, причем это минимум, если при переходе через точку $x_0$ производная меняет свой знак с минуса на плюс; максимум, если при переходе через точку $x_0$ производная меняет свой знак с плюса на минус. *Теорема (второе достаточное условие экстремума).* Пусть для функции $y = f(x)$ выполнены следующие условия: 1. она непрерывна в окрестности точки $x_0$; 2. первая производная $f prime (x) = 0$ в точке $x_0$; 3. $f prime.double (x) eq.not 0$ в точке $x_0$; Тогда в точке $x_0$ достигается экстремум, причем если $f prime.double (x_0) > 0$, то в тчоке $x = x_0$ функция $y = f(x)$ имеет минимум; если $f prime.double (x_0) < 0$, то в точке $x = x_0$ функция $y = f(x)$ достигает максимум. *<NAME>.* Пусть функция $f(x)$ определена в некотором промежутке $X$ и во внутренней точке с этого промежутка принимает наибольшее (наименьшее) значение. Если существует двусторонняя конечная производная $f prime (c)$ в этой точке, то необходимо $f prime (c) = 0$. *Геометрический смысл.* Теорема означает, что касательная, проведенная к графику функции в точке $(c; f(c))$ параллельно оси $O x$. *<NAME>.* Пусть 1) функция $f(x)$ определена и непрерывна в замкнутом промежутке $[a; b]$; 2) существукет конечная производная $f prime (x)$, по крайней мере, в открытом промежутке $(a, b);$ 3) на концах промежутка функция принимает равные значения: $f(a) = f(b)$. Тогда между $a$ и $b$ найдется такая точка, $c space (a < c < b)$, что $f prime (c) = 0$. *Геометрический смысл.* Теорема означает, что если функция $y = f(x)$ удовлетворяет теореме Ролля, то найдется хотя бы одна точка $(c; f(c))$, где $c space (a < c < b)$, такая, что каcательная к графику функци, проведенная в этой точке, параллельна оси $O x$. 38. *Правило Лопиталя раскрытия неопределннойстей.* *Теорема 1.* Пусть: 1) функции $f(x)$ и $g(x)$ определены в промежутке $[a, b]$, 2) $display(lim_(x -> a)) f(x) = 0, space display(lim_(x -> a)) g(x) = 0$, 3) существуют конечные производные $f prime (a)$ и $g prime (a)$, причем $g prime (a) eq.not 0$. Тогда $ lim_(x -> a) (f(x))/(g(x)) = (f prime (a))/(g prime (a)). $ *Теорема 2.* Пусть: 1) функции $f(x)$ и $g(x)$ определены в промежутке $[a, b]$, 2) $display(lim_(x -> 0)) f(x) = 0, space display(lim_(x -> 0)) g(x) = 0$, 3) в промежутке $[a, b]$ существуют конечные производные всех порядков до $(n - 1)$-го включительно $f prime (x), f prime.double (x), ..., f^((n - 1)) (x), g prime (x), g prime.double (x), ..., g^((n - 1)) (x)$, 4) при $x = a$ они все обращаются в $0$, 5) существуют конечные производные $f^((n)) (a)$ и $g^((n)) (a)$, причем $g^((n)) (a) eq.not 0$. Тогда $ lim_(x -> a) (f(x))/(g(x)) = (f^((n)) (a))/(g^((n)) (a)). $ *Теорема 3.* Пусть: 1) функции $f(x)$ и $g(x)$ определены в промежутке $(a, b]$, 2) $display(lim_(x -> a)) f(x) = 0, display(lim_(x -> a)) g(x) = 0$, 3) в промежутке $(a, b]$ существуют конечные производные $f prime (x)$ и $g prime (x)$ причем $g prime (x) eq.not 0$, и наконец, 4) существует (конечный или нет) предел $ lim_(x -> a) (f prime (x))/(g prime (x)) = K. $ Тогда и $ lim_(x -> a) (f(x))/(g(x)) = K. $ *Теорема 3 (распространение на случай $x -> plus.minus infinity)$.* Пусть: 1) функции $f(x)$ и $g(x)$ определены в промежутке $[c, +infinity]$, где $c > 0$, 2) $display(lim_(x -> +infinity)) f(x) = 0, display(lim_(x -> +infinity)) g(x) = 0$, 3) существуют в промежутке $[c, + infinity]$ конечные производные $f prime (x)$ и $g prime (x)$, причем $g prime (x) eq.not 0$, и, наконец, 4) существует (конечный или нет) предел $ lim_(x -> +infinity) (f prime (x))/(g prime (x)) = K. $ Тогда и $ lim_(x -> +infinity) (f(x))/(g(x)) = K. $ *Теорема 4.* Пусть: 1) функции $f(x)$ и $g(x)$ определены в промежутке $(a; b]$, 2) $display(lim_(x -> a)) f(x) = +infinity, display(lim_(x -> a)) g(x) = +infinity$, 3) существуют в промежутке $(a, b]$ конечные производные $f prime (x)$ и $g prime (x)$, причем $g prime (x) eq.not 0$, и, наконец, 4) существует (конечный или нет) предел $ lim_(x -> a) (f prime (x))/(g prime (x)) = K. $ Тогда и $ lim_(x -> a) (f(x))/(g(x)) = K. $ 39. *Т<NAME>, Коши.* *<NAME>.* Пусть 1) $f(x)$ определена и непрерывна в замкнутом промежутке $[a, b]$, 2) существует конечная ироизводная $f prime (x)$, по крайней мере, в открытом промежутке $(a, b)$. Тогда между $a$ и $b$ найдется такая точка $c space (a < c < b)$, что для нее выполняется равенство $ (f(b) - f(a))/(b - a) = f prime (c). $ *Т<NAME>.* Пусть 1) функции $f(x)$ и $g(x)$ непрерывны замкнутом промежутке $[a, b]$; 2) существуют конечные производные $f prime (x)$ и $g prime (x)$, по крайней мере, в открытом промежутке $(a, b)$; 3) $g prime (x) eq.not 0$ в промежутке $(a, b)$. Тогда *между* $a$ и $b$ найдется такая точка $c space (a < c < b)$, что $ (f(b) - f(a))/(g(b) - g(a)) = (f prime (c))/(g prime (c)). $ 40. *Формула Тейлора. Предстваления остаточного члена в различных формах.* *Определение.* Многочленом Тейлора степени $n$ функции $f(x)$ в точке $c$ называются многочлен вида $ P_n (x) = f(c) + 1/(1!) f prime (c) (x - c) + 1/(2!) f prime.double (c) (x - c)^2 + ... + 1/(n!) f^((n)) (c) (x - c)^n. $ *Свойство многочлена Тейлора.* В точке $c$ совпадают значения функции и её многочлена Тейлора, а также значения их первых $n$ производных, т.е. $P_n (c) = f(c), P_n prime (c) = f prime (c), ..., (P_n)^((n)) (c) = f^((n)) (c).$ *Теорема (формула Тейлора).* Пусть функция $f(x)$ определена на интервале $(a, b)$ и имеет в точке $c in (a, b)$ производные до порядка $n$ включительно. Тогда $forall x in (a, b)$ справедлива формула Тейлора $n$-го порядка $ f(x) = f(c) + 1/(1!) f prime (c) (x - c) + 1/(2!) f prime.double (c) (x - c)^2 + ... + 1/(n!) f^((n)) (c) (x - c)^n + r_n, $ где $r_n$ – остаточный член формулы Тейлора. *Формы записи остаточного члена*: + форма Пеано: $r_n = o((x - c)^n), x -> c$ + форма Лагранжа: $r_n = 1/((n + 1)!) f^((n - 1)) (c + theta(x - c))(x - c)^(n + 1), 0 < theta < 1$ Формулу Тейлора можно переписать в виде: $f(x) = P_n (x) + r_n$. Отбросив остаточный член, получим $f(x) ≈ P_n (x)$. 41. *Разложение функций $e^x$, $sin x$, $cos x$, $(1 + x)^alpha$, $1/(1 + x)$, $ln(1 + x)$ по формуле Тейлора в окрестности точки $x = 0$.* Разложение $e^x$: $ f(0) = 1 $ $ f^((m)) (x) = e^x $ $ f^((m)) (0) = 1 $ $ => e^x = 1 + x + (x^2)/(2!) + (x^3)/(3!) + ... + (x^n)/(n!) + o(x^n), x -> 0. $ Разложение $sin x$: $ f(0) = 0 $ $ f prime (x) = cos x, space f prime (0) = 1 $ $ f prime.double (x) = -sin x, space f prime.double (0) = 0 $ $ f prime.triple (x) = -cos x, space f prime.triple (0) = -1 $ $ f^(italic("IV")) (x) = sin x, space f^(italic("IV")) (0) = 0 $ $ f^(V) (x) = cos x, space f^(V) (0) = 1 $ $ => f^((m)) (0) = cases(0 "если" m = 2 n, (-1)^n "если" m = 2n + 1) space n = 0,1,2... $ Тогда по формуле Тейлора в окрестности точки $x = 0$ имеем: $ sin x = 0 + 1/(1!) dot 1 dot x + 1/(2!) dot 0 dot x^2 + 1/(3!) dot (-1) dot x^3 + 1/(4!) dot 0 dot x^4 + $ $ + 1/(5!) dot 1 dot x^5 + ... + 1/((2n)!) dot 0 dot x^(2n) + 1/((2n + 1)!) dot (-1)^n dot x^(2n + 1) + $ $ + 1/((2n + 2)!) dot 0 dot x^(2n + 2) + o(x^(2n + 2)) = $ $ = x - (x^3)/(3!) + (x^5)/(5!) - (x^7)/(7!) + ... + (-1)^n (x^(2n + 1))/((2n + 1)!) + o(x^(2n + 2)) = $ $ sum_(k = 0)^n (-1)^k (x^(2k + 1))/((2k + 1)!) + o(x^(2n + 2)), x -> 0. $ Разложение $cos x$: $ f(0) = 1 $ $ f prime (x) = -sin x, space f prime (0) = 0 $ $ f prime.double (x) = -cos x, space f prime.double (0) = -1 $ $ f prime.triple (x) = sin x, space f prime.triple (0) = 0 $ $ f^(italic("IV")) (x) = cos x, space f^(italic("IV")) (0) = 1 $ $ f^(V) (x) = -sin x, space f^(V) (0) = 0 $ $ => f^((m)) (0) = cases(0 "если" m = 2 n + 1, (-1)^n "если" m = 2n) space n = 0,1,2... $ Тогда по формуле Тейлора в окрестности точки $x = 0$ имеем: $ cos x = 1 - (x^2)/(2!) + (x^4)/(4!) - (x^6)/(6!) + ... + (-1)^n (x^(2n))/(2n!) + o(x^(2n + 1)) = $ $ = sum_(k = 0)^n (-1)^k (x^(2k))/(2k!) + o(x^(2n + 1)), x -> 0. $ Разложение $(1 + x)^alpha$: $ f(0) = 1 $ $ f^((m)) (x) = alpha(alpha - 1)...(alpha - m + 1)(1 + x)^(alpha - m) $ $ f^((m)) (0) = alpha(alpha - 1)...(alpha - m + 1) $ $ => (1 + x)^alpha = 1 + alpha x + (alpha(alpha - 1))/(2!) x^2 + (alpha(alpha - 1)(alpha - 2))/(3!) + ... + $ $ + (alpha(alpha - 1)...(alpha - n + 1))/(n!) x^n + o(x^n) = $ $ 1 + sum_(k = 1)^n (alpha(alpha - 1)...(alpha - k + 1))/(k!) x^n + o(x^n), x -> 0. $ Разложение $1/(1 + x)$: $ f(0) = 1 $ $ f^((m)) (x) = (-1)^m (m!)/(1 - x)^(m + 1) $ $ f^((m)) (0) = (-1)^m m! $ $ => 1/(1 + x) = 1 - x + x^2 + ... + (-1)^n x^n + o(x^n), x -> 0. $ Разложение $ln(1 + x)$: $ f(0) = 0 $ $ f^((m)) (x) = (-1)^(m - 1) ((m - 1)!)/(1 + x)^m $ $ f^((m)) (0) = (-1)^(m - 1) (m - 1)! $ $ => ln(1 + x) = x - (x^2)/2 + ... + (-1)^(n - 1) (x^n)/n + o(x^n), x -> 0. $ 42. *Условия монотонности функции.* *Теорема 1.* Пусть функция $f(x)$ определена и непрерывна в промежутке $X$ и *внутри* него имеет конечную производную $f prime (x)$. Для того чтобы $f(x)$ была в $X$ монотонно возрастающей (убывающей) в широком смысле, необходимо и достаточно условие $ f prime (x) >= 0 space space space (<= 0 "внутри" X). $ *Теорема 2.* При сохранении тех же предопложений относительно непрерывности функции $f(x)$ и существования ее производной $f prime (x)$, для того чтобы $f(x)$ была монотонно возрастающей (убывающей) в строгом смысле, необходимы и достаточны условия: 1) $f prime (x) >= 0 space (<= 0)$ для $x$ внутри $X$. 2) $f prime (x)$ не обращается тождественно в $0$ ни в каком промежутке, составляющем часть $X$. 43. *Достаточные условия монотонности функции.* *Первое правило.* Предположим, что в некоторой окрестности $(x_0 - delta, x_0 + delta)$ точки $x_0$ (по крайней мере, для $x eq.not x_0$) существует конечная производная $f prime (x)$ и как слева от $x_0$, так и справа от $x_0$ (в отдельности ) *сохраняет определенный знак*. Подставляя в производную $f prime (x)$ сначала $x < x_0$, а затем $x > x_0$, устанавливаем знак производной вблизи от точки $x_0$ слева и справа от неё; если при этом производная $f prime (x)$ меняет знак плюс на минус, то налицо максимум, если меняет знак минус на плюс, то – минимум; если же знака не меняет, то экстремума вовсе нет. *Второе правило.* Пусть функция $f(x)$ не только имеет производную $f prime (x)$ в окрестности точки $x_0$, но и вторую производную в самой точке $x_0$: $f prime.double (x_0)$. Подставляем $x_0$ во вторую производную $f prime.double (x)$; если $f prime.double (x_0) > 0$, то функция имеет минимум, если же $f prime.double (x_0) < 0$, то – максимум. *Дополнение ко второму правилу (высшие производные).* Если первая из производных, не обращающихся в точке $x_0$ в нуль, есть производная нечетного порядка, функция не имеет в точках $x_0$ ни максимума, ни минимума. Если такой производной является производная четного порядка, функция в точке $x_0$ имеет максимум или минимум, смотря по тому, будет ли эта производная отрицательна или положительна. 44. *Выпуклость функции. Условия выпуклости.* *Определение.* Функция $f(x)$, определенная и *непрерывная* в промежутке $X$, называется *выпуклой* (выпуклой *вниз*), если для любых точек $x_1$ и $x_2$ из $X$ ($x_1 gt.lt x_2$) выполняется неравенство $ f(q_1 x_1 + q_2 x_2) <= q_1 dot f(x_1) + q_2 dot f(x_2), space space space (1) $ каковы бы ни были положительные числа $q_1$ и $q_2$, в сумме дающие единицу. Функция называется *вогнутой* (выпуклой *вверх*), если – вместо $(1)$ – имеем $ f(q_1 x_1 + q_2 x_2) >= q_1 dot f(x_1) + q_2 dot f(x_2). $ *Простейшие предложения о выпуклых функциях*: 1. Произведение выпуклой функции на положительную постоянную есть выпуклая функция. 2. Сумма двух или нескольких выпуклых функций тоже выпукла. Замечание. Произведение двух выпуклых функций может не оказаться выпуклой функцией. 3. Если $phi(u)$ есть выпуклая и притом возрастающая функция, а $u = f(x)$ также выпукла, то и сложная функция $phi(f(x))$ будет выпуклой. 4. Если $y = f(x)$ и $x = g(y)$ суть однозначные взаимно обратные функции (в соответствующих промежутказ), то одновременно #show table: t => [ #set align(center) #text(t) ] #table( columns: (auto, auto), align: center, [f(x)], [f(x)], [ выпукла, возрастает выпукла, убывает вогнута, убывает ], [ вогнута, возрастает выпукла, убывает вогнута, убывает ] ) 5. Выпуклая в промежутке $X$ функция $f(x)$, отличная от постоянной, не может достигать *наибольшего* значения *внутри* этого промежутка. 6. Если промежуток $[x_1, x_2]$, где $x_1 < x_2$, содержится в промежутке $X$, в котором функция $f(x)$ выпукла, то соотношение $(1)$ выполняется либо *всегда* со знаком равенства, либо *всегда* со знаком неравенства. Если для *любого* промежутка $[x_1, x_2]$, $x_1 < x_2$, содержащегося в $X$, соотношение $(1)$ выполняется со знаком неравенства, будем функцию $f(x)$ называть *строго выпуклой*. Аналогично устанавливается понятие *строго вогнутой* функции. *Теорема 1.* Пусть функция $f(x)$ определена и непрерывна в промежутке $X$ и имеет в нем конечную производную $f prime (x)$. Для того, чтобы $f(x)$ была выпуклой в $X$, необходимо и достаточно, чтобы ее производная $f prime (x)$ возрастала (в широком смысле). *Теорема 2.* Пусть функция $f(x)$ определена и непрерывная вместе со своей производной $f prime (x)$ в промежутке $X$ и имеет *внутри* него конечную вторую производную $f prime.double (x)$. Для выпуклости функции $f(x)$ в $X$ необходимо и достаточно, чтобы *внутри* $X$ было $ f prime.double (x) >= 0. $ Для вогнутости функции аналогично получается условие $ f prime.double (x) <= 0. $ Таким образом, требование $ f prime.double (x) > 0 space space (< 0) $ заведомо обеспечивает *строгую* выпуклость (вогнутость), ибо исключает возможность для функции $f(x)$ быть линейной в каком бы то ни было промежутке. *Теорема 3.* Пусть функция $f(x)$ определена и непрерывна в промежутке $X$ и имеет в нем конечную производную $f prime (x)$. Для выпуклости функции $f(x)$ необходимо и достаточно, чтобы ее график всеми точками лежал *над* любой своей касательной (или на ней). 45. *Точки перегиба. Условия перегиба.* *Определение.* Точку $M(x_0, f(x_0))$ кривой называет ее *точкой перегиба*, если она отделяет участок кривой, где функция $f(x)$ выпукла (выпукла вниз), от участка, где эта функция вогнута (выпукла вверх). *Условия перегиба*: (Первое достаточное условие) Пусть в некоторых окрестностях $[x_0 - delta, x_0)$ и $(x_0, x_0 + delta]$ слева и справа от $x_0$ производная $f prime.double (x)$ *сохраняет определенный знак*. Тогда для распознавания точки прегиба можно дать такое *правило*: если при переходе через значение $x = x_0$ производная $f prime.double (x)$ меняет знак, то налицо перегиб, если же знака не меняет, то перегиба нет. (Второе достаточное условие) Если первая из производных (выше второго порядка), не обращающихся в точке $x_0$ в нуль, есть производная нечетного порядка, то налицо перегиб; если же такой производной является производная четного порядка, то перегиба нет. 46. *Асимптоты графика функции.* Пусть имеем кривую, ветвь которой в том или ином направлении удаляется в бесконечность. Если расстояние $delta$ от точки кривой до некоторой определенной прямой по мере удаления точки в бесконечность стремится к нулю, то эта прямая называется *асимптотой* кривой. Существуют 3 вида асимптот: - вертикальная; - горизонтальна; - наклонная. Вертикальная асимптота графика, как правило, находится *в точке бесконечного разрыва* функции. Другими слвоами, если в точке $x = alpha$ функция $y = f(x)$ терпит бесконечный разрыв, то прямая, заданная уравнением $x = alpha$ является вертикальной асимптотой графика. *Замечание.* Чтобы установить наличие вертикальной асимптоты $x = alpha$ в точке $x = alpha$ достаточно показать, что *хотя бы один* из односторонних пределов $display(lim_(x -> alpha - 0)) f(x), display(lim_(x -> alpha + 0)) f(x)$ бесконечен. Из вышесказанного следует факт: _если функция непрерывна на $RR$, то вертикальные асимптоты отсутствют_. *Наклонные асимптоты*: Наклонные (как частный случай – горизонтальные) асимптоты могут проявляться, если аргумент функции $f(x)$ стремится к $+infinity$ или к $-infinity$. Таким образом, *график функции не может иметь больше двух наклонных асимптот*. _Общее правило нахождения наклонных асимптот_: Если существуют два _конечных_ предела $display(lim_(x -> plus.minus infinity)) (f(x))/x = k, display(lim_(x -> plus.minus infinity)) (f(x) - k x) = b$, то прямая $y = k x + b$ является наклонной асимптотой графика функции $y = f(x)$ при $x -> plus.minus infinity$. Если *хотя бы один* из перечисленных пределов бесконечен, то наклонная асимптота отсутствует. *Замечание.* Формулы остаются справедливыми, если "икс" стремится только к "плюс бесконечности" или только к "минус бесконечности". Для нахождения горизонтальной асимптоты можно пользоваться упрощенной формулой: если существует _конечный_ предел $display(lim_(x -> plus.minus infinity)) f(x) = b$, то прямая $y = b$ является горизонтальной асимптотой графика функции $y = f(x)$ при $x -> plus.minus infinity$.
https://github.com/Raunak12775/aloecius-aip
https://raw.githubusercontent.com/Raunak12775/aloecius-aip/main/README.md
markdown
# aloecius-aip This is a typst template for reproducing papers of American Institute of Physics (AIP) publishing house, mainly draft version of Journal of Chemical Physics. This is inspired by the overleaf $\LaTeX$ template of AIP journals. ## Usage You can use this template with typst web app by simply clicking on "Start from template" on the dashboard and searching for `aloecius-aip`. For local usage, you can use the typst CLI by invoking the following command ``` typst init @preview/aloecius-aip ``` typst will automatically create a new directory with all the necessary files needed to compile the project. ## Configuration The preamble or the header of the document should be written in the following way with your own necessary input variables to recreate the same formatting as seen in the [`sample.pdf`](sample.pdf) ``` #import "@preview/aloecius-aip:0.0.1": * #show: article.with( title: "Typst Template for Journal of Chemical Physics (Draft)", authors: ( "Author 1": author-meta( "GU", email: "<EMAIL>", ), "Author 2": author-meta( "GU", cofirst: false ), "Author 3": author-meta( "UG" ) ), affiliations: ( "UG": "University of Global Sciences", "GU": "Institute for Chemistry, Global University of Sciences" ), abstract: [ Here goes the abstract. ], bib: bibliography("./reference.bib") ) ``` ## Important Variables - `title` : Title of the paper - `authors` : A dictionary connecting the key as name of the author(s) and the value to be the affiliation of them including university, email, mail address, authorship and an alias, an example usage is shown below ``` Example: ( "Author Name": ( "affiliation": "affiliation-label", "email": "<EMAIL>", // Optional "address": "Mail address", // Optional "name": "<NAME>", // Optional "cofirst": false // Optional, identify whether this author is the co-first author ) ) ``` - `affiliations` : Dictionary of affiliations where keys are affiliations labels and values are affiliations addresses, and example usage is as follows ``` Example: ( "affiliation-label": "Institution Name, University Name, Road, Post Code, Country" ) ``` - `abstract` : Abstract of the paper - `bib` : passing the bibliography file wrapped into the typst `bibliography()` function, both `Hayagriva` and `.bib` format is supported.
https://github.com/lucannez64/Notes
https://raw.githubusercontent.com/lucannez64/Notes/master/Lecture%203%20Special%20Relativity%20(2).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: "Lecture 3 Special Relativity (2)", authors: ( "<NAME>", ), date: "30 Octobre, 2023", ) #set heading(numbering: "1.1.") = Invariance of the Laws of Nature <invariance-of-the-laws-of-nature> Laws take the same form in every reference frame. Definition of a straight line for example is the "shortest distance between two points" does not reference a coordinate system. Apply the Pythagorean Theorem at the infinitesimal level. $ d s eq sqrt(d x^2 plus d y^2) $ The distance between two points is $ s eq integral d s eq integral d x sqrt(1 plus lr((frac(d y, d x)))^2) $ find the curve that minimizes the distance $s$. Find quantities which are invariant under coordinate transformations The vector $lr((d x comma d y))$ for example is not invariant under a rotation, but $d s^2$ is invariant. For example, a vector (tensor) rotation (transformation): $ & A_s eq A_x cos theta minus A_y sin theta\ & A_y eq A_x sin theta plus A_y cos theta $ Compare to a Lorentz transformation: $ & x^prime eq x cosh omega minus T sinh omega\ & T^prime eq minus x sinh omega plus T cosh omega\ & y^prime eq y\ & z^prime eq z $ The invariant combination is $ d tau^2 eq T^2 minus x^2 minus y^2 minus z^2 $ Time $T$ does not change under a spatial rotation. All 4-vectors transform as indicated under a Lorentz transformation. How to construct quantities which are scalar invariants with respect to a Lorentz transformation? Consider the contravariant 4-vector $ d x^mu eq lr((d T comma d x comma d y comma d z)) $ Construct the covariant vector by reversing the sign of the time coordinate. $ d x_mu eq lr((minus d T comma d x comma d y comma d z)) $ Note that the product between these two vectors is invariant. Use the summation convention. $ d tau^2 eq d x^4 d x_mu eq minus d T^2 plus d x^2 plus d y^2 plus d z^2 $ In general, given the contravariant vector $A^mu$ and the covariant vector $zws^(B_mu)$, then $zws^(A^mu B_mu)$ is invariant by construction under the Lorentz Transformation. $ A^mu B_mu eq minus A_T B_T plus A_x B_x plus A_y B_y plus A_z B_z $ The inertial reference frame implies Cartesian coordinates and that Newton’s Laws are satisfied. === Transformation rule <transformation-rule> If $A^mu$ is a 4-vector and $zws^(B_mu)$ has unknown transformation properties, then if $zws^(A^mu B_mu)$ is a scalar then $zws^(B_mu)$ is a 4-vector. == Field Theory <field-theory> Fields in nature: \* Higgs field is a scalar. \* 4-vector electromagnetic field is a 4-vector. \* Energy and momentum are parts of a 4-vector. \* Temperature field in a room is a scalar field. Lagrangians must be scalars. The partial derivative of a scalar is a covariant 4 -vector. $ frac(diff phi.alt, diff x^(2 x)) eq phi.alt $ The quantity $d x^mu$ is a contravariant vector, so then $ frac(diff phi.alt, diff x^alpha) d x^alpha $ should be a scalar. Identify this expression as the total derivative. $ frac(diff phi.alt, diff x^mu) d x^mu eq d phi.alt $ The right hand side is scalar, therefore the left hand side is a scalar, therefore $ frac(diff phi.alt, diff x^x) $ is a covariant 4 -vector. Invent $phi.alt^mu$ by changing the sign of the time component. $ & phi.alt_(mu mu) eq lr((frac(diff phi.alt, diff t) comma frac(diff phi.alt, diff x) comma frac(diff phi.alt, diff y) comma frac(diff phi.alt, diff z)))\ & phi.alt_(mu mu) eq lr((minus frac(diff phi.alt, diff t) comma frac(diff phi.alt, diff x) comma frac(diff phi.alt, diff y) comma frac(diff phi.alt, diff z))) $ then $phi.alt_(mu mu) phi.alt^mu$ is a scalar. $ phi.alt_(mu mu) phi.alt^mu lr((minus lr((frac(diff phi.alt, diff t)))^2 comma lr((frac(diff phi.alt, diff x)))^2 comma lr((frac(diff phi.alt, diff y)))^2 comma lr((frac(diff phi.alt, diff z)))^2)) $ === The four-dimensional Lagrangian <the-four-dimensional-lagrangian> Generalize the action from $ upright(" Action ") eq integral d t cal(L) $ to a four-dimensional integration. $ upright(" Action ") eq integral d x d t L quad upright(" Integrate over spacetime. ") $ Return to the vibrating string problem. $ L eq phi.alt^2 / 2 minus frac(c^2 lr((diff_x phi.alt))^2, 2) $ The Lagrangian $L$ is a scalar which implies Lorentz invariant equations of motion. $ upright(" Action ") eq integral d x^4 lr([phi.alt_i^2 minus phi.alt_x^2 minus phi.alt_y^2 minus phi.alt_z^2]) $ or $ upright(" Action ") eq integral d x^4 lr([phi.alt^mu phi.alt_(j mu)]) $ Minimize the action. Start with minimizing a little region… to be continued.
https://github.com/fenjalien/metro
https://raw.githubusercontent.com/fenjalien/metro/main/tests/angle/angle-symbol/test.typ
typst
Apache License 2.0
#import "/src/lib.typ": * #set page(width: auto, height: auto, margin: 1cm) #ang(6, 7, 6.5) #metro-setup( angle-symbol-degree: math.upright("d"), angle-symbol-minute: math.upright("m"), angle-symbol-second: math.upright("s"), ) #ang(6, 7, 6.5)
https://github.com/daniel-eder/typst-template-jku
https://raw.githubusercontent.com/daniel-eder/typst-template-jku/main/README.md
markdown
<!-- SPDX-FileCopyrightText: 2023 <NAME> SPDX-License-Identifier: CC0-1.0 --> # Typst Template: JKU Dissertation A typst template conforming with the [requirements of the Johannes Kepler University Linz for a dissertation](https://www.jku.at/studium/studierende/abschlussarbeiten/dissertation/). The template is based on https://github.com/zagoli/simple-typst-thesis. ## Usage Notes Presuming that you are familiar with typst and have an environment set up all you need to do to use this template is: 1. download it (or better: create a repository based on this template) 2. leave `./src/template` and the files in it unmodified, unless you want to change how the template works 3. add your content to `./src/main.typ` (optionally, of course, including other files in `./src/main.typ`) 4. add your literary sources to `./src/literature.bib` (e.g. by exporting from Zotero) ### Choosing a citation style The template comes with OSCOLA citation style pre-set. To change this: 1. download the desired citation style in CSL format, e.g. from https://github.com/citation-style-language/styles/ 2. place the file in `./src/<my-style>.csl` (of course, replace `<my-style>` with the name of the file you downloaded) 3. open `./src/main.typ` 4. navigate to the bottom and finde `#bibliography("literature.bib", style: "./oscola-no-ibid.csl", title: [Bibliography])` 5. change the style parameter to `style: "./<my-style>.csl"` (of course, replace `<my-style>` with the name of the file you downloaded) ### Style changes Most style changes for can be made by editing `./src/template/styles/default.typ`. The other files in the `./src/template/styles` folder may also be of interest. `./src/template/styles/content.typ` allows to make style changes that only affect content pages but not the pages up to the table of contents. #### New page for level 1 headings (chapters) By default each chapter starts on a new page. To change this 1. open `./src/template/styles/default.typ` 2. find `show heading.where(level: 1): it => [` 3. and in that block remove (or comment out) `#pagebreak(weak: true)` #### Large vertical space before level 1 headings (chapters) By default each chapter heading has a large vertical space before it. To change this 1. open `./src/template/styles/default.typ` 2. find ` show heading.where(level: 1): it => [` 3. and in that block find the first `#v(<x.y>cm)` 4. And set it to a lower value, e.g. `#v(0.5cm)` ## License This project follows the REUSE standard for software licensing. Each file contains copyright and license information, and license texts can be found in the ./LICENSES folder. For more information visit https://reuse.software/. The main template files are licensed under the [Apache-2.0 license](./LICENSES/Apache-2.0).
https://github.com/jamesrswift/springer-spaniel
https://raw.githubusercontent.com/jamesrswift/springer-spaniel/main/tests/drafting/test.typ
typst
The Unlicense
#import "/tests/preamble.typ": * #import springer-spaniel.drafting: * #show: springer-spaniel.template( title: [Towards Swifter Interstellar Mail Delivery] + margin-note(text(size:9pt, weight: 450,[We need a better title than this])), authors: ( ( name: [<NAME>] + margin-note(side: left)[Do we like this person?], institute: "Primary Logistics Departmen", address: "Delivery Institute, Berlin, Germany", email: "<EMAIL>" ), ( name: "<NAME>", institute: "Communications Group", address: "Space Institute, Florence, Italy", email: "<EMAIL>" ), ( name: "<NAME>", institute: "Missing Letters Task Force", address: "Mail Institute, Budapest, Hungary", email: "<EMAIL>" ) ), abstract: lorem(75) + inline-note(par-break: false)[I'm not so sure about this], )