repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/0x1B05/english | https://raw.githubusercontent.com/0x1B05/english/main/kaoyan/content/words.typ | typst | #import "../template.typ": *
#pagebreak()
= Words
== 2005
=== 完形
==== vocabulary
- dilute: 稀释
- disolve: 溶解
- disperse: 散开
- diffuse:(气味)扩散
- whereas: 而
- repel: 推开
- neglect: 忽视
=== text1
==== vocabulary
- slack: 松懈
- grievance: 不满
- token: 金属代币
- adjoining chamber: 相邻的房间
- induce: 招致
- righteous: morally right or justifiable
- indignation: 愤怒
- temperament: 性情
==== phrases
- be subjected to: 遭受
- be drawn to: 被吸引
- opening paragraph: 开头段
#tip("Tip")[
- posing a contrast: 差异
- making a comparation: 异同
]
==== sentences
=== text2
==== vocabulary
- inconclusive: 不确凿的
- buy: 相信
- panel: 专家团
- enlist: 谋求帮助;引起(attract)
- fume: cn. 烟
- prudent: 谨慎明智的
- steward: 管家
- fashion: 形成
- power plant: 发电厂
- argument: 争论;论点
- hinder: 阻碍
==== phrases
- be out to: 为了
- stay out of the way: 置身事外
==== sentences
=== text3
==== vocabulary
- formulate: 制定
- disguise: 掩饰
- byproduct: 副产品
- themostat: 恒温器
- limbic: 边缘的
- profontal cortex: 前额叶皮质
- recur: 重现
- course: 过程
- terrorism: 恐怖主义
- therapist: 临床
- aggravate: 加重
==== phrases
- work through: 克服
- at the end of the day: 说到底
==== sentences
=== text4
==== vocabulary
- aspire: 立志做
- degradation: 退化
- triumph: 胜利
- counter-culture: 反文化
- permissive: 放任的
- case: (语法的)格
- cult: 狂热;宗教
- authentic: 可靠的
- spell: 招致
- elevated: 提高的
- well regarded: 广受好评的
- capture: 充分体现
- performative: 表述行为的
- liveliness: 生动
- spontaneity: 自发性
- unmistakable: 无可置疑的
- elaborate: 详尽说明
- memory: 记忆力
==== sentences
=== 七选五
==== vocabulary
- premier: 首相
- groan: 抱怨
- soar: 猛增
- budget: 预算
- pharmaceutical: 制药的
- pool: 共享
- coordinating: 使协作
- string: 条件,限制
- assemble: 集合
- jurisiction: 司法权
- provincialist: 地方主义者
- skyrocket: 急升
- stark: 明显的;严酷的
- interest: 利益
==== phrases
- fork over: 额外支付
- get crack about: 积极主动做
- play off against: 挑拨离间
==== sentences
== 2006
=== 完形
==== vocabulary
- estimate: (noun)估算数字
- disorder: 疾病
- likewise: 同样的
- retain: 保持
- lodge: 寄宿处
- dwell: 住处
- comprehensive: 综合的,全面的
- complementary: 互补的
==== phrases
- make up: 构成
- turn around: 扭转局势
=== text1
==== vocabulary
- homogenize: 同化
- democratize: 大众化
- uniformity: 一致性
- discourse: 正式的言论、讨论或对话
- casualness: 随意
- deference: 尊重,顺从
- elevate: 提升
- unprecedented: 空前的
- indice: 指标
- home ownership: 住房自有
- intermarriage: 不同种族、民族、宗教或社会群体之间的婚姻
- bilingual: 双语的
- proficient: 精通
- graveyard: 墓地
- foreign-born: 境外移民
- divisive: 引起分裂的
- seething: 翻滚
- turbulent: 动荡的
- assimilate: 同化
- monopolize: 垄断
- constitute: 构成
- fruitless: 毫无成果的
==== phrases
- prior to: 在...之前
==== sentences
=== text2
==== vocabulary
- hostile: 敌对
- beard: 小胡子
- sandal: 凉鞋
- share: 一份(his share of noise-making)
- contend: 坚称
- subsidy: 补贴
- wing: 侧厅
- cocktail lounge: 雅间
- clientele: 顾客
- pointed: 尖锐的
- box office: 票房/售票处
- imitate: 模仿
==== phrases
- live off: 以...为生
- in a row: 连续的
- on good terms: 友好关系
- take a detached attitude: 客观中立的态度
==== sentences
=== text3
==== vocabulary
- easy game: 没挑战性的
- biomass: 生物量
- fishery: 渔场
- sonar: 声呐
- longlines: 长线钓
- saturate: 使充满
- bait: 置(饵)于...上
- crop: 收成
==== sentences
=== text4
==== vocabulary
- phony: 假冒的
- daffodil: 水仙
- perpetual: 连年
- massacre: 大规模屠杀
- ideology: 意识形态
- bummer: 令人失望的事
- agenda: 目的
- lure: 诱使
- idea: 概念
- command: 鼓动
- arthritis: 关节炎
==== phrases
- from ... onward: 从...起
- live with sth: 忍受
- emerge in the wake of ...: 随着...的出现
==== sentences
=== 七选五
==== vocabulary
- casino: 赌场
- dock: 码头/进港
- sue: 控告
- patronage: 光顾
- patronize: 光顾
- voluntary: 自觉的;自愿的
- involuntary: 不自觉的
- suit: 诉讼
- pathological: 病态的
- windfall: 意外之财
- failing: 缺点
- wager: 赌博
- pornograghy: 色情
- pepper: 小物品打击
- compulsive: 难控制的
- stern: 严厉的
- ground: 依据
==== phrases
- akin to: 相似
- get back to even: 回本
==== sentences
== 2007
=== 完形
==== vocabulary
- regime: 政体
- colonialism: 殖民主义
- sovereign: 有主权的
- egalitarian: 平等主义的
- liberate: 解放
- temper: 使缓和
- the mass of population: 大众
- inhabitant: 居民
- attained: 获得,达到
- presumably: 大概
- incidental: 附带的
- incidentally: 顺便一提
- common: 共有的
- preach: 宣扬
- rallying cry: 激励性的口号
- plea: 请愿
- pessimistic: 悲观的
=== text1
==== vocabulary
- tournament: 锦标赛
- quirk: 怪现象
- rank: 成员
- pronounced: 显著的
- confer: 赋予
- stamina: 耐力
- conceive: 设想;怀孕
- inborn: 与生俱来的
- exhibit: 表现
- swamp: 淹没
- entail: 使必须做
- nurture: 培养
==== phrases
- couple with: 加上
- be more of ... than ...: 与其说...,不如说...
==== sentences
- _One reaps what one sows._
=== text2
==== vocabulary
- feature: 以...为特色
- analogy: 类比
- envision: 想象
- deduce: 推断
- field: 处理
- suit: 使有资格
- elude: 难倒
- encompass: 包含
- populate: 居住于,在...占有位置
- chronological: 生理年龄
- testify: 证明
- test-taking skill: 应试技巧
- indicator: 指标
- impartial: 公正的
==== phrases
- toil through: 艰难跋涉
==== sentences
=== text3
==== vocabulary
- a pink slip: 小粉条(引申解雇通知)
- stripe: 类别
- parachute: 保护伞
- weather: 经受住
- fluctuation: 震荡
- outlive: 持续存在
- bear -> borne
- deductible: 免赔额
- dose: 增加
- demographic: 人口统计数据
- odd(s): 可能性
- attendant: 随之而来的
- eightfold: 八倍的
- wholesale: 批发
- fallout: 后果,余波
- deprive: 剥夺
- popularize: 普及
- outweigh: 超过
- cliff: 悬崖边
==== phrases
- count on: 依靠,依赖
==== sentences
=== text4
==== vocabulary
- board: 董事
- sort out: 解决
- compliance: 服从
- feeble: 脆弱的
- governance: 治理
- earn: 招惹
- nasty: 负面的;危险的
- headline: 头条
- executive: 经理
- suite: 随从
- dimmest: 笨
- disclose: 揭露
- overshadow: 使扫兴
- due: 足够的
==== phrases
- put right: 纠正
- peer into: 仔细观察
- went astray:
- do the rounds: 四处走访
- put sth on notice: 警告
==== sentences
=== 七选五
==== vocabulary
- setback: 挫折
- role model: 榜样
- clique: 小团体
- vaunt: 受吹捧的
- downside: 缺点
- gratification: 满足
- deploy: 运用
- canned: 预先录制的
- stretch: 一段时间
- delicate: 微妙的
- fledge: 鸟类成长的过程
- fleding: 羽翼未满的
==== phrases
- come across as: 显得
==== sentences
== 2008
=== 完形
==== vocabulary
- renowned: 著名的
- disproportionately: 不成比例地
- unaccountably: 莫名其妙地
- affirm: 证实
- career: 成功
- value: verb. 尊重,重视
- instrument: 法律文件;手段或方法
- weave: 编织
- paradoxical: 似是而非的
==== phrases
- in progress: 进行中的
- in question: 正讨论的
- give up to: 把...让给
- get over: 说清楚
=== text1
==== vocabulary
- sphere: 范围
- way: adv.远远的
- susceptible: 易受...的影响
- ovary: 卵巢
- observe: 评论
- visibly: 明显地
- interpersonal: 人际间
- one-shot deal: 一次性事件
- wear-and-teat: 磨损
- inclination: 倾向
- paycheck: 工资支票
==== phrases
- It's not necessarily that ...:
==== sentences
=== text2
==== vocabulary
- affiliation: 从属
- ready: (adj.)易得到的
- facilitate: 使便利
==== phrases
- be rested with: 权力、责任或权利的归属或赋予
- make heavy reading: 读起来让人心情沉重
==== sentences
=== text3
==== vocabulary
- frame: 体格
- obscure: 遮掩
- notably: 尤其
- secular: 长期的
- genetically: 基因角度
- substantial: 大量的
- canal: 管
- bipedal: 两足动物的
- withstand: 承受
- impose: 施加
- limb: 肢体
- non-Americans: 非美国人
==== sentences
=== text4
==== vocabulary
- fragile nature: 脆弱性
- country's infancy: 建国初期
- hamper: 妨碍
- bedrock: 基石
- clause: 条款
- prestige: 名声
==== phrases
- part with: 不情愿地放弃
==== sentences
=== 七选五
==== vocabulary
- railroad: 仓促执行;陷害
- clip: 剪切
- thesis: 论点
- chauvinistic: 大男子主义的
- abrupt: 支离破碎的
- wordy: 冗长的
- poke: 捅
- prod: 捅
- tentative: 试探性的
==== phrases
- work sth into: 包括
- flesh out: 完善
==== sentences
== 2009
=== 完形
==== vocabulary
- fruit-fly: 果蝇
- upkeep: 保养维修费
- wistful: 惆怅的
- operant conditioning: 条件反射
- fight: (对情感欲望的)抑制
==== phrases
- left in the dust: 望尘莫及的
- determine: 测定
- above all: 最重要的是;尤其是
- after all: 终究;毕竟
- better still: 更好的是
- in times: 迟早;及时
=== text1
==== vocabulary
- unreflecting: 缺乏思考的
- herd: 人群
- trains of thought: 一连串的想法
- inherently: 固有地
- rut: 辙痕
- perpetuate: 使持久化
- regulated: 约束的
==== phrases
- wear into: 磨出
- comply with: 与...一致
==== sentences
=== text2
==== vocabulary
- paternal: 父亲的
- kit: 工具包
- kinship: 亲属关系
- rage: 时尚,流行
- genealogist: 系谱学者
- hawk: 叫卖,兜售
- mitochondrial: 线粒体
- lump: 归并
==== phrases
- shell out: 付款
==== sentences
=== text3
==== vocabulary
- radically: 根本上
- workforce: 劳动力
- deride: 嘲笑
- automotive: 汽车
- assembly: 装配
- illiterate: 不识字的
==== sentences
=== text4
==== vocabulary
- intellectual: 知识分子
- pursuit: 爱好
- preoccupation: 令人全神贯注的失误
- Puritan: 清教徒
- virtuosity: 技艺
- extensively: 广泛地
- reach: 被...看到/听到
- dependent: 侍从
- superstitious quality: 迷信色彩
- emigrate: 移居
- sermon: 说教
- comparatively: 相对地
- illusory: 虚幻的
==== sentences
=== 七选五
==== vocabulary
- worldly: 世俗的
- virtually: 几乎
- diffusionism: 文化传播理论
- ritual: 仪式
- signify: 预示
==== phrases
- attribute ... to ...: 把...归因于...
==== sentences
== 2010
=== 完形
==== vocabulary
- shop-floor: 车间
- the very ...: 正是...
- being experimented upon: 受试者
- subject: 实验对象
- econometric: 计量经济学的
- plateau: 稳定期/停滞期
- perplexing: 令人费解的
- mischievous: 恶作剧的
- enlightening: 有启发性的
- duly: 如期的
==== phrases
- slack off: 萧条
- pin down: 确切说明
=== text1
==== vocabulary
- inexorable: 不可阻挡地
- coverage: 报道
- learned: 博学的
- deem: 认为
- circulation: 发行
- dirt-cheap: 廉如土
- ornament: 装饰,点缀
- far-off: 遥远的
- calling: 天职
- cricket: 板球
- foremost: 第一的
- save: prep/conj 除了
- revival: 复兴
- prospect: 前景
- upholster: 装饰(家具)
- prose: 散文
- headlong: 迅速
- retreat: 撤退
- radical: 根本的;激进的
- horizon: 范围,见识
- prominent: 卓越的;显著的
==== phrases
- to the point of: 达到...的程度
- be taken for granted that...: 被视作理所当然
- be about sth: 忙于
- keep one's own end up: 再困难前坚持下去
==== sentences
=== text2
==== vocabulary
- abuzz: 嘈杂的
- about-face: 政策180度大转变
- pool: 集中
- filing: 卷宗
- issue: 发出
- practice: 惯例
- hedge: 减轻损失
- uphold: 维持(原判;裁决)
- attorney: 律师
- goodwill: 善意
- incidence: 发生率
- looming: 潜在的
- prevailing: 普遍的
==== phrases
- scale back: 缩减
- stake out exclusive rights to ...: 宣布对...的独占权
- comply with: 顺从
==== sentences
=== text3
==== vocabulary
- epidemic: 泛滥
- influential: 有影响力的人
- informed: 见识广博的
- compelling: 令人信服的
- plausible-sounding: 听起来有道理的
- embrace: 乐意采纳
- cursory: 粗略的
- outsize presence: 特大的影响力
- interpersonal: 人际
- cascade: 瀑布;大量倾泻
==== sentences
=== text4
==== vocabulary
- standard-setter: 标准制定者
- moan: 抱怨
- compromise: 陷入危险
- carry: 出售
- revive: 复兴
- management: 管理部门
- book value: 帐面价值
- pension: 养老金
- invite: 招致
- concession:
- diminish:
- evade:
==== phrases
- take aim at: 把矛头对准
- rush through: 匆匆修改
- do likewise: 采取同样的做法
- give in to: 屈服
==== sentences
=== 七选五
==== vocabulary
- food service segment: 食品服务业
- loom: 隐约出现
- acclaim: 给予高度评价
- gigantic: 巨大的
- intricacy: 错综复杂的
- unseat: 罢免
- entrenched: 根深蒂固的
- building blocks: 组成部分
- sluggish: 缓慢的
- mask: 掩盖
- margin: 盈利
- consolidate: 合并
- deter: 阻止
- reap: 收获
==== phrases
- at a standstill: 处于停滞期
- rake in substantial ...: 迅速大量获得...
- Despite variations in detail: 尽管细节上有所不同
- try one's hand: 一试身手
- stand to: 很可能
==== sentences
== 2011
=== 完形
==== vocabulary
- tone: 结实
- conceivably: 可想象的
- contract: 收缩
- impair: 损害
- measurable: 显著的
- consequently: 因此(因果关系逻辑结果)
==== phrases
- die down: 逐渐变弱
=== text1
==== vocabulary
- appointment: 聘请
- favorable: 称赞的
- sober-sided: 严肃的
- unpretentious: 不爱炫耀的
- air: 外表
- formidable: 令人敬畏的
- conductor: 指挥家
- orchestra: 管弦乐队
- hitherto: 迄今
- troupe: 剧团
- institution: 制度
- repertoire: 全部曲目
- incur: 招致
==== phrases
- with no air of: 没...的架子
==== sentences
=== text2
==== vocabulary
- straight up: 直截了当的
- cloak: 掩盖
- line up: 排队
- post: 职位
- cloud: 使...蒙上阴影
- deputy chief: 副总裁
- turnover: 人事变更率
- pick up: 恢复
- abound: 大量存在
- adhere to: 坚持
- sitting CEO: 现任CEO
- disgrace: 丢脸
- spur: 驱使
==== phrases
- came right out: 公开表明
- attend to: 关注
- guard against: 提防
==== sentences
=== text3
==== vocabulary
- print advertisements: 平面广告
- leverage: 利用
- initiator: 创始人
- hostage: 人质
- stakeholder: 利益相关者
- well-orchestrated: 精心策划的
==== phrases
- engage with: 与...交流
==== sentences
=== text4
==== vocabulary
- insightful: 有洞察力的
- provocative: 挑衅的
- fulfilling: 令人满足的
- dampen: 使扫兴
- newsstand: 报摊
- celebrate: 赞扬
- procreation: 生育
- kitten-killing: 杀小猫
- provoke: 煽动
- retrospect: 回想
==== phrases
- anything less than: 绝不是
- in progress: 过程中
- round-the-clock: 夜以继日
==== sentences
=== 七选五
==== vocabulary
- grounding: 基础训练
- canon: 原则,准则
- professionalise: 专业化
- transmissible: 可传递的
- transferable: 可转用的
- monopoly: 垄断
- exclusionary: 排外的
- holistic: 全面的
==== phrases
- seize on: 大为关注
- take its toll: 产生恶果
==== sentences
== 2012
=== 完形
==== vocabulary
- legitimacy: 合法
- the rule of law: 法治
- justice: (cn.)法官
- judiciary: 司法部
- framer: 制订者
- ideological: 意识形态的
- compromise: 违背;达不到;使遭受危险
- suspect: 怀疑
- bound: 绑定
- prone: 有倾向的
- resort: 诉诸
- cultivate: 结交,获得
- distort: 扭曲
- address: 处理
- amiable: 亲切友好的
- accountable: 负有责任的
=== text1
==== vocabulary
- contend: 主张
- group dynamics: 群体互动
- recipient: 接受者
- critique: 批评
- lameness: 缺陷
- spot-on: 准确的
- mobilize: 动员
- glaring: 明显的
- virtuous: 有道德的
- tactic: 策略
- engineer: 策划
==== phrases
- take a page from: 向...学习
==== sentences
=== text2
==== vocabulary
- justified: 合理的
- renege on: 食言
- longstanding: 长期的
- commitment: 承诺
- abide by: 遵守
- constitutionality: 合宪性
- desperate: 孤注一掷的
- reactor: 反应堆
- condition: 条件
- operate: 运营
- enrage: 激怒
- pledge: 正式承诺
- dishonor: 违背
- extension: 延期
- patchwork: 补丁
- defy: 藐视
==== phrases
- go along: 同意
==== sentences
=== text3
==== vocabulary
- deception: 欺骗
- protoscience: 源科学
- stake: 用桩支撑
- refutation: 反驳
- evolution: 发展
==== phrases
- stake out a claim: 公开声明对...拥有所有权
==== sentences
=== text4
==== vocabulary
- unionist: 工会主义者
- civil servant: 公务员
- prime: 全盛时期
- left of centre: 左倾(激进)
- patrol: 巡查
- charter school: 特许学校
- merit pay: 绩效工资
- hardline: 强硬的
- augment: 增加
==== phrases
- clamp down: 镇压
- go back a long way: 回溯到很久以前
==== sentences
=== 七选五
==== vocabulary
- fleet: 飞逝
- warrior: 勇士
- superfluous: 多余的
- millennium: 千禧年
- mount: 施加
==== phrases
==== sentences
== 2013
=== 完形
==== vocabulary
- speculate: 推测
- inability: 不能
- theorise: 提出理论
- defendant: 被告
- applicant: 申请者
- grant: 授予
- big picture: 大局
- thoughtless: 考虑不周的
- defensible: 可辩解的
- fluctuate: 涨落,波动
- disregard: 忽视
==== phrases
- on the whole: 总体而言
=== text1
==== vocabulary
- high fashion: 高端时尚
- feverish: 发热的
- indictment: 控告
- turnarounds: 转变
- inventory: 存货
- knit: 编织衣物
- strain: 极限相关
- vanity: 虚荣心
- accusation: 谴责
- satire: 讽刺
- exposure: 揭露
==== phrases
- at odds with: 与...相矛盾
- in volumes: 大量
- knock off: 迅速而轻松地完成某事
==== sentences
=== text2
==== vocabulary
- fine-grained: 细粒度的
- alliance: 联盟
==== phrases
- set off the row: 挑起争论
- better/worse off: 好转/恶化
- press on: 坚定地继续
- on that count: 在那方面
==== sentences
=== text3
==== vocabulary
- glow: 热
- utopia: 乌托邦
- gloominess: 沮丧
- flagship: 旗舰
- mechanical: 机械的
- willfully: 任性固执的
- dazzling: 耀眼地
- envisage: 想象
- identified: 确定
- descendant: 后代
- fad: 时尚
- rosy: 美好的
==== phrases
- mark time: 计时
==== sentences
=== text4
==== vocabulary
- contest: (v)质疑
- provision: 条款
- enforce: 条款
- intrude: 闯入
- statute: 法规
- exclusively: 唯一地
- overturn: 推翻
- withhold: 保密
==== phrases
- knock out: 破坏
- come in contact with: 接触到
- go back to: 追溯到
- in essence: 实际上
==== sentences
=== 七选五
==== vocabulary
- flourish: 繁荣的
- paraphrase: 解释
- enact: 制订
==== phrases
- up in arms: 竭力反对
==== sentences
- The number of social science students world wide has *swollen* by about 11% every year since 2000.
== 2014
=== 完形
==== vocabulary
- clarity: 清晰
- uneven: 不平均的
- obscure: 鲜为人知的
- wellbeing: 幸福
- outlook: 看法/展望
- roundabout: 交通环岛
- sharpness: 敏锐度
==== phrases
- feature in: 在...起重要作用
=== text1
==== vocabulary
- chancellor: 大臣
- exchequer: 财政部
- upfront: 预先
- CV: 简历
- benefit: 津贴,救济金
- allowance: 津贴
- indulgent: 放纵的
- zeal: 热情
- claimant: 申请人
- prospect: 可能性
- entitlement: 拥有/获得某物的权利
==== phrases
- stay off: 远离
- complete with: 装备有某物
==== sentences
=== text2
==== vocabulary
- generate: 招惹
- skyscraper: 摩天大楼
- nuisance-lawsuit: 危害公共利益的行为
- filer: 诉讼律师
- tort: 民事侵权行为
- costly: 昂贵的
- the bar: 法律界
- sensible: 明智的
- around: 存在
- body: 团体
- stern: 严格的
- guild: 协会
==== phrases
- pile into: 扎堆进
==== sentences
=== text3
==== vocabulary
- lucrative: 利润丰润的
- benefactor: 捐助人
- upstart: 暴富的
- exercise: 活动,任务
- self-promotion: 自我宣传
- cement: 加强
- status quo: 现状
- perpetuate: 使持续
- scatter: 分散的
- outgrouwn: 长得太大而不适用
- row: 争议
- grace: 优雅
==== phrases
- a handful of: 少数
==== sentences
- _What's not to like?_
=== text4
==== vocabulary
- top-tier: 顶尖的
- business executive: 企业高管
- crafting: 精致
- coherent: 连贯的
- illiberal: 缺少人文教育的
- deprive: 剥夺
- progressive: 进步的
- self-reliance: 自力更生
- illuminate: 说明
- contemptuous: 蔑视的
- tolerant: 宽容的
- exclusive: 专注于
==== phrases
- in the making: 在发展中
- at home: 运用自如的
- set back: 阻碍
==== sentences
=== 七选五
==== vocabulary
- megalith: (史前)巨石
- hominid: 人科的
- ornate: 华丽的
- ceremonial: 礼仪的
- complexes: 综合楼群
- sample: 抽样
- excavation: 挖掘
- terrain: 地层
- radar: 雷达
- pharaoh: 法老
- rubble: 碎石
- comb: 梳理
- antique: 古玩
- dealer: 商人
- engrave: 雕刻
- seal: 印章
- pinpoint: 精准定位
- pottery: 陶器
==== phrases
==== sentences
== 2015
=== 完形
==== vocabulary
- genome-wide: 全基因组
- kin: 亲戚
- ethnic: 民族的
- see: 确保,设法做到
==== sentences
- _There's more to it._ 事情没那么简单。
=== text1
==== vocabulary
- abdicate: 退位
- monarchy: 君主制
- majestic: 庄严的
- argument: 论据
- polarise: 两极分化的
- embody: 表现;象征
- transcendence: 超越
- infest: 大批滋生
- absolutist: 专制主义者
- bizarre: 奇怪的
- intrusiveness: 侵扰
- well-heeled: 富有的
- granny: 老奶奶
- ease: 缓和
- reign: 统治
==== phrases
- eat one's words: 承认自己说错了话
- stand down: 辞职
- the writing is on the wall: 厄运来临
- take a tough line: 采取强硬态度
==== sentences
=== text2
==== vocabulary
- warrant: 搜查令
- refrain: 抑制
- sweeping: 彻底的
- implication: 可能的影响
- reckless: 不顾后果的
- discernable: 可认识的
- defendant: 被告人
- lame: 差劲的,蹩脚的
- arrestee: 被捕者
- correspondence: 通信
- line-drawing: 界限划定
- cite: 引证
- swallow: 忍受
- passenger-car: 小客车
==== phrases
==== sentences
=== text3
==== vocabulary
- irreproducibility: 不可复制性
- manuscript: 原稿
- impel: 推动
- drive: 驱动
- advisory: 忠告的
- model: 模仿
- long overdue: 姗姗来迟
- literate: 精通的
- merit: 优点
==== phrases
==== sentences
=== text4
==== vocabulary
- unsettling: 令人不安的
- dearth: 缺乏
- integrity: 正直
- sorting mechanism: 分选机制
- conspire: 阴谋策划
- await: 等候
- frame: verb. 表达
- revelation: 揭发
- cunning: 狡诈的
- marginalized: 边缘化
==== phrases
==== sentences
- Speaking of ...,
- Driving her point home: 彻底将观点阐述清楚
=== 七选五
==== vocabulary
- comprehend: 理解
- assimilation: 吸收
- retrieval: 检索
- read off: 快速读完
- timeless: 永恒的
- pointless: 无益的
- discourse entity: 语篇实体
- mouthpiece: 代言人
- ascribe: 赋予
==== phrases
- draw on: 利用
- in effect: 事实上
==== sentences
== 2016
=== 完形
==== vocabulary
- matchmake: 媒人
- veto: 否决
- sermon: 布道
- newlyweds: 新婚夫妇
- prejudice: 偏见
==== phrases
- above all: 最重要的是
- in time: 及时;最后,终于
=== text1
==== vocabulary
- preliminary: 预备的
- runway: T台
- incite: 煽动
- uplifting: 进行提升的
- motive: 目的
- arbiter: 仲裁者
- intangible: 无形的
- inherent: 固有的
- adornment: 装饰
- voluntary: 自愿的
- charter: 宪章
==== phrases
- impinge on: 侵犯(impinge on sb's right)
==== sentences
=== text2
==== vocabulary
- country: 乡村
- alongside: 与...相比
- launch: 发起
- dweller: 居民
- pressure: 强迫
- green belt: 绿化带
- guardianship: 保护
- endorse: 赞同
- sentiment: 观点
- off-plan: 计划外
- Ukip: 独立党
- considered: 深思熟虑的
- intrusion: 侵犯
- meadow: 草地
- renovation: 翻新
- renewal: 复兴
- high street: 商业街
- rip: 撕裂;快速移动
- coherence: 协调
- disregard: 忽视
==== phrases
- strike terror into: 使...胆战心惊
==== sentences
=== text3
==== vocabulary
- premise: 前提
- clear-cut: 界限分明的
- monetary: 金融的
- prosecute: 起诉
- good cause: 慈善
- halo effect: 光环效应
- whereby: 凭借
- consideration: 尊重
- bribery: 贿赂
- lenient: 宽大
- leniency: 宽大
- whereas: 尽管
==== phrases
- rule out: 排除
- bank on: 指望
==== sentences
=== text4
==== vocabulary
- nostalgia: 思乡
- rustle: 沙沙声
- aside: adv. 且不谈(名词后)
- ditch: 丢弃
- infrastructure: 基础设施
- excessive: 过度的
- dwarf: 使...相形见绌
- overhead: 日常支出
- circulation: 发行量
- blunder: 愚蠢的错误
- foresighted: 先见之明
- legacy: 遗产
==== phrases
- migrate away from: 从...转移
==== sentences
=== 七选五
==== vocabulary
- likeability: 魅力
- headshot: 大头照
- rut: 乏味
- cue: 线索
- pivot: 以...为中心旋转
- enlist: 争取
==== phrases
==== sentences
== 2017
=== 完形
==== vocabulary
- resounding: 响亮的
- oxytocin: 催产素
- host: 大量的
==== phrases
- come across with: 被理解;提供
- come down with: 染上
=== text1
==== vocabulary
- security lines: 安检队伍
- infuriating: 令人极为生气
- undercover: 暗中的
- screener: 安检员
- screening lanes: 安检通道
- expedited: 加速的
- sticker shock: 标价冲击波
- underused: 未被充分利用的
- belated: 迟来的
==== phrases
==== sentences
=== text2
==== vocabulary
- reign: 当政的
- monarch: 君主
- cosmos: 宇宙
- dormant: 休眠的
- unsurpassed: 无比的
- clarity: 图像
- vocal: 大声表达的
- sovereign: 有主权的
- holiness: 神圣性
- renaissance: 复兴
- dawn: 开端
- Polynesian: 波利尼西亚人
- disassemble: 拆开
- primal: 原始的
- feat: 功绩
==== phrases
==== sentences
=== text3
==== vocabulary
- timely: 及时的
- record: 创纪录的
- Brexit: 脱欧
- rounded: 全面的
- budding: 萌芽的
- remold: 重新形成
- sponsor: 发起
==== phrases
- shed some light on: 有助于解释
==== sentences
=== text4
==== vocabulary
- unanimous: 一致通过的
- conviction: 定罪
- ethic: 道德
- intent: 意图
- found(find): verb. 判决
- favor: 礼物
- favoritism: 偏袒行为
- compact: 协定
- representative government: 代议制政府
- constituent: 选民
- reinforce: 强化
- fan: 煽起
- rather: adv. 相反
- extent: 范围
- contemptuous: 蔑视的
- justified: 有正当理由的
==== phrases
- hold one nose: 捏住鼻子(反感)
- play favorites in: 偏袒
==== sentences
=== 七选五
==== vocabulary
- sketch: 随笔
- chronicle: 纪事
- runaway: 脱离控制的
- plump: 丰满的
- spectacled: 戴眼镜的
- installment: 部分
- backdrop: 背景
- woodcut: 木刻
- posthumous: 死后发生的
- satirist: 讽刺作家
- panorama: 全貌
- errand: 差事
- shorthand: 速记
- stenographer: 速记员
- transcribe: 记录
- obscure: 无名的
- humiliation: 屈辱
- confide: 吐露
- bleaker: 阴郁的
- slum: 贫民窟
- consolidate: 巩固
- letter: 写作生涯
==== phrases
==== sentences
== 2018
=== 完形
==== vocabulary
- herding instinct: 羊群效应
- spray: 喷
- inhale: 吸入
- toddler: 学步的儿童
- wronged: 被冤枉的
==== phrases
=== text1
==== vocabulary
- presidential campaign: 总统大选
- alarmist: 危言耸听的
- Luddites: 卢德分子(反对新技术的人)
- displace: 取代
- mechanized: 机械化的
- loom: 织布机
- vocational: 职业技术的
- upend: 翻倒
- nut: 发狂的
- indispensable: 不可或缺的
==== phrases
- come for: 强行带走
==== sentences
=== text2
==== vocabulary
- assume: 开始承担(责任)
- reliance: 信赖
- projection: 体现
- counteracting: 抵抗
==== phrases
- beef up: 加强
==== sentences
=== text3
==== vocabulary
- commissioner: 专员
- verdict: 判决
- scrutinise: 仔细研究
- informed: 消息灵通的
- consent: 许可
- surveillance: 监测
- maladapted: 不合适的
- pharma: 制药公司
- feudalism: 分封制
- vicious: 恶意
==== phrases
- take account of: 考虑
==== sentences
=== text4
==== vocabulary
- liability: 债务
- bankruptcy: 破产
- oversee: 监督
- status quo: 现状
- defer: 推迟
- bare: 勉强的
- omission: 遗漏
- consensus: 共识
- discontent: 不满
- Band-Aid: 创可贴->权宜之计
==== phrases
- aspects of sth: ...的方方面面
- amount to: 等同
- keep afloat: 维持
==== sentences
=== 七选五
==== vocabulary
- commission: 委员会
- Treasury: 财政部
- story: 楼层
- stenciling: 用模板印制
- marquetry: 镶嵌细工
- diplomat: 外交家
- granite: 花岗岩
- emissary: 特使
- tile: 贴地砖于
- monumental: 非常大的
- bronze: 青铜
- baluster: 栏杆柱
- cap: verb. 覆盖顶部
- skylight: 天窗
- dome: 穹顶
- stained glass: 彩色玻璃
- rotundas: 回形大厅
- necessitate: 使...成为必需
- demolition: 拆除
==== phrases
- lay foundation: 打地基
==== sentences
== 2019
=== 完形
==== vocabulary
- woods: 森林
- downhill: 下坡
- fresh water: 淡水
- bearing: 方向
- glow: 光辉
- literally: 的确;字面上
- post: 杆;柱
- link: 线路
- shade: 阴凉处
==== phrases
- put on: 穿戴;举办
=== text1
==== vocabulary
- impose: 强制推行
- clawback: 收回
- publicly traded company: 上市公司
- plum: 葡萄干
- pudding: 布丁
- transient: 短暂的
- quarterly: 季度的
- equity: 股票
- attention span: 注意力持续时间
- predominance: 主导地位
- performance bonus: 绩效奖金
- compensation: 工资
- decisiveness: 果决
==== phrases
==== sentences
=== text2
==== vocabulary
- catalog: 目录
- retention: 保留
- counterbalance: 抗衡
==== phrases
- do one's utmost: 竭尽所能
==== sentences
=== text3
==== vocabulary
- speculative: 非凡的
- foreshadow: 预示
- evade: 躲避
- reproduce: 复制
- thorny: 棘手的
- split-second: 一瞬间的
- reflex: 本能反应
- mega: 巨大的
- pledge: 正式承诺
- surveillance: 监视
- starting point: 起点
- spark: 引发
==== phrases
==== sentences
=== text4
==== vocabulary
- overrule: 推翻
- warehouse: 仓库
- charge: 收费
- advocacy: 倡议
- factual account: 事实的描述
==== phrases
- be further removed from: 与...大相径庭
- level the playing field: 打造公平的竞争环境
==== sentences
=== 七选五
==== vocabulary
- reasoned: 理智的
- charitably: 宽容地
- aversion: 厌恶
- counter: 反驳
- needy: 贫困的
==== phrases
- take a stand: 表明立场;持某观点
- spell out: 研究
- better off: 更好的
==== sentences
== 2020
=== 完形
==== vocabulary
- Briton: 美国人
- roast: 烤肉
- culinary: 烹调的
- render: 宣布
- compound: 化合物
- acrylamide: 丙烯酰胺
- crisp: 脆
- thin-crust: 薄皮
- toast: 烤
- precautionary: 预防的
- rumour: 流言
- intensified: 加强的
- compel: 强迫的
- secondary: 次要的;中等的
==== phrases
- save up: 攒钱
- To be fair,...: 说句公道话
=== text1
==== vocabulary
- Labour MPs: 工党议员
- institute: 建立;实行
- avalanche: 雪崩
- bid: 尝试,努力争取
- booby prize: 安慰
- sought-after: 争相获得的
- bag: 抢占
- cynic: 悲观者
- post-Brexit: 脱欧
- suburb: 郊区
- hamlet: 村
- cure-all: 万灵药
- spell: 一段时间
- nudge: 逐步推进
- powerhouse: 重要的地方
- peculiarity: 特点
- celebrate: 赞美
==== phrases
- be confined to: 局限于
- reinvent oneself: 新形象
==== sentences
=== text2
==== vocabulary
- a licence to print money: 一本万利
- monetary: 金融的
- secured: (经过努力)获得
- profit margin: 利润率
- existential: 生死存亡
- drastic: 急剧的
- paywalled: 付费的
- relieved: 如释重负的
==== phrases
- feed on: 依赖
==== sentences
=== text3
==== vocabulary
- progressive: noun. 进步人士
- mandate: 命令/训令
- sponsor: 倡议;提交(法案)
- parity: (薪金,地位)对等
- quota: 配额
- expressly: 明确地;故意地
- mirror: 反映
- pool: 备用人员
- self-serving: 谋私利的
==== phrases
- frown on: 不赞成
==== sentences
=== text4
==== vocabulary
- multinational: 跨国公司
- outlet: 出口
- unilateral: 单边的
- provision: 规定;条款
- contemplate: 考虑
- specific: cn. 详情,细节
- levy: 征税
- countermeasure: 反制措施
==== phrases
- put in place: 实施
- an alphabet soup of ...: 大杂烩
- follow suit: 效仿
- be apt to: 容易
==== sentences
=== 七选五
==== vocabulary
- antagonistic: 敌对的
- attachment: 依恋
- complimentary: 赞赏的
- autistic: 自闭症的
- spectrum: 范围;光谱
- intimidation: 恐吓
- backfire: 事与愿违
==== phrases
==== sentences
|
|
https://github.com/drupol/master-thesis | https://raw.githubusercontent.com/drupol/master-thesis/main/src/thesis/imports/colors.typ | typst | Other | #let color-a = rgb("#990027") // #5D071D
|
https://github.com/augustebaum/epfl-thesis-typst | https://raw.githubusercontent.com/augustebaum/epfl-thesis-typst/main/example/main/ch1_introduction.typ | typst | MIT License | = Introduction
#lorem(100)
#pagebreak()
#lorem(75)
#pagebreak()
#lorem(75)
|
https://github.com/mrwunderbar666/typst-apa7ish | https://raw.githubusercontent.com/mrwunderbar666/typst-apa7ish/main/README.md | markdown | MIT License | # APA7 (-ish) Template for Typst
[Typst](https://typst.app/) Template that (mostly) complies with APA7 Style (Work in Progress).
The template does not follow all recommendations by the APA Manual, especially when the suggestions break with typographic conventions (such as double line spacing :vomiting_face:). Instead, the goal of this template is that it generates you a high-quality manuscript that has all the important components of the APA7 format, but is aesthetically pleasing.
# Work in Progress
The following works already quite well:
- consistent and simple typesetting
- correct display of author information / author note
- citations and references
- Page headers and footers (show short title in header)
- Option to anonymize the paper
This is still not finished:
- Tables: seeking to implement 3-part-tables (caption, content, and table notes)
- figures
- complete pandoc integration (template for pandoc to replace Latex-based workflows)
- automatic calculation of page margins (like memoir-class for Latex)
# Basic Usage
The easiest way to get started is to edit the example file, which has sensible default values. Most fields in the configuration are optional and will safely be ignored (not rendered) when you set them to `none`.
## Authors
The `authors` setting expects an array of dictionaries with the following fields:
```typst
(
name: "<NAME>", // Name of author as it should appear on the paper title page
affiliation: "University, Department", // affiliation of author as it should appear on the title page
orcid: "0000-0000-0000-0000", // optional for author note
corresponding: true, // optional to mark an author as corresponding author
email: "<EMAIL>", // optional email address, required if author is corresponding
postal: "Longer string", // optional postal address for corresponding author
)
```
## Anonymization
Sometimes you need to submit a paper without any author information. In such cases you can set `anonymous` to `false`.
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/edge_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set page(width: 160pt)
#set text(size: 8pt)
#let try(top, bottom) = rect(inset: 0pt, fill: conifer)[
#set text(font: "IBM Plex Mono", top-edge: top, bottom-edge: bottom)
From #top to #bottom
]
#let try-bounds(top, bottom) = rect(inset: 0pt, fill: conifer)[
#set text(font: "IBM Plex Mono", top-edge: top, bottom-edge: bottom)
#top to #bottom: "yay, Typst"
]
#try("ascender", "descender")
#try("ascender", "baseline")
#try("cap-height", "baseline")
#try("x-height", "baseline")
#try-bounds("cap-height", "baseline")
#try-bounds("bounds", "baseline")
#try-bounds("bounds", "bounds")
#try-bounds("x-height", "bounds")
#try(4pt, -2pt)
#try(1pt + 0.3em, -0.15em)
|
https://github.com/gabrielluizep/typst-ifsc | https://raw.githubusercontent.com/gabrielluizep/typst-ifsc/main/template/ifscyan.typ | typst | Creative Commons Zero v1.0 Universal | #import "@preview/polylux:0.3.1": *
#let primaryColor = rgb("#30504e")
#let bgColor = rgb("eef1ec")
#let paddingX = 1.5em
#let paddingY = 1em
#let footer = [
#set align(left + bottom)
#box(width: 100.1%, height: 1em, fill: primaryColor)[
#box(width: 50%, height: 100%)[
#align(horizon)[
#pad(x: paddingX / 2)[
#text(.6em, fill: bgColor)[
#counter(page).display("1 / 1", both: true)
]
]
]
]
#align(right)[
#pad(x: 0em)[
#circle(width: 1.8em, height: 1.8em, fill: primaryColor)[
#align(center + horizon)[
#image("../assets/ifsc-logo.png", width: 70%)
]
]
]
]
]
]
#let ifscyan-footer = state("ifscyan-footer", [])
#let ifscyan-theme(aspect-ratio: "16-9", body) = {
set page(
paper: "presentation-" + aspect-ratio,
margin: 0cm,
fill: bgColor,
header: none,
footer: none,
)
set text(size: 25pt, font: "FreeSans")
show footnote.entry: set text(size: .6em)
ifscyan-footer.update(footer)
body
}
#let title-slide = (title: "IFSC Polylux", doc) => polylux-slide[
#box(width: 100.1%, height: 40%, fill: primaryColor)[
#align(left + bottom)[
#pad(x: paddingX, y: paddingY)[
#text([*#title*], 2em, fill: bgColor)
]
]
]
#pad(x: paddingX, y: paddingY)[
#grid(columns: (1fr, 1fr), [
#doc
], [
#align(right)[
#image("../assets/ifsc-v.png", width: 30%)
]
])
]
]
#let slide = (title: none, doc) => polylux-slide[
#box(width: 100.1%, height: 10%, fill: primaryColor)[
#align(left + horizon)[
#pad(x: paddingX)[
#text([#title], fill: bgColor)
]
]
]
#pad(x: paddingX, y: paddingY)[
#doc
]
#ifscyan-footer.display()
]
|
https://github.com/MrPicklePinosaur/typst-conceal.vim | https://raw.githubusercontent.com/MrPicklePinosaur/typst-conceal.vim/master/README.md | markdown | MIT License | <div align="center">
# typst-conceal.vim
Vim Conceal for Typst
</div>
### Before
<img src="media/noconceal.png" width=60% />
### After
<img src="media/conceal.png" width=60% />
### Output
<img src="media/output.png" width=60% />
## Installation
```vim
Plug 'MrPicklePinosaur/typst-conceal.vim', {'for': 'typst'} " vim plug
Plugin 'MrPicklePinosaur/typst-conceal.vim' " vundle
```
Also ensure that conceal level is set
```vim
set conceallevel=2
```
## Configuration
It is possible to individually configure if math symbols and emoji are
concealed. By default all conceals are enabled by default.
```vim
let g:typst_conceal_math=1
let g:typst_conceal_emoji=1
```
## Credits
Based off of [tex-conceal.vim](https://github.com/KeitaNakamura/tex-conceal.vim)
|
https://github.com/ntjess/wrap-it | https://raw.githubusercontent.com/ntjess/wrap-it/main/README.md | markdown | The Unlicense | # Wrap-It: Wrapping text around figures & content
Until <u><https://github.com/typst/typst/issues/553></u> is resolved,
`typst` doesn’t natively support wrapping text around figures or other
content. However, you can use `wrap-it` to mimic much of this
functionality:
- Wrapping images left or right of their text
- Specifying margins
- And more
Detailed descriptions of each parameter are available in the <u>[wrap-it
documentation](https://github.com/ntjess/wrap-it/blob/main/docs/manual.pdf)</u>.
# Installation
The easiest method is to import `wrap-it: wrap-content` from the
`@preview` package:
``` typ
#import "@preview/wrap-it:0.1.0": wrap-content
```
# Sample use:
## Vanilla
``` typst
#set par(justify: true)
#let fig = figure(
rect(fill: teal, radius: 0.5em, width: 8em),
caption: [A figure],
)
#let body = lorem(40)
#wrap-content(fig, body)
```

## Changing alignment and margin
``` typst
#wrap-content(
fig,
body,
align: bottom + right,
column-gutter: 2em
)
```

## Uniform margin around the image
The easiest way to get a uniform, highly-customizable margin is through
boxing your image:
``` typst
#let boxed = box(fig, inset: 0.5em)
#wrap-content(boxed)[
#lorem(40)
]
```

## Wrapping two images in the same paragraph
``` typst
#let fig2 = figure(
rect(fill: lime, radius: 0.5em),
caption: [Another figure],
)
#wrap-top-bottom(boxed, fig2, lorem(60))
```
 |
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/visualize/shape-square-00.typ | typst | Other | // Default square.
#box(square())
#box(square[hey!])
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/enum_06.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test item number overriding.
1. first
+ second
5. fifth
#enum(
enum.item(1)[First],
[Second],
enum.item(5)[Fifth]
)
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/181.%20kids.html.typ | typst | kids.html
Having Kids
December 2019Before I had kids, I was afraid of having kids. Up to that point I
felt about kids the way the young Augustine felt about living
virtuously. I'd have been sad to think I'd never have children.
But did I want them now? No.If I had kids, I'd become a parent, and parents, as I'd known since
I was a kid, were uncool. They were dull and responsible and had
no fun. And while it's not surprising that kids would believe that,
to be honest I hadn't seen much as an adult to change my mind.
Whenever I'd noticed parents with kids, the kids seemed to be
terrors, and the parents pathetic harried creatures, even when they
prevailed.When people had babies, I congratulated them enthusiastically,
because that seemed to be what one did. But I didn't feel it at
all. "Better you than me," I was thinking.Now when people have babies I congratulate them enthusiastically and
I mean it. Especially the first one. I feel like they just got the best gift in the world.What changed, of course, is that I had kids. Something I dreaded
turned out to be wonderful.Partly, and I won't deny it, this is because of serious chemical
changes that happened almost instantly when our first child was
born. It was like someone flipped a switch. I suddenly felt
protective not just toward our child, but toward all children. As I was
driving my wife and new son home from the hospital, I approached a
crosswalk full of pedestrians, and I found myself thinking "I have
to be really careful of all these people. Every one of them is
someone's child!"So to some extent you can't trust me when I say having kids is
great. To some extent I'm like a religious cultist telling you
that you'll be happy if you join the cult too � but only because
joining the cult will alter your mind in a way that will make you
happy to be a cult member.But not entirely. There were some things
about having kids that I clearly got wrong before I had them.For example, there was a huge amount of selection bias in my
observations of parents and children. Some parents may have noticed
that I wrote "Whenever I'd noticed parents with kids." Of course
the times I noticed kids were when things were going wrong. I only
noticed them when they made noise. And where was I when I noticed
them? Ordinarily I never went to places with kids, so the only
times I encountered them were in shared bottlenecks like airplanes.
Which is not exactly a representative sample. Flying with a toddler
is something very few parents enjoy.What I didn't notice, because they tend to be much quieter, were
all the great moments parents had with kids. People don't talk about
these much � the magic is hard to put into words, and all other
parents know about them anyway � but one of the great things about
having kids is that there are so many times when you feel there is
nowhere else you'd rather be, and nothing else you'd rather be
doing. You don't have to be doing anything special. You could just
be going somewhere together, or putting them to bed, or pushing
them on the swings at the park. But you wouldn't trade these moments
for anything. One doesn't tend to associate kids with peace, but
that's what you feel. You don't need to look any
further than where you are right now.Before I had kids, I had moments of this kind of peace, but they
were rarer. With kids it can happen several times a day.My other source of data about kids was my own childhood, and that
was similarly misleading. I was pretty bad, and was always in trouble
for something or other. So it seemed to me that parenthood was
essentially law enforcement. I didn't realize there were good times
too.I remember my mother telling me once when I was about 30 that she'd
really enjoyed having me and my sister. My god, I thought, this
woman is a saint. She not only endured all the pain we subjected
her to, but actually enjoyed it? Now I realize she was simply telling
the truth.She said that one reason she liked having us was that we'd been
interesting to talk to. That took me by surprise when I had kids.
You don't just love them. They become your friends too. They're
really interesting. And while I admit small children are disastrously
fond of repetition (anything worth doing once is worth doing fifty
times) it's often genuinely fun to play with them. That surprised
me too. Playing with a 2 year old was fun when I was 2 and definitely
not fun when I was 6. Why would it become fun again later? But it
does.There are of course times that are pure drudgery. Or worse still,
terror. Having kids is one of those intense types of experience
that are hard to imagine unless you've had them. But it is not, as I
implicitly believed before having kids, simply your DNA heading for
the lifeboats.Some of my worries about having kids were right, though. They
definitely make you less productive. I know having kids makes some
people get their act together, but if your act was already together,
you're going to have less time to do it in. In particular, you're
going to have to work to a schedule. Kids have schedules. I'm not
sure if it's because that's how kids are, or because it's the only
way to integrate their lives with adults', but once you have kids,
you tend to have to work on their schedule.You will have chunks of time to work. But you can't let work spill
promiscuously through your whole life, like I used to before I had
kids. You're going to have to work at the same time every day,
whether inspiration is flowing or not, and there are going to be
times when you have to stop, even if it is.I've been able to adapt to working this way. Work, like love, finds
a way. If there are only certain times it can happen, it happens
at those times. So while I don't get as much done as before I had
kids, I get enough done.I hate to say this, because being ambitious has always been a part
of my identity, but having kids may make one less ambitious. It
hurts to see that sentence written down. I squirm to avoid it. But
if there weren't something real there, why would I squirm? The
fact is, once you have kids, you're probably going to care more
about them than you do about yourself. And attention is a zero-sum
game. Only one idea at a time can be the
top idea in your mind.
Once you have kids, it will often be your kids, and that means it
will less often be some project you're working on.I have some hacks for sailing close to this wind. For example, when
I write essays, I think about what I'd want my kids to know. That
drives me to get things right. And when I was writing
Bel, I told
my kids that once I finished it I'd take them to Africa. When you
say that sort of thing to a little kid, they treat it as a promise.
Which meant I had to finish or I'd be taking away their trip to
Africa. Maybe if I'm really lucky such tricks could put me net
ahead. But the wind is there, no question.On the other hand, what kind of wimpy ambition do you have if it
won't survive having kids? Do you have so little to spare?And while having kids may be warping my present judgement, it hasn't
overwritten my memory. I remember perfectly well what life was like
before. Well enough to miss some things a lot, like the
ability to take off for some other country at a moment's notice.
That was so great. Why did I never do that?See what I did there? The fact is, most of the freedom I had before
kids, I never used. I paid for it in loneliness, but I never used
it.I had plenty of happy times before I had kids. But if I count up
happy moments, not just potential happiness but actual happy moments,
there are more after kids than before. Now I practically have it
on tap, almost any bedtime.People's experiences as parents
vary a lot, and I know I've been lucky. But I think the worries I
had before having kids must be pretty common, and judging by other
parents' faces when they see their kids, so must the happiness that
kids bring.
Note[1] Adults are sophisticated enough to see 2 year olds for the
fascinatingly complex characters they are, whereas to most 6 year
olds, 2 year olds are just defective 6 year olds.Thanks to <NAME>, <NAME>, and <NAME>
for reading drafts of this.Arabic TranslationSlovak Translation
|
|
https://github.com/NamLe0609/bias-ai-report | https://raw.githubusercontent.com/NamLe0609/bias-ai-report/main/post_body.typ | typst | The values used in @ethical-impact-assessment-hospital are from both traditional @VSD-paper and AI-specific @Mapping-VSD sources.
The values in @ethical-impact-assessment-hospital have been acquired purely through conceptual investigations, which are prone to researcher bias and tend to misrepresent the stakeholders' actual views @VSD-book.
Only after closer examination of the stakeholders' understandings, contexts, and experiences through empirical investigations @Human-computer-handbook, can we update the previously acquired values and guarantee their trustworthiness. This can be done using traditional methods such as interviews and surveys, or more VSD-specific methods such as participatory design and envisioning cards @VSD-book.
An important step of the process is analyzing value conflicts, and deciding which stakeholders' needs should be prioritized (known as the dams-and-flows method @Value-dams-flows).
One value conflict is between patients' need for privacy and the insurance companies' desire for explicability. In order to explain the decisions made by the model, the insurance companies will need access to the patient's data, which is a clear violation of the patient's privacy.
An approach to resolve this is to have the model explain its decisions in a general but informative way, like providing a descriptive summary of the patient's condition.
Another conflict is between the medical institution's need for efficiency and the healthcare providers' want for autonomy. Healthcare providers require lots of time and resources to make decisions, which would make diagnosis and treatment slower. The institution could use this time and resources to treat more patients instead. This is a difficult tension to resolve, but we believe that the model should be used as a tool to assist the healthcare providers, not replace them. As such, the healthcare providers' interest should be prioritized.
Whilst emotion recognition technology has benefits in diagnosing mental health issues, using it for crime prevention and/or in public spaces is a completely different matter. From past research, it is clear that the technology is not accurate enough to be used in these scenarios. Even if it were, using it would be ethically questionable (see @Public-surveillance-paper@Public-surveillance-bbc).
= Recommendations & Considerations
From the ethical impact assessment in @ethical-impact-assessment-hospital, we have identified additional features which should be built on top of the model to satisfy the stakeholders' needs.
These include, but are not limited to:
- Mandatory approval of decisions by human overseers
- GDPR-compliant data handling
- Overviews of performance and bias
- General, descriptive explanations of outcomes
We also have to be prepared to update the model in an integrative manner during the design process, as results from our empirical investigations may reveal new values and tensions that needs to be addressed.
Deployment should also be rolled out in a controlled manner. By releasing the model to a small group of hospitals first, we can deal with any potential emerging biases and other issues before they become widespread.
== Datasets
Choosing a dataset is the most important part of the process, especially in avoiding bias. Our goal is to have a dataset that:
- Contains at least 7 of 8 emotions mentioned in @emotion-wheel
- Is reliable, meaning accurate labels and little noise @Google-data-quality
- Contains GDPR-compliant @GDPR-data-ethics data collected ethically
- Contains realistic, and preferably medical data
- Is representative of the user base of the technology
This last point is the hardest to handle, as most facial emotion recognition (FER) datasets simply are not representative. This can be seen in @racial-composition, @gender-composition, and @source-composition.
#figure(
image("racial-composition-dataset.png", width: 99%),
caption: [Racial composition in common FER datasets with "White" (in red) being the majority class @Dataset-analysis-paper.],
) <racial-composition>
#figure(
image("gender-composition-dataset.png", width: 99%),
caption: [Gender composition in common FER datasets with "Male" (in red) being the majority class @Dataset-analysis-paper.],
) <gender-composition>
#figure(
image("source-distribution.png", width: 98%),
caption: [Source distribution of FER datasets. North/South America, Asia and Europe make up 87.5% of all frequencies @Dataset-analysis-paper.],
) <source-composition>
Some datasets are made to be representative, however these tend to be much smaller compared to mainstream ones like AffectNet. Hence training a model solely on these is not a viable option.
To deal with this issue, we decided on aggregating multiple datasets to create a more representative one. We chose this option since it ensures a decent quality of data, whilst taking up much less time and resources than creating creating a dataset from scratch. We will document our dataset using the structure given in @Datasheet-for-dataset, but removing some sections like "Data Collection Process" and "Data Preprocessing".
Algorithms in @Dataset-analysis-paper will be used to measure the bias in our new dataset.
== Risk and bias mitigation measures
When training the model, we resort to the process in @emotion-recognition-process.
#figure(
image("training-process.jpg", width: 100%),
caption: [Process of training an emotion recognition model to be used for our model from choosing a dataset to outputting a verdict @Emotion-recognition-meta-review.],
) <emotion-recognition-process>
For risk and bias mitigation during the last four steps of @emotion-recognition-process, we look to @bias-sources-diagram.
#figure(
image("bias-mitigation-model.png", width: 100%),
caption: [Potential areas of bias during the model training and implementation process @Sources-bias-ML.],
) <bias-sources-diagram>
We will now analyze a source of bias shown in @bias-sources-diagram.
Learning bias is an issue where the model is optimized for a specific metric, like accuracy, while disregarding fairness metrics like f1 score, precision or recall.
To mitigate this, we can assign different weights to metrics depending on their importance. For our use case (medical diagnosis), precision would be valued more, as a false-negative output could be life-threatening. Pharmaceutical companies would be most interested in mitigating this bias, as they require the model's data to be as accurate as possible.
Other sources of bias can be mitigated in a similar and relatively simple manner, as long as model engineers are aware of them.
Another method of mitigation is seen in @Gender-shades, where the model is tested on a predefined groups, such as men and women, light and dark skinned individuals, etcetera. Afterwards, the performance for each group is listed out for comparison purposes. An unbiased model should perform equally well on every group. Note that while useful, this is not a complete solution, as it is impossible to test the model on every possible group. This is useful for medical institutions as they require the model to be as unbiased as possible for the equal treatment of all patients.
After training the model, we aim to document the process in a model card, which has the added benefit of increasing transparency @Model-cards. This would greatly benefit policymakers as they can quickly grasp key information about the model, allowing more informed decision-making on how to regulate such technologies. Greater transparency would also help with explainability, which insurance companies are interested in.
== Critical assessment and limitations
The recommendations given in this section aims to provide an unbiased and fair model using well-researched methodologies, however there are clear limitations.
The main issue is the lack of empirical investigations. The values identified in @ethical-impact-assessment-hospital are purely speculative, and may not reflect the actual views of the stakeholders. Seeing as this entire section is based on these values, the entire process may be flawed. There is a simple solution to this, however, which is to carry out empirical investigations and update our process accordingly.
An issue which is not as easily solved is with regards to the dataset. Aggregating multiple datasets for better representation is a good idea, but it is not perfect.
#figure(
image("bias-mitigation-data.png", width: 100%),
caption: [Potential areas of bias during the data collection process @Sources-bias-ML.],
) <bias-sources-data-diagram>
Bias can be introduced at every step of data collection, but as we do not have control over the original datasets, we cannot mitigate these biases. The only solution, besides creating a dataset from scratch, is to be aware of these biases and to document them in the model card.
In this paper, we cover the ethics of the technology, but failed to provide any implementation details, such as providing what algorithms to use since there are plenty of existing resources on this topic @Emotion-recognition-technique-1@Emotion-recognition-technique-2@Emotion-recognition-technique-3@Emotion-recognition-technique-4. Regardless, before any definitive recommendations is made, it would be helpful to cover these in more detail. |
|
https://github.com/antran22/typst-cv-builder | https://raw.githubusercontent.com/antran22/typst-cv-builder/main/lib/resume/experiences.typ | typst | MIT License | #import "@preview/cmarker:0.1.0"
#import "./components.typ": *
#import "../util.typ": *
#let ResumeExperienceSection(experiences) = [
#stick_together(
threshold: 60pt,
[= Experience],
grid(
columns: (1fr),
rows: (auto),
row-gutter: 24pt,
..experiences.map(exp => {
ResumeEntry(
title: if "url" in exp {
link(exp.url)[#exp.company]
} else {
exp.company
},
title-r: exp.position,
subtitle: exp.date,
subtitle-r: exp.location,
)
ResumeItem(
cmarker.render(exp.summary)
)
})
)
)
] |
https://github.com/jbirnick/typst-headcount | https://raw.githubusercontent.com/jbirnick/typst-headcount/master/example.typ | typst | MIT License | #import "@preview/headcount:0.1.0": *
#import "@preview/great-theorems:0.1.0": *
#show: great-theorems-init
#set heading(numbering: "1.1")
// contruct theorem environment with counter that inherits 2 levels from heading
#let thmcounter = counter("hello")
#let theorem = mathblock(
blocktitle: [Theorem],
counter: thmcounter,
numbering: dependent-numbering("1.1", levels: 2)
)
#show heading: reset-counter(thmcounter, levels: 2)
// set figure counter so that it inherits 1 level from heading
#set figure(numbering: dependent-numbering("1.1"))
#show heading: reset-counter(counter(figure.where(kind: image)))
= First heading
The theorems inherit 2 levels from the headings and the figures inherit 1 level from the headings.
#theorem[Some theorem.]
#theorem[Some theorem.]
#figure([SOME FIGURE], caption: [some figure])
#figure([SOME FIGURE], caption: [some figure])
== Subheading
#theorem[Some theorem.]
#figure([SOME FIGURE], caption: [some figure])
#figure([SOME FIGURE], caption: [some figure])
= Second heading
#theorem[Some theorem.]
#figure([SOME FIGURE], caption: [some figure])
#theorem[Some theorem.]
|
https://github.com/Enter-tainer/typst-preview | https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/.github/ISSUE_TEMPLATE/bug_report.md | markdown | MIT License | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior (Library test):
1. Declare a rust test 'fn test_xxx() { ... }' or typescript test 'it_should(function () { ... })'
2. Execute test function
3. See error
Or (Shell code):
1. Attach necessary resources to execute shell code
2. Put down some shell code 'cargo run --bin typst-ts-cli -- ...'
3. Execute shell code
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Package/Software version:**
VSCode version(Help -> About):
```plain
Version: 1.81.1
Commit: <PASSWORD>
Date: 2023-08-09T22:18:39.991Z
Electron: 22.3.18
ElectronBuildId: 22689846
Chromium: 108.0.5359.215
Node.js: 16.17.1
V8: 10.8.168.25-electron.0
OS: Linux x64 6.4.12-x64v4-xanmod1
```
typst-preview extension version: `v0.7.3`
**Logs:**
typst-preview server log(Output Panel -> typst-preview):
```plain
```
typst-preview client log(Help -> Toggle Developer Tools -> Console):
```plain
```
**Additional context**
Add any other context about the problem here.
|
https://github.com/kotfind/hse-se-2-notes | https://raw.githubusercontent.com/kotfind/hse-se-2-notes/master/prob/seminars/2024-10-07.typ | typst | #import "/utils/math.typ": *
= Распределения
#figure(
caption: [Плотность распределения],
image("graph.svg", height: 3cm)
)
#figure(
caption: [Гистограмма],
image("./hystogram.svg", height: 3cm)
)
= Задачи
== Задача
#blk[
В этой задаче я, видимо, неправильно переписал табличку с условием, но
матожидаение считается по-обычному: $M(x) = sum x_i p_i$.
]
Ежедневные расходы 100'000 рублей. Число машин, проданных за день ($x$):
#figure(
table(
columns: 10,
$x$, $1$, $2$, $3$, $4$, $5$, $6$, $7$, $8$, $9$,
$p$, $0.25$, $0.2$, $0.1$, $0.1$, $0.1$, $0.1$, $0.05$, $0.025$, $0.025$
)
)
Цена машины 150'000
$ "П" = 150 x - 100 $
$ M("П") = M(150 x - 100) = 150 M(x) - 100 $
$ M(x) = 0.025 + 1 dot 0.2 + ... = 2.675 $
$ M("П") = 301'100 $
== Задача
#figure(
table(
columns: 7,
$xi$, $0$, $1$, $2$, $3$, $4$, $5$,
$p$, $1/2$, $1/4$, $1/8$, $1/16$, $1/32$, $1/32$,
)
)
$ M(xi) = 0 + 1/4 + 1/4 + 3/16 + ... = 31/32 $
== Задача
#figure(
table(
columns: 3,
$X$, $a$, $-a$,
$P$, $1/2$, $1/2$,
)
)
$ M(x) = 0 $
$ D(x) = M(x^2) - (M(x))^2 = a^2 - 0 = a^2 $
== Задача
$ n = 10'000; p = 0.2 $
$ x ~ "Bi"(n, p) = "Bi"(10'000, 0.2) $
$ M(x) = n p = 2'000 $
$ D(x) = n p q = 1'600 $
$ sigma(x) = 40 $
== Задача 11
$ x ~ "Bi"(1; 1/2) $
$ (M(x))^2 = (n p)^2 = (1 dot 1/2)^2 = 1/4 $
$ D(x) = n p q = 1 dot 1/2 dot 1/2 = 1/4 $
$ D(x) - (M(x))^2 = 0 $
== Задача 28 (а)
$ p = 0.3 $
$ n = 200 $
$ x ~ "Bi"(200, 0.3) $
$ M(x) = n p = 200 dot 0.3 = 60 $
$ D(x) = n p q = 42 $
|
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/023%20-%20Oath%20of%20the%20Gatewatch/005_Up%20in%20Flames.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Up in Flames",
set_name: "Oath of the Gatewatch",
story_date: datetime(day: 20, month: 01, year: 2016),
author: "<NAME>",
doc
)
#emph[<NAME> arrived on Zendikar just as ] all hell was breaking loose#emph[. The demon Ob Nixilis had regained his Planeswalker spark, awakened a titan, and caused the destruction of Sea Gate. Now two Eldrazi titans roam free on Zendikar, and the Zendikari are scattered. Chandra is committed to reuniting with her compatriots, but in all the chaos, she has yet to locate them—or the vengeful demon.]
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Chandra scrambled up a rock outcropping, looking for two particular faces, but she saw only destruction and retreat. Kozilek and Ulamog were wandering the landscape now, cutting two ravines of blighted land behind them. They didn't flinch at her blasts of fire, but she got the sense that they would simply turn and devour her if she made a big enough nuisance of herself.
Swaths of corruption crisscrossed the battlefield, marking the travels of spawn. Eldrazi broodlings were running out of humanoids to chase. Many of the Zendikari had fled when Kozilek rose and the sea wall broke. Many had been consumed. There was no sign of the faces Chandra sought.
There was also no sign of the demon whose interference led to all of this.
"Gideon?" she shouted once, twice, three times. Louder each time, with a growing edge in her voice.
A chittering-crackling sound announced a fresh swarm of Eldrazi skittering over a hill toward her. They would be here soon. Too many to take on by herself.
She closed her eyes like fists and thought, "#emph[Jace?] " as loudly as she could. She instantly felt ridiculous.
There was no reply, mental or otherwise.
Chandra narrowed her eyes at the oncoming swarm. They had too many knees and elbows, with unblinking eyes positioned at the joints. She glanced behind her, but the land dropped away into a glimmering valley of Eldrazi-ruined ground. She stood tall, feet spaced wide, in front of the swarm. She snapped her goggles down over her eyes and tilted her head to one side so that her neck cracked.
As she took her stance, her foot tapped something metal, and she glanced down. It was a large buckler shield, wedged in a depression of mud. She cast a glare at the line of Eldrazi, and deliberately bent down and picked up the shield without breaking eye contact. It was dented, but she recognized it.
#figure(image("005_Up in Flames/01.jpg", width: 100%), caption: [Gideon's Phalanx | Art by <NAME>], supplement: none, numbering: none)
She swallowed hard. She pressed the shield against her forehead for a moment, and something prickled in her throat. She squeezed the metal buckler in her fists until the edges crinkled.
For some reason the faces of her parents flashed in her head. She never understood why she would think of them at odd times—they just came to her. They never aged in her mind; they were still the same age as when she saw them last, when she was still a child on Kaladesh. She didn't think of their last moments; she didn't see her father falling to his knees with a knife in his gut, and she didn't see her mother's shawl in the mud, its edges burned as the village burned around it. She just saw them looking at her with parents' eyes, kindly and proud.
She gnashed her teeth. She had come to Zendikar entirely too late.
A woman's voice came from behind her, down in the ravine. "Hey, fire mage."
She turned.
"Is that the Commander-General's?" A tall, plate-armored woman crouched in the ditch of Kozilek's corruption. Pressed against the wall beside her were a small party of Zendikari—mostly scouts and foot soldiers, many of them wounded.
#figure(image("005_Up in Flames/02.jpg", width: 100%), caption: [General Tazri | Art by <NAME>], supplement: none, numbering: none)
Chandra eyed the encroaching swarm again, watching them skitter slowly toward her. She slipped down into the ravine and held up the shield. "It's Gideon's. Did you see what happened to him?"
"He was battling the demon," the woman said. "He went down, hard."
Chandra's shoulders dropped.
"But he's alive," the woman added.
"<NAME>—" one of the scouts began.
"He's alive," she repeated.
"<NAME>," Chandra said, "it's urgent I find him."
"We need him too," Tazri said. She tore a strip of bandage with her teeth, and wrapped it around the leg of one kor scout, then tugged it taut. "The demon took him, and two others."
"#emph[Took] him? Where?"
"He was heading toward a cavern," said another one of the scouts. His eyes and fangs marked him as a vampire. He pointed in the direction of some rocky bluffs in the distance. "The mouth is there, in the cleft between those two peaks. Only a handful of miles, by air."
"Thank you," Chandra said. She tucked the buckler onto her arm and grabbed hold of the shimmering minerals to climb out of the ravine.
"Wait," Tazri said. She tilted her head toward her group. "I have wounded. We're in no shape to lead a rescue party now."
Chandra wondered what exactly that had to do with her. "I'm going to him. Stay here."
"What about the swarm?" Tazri asked.
Chandra peeked her head out of the ravine. The Eldrazi were still making a direct line for them. "I'll lead them away."
Tazri looked Chandra up and down, frowning. Then she produced a heavy mace and nodded. "We'll cover your exit. Thank you."
"Just stay down, and stay safe."
Chandra clambered up out of the ravine. She stood up, dusted herself off, and ignited all at once.
Her hair blazed to life, and her hands glowed hot. A muscle-tensing, punch-throwing anger warmed her limbs. The anger was familiar, comforting, and she leaned into it like a dependable friend. Chandra twirled her body, and in her spinning, the air around her caught fire. A roaring cyclone made of churning flame whirled across the field ahead of her, and she chased it as it tore through the swarm of Eldrazi. Eldrazi parts flew high into the air, and bits flopped down onto the ground, smoking.
The swarm of Eldrazi made a harsh fizzing sound, and refolded themselves to orient themselves toward her, rather than toward Tazri's soldiers. Her pulse quickened. Her hair burned hotter.
"That's right," Chandra said. "I'm a glorious beacon of mana and light, you bastards."
She turned toward the bluffs. As she ran, the flame of her hair streaked behind her like a banner.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
She vaulted over crags and hopped small fissures, checking behind her without stopping. From here she could see that Kozilek's spawn carried devastation along with their general unsettling grossness. A wake of ruin spread out behind the swarm, with abnormal quadrangular patterns where the living land of Zendikar used to be.
#figure(image("005_Up in Flames/03.jpg", width: 100%), caption: [Warden of Geometries | Art by Jason Felix], supplement: none, numbering: none)
She stayed hot and ran on, throwing blasts of fire behind her in furious jets. Occasionally she spun, hurling a barrage of fire, taking out one or two more of the Eldrazi and goading on the rest, drawing them away from Tazri's wounded.
After several miles, the swarm was falling behind. She could barely see their hovering black plates in the distance, and she had advanced beyond their grotesque swath on the landscape. Chandra focused on the two peaks ahead.
She reached a crest, and the land fell away, sloping down to a huge cavity in the earth: a cavern's mouth, surrounded by spiky hedrons that all pointed inward, toward the depths of the cave.
As she approached, she saw that the way was blocked. The entrance was entirely covered over with a newly-forged crust, gleaming in square spiral patterns. This was the cavern where the demon had taken them, but the iridescent crust blocked her path.
Chandra's breath caught in her chest. In the twisted surface, she saw a broken reflection. It was not of her own face, though, but of her mother and father. Their eyes were tender. Their mouths moved and they nodded reassuringly, but their faces moved strangely along the planes of the surface, and she couldn't make out what they were saying. She reached toward them, but the image broke into a million angles. Without her permission, her brain turned to thoughts of her mother's burned shawl on the ground outside a Kaladesh village, and of her father's apologetic eyes as he sank to his knees, hands on his stomach to hold the blood in—
She gritted her teeth and pressed her fists into her eye sockets. When she unclenched and opened her eyes, the only thing she saw reflected in the spirals was herself, ringed in fire, her eyes two hot coals. She turned back to the barrier. She glanced at her hands. They were not child's hands, like they had been when her parents died, when her Planeswalker spark first ignited. They were the weapons of a pyromancer. She clutched her hands together, interweaving the fingers to form a single fist. She raised her arms, gathering a white-hot ball of fire around her hands. She said nothing as she faced the distorted spirals and smashed at her own reflection.
The crust exploded. A cloud of fragments and clods of earth rained down. She had intended to punch a hole just large enough for her own ingress, but instead she had crumbled the entire barrier, leaving the cavern mouth open wide.
Inside, the cavern was etched with more of the patterns of ruin. The bowels of the earth here had been scoured, depleted, transformed.
Chandra remembered the demon calling the titan Kozilek to rise, laughing coldly at the armies below him, laughing at this entire world. She knew Kozilek wasn't here. This was the lair of a demon.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Up in Flames/04.jpg", width: 100%), caption: [Chandra, Flamecaller | Art by Jason Rainville], supplement: none, numbering: none)
Chandra kept anger close as she climbed and descended through meandering passages. The spiral-etched ruins around her shimmered weirdly in the light of her fire.
She could hear a deep, unhurried voice intoning in the chamber ahead. "...lifetimes of agony on this wretched world," the voice was saying. "I've far less time to share with you, but I assure you, no less pain."
When she emerged into the chamber, she saw the three of them hanging in midair, suspended by magic like limp marionettes: Gideon, his chin dropped onto his chest, with lines of agony creasing his forehead. Jace, his head lolled to one side, his hood shrouding his face. And an elf woman, her braid and arms hanging limp, her eyelids parted to reveal slitted, unseeing, green-on-green eyes, with a tear streaked down her cheek to her chin. Their bodies dangled there in air, surrounded by coils of enervating magic. Three or four Eldrazi drones of Kozilek's lineage chittered nearby, not even turning their bladelike projections to notice her.
#figure(image("005_Up in Flames/05.jpg", width: 100%), caption: [Remorseless Punishment | Art by <NAME>], supplement: none, numbering: none)
"I'm sorry, did you get the impression you were invited?" The demon, the source of the deep, echoing voice, emerged from a side passage. His body looked like raw black tendon had melded with fragments of armor, with a hellish internal heat showing through at the seams. His eyes were aglow with hate and amused interest somehow at once.
"I'm inviting myself," Chandra said. "Free them or die."
"I wasn't aware they had a sidekick," said the demon.
Chandra curled her fingers into a fist, and threw herself and her magic at her foe. The demon deflected her fiery blow with his forearm, raising tattered wings like a dragon. He smiled or grimaced, showing ranks of sharp teeth.
Chandra recovered from the deflection. She pivoted, whirled, and lobbed a volley of darts of fire at the demon's eye.
The demon shielded his face with a wing, shrugging off the worst of it, but he grunted with the effort. He swiveled on one foot and backhanded Chandra with his claw.
Chandra slammed against the wall, knocking her skull against stone. She coughed, doubled over and struggling for breath. Nearby, the Eldrazi drones flexed their pincers, but did not advance toward her.
She spat blood and regained her stance. She forced her fire to grow larger, letting the pain feed her magic. Her hands extended into long whips of fire. She drew back her arm, gathering up anger. The crackling heat of her fist distorted the cavern air.
She leaped, lashing out with two quick blasts of fire. Deflected.
She continued her leap into a physical attack, swinging down with Gideon's buckler as a blunt weapon. Clanged off of the demon's pauldron.
She recovered to one side and spun. Two more blasts from her knuckles, and a whoosh of flame shot forth from both palms. Caught in the demon's claw, and crushed to nothing.
He swung at her, and although she dodged her head out of the path of his claw, she still felt piercing pain raking across her face.
She gasped as the skin of her face stung like acid. Her fire flickered, and she shook her hands as if to shake more fire into them.
#emph[No! Stay lit. Burn him to cinders. Pain is fuel.]
She brought her fists close to her chest, collecting all of her fire together at her core. She blasted everything she had at him, not a single flash but a sustained torrent of fire, all of her rage pressurized and forced into a cone of boiling air—
#emph[WHOOOOSH—]
The demon walked through her spell toward her. The fire charred his chest, but he raised his arm and grabbed Chandra under the chin, raising her up by the throat.
#emph[—GLURK] .
Chandra's spell broke. She struggled, grabbing at his claw, prying at the fingers. "Bastard," she choked out.
The demon was smiling, fangs bright. "Nothing so far has managed to stop me, little candle. And it's not going to be you."
She wrestled his fingers loose, and bit through the skin of his hand. He dropped her and she collapsed onto her hands and knees. She forced herself to lift her head. "It's going to be me," she muttered. She willed her legs to stand her back up, but one leg just trembled instead of complying.
The demon tilted his head in mock concern. "But you're burning so quickly, little candle. What happens when you sputter out?" He summoned a spell and shoved it forward with a claw.
Chandra's body twisted as the demon's magic tore at her. It felt like erosion, like years of time tearing at a mountainside, but accelerated into a horrid moment. She felt enervated, as if a lifelong, debilitating illness had gripped her all at once. Her limbs weighed a ton each.
Chandra's head wanted very desperately to dip down, to make contact with the stone floor. But she did not let it. Her arms shook, holding her body up like brittle columns. Her vision swam, and the cavern became vague shapes and shadows.
The cavern grew darker. She could feel herself flickering, dimming by degrees. She was going out.
#emph[NO. STAY LIT.]
She concentrated on her hands, the palms ground into the cavern grit. If her hands didn't go out, she still had life in her. Weapons of a pyromancer.
She sensed the demon come quite close to her, a dark blob by her ear. "Are you supposed to be the rescuer?" There was a tsking sound. "But—I don't understand. What good would #emph[you] be to anyone?"
Chandra demanded her eyes stay open, that her head stay upright. Her muscles shuddered with effort.
"And now I have to punish you, as well. I wouldn't have wanted this. But my hand is forced. Lie down."
Chandra slowly turned her face toward him. She could barely see through wet lashes, through her clouded vision.
His splotch of a face altered, became kindly. Became familiar.
"#emph[Chandra, honey] ," said the vague face, in her father's voice. The voice had her father's kindness, his warmth, his steady patience.
She didn't want this. She didn't ask to see him. Not now.
"#emph[Give up] ,#emph[ my Chandra] ," he said. Chandra winced. "#emph[You've done enough. Lie down. Lie down on the ground] ."
Chandra squinted at the shapes of her father's dim face. Gravity pressed down on every square inch of her, sapping her rebellion. Her eyes brimmed.
"#emph[Chandra, my dear daughter] ," said the face, now in her mother's voice, her mother's loving, iron-strong voice. "#emph[You've done enough. You've failed them, Chandra. Give up now. Fall onto the ground." ] Chandra shuddered. Her elbows bowed. "#emph[You've failed them, Chandra. Just like you failed us] ."
Chandra's body wanted to exhale, wanted to cough her life out of her chest, wanted to let go. She wanted to sneer at the face, to mutter a string of curse words at it, but she couldn't summon the strength. The world closed in.
The cavern, the face, everything went dark. Her mother's face disappeared, and she could only see streaks of the demon's disembodied, hellish eyes in the gloom.
Her fire was out. Her hands were extinguished. She could feel her hair hanging down around her face, clammy with sweat.
"#emph[Chandra] , #emph[the...dr...] " said the voice. It had a weird echo now, not like a whisper in her ear—it was, somehow, even closer than that. "#emph[The dr...oans, Chhhandra] ."
"Don't take your defeat personally," said the demon, his voice now undistorted, with its usual callous edge. "I tend to bring out the weakest in people."
#emph["<NAME>...his Eldr...azi drones] ," said the echoing voice. It sounded like a headache. It also sounded distinctly not like her parents. "#emph[Blassst the. Drones] ."
Jace. Jace was—conscious!
"#emph[With ffff] ," Jace slurred in her mind. "#emph[Ffffi. Fiiiyer.] "
Jace was—somewhat conscious!
"#emph[I can't] ," Chandra thought dully.
"#emph[You damned...] " Jace was struggling to form the words in her head as much as she struggled to absorb them. "#emph[You damned well c-can. Get up.] "
"Don't," Chandra said aloud. Her actual voice sounded odd to her own ears. Blunted. She was probably drooling.
"What's that now?" the demon asked. "Please don't tell me you're about to plead for a stay of execution. It insults us both."
"Don't...tell me," she croaked. Her hands became fists, and her fists became fire, illuminating the chamber again. "Don't tell me," she repeated, stumbling to her feet, swaying.
The figure of the demon swam before her. She could see the amusement in the way he shook his head just slightly, and the malice in the way he summoned one final, dark knot of energy in one claw. "Lie #emph[down] , little candle," he said.
"Don't...tell me. What. TO DO."
Chandra lurched forward with her fists. The demon merely tilted his head to avoid the assault. But her hail of fiery missiles arced toward their intended targets, slamming into the Eldrazi drones that lurked near her friends. The drones convulsed as they burned, their skin crackling as miniature suns consumed them.
#figure(image("005_Up in Flames/06.jpg", width: 100%), caption: [Devour in Flames | Art by <NAME>], supplement: none, numbering: none)
Gideon, Jace, and the elf collapsed to the floor in a heap. And then they disappeared.
The demon snarled at the disruption of the imprisonment spell, and the vanishing of his prey. He turned back to Chandra and reared back to loose his deathblow.
Chandra winced, unable to summon the strength to dodge, or even collapse. But when she was still alive a heartbeat later, she glanced at the demon. He was staring around, speaking dark words in a growing fit of fury.
"#emph[You've invisible, as far as he can see] ," said Jace's voice in her head. "#emph[For now] ."
Chandra staggered away, leaning against the cavern wall as the demon searched for them.
"#emph[The others. Are they alive?] " Chandra asked in her mind.
"#emph[Barely] ."
"#emph[We'll have to take him on. On my signal. Ready?] "
"#emph[No! We are nowhere near ready. We don't have much left in us] ."
Chandra made fists. "#emph[How long before he figures out we're still here? We can do this.] "
"#emph[Chandra. We've been—tormented. For...I don't know how long] . #emph[Felt...long] ."
Chandra didn't like the uncertainty in Jace's thoughts, the frank admission of pain. The demon was kicking and stomping over the cavern floor. He couldn't see them, but there was no way he was fooled into thinking they had disappeared for good.
Chandra squared her shoulders. Fire flickered from her fingertips, growing into palm-sized spheres of heat. #emph["All the more reason to take him down] ."
Jace's hesitating reply: "#emph[They need rest] ."
"#emph[Jace. We came here to do a job. That job's not done. Is it.] "
"#emph[Chandra] —" Jace thought at her.
Chandra's fire grew. "#emph[Is it?] "
"#emph[Chandra, I can't—] "
The others reappeared in a flash, the concealment spell broken. Jace and the elf woman had moved further back in the chamber from where Chandra had seen them last. They looked conscious but weak.
Gideon had reappeared too. The demon already had him by the neck, raising him up off his feet.
"Gideon!"
The demon turned to face Chandra and grinned wide, a thudding laugh rising from deep within him. The sound held the built-up malice of being trapped on Zendikar for eons—and the satisfaction of finally being repaid for it.
"Your friends should thank you, little candle," said the demon. "Not for giving them hope—that was, in fact, quite cruel of you. But no, without you, they would have had no audience for their deaths." The demon squeezed on Gideon's throat, and Chandra could hear bone cracking.
Chandra couldn't budge. She knew any step she might take would just hasten Gideon's demise.
But she saw that Gideon was struggling. His hands clamped onto the demon's, trying to break free, and even in his weary state, sparks of light protected his flesh. She saw Jace's eyes glow with azure smoke, conjuring some mind-piercing spell even as he fought to remain standing. And she saw the elf woman's hair blow back as she summoned up desperate magic. Vines of mana twisted out of the ground and flowed into her.
#emph[I haven't failed them. We haven't failed each other.]
Chandra stomped on the ground, and a streak of fire raced along from her foot to the demon, setting the cavern floor on fire beneath his feet. Gideon elbowed the demon's arms and kicked at his chest, wresting himself free and rolling away just as fire engulfed the demon.
The demon emerged surrounded. Gideon now wielded his sural, Jace had a spell at the ready, and the elf's eyes were glimmering with mana.
"All together!" Gideon shouted, and Chandra knew exactly what he meant.
All four of them attacked the demon simultaneously. Flashing whip-blades and elemental vines and punishing mind magic coincided with Chandra's from-the-gut rush of fire.
#figure(image("005_Up in Flames/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The demon grimaced, doubling his wings over himself for protection. He attempted to blast back with a spell, but Jace was too quick for him, and the demon's spell dissolved just as Gideon slashed at him from another direction. He lashed out toward the elf, but Chandra cut him off with a column of flame.
The demon clapped his wings together, buffeting Chandra back against a wall and giving him time to kick Jace in the gut. But Gideon tangled the demon's leg in sural blades and yanked, combining with Nissa's vines to topple him to the ground.
Chandra made eye contact with Gideon as she unstrapped his buckler from her arm, and he nodded. She tossed the shield into the air and Gideon slid it on in one motion, and he elbow-dropped the metal shield onto the prone demon's cranium, just as Chandra melted the metal of his helmet to putty. The crack was audible.
The demon roared and burst back up to his feet, throwing Gideon off of him, wobbling his head slightly. Chandra gathered a barrage of fire to knock him off his feet—but agony surged through her veins.
"Enough," the demon said through his fangs. Chandra's heartbeats were jagged pulses of pain, like her bloodstream had become needles.
Jace became a coterie of four Jaces, each one seemingly drilling into the demon's mind, while Gideon shoulder-rammed into the demon's chest. Chandra felt the elf woman's hand on her arm, and at her touch, Chandra's heart soothed, regaining its natural rhythms.
"Prepare something big," whispered the elf. "We'll tell you when." And she spun to lash at the demon with a swirl of living magic.
Between the multiple illusionary Jaces, the slashing physical prowess of Gideon, and the relentless wild magic of the elf, the demon was doing more dodging than attacking. He grimaced, claws holding his head, using his elbows and wings to minimize incoming attacks while Jace's magic pummeled his mind.
With the demon occupied, Chandra sculpted a tiny fire cyclone out of the air. She spun with it, letting it grow as she fed its fire, building up strength. She was immersed in it, consumed by it, dancing with the hot spiraling winds as part of it.
"#emph[Ready?] " came Jace's voice in her head.
"Ready!" Chandra shouted aloud.
The others simultaneously dodged out of the way, leaving Chandra a clear shot at the demon. She loosed her cyclone with a shout, and it tore across the chamber, slamming into him and blasting him against the wall.
Chandra's spell dispersed. The demon was charred, smoking, propping his shoulder against the wall of the chamber. His hell-coal eyes looked to each of them, one by one. "Well done," he said. "Well done. You've chosen to spend your efforts to defeat me, and you have. But every moment you've spent on me, you've allowed Zendikar to suffer. So you've still, of course, lost."
Chandra and the others looked at each other.
"I promise you this," the demon said in a low snarl. "I will walk every plane, scour every pathetic world, until I find a way to bring fitting punishment down upon your misguided lives."
The air folded in on itself, swallowing the demon, and he was gone.
Chandra stood with the others. Jace's hair was ruffled boyishly, belying his usual air of mystery. Gideon looked battered, but he had a grin on his face that made his facial hair crooked.
"Knew you'd come," he said.
"But I told you no," Chandra said with a raised eyebrow.
"I knew," Gideon said.
"I'm Nissa," said the elf.
"Chandra," she said, offering her palm.
Nissa clasped Chandra's hand in both of her own. Her fingers were soft, and her green-tinted eyes looked as deep as mossy wells. "Thank you."
They all heard an echoing, scuffling, chittering sound. They turned to look at the passageway that led into the chamber. The Eldrazi swarm, the same horde that Chandra had lured away from Sea Gate, came skittering into the chamber, clambering on every surface.
Chandra looked to the spawn, and back to the others. Four nods. And like a chord played in harmony, four spells crackled to life.
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/page-style_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Empty with multiple page styles.
// Should result in one eastern-colored A11 page.
#set page("a4")
#set page("a5")
#set page("a11", flipped: true, fill: eastern)
#set text(font: "Roboto", white)
#smallcaps[Typst]
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/numbers_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test the `str` function with floats.
#str(12.0) \
#str(3.14) \
#str(1234567890.0) \
#str(0123456789.0) \
#str(0.0) \
#str(-0.0) \
#str(-1.0) \
#str(-9876543210.0) \
#str(-0987654321.0) \
#str(-3.14) \
#str(4.0 - 8.0)
|
https://github.com/lucannez64/Notes | https://raw.githubusercontent.com/lucannez64/Notes/master/MPSI.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: "MPSI",
authors: (
"<NAME>",
),
date: "30 Octobre, 2023",
)
#set heading(numbering: "1.1.")
Physique:
#link("http://benjamin.mollier.free.fr/index.php?page=Cours&annee=2023")[1]
#link("https://youtube.com/playlist?list=PL2XGPADmCHWmSXGGcTVA3ZvW8tMc2zIkb&si=W31cJing_28A5N8g")[2]
Maths:
#link("Maths_Sup.pdf")[Maths Sup]
#link("http://christophebertault.fr/cours-et-exercices/")[1]
#link("https://gerardlavau.fr/cpge/cpge1/")[2]
#link("http://melissa.inglart.free.fr/index.php?option=com_content&view=category&id=19:cours-et-exrcices&Itemid=29&layout=default")[3]
#link("http://desaintar.free.fr/chapitres.php")[4]
#link("http://833duparc.free.fr/tableau2_MPSI.html")[5]
|
|
https://github.com/Shuenhoy/modern-zju-thesis | https://raw.githubusercontent.com/Shuenhoy/modern-zju-thesis/master/utils/appendix.typ | typst | MIT License | #let appendix(level: 2, body) = {
counter(heading).update(0)
show heading: set heading(
numbering: (..numbers) => {
let clevel = numbers.pos().len()
if (clevel <= level) {
return none
} else {
return numbering("A ", ..numbers.pos().slice(level))
}
},
supplement: [附录],
)
body
} |
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/tests/typ/bugs/table-lines.typ | typst | Apache License 2.0 | // Ensure no empty lines before a table that doesn't fit into the first page.
---
#set page(height: 50pt)
Hello
#table(
columns: 4,
[1], [2], [3], [4]
)
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/007%20-%20Theros/009_The%20Sea%20God's%20Labyrinth%2C%20Part%202.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"The Sea God's Labyrinth, Part 2",
set_name: "Theros",
story_date: datetime(day: 20, month: 11, year: 2013),
author: "<NAME>",
doc
)
#emph[Diary of Solon—Scholar, Athlete, and Champion of Oxus]
=== Day Ten
The labyrinth seems to be decomposing around me. The ground has become muddy and bog-like. I have had to wade through standing water in places and the going has been both slow and tense. The bogs are full of poisonous and venomous creatures. The sound of frogs has been my constant companion all day, and I narrowly escaped what would surely have been a painful death at the fangs of a large serpent as I waded through a knee-deep swamp. Having my long knife already in hand was my only saving grace.
#figure(image("009_The Sea God's Labyrinth, Part 2/01.jpg", width: 100%), caption: [Erebos's Emissary | Art by Sam Burley], supplement: none, numbering: none)
The labyrinth itself has become overgrown and broken, with many holes in the wall left by fallen, rotting trees. Obstacles are everywhere. I have had to step carefully to avoid quicksand, poisonous plants, and snakes. I am thankful for my pole.
Unfortunately, my food rations are almost gone. I am weary from hunger. I tried to eat some berries but they were bitter with poison. I was afraid to eat the snake I killed for fear of poison as well, so foul was its entire visage. I saw a large water rat, but have no arrows, so I was unable to hunt it. Without more food, I will die in this maze, and without arrows, my chances of a successful hunt are small.
I am soaked from head to toe and shivering as the sun passes behind the walls. I have found a dry mound of grass in the middle of the bog and tonight I am going to have a fire to dry my clothes and armor.
I also plan to forge an arrowhead from the tip of the enchanted dagger I recovered from the body of Praxitelius. I have collected a straight length of hard wood for a shaft, cut from a black ash tree, and the feather of a waterfowl I found on the ground.
From the gods' voice to my ears I pray the fire will not attract snakes, beasts or worse.
=== Day Eleven
Thank Thassa for the enchanted dagger I used to forge my arrowhead! The arrow I crafted last night has saved me, at least for a while longer. It has brought me sustenance.
Today, after eating the last of my cheese and bread, I turned the corner of the maze, and there before me stood a hart, grazing on leaves. I nocked my homemade arrow and shot without hesitation. My shot was true. I followed the blood trail of the wounded animal for a few minutes until I found it laying in the path, breathing rapidly, eyes glazed. I killed it with my knife and field dressed it.
#figure(image("009_The Sea God's Labyrinth, Part 2/02.jpg", width: 100%), caption: [Burnished Hart | Art by Yeong-Hao Han], supplement: none, numbering: none)
It is far too big to take with me, so I butchered as much as I could carry and moved on quickly, for fear of the carcass attracting unwanted attention. Luckily, I was able to retrieve my arrow as well. This arrow is a blessing. One that I am deeply thankful for.
Tonight, I will again have a fire to cook the meat, in the hopes of preserving it for as long as I can. Death has been thwarted once more. The closer I get to my goal, the more I intend to live to see it through.
=== Day Twelve
My strength restored, I have pressed on. This journey has taken far longer than I had anticipated. Even if I find the center, I know not how I am to make it back alive. The task seems impossible, but I have trained both physically and mentally, and I will proceed one day at a time.
The labyrinth has once again changed its form. As I wandered through the day, the maze became drier and rockier. I have left the wetlands behind and entered an area more desert than grassland. The vegetation morphed from deciduous to coniferous and then—a surprise—I came upon walls of ancient rockwork. The ground is rocky and sandy, the climate arid.
The stone walls rise well above my head and are composed of finely cut stone blocks and sealed with cunning mortar work, such that I can find no purchase with which to climb them. I am truly inside a canyon. Although I no longer have to fear wading through a bog of venomous creatures, I am now experiencing claustrophobia such as I have not felt so far.
Although I have nothing left to eat except a few strips of decomposing meat, at least my pack lies spry on my back. If only I could rid myself of the foul reek of clothing soaked in sweat and bog water.
=== Day Thirteen
Eureka! I have come across a section of wall that has crumbled from disrepair. I was able to climb to the top. From that vantage, I have mapped my way to what I believe is the center of the labyrinth. I am so close I can hardly believe it. I should be able to breach the center within hours. I surveyed the entirety of the maze from atop the wall. I am astounded at how vast it truly is.
To the east, it is shrouded in mist, presumably from the sea. Should I find the center, and the prize that I pray awaits me there, I will attempt to exit the labyrinth from the west, the way I have come.
Although I hope to find a way around the dreaded underground...
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
My hand is shaking so much I can hardly keep ink on my quill. I believe I have passed the labyrinth's ultimate test—I have slayed a minotaur.
#figure(image("009_The Sea God's Labyrinth, Part 2/03.jpg", width: 100%), caption: [Minotaur Skullcleaver | Art by <NAME>mer], supplement: none, numbering: none)
I came upon it, or rather, it came upon me, in a particularly twisted section of walls. The beast was horrible. Gigantic. Braying and snorting. Wielding a great axe—such that the weight of it alone could have cleaved my entire body. It was so close; I instinctively drew my long knife, although by all rights I should have been paralyzed with fear.
When it hefted its axe in the air to destroy me, I quickly slashed its forearm, hoping to disarm it. The wound, however, was like a scratch to the beast, and I narrowly dodged the fall of the axe, which broke a stone in two.
I turned and ran the way I had come but quickly ascertained that I could not outrun the monster. It was born into the labyrinth, and I am a stranger here. So I latched onto my only hope.
I dropped my knife and drew my bow, the thunderous footfalls of the minotaur closing behind me. I nocked my arrow, my one true arrow, and turned to shoot.
The monster was only steps away and I stumbled backwards, my heel catching on a bit of stone jutting from the ground. I fell backwards. My gods, I thought I was doomed for certain. As the monster loomed over me to finish the deed, I held my breath and loosed the arrow.
It sank straight into the monster's neck, cutting its braying short with a violent silence. The minotaur dropped its axe and grabbed at the wound, blood spraying from between its massive fingers. It fell to its knees, barely an arm's length away. I could smell its hot breath. Its glassy, bulbous eyes rolled into its head and it fell over, gurgling, until it died, its blood soaking the sand between the rocks.
I feel triumphant, yet somehow sad at the felling of this mighty creature. Once I catch my breath I will press on to the center, with anticipation for what I will find there.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
At last. I have reached the center of the labyrinth. It is a large, open square chamber with an arched doorway on each side leading back out to the maze. In the center is a large round well. I was elated to find water, but quickly discovered that it is not fresh water, but salt. I believe it is a blue hole, leading to an underground sea that connects with the ocean to the east.
Far down under the water I can see something shimmering in the depths. I believe it is the artifact I have been sent here to retrieve. I believe it is Thassa's bident, Dekella.
I have also seen creatures swimming in the depths of the hole, and they are calling to me. I am certain they are naiads, emissaries of Thassa herself. I must go to them, for they will help me retrieve what I have come for.
I have dropped my pearl into the watery hole and offered a prayer. I have doffed my armor, clothes, and backpack. I wear only a belt with my knife and waterproof pouch that protects my diary. I am prepared mentally, physically, and spiritually.
I cannot say what will happen next, but I know I must dive into the depths—a final test of my faith.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("009_The Sea God's Labyrinth, Part 2/04.jpg", width: 100%), caption: [Island | Art by <NAME>], supplement: none, numbering: none)
I know not the day, nor my whereabouts. I awoke on a beach this morning, washed up from somewhere beneath the depths. My body is covered in glowing geometric patterns.
I dove into the blue hole, headfirst, and swam down, down, farther that I have ever dared, yet what I thought to be the bident always remained a little farther still. As I ran out of breath, and knew that I was too far down to make it back up alive, I chose to embrace my fate instead of fear it. It was then that the naiads emerged from their hiding places and surrounded me with sweet voices that formed a bubble filled with air around my entire body.
It all seems like a dream now. I am not certain I can even recount it in truth. The water nymphs towed me through the darkness of the underground sea; the only light the cool blue glow of their magic. Eventually, after I know not how long, we entered the Siren Sea, and they took me down into the depths, where only the faintest light could penetrate. Strange and mighty creatures passed by on our way out into the sea, but none molested my procession.
In time, again I know not after how long, Thassa herself approached. Her spindly fins rippled to and fro majestically. The naiads gave way and left me alone before her. She parted the bubble and swam inside, facing me eye to eye. She spoke! Her tongue I could not understand, but the meaning seemed to penetrate my mind—time is long, and the lives of men are but a shadow passing in the night. What came yesterday is soon to be lost, like a mote of dust in the sun. What comes tomorrow is the only mission of our fragile lives.
She reached out to me with a spindly finger and drew a pattern of light over my entire body, etching it into my skin with the sharp tip of her fingernail. And suddenly, she withdrew into the black depths and disappeared as if a dream. That is the last thing I remember.
I have parlayed with Thassa herself, and she has spat me back on dry land, naked and renewed.
#figure(image("009_The Sea God's Labyrinth, Part 2/05.jpg", width: 100%), caption: [Bident of Thassa | Art by Yeong-Hao Han], supplement: none, numbering: none)
I now realize that retrieving Dekella was always a fool's errand. Who were we to think we could possess it? How did we imagine we could wield it? Why did we put our hope in an object when it is we, ourselves, who must shape our fates?
The crucible of the labyrinth has changed me forever. I have been blessed by a god. I will return to my polis and be hailed as a great warrior, but my true gift will be the wisdom to shape a greater future for ourselves—to contribute to our edifice of knowledge.
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-12.typ | typst | Other | // Ref: false
// Destructuring with unnamed sink.
#let (a, .., b) = (1, 2, 3, 4)
#test(a, 1)
#test(b, 4)
// Error: 10-11 at most one binding per identifier is allowed
#let (a, a) = (1, 2)
// Error: 12-15 at most one destructuring sink is allowed
#let (..a, ..a) = (1, 2)
// Error: 12-13 at most one binding per identifier is allowed
#let (a, ..a) = (1, 2)
// Error: 13-14 at most one binding per identifier is allowed
#let (a: a, a) = (a: 1, b: 2)
// Error: 13-20 expected identifier, found function call
#let (a, b: b.at(0)) = (a: 1, b: 2)
// Error: 7-14 expected identifier or destructuring sink, found function call
#let (a.at(0),) = (1,)
|
https://github.com/Ttajika/class | https://raw.githubusercontent.com/Ttajika/class/main/microecon/answer_box.typ | typst | //answerbox.sty (https://hohei3108.hatenablog.com/entry/2022/01/27/005123) をTypstに移植することを目標にする
//#let ansbox_num = counter("ansbox_num")
#let copy_array(height, rows) = {
if type(height) != array {
let heights = ()
for i in range(rows){
heights.push(height)
}
return heights
}
else {return height }
}
#let ansbox(..args, type: "default", daimon: "1", shomon: "(1)", height:1.5cm,content:(), hide-content:false, shomon_width:2em, daimon_width:2em, box_width:1fr, shomon_start:1, inset: 4pt) = {
let list = args.pos()
let rows = list.len()
let heights = copy_array(height, rows)
let box_widths = copy_array(box_width, rows)
//ansbox_num.step()
let row_list = ()
let cur_sho = shomon_start
let total = 0
for i in range(rows) {
let cells = ()
let col_cel = ()
let algn = ()
for j in range(list.at(i)){
algn.push(center+horizon)
algn.push(left)
col_cel.push(shomon_width)
col_cel.push(box_widths.at(i))
cells.push([#numbering(shomon, cur_sho)])
cells.push([#if content != () {if hide-content == true{hide[#content.at(total+j)]}else{content.at(total+j)} }])
cur_sho = cur_sho + 1
}
row_list.push(table(inset:inset,stroke: (x,y) => {if calc.odd(x) {(left:(dash:"dotted"), right:1pt, y:1pt) } else {(x:1pt, y:1pt)}}, columns:col_cel,..cells,rows:heights.at(i), align:algn))
total = total + list.at(i)
}
let colls
show figure: it => {
if daimon != none{
grid(
columns:(daimon_width, 1fr),
grid.cell(rowspan: rows,
stroke: 1pt,
align:center+horizon,
[#numbering(daimon,..it.counter.at(it.location()))],
), ..row_list
)
} else {
grid(columns:(1fr),
..row_list
)
}
}
figure([],kind:"answerbox",supplement: none)
}
= example:
#ansbox(1,4,3)
#ansbox(4,2,3, daimon:"1", shomon:"(a)", height:(1cm,2cm,3cm))
#ansbox(2,3, content:([2],[3],[4],[5],[$
(sum d^3)/(sum d^3)
$]),height:(2cm,auto,auto))
#ansbox(2,3, content:([2],[3],[4],[5],[$
(sum d^3)/(sum d^3)
$]),height:auto,hide-content:true)
//#ansbox(3,2,1, daimon:none, shomon:"問1.", shomon_width:4em)
#ansbox(3,2, inset:0pt, daimon:none, shomon:"問1.", shomon_width:4em, shomon_start:7, content:([],[],[],[#h(1fr)],ansbox(1,2,daimon:none,box_width:(2cm,1fr))), box_width:(2cm,auto,auto), height:(1cm,auto,auto)) |
|
https://github.com/nixon-voxell/nixon_cover_letter_template | https://raw.githubusercontent.com/nixon-voxell/nixon_cover_letter_template/main/letter.typ | typst | MIT License | #import "template.typ": *
#show: letter.with(
author: (
firstname: "(Nixon) <NAME>",
lastname: "Cheng",
email: "<EMAIL>",
phone: "(+60) 173389100",
loc: "Malaysia",
linkedin: "nixonyh",
github: "nixon-voxell",
url_name: "linktr.ee/voxell",
url: "https://linktr.ee/voxell",
youtube: "@voxelltech",
itchio: "nixon-voxell",
positions: (
"Computer Graphics Engineer",
"\nTechnical Artist",
),
),
date: datetime.today().display("[day] [month repr:long] [year]")
)
#lorem(80)
#lorem(100)
#lorem(90)
#lorem(40)
|
https://github.com/VJMReichenbach/Merkzettel | https://raw.githubusercontent.com/VJMReichenbach/Merkzettel/main/DGL/dgl.typ | typst | #import "conf.typ": conf
= DGL Lernzettel Valentin Reichenbach
== Begrifflichkeiten
- Ordnung: Höchste Ableitung
- Skalar: Gesuchte Funktion hat $italic("Dim") = 1$
- autonom: $F$ hängt nicht direkt von $t$ ab
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz-plot/0.1.0/src/axes.typ | typst | Apache License 2.0 | #import "/src/cetz.typ": util, draw, vector, matrix, styles, process, drawable, path-util, process
#import "/src/plot/formats.typ"
/// Default axis style
///
/// #show-parameter-block("tick-limit", "int", default: 100, [Upper major tick limit.])
/// #show-parameter-block("minor-tick-limit", "int", default: 1000, [Upper minor tick limit.])
/// #show-parameter-block("auto-tick-factors", "array", [List of tick factors used for automatic tick step determination.])
/// #show-parameter-block("auto-tick-count", "int", [Number of ticks to generate by default.])
/// #show-parameter-block("stroke", "stroke", [Axis stroke style.])
/// #show-parameter-block("label.offset", "number", [Distance to move axis labels away from the axis.])
/// #show-parameter-block("label.anchor", "anchor", [Anchor of the axis label to use for it's placement.])
/// #show-parameter-block("label.angle", "angle", [Angle of the axis label.])
/// #show-parameter-block("axis-layer", "float", [Layer to draw axes on (see @@on-layer() )])
/// #show-parameter-block("grid-layer", "float", [Layer to draw the grid on (see @@on-layer() )])
/// #show-parameter-block("background-layer", "float", [Layer to draw the background on (see @@on-layer() )])
/// #show-parameter-block("padding", "number", [Extra distance between axes and plotting area. For schoolbook axes, this is the length of how much axes grow out of the plotting area.])
/// #show-parameter-block("overshoot", "number", [School-book style axes only: Extra length to add to the end (right, top) of axes.])
/// #show-parameter-block("tick.stroke", "stroke", [Major tick stroke style.])
/// #show-parameter-block("tick.minor-stroke", "stroke", [Minor tick stroke style.])
/// #show-parameter-block("tick.offset", ("number", "ratio"), [Major tick offset along the tick's direction, can be relative to the length.])
/// #show-parameter-block("tick.minor-offset", ("number", "ratio"), [Minor tick offset along the tick's direction, can be relative to the length.])
/// #show-parameter-block("tick.length", ("number"), [Major tick length.])
/// #show-parameter-block("tick.minor-length", ("number", "ratio"), [Minor tick length, can be relative to the major tick length.])
/// #show-parameter-block("tick.label.offset", ("number"), [Major tick label offset away from the tick.])
/// #show-parameter-block("tick.label.angle", ("angle"), [Major tick label angle.])
/// #show-parameter-block("tick.label.anchor", ("anchor"), [Anchor of major tick labels used for positioning.])
/// #show-parameter-block("tick.label.show", ("auto", "bool"), default: auto, [Set visibility of tick labels. A value of `auto` shows tick labels for all but mirrored axes.])
/// #show-parameter-block("grid.stroke", "stroke", [Major grid line stroke style.])
/// #show-parameter-block("break-point.width", "number", [Axis break width along the axis.])
/// #show-parameter-block("break-point.length", "number", [Axis break length.])
/// #show-parameter-block("minor-grid.stroke", "stroke", [Minor grid line stroke style.])
/// #show-parameter-block("shared-zero", ("bool", "content"), default: "$0$", [School-book style axes only: Content to display at the plots origin (0,0). If set to `false`, nothing is shown. Having this set, suppresses auto-generated ticks for $0$!])
#let default-style = (
tick-limit: 100,
minor-tick-limit: 1000,
auto-tick-factors: (1, 1.5, 2, 2.5, 3, 4, 5, 6, 8, 10), // Tick factor to try
auto-tick-count: 11, // Number of ticks the plot tries to place
fill: none,
stroke: auto,
label: (
offset: .2cm, // Axis label offset
anchor: auto, // Axis label anchor
angle: auto, // Axis label angle
),
axis-layer: 0,
grid-layer: 0,
background-layer: 0,
padding: 0,
tick: (
fill: none,
stroke: black + 1pt,
minor-stroke: black + .5pt,
offset: 0,
minor-offset: 0,
length: .1cm, // Tick length: Number
minor-length: 70%, // Minor tick length: Number, Ratio
label: (
offset: .15cm, // Tick label offset
angle: 0deg, // Tick label angle
anchor: auto, // Tick label anchor
"show": auto, // Show tick labels for axes in use
)
),
break-point: (
width: .75cm,
length: .15cm,
),
grid: (
stroke: (paint: gray.lighten(50%), thickness: 1pt),
),
minor-grid: (
stroke: (paint: gray.lighten(50%), thickness: .5pt),
),
)
// Default Scientific Style
#let default-style-scientific = util.merge-dictionary(default-style, (
left: (tick: (label: (anchor: "east"))),
bottom: (tick: (label: (anchor: "north"))),
right: (tick: (label: (anchor: "west"))),
top: (tick: (label: (anchor: "south"))),
stroke: (cap: "square"),
padding: 0,
))
// Default Schoolbook Style
#let default-style-schoolbook = util.merge-dictionary(default-style, (
x: (stroke: auto, fill: none, mark: (start: none, end: "straight"),
tick: (label: (anchor: "north"))),
y: (stroke: auto, fill: none, mark: (start: none, end: "straight"),
tick: (label: (anchor: "east"))),
label: (offset: .1cm),
origin: (label: (offset: .05cm)),
padding: .1cm, // Axis padding on both sides outsides the plotting area
overshoot: .5cm, // Axis end "overshoot" out of the plotting area
tick: (
offset: -50%,
minor-offset: -50%,
length: .2cm,
minor-length: 70%,
),
shared-zero: $0$, // Show zero tick label at (0, 0)
))
#let _prepare-style(ctx, style) = {
if type(style) != dictionary { return style }
let res = util.resolve-number.with(ctx)
let rel-to(v, to) = {
if type(v) == ratio {
return v * to / 100%
} else {
return res(v)
}
}
style.tick.length = res(style.tick.length)
style.tick.offset = rel-to(style.tick.offset, style.tick.length)
style.tick.minor-length = rel-to(style.tick.minor-length, style.tick.length)
style.tick.minor-offset = rel-to(style.tick.minor-offset, style.tick.minor-length)
style.tick.label.offset = res(style.tick.label.offset)
// Break points
style.break-point.width = res(style.break-point.width)
style.break-point.length = res(style.break-point.length)
// Padding
style.padding = res(style.padding)
if "overshoot" in style {
style.overshoot = res(style.overshoot)
}
return style
}
#let _get-axis-style(ctx, style, name) = {
if not name in style {
return style
}
style = styles.resolve(style, merge: style.at(name))
return _prepare-style(ctx, style)
}
#let _get-grid-type(axis) = {
let grid = axis.ticks.at("grid", default: false)
if grid == "major" or grid == true { return 1 }
if grid == "minor" { return 2 }
if grid == "both" { return 3 }
return 0
}
#let _inset-axis-points(ctx, style, axis, start, end) = {
if axis == none { return (start, end) }
let (low, high) = axis.inset.map(v => util.resolve-number(ctx, v))
let is-horizontal = start.at(1) == end.at(1)
if is-horizontal {
start = vector.add(start, (low, 0))
end = vector.sub(end, (high, 0))
} else {
start = vector.add(start, (0, low))
end = vector.sub(end, (0, high))
}
return (start, end)
}
#let _draw-axis-line(start, end, axis, is-horizontal, style) = {
let enabled = if axis != none and axis.show-break {
axis.min > 0 or axis.max < 0
} else { false }
if enabled {
let size = if is-horizontal {
(style.break-point.width, 0)
} else {
(0, style.break-point.width, 0)
}
let up = if is-horizontal {
(0, style.break-point.length)
} else {
(style.break-point.length, 0)
}
let add-break(is-end) = {
let a = ()
let b = (rel: vector.scale(size, .3), update: false)
let c = (rel: vector.add(vector.scale(size, .4), vector.scale(up, -1)), update: false)
let d = (rel: vector.add(vector.scale(size, .6), vector.scale(up, +1)), update: false)
let e = (rel: vector.scale(size, .7), update: false)
let f = (rel: size)
let mark = if is-end {
style.at("mark", default: none)
}
draw.line(a, b, c, d, e, f, stroke: style.stroke, mark: mark)
}
draw.merge-path({
draw.move-to(start)
if axis.min > 0 {
add-break(false)
draw.line((rel: size, to: start), end, mark: style.at("mark", default: none))
} else if axis.max < 0 {
draw.line(start, (rel: vector.scale(size, -1), to: end))
add-break(true)
}
}, stroke: style.stroke)
} else {
draw.line(start, end, stroke: style.stroke, mark: style.at("mark", default: none))
}
}
// Construct Axis Object
//
// - min (number): Minimum value
// - max (number): Maximum value
// - ticks (dictionary): Tick settings:
// - step (number): Major tic step
// - minor-step (number): Minor tic step
// - decimals (int): Tick float decimal length
// - label (content): Axis label
// - mode (string): Axis scaling function. Takes `lin` or `log`
// - base (number): Base for tick labels when logarithmically scaled.
#let axis(min: -1, max: 1, label: none,
ticks: (step: auto, minor-step: none,
decimals: 2, grid: false,
format: "float"
),
mode: auto, base: auto) = (
min: min, max: max, ticks: ticks, label: label, inset: (0, 0), show-break: false, mode: mode, base: base
)
// Format a tick value
#let format-tick-value(value, tic-options) = {
// Without it we get negative zero in conversion
// to content! Typst has negative zero floats.
if value == 0 { value = 0 }
if type(value) != std.content {
let format = tic-options.at("format", default: "float")
if format == none {
value = []
} else if type(format) == std.content {
value = format
} else if type(format) == function {
value = (format)(value)
} else if format == "sci" {
value = formats.sci(value, digits: tic-options.at("decimals", default: 2))
} else {
value = formats.decimal(value, digits: tic-options.at("decimals", default: 2))
}
} else if type(value) != std.content {
value = str(value)
}
return value
}
// Get value on axis [0, 1]
//
// - axis (axis): Axis
// - v (number): Value
// -> float
#let value-on-axis(axis, v) = {
if v == none { return }
let (min, max) = (axis.min, axis.max)
let dt = max - min; if dt == 0 { dt = 1 }
return (v - min) / dt
}
// Compute list of linear ticks for axis
//
// - axis (axis): Axis
#let compute-linear-ticks(axis, style, add-zero: true) = {
let (min, max) = (axis.min, axis.max)
let dt = max - min; if (dt == 0) { dt = 1 }
let ticks = axis.ticks
let ferr = util.float-epsilon
let tick-limit = style.tick-limit
let minor-tick-limit = style.minor-tick-limit
let l = ()
if ticks != none {
let major-tick-values = ()
if "step" in ticks and ticks.step != none {
assert(ticks.step >= 0,
message: "Axis tick step must be positive and non 0.")
if axis.min > axis.max { ticks.step *= -1 }
let s = 1 / ticks.step
let num-ticks = int(max * s + 1.5) - int(min * s)
assert(num-ticks <= tick-limit,
message: "Number of major ticks exceeds limit " + str(tick-limit))
let n = range(int(min * s), int(max * s + 1.5))
for t in n {
let v = (t / s - min) / dt
if t / s == 0 and not add-zero { continue }
if v >= 0 - ferr and v <= 1 + ferr {
l.push((v, format-tick-value(t / s, ticks), true))
major-tick-values.push(v)
}
}
}
if "minor-step" in ticks and ticks.minor-step != none {
assert(ticks.minor-step >= 0,
message: "Axis minor tick step must be positive")
if axis.min > axis.max { ticks.minor-step *= -1 }
let s = 1 / ticks.minor-step
let num-ticks = int(max * s + 1.5) - int(min * s)
assert(num-ticks <= minor-tick-limit,
message: "Number of minor ticks exceeds limit " + str(minor-tick-limit))
let n = range(int(min * s), int(max * s + 1.5))
for t in n {
let v = (t / s - min) / dt
if v in major-tick-values {
// Prefer major ticks over minor ticks
continue
}
if v != none and v >= 0 and v <= 1 + ferr {
l.push((v, none, false))
}
}
}
}
return l
}
// Compute list of linear ticks for axis
//
// - axis (axis): Axis
#let compute-logarithmic-ticks(axis, style, add-zero: true) = {
let ferr = util.float-epsilon
let (min, max) = (
calc.log(calc.max(axis.min, ferr), base: axis.base),
calc.log(calc.max(axis.max, ferr), base: axis.base)
)
let dt = max - min; if (dt == 0) { dt = 1 }
let ticks = axis.ticks
let tick-limit = style.tick-limit
let minor-tick-limit = style.minor-tick-limit
let l = ()
if ticks != none {
let major-tick-values = ()
if "step" in ticks and ticks.step != none {
assert(ticks.step >= 0,
message: "Axis tick step must be positive and non 0.")
if axis.min > axis.max { ticks.step *= -1 }
let s = 1 / ticks.step
let num-ticks = int(max * s + 1.5) - int(min * s)
assert(num-ticks <= tick-limit,
message: "Number of major ticks exceeds limit " + str(tick-limit))
let n = range(
int(min * s),
int(max * s + 1.5)
)
for t in n {
let v = (t / s - min) / dt
if t / s == 0 and not add-zero { continue }
if v >= 0 - ferr and v <= 1 + ferr {
l.push((v, format-tick-value( calc.pow(axis.base, t / s), ticks), true))
major-tick-values.push(v)
}
}
}
if "minor-step" in ticks and ticks.minor-step != none {
assert(ticks.minor-step >= 0,
message: "Axis minor tick step must be positive")
if axis.min > axis.max { ticks.minor-step *= -1 }
let s = 1 / ticks.step
let n = range(int(min * s)-1, int(max * s + 1.5)+1)
for t in n {
for vv in range(1, int(axis.base / ticks.minor-step)) {
let v = ( (calc.log(vv * ticks.minor-step, base: axis.base) + t)/ s - min) / dt
if v in major-tick-values {continue}
if v != none and v >= 0 and v <= 1 + ferr {
l.push((v, none, false))
}
}
}
}
}
return l
}
// Get list of fixed axis ticks
//
// - axis (axis): Axis object
#let fixed-ticks(axis) = {
let l = ()
if "list" in axis.ticks {
for t in axis.ticks.list {
let (v, label) = (none, none)
if type(t) in (float, int) {
v = t
label = format-tick-value(t, axis.ticks)
} else {
(v, label) = t
}
v = value-on-axis(axis, v)
if v != none and v >= 0 and v <= 1 {
l.push((v, label, true))
}
}
}
return l
}
// Compute list of axis ticks
//
// A tick triple has the format:
// (rel-value: float, label: content, major: bool)
//
// - axis (axis): Axis object
#let compute-ticks(axis, style, add-zero: true) = {
let find-max-n-ticks(axis, n: 11) = {
let dt = calc.abs(axis.max - axis.min)
let scale = calc.floor(calc.log(dt, base: 10) - 1)
if scale > 5 or scale < -5 {return none}
let (step, best) = (none, 0)
for s in style.auto-tick-factors {
s = s * calc.pow(10, scale)
let divs = calc.abs(dt / s)
if divs >= best and divs <= n {
step = s
best = divs
}
}
return step
}
if axis == none or axis.ticks == none { return () }
if axis.ticks.step == auto {
axis.ticks.step = find-max-n-ticks(axis, n: style.auto-tick-count)
}
if axis.ticks.minor-step == auto {
axis.ticks.minor-step = if axis.ticks.step != none {
axis.ticks.step / 5
} else {
none
}
}
let ticks = if axis.mode == "log" {
compute-logarithmic-ticks(axis, style, add-zero: add-zero)
} else {
compute-linear-ticks(axis, style, add-zero: add-zero)
}
ticks += fixed-ticks(axis)
return ticks
}
// Prepares the axis post creation. The given axis
// must be completely set-up, including its interval.
// Returns the prepared axis
#let prepare-axis(ctx, axis, name) = {
let style = styles.resolve(ctx.style, root: "axes",
base: default-style-scientific)
style = _prepare-style(ctx, style)
style = _get-axis-style(ctx, style, name)
if type(axis.inset) != array {
axis.inset = (axis.inset, axis.inset)
}
axis.inset = axis.inset.map(v => util.resolve-number(ctx, v))
if axis.show-break {
if axis.min > 0 {
axis.inset.at(0) += style.break-point.width
} else if axis.max < 0 {
axis.inset.at(1) += style.break-point.width
}
}
return axis
}
// Transform a single vector along a x, y and z axis
//
// - size (vector): Coordinate system size
// - x-axis (axis): X axis
// - y-axis (axis): Y axis
// - z-axis (axis): Z axis
// - vec (vector): Input vector to transform
// -> vector
#let transform-vec(size, x-axis, y-axis, z-axis, vec) = {
let axes = (x-axis, y-axis)
let (x, y,) = for (dim, axis) in axes.enumerate() {
let s = size.at(dim) - axis.inset.sum()
let o = axis.inset.at(0)
let transform-func(n) = if axis.mode == "log" {
calc.log(calc.max(n, util.float-epsilon), base: axis.base)
} else {
n
}
let range = transform-func(axis.max) - transform-func(axis.min)
let f = s / range
((transform-func(vec.at(dim)) - transform-func(axis.min)) * f + o,)
}
return (x, y, 0)
}
// Draw inside viewport coordinates of two axes
//
// - size (vector): Axis canvas size (relative to origin)
// - x (axis): Horizontal axis
// - y (axis): Vertical axis
// - z (axis): Z axis
// - name (string,none): Group name
#let axis-viewport(size, x, y, z, body, name: none) = {
draw.group(name: name, (ctx => {
let transform = ctx.transform
ctx.transform = matrix.ident()
let (ctx, drawables, bounds) = process.many(ctx, util.resolve-body(ctx, body))
ctx.transform = transform
drawables = drawables.map(d => {
if "segments" in d {
d.segments = d.segments.map(((kind, ..pts)) => {
(kind, ..pts.map(pt => {
transform-vec(size, x, y, none, pt)
}))
})
}
if "pos" in d {
d.pos = transform-vec(size, x, y, none, d.pos)
}
return d
})
return (
ctx: ctx,
drawables: drawable.apply-transform(ctx.transform, drawables)
)
},))
}
// Draw grid lines for the ticks of an axis
//
// - cxt (context):
// - axis (dictionary): The axis
// - ticks (array): The computed ticks
// - low (vector): Start position of a grid-line at tick 0
// - high (vector): End position of a grid-line at tick 0
// - dir (vector): Normalized grid direction vector along the grid axis
// - style (style): Axis style
#let draw-grid-lines(ctx, axis, ticks, low, high, dir, style) = {
let offset = (0,0)
if axis.inset != none {
let (inset-low, inset-high) = axis.inset.map(v => util.resolve-number(ctx, v))
offset = vector.scale(vector.norm(dir), inset-low)
dir = vector.sub(dir, vector.scale(vector.norm(dir), inset-low + inset-high))
}
let kind = _get-grid-type(axis)
if kind > 0 {
for (distance, label, is-major) in ticks {
let offset = vector.add(vector.scale(dir, distance), offset)
let start = vector.add(low, offset)
let end = vector.add(high, offset)
// Draw a major line
if is-major and (kind == 1 or kind == 3) {
draw.line(start, end, stroke: style.grid.stroke)
}
// Draw a minor line
if not is-major and kind >= 2 {
draw.line(start, end, stroke: style.minor-grid.stroke)
}
}
}
}
// Place a list of tick marks and labels along a path
#let place-ticks-on-line(ticks, start, stop, style, flip: false, is-mirror: false) = {
let dir = vector.sub(stop, start)
let norm = vector.norm((-dir.at(1), dir.at(0), dir.at(2, default: 0)))
let def(v, d) = {
return if v == none or v == auto {d} else {v}
}
let show-label = style.tick.label.show
if show-label == auto {
show-label = not is-mirror
}
for (distance, label, is-major) in ticks {
let offset = style.tick.offset
let length = if is-major { style.tick.length } else { style.tick.minor-length }
if flip {
offset *= -1
length *= -1
}
let pt = vector.lerp(start, stop, distance)
let a = vector.add(pt, vector.scale(norm, offset))
let b = vector.add(a, vector.scale(norm, length))
draw.line(a, b, stroke: style.tick.stroke)
if show-label and label != none {
let offset = style.tick.label.offset
if flip {
offset *= -1
length *= -1
}
let c = vector.sub(if length <= 0 { b } else { a },
vector.scale(norm, offset))
let angle = def(style.tick.label.angle, 0deg)
let anchor = def(style.tick.label.anchor, "center")
draw.content(c, [#label], angle: angle, anchor: anchor)
}
}
}
// Draw up to four axes in an "scientific" style at origin (0, 0)
//
// - size (array): Size (width, height)
// - left (axis): Left (y) axis
// - bottom (axis): Bottom (x) axis
// - right (axis): Right axis
// - top (axis): Top axis
// - name (string): Object name
// - draw-unset (bool): Draw axes that are set to `none`
// - ..style (any): Style
#let scientific(size: (1, 1),
left: none,
right: auto,
bottom: none,
top: auto,
draw-unset: true,
name: none,
..style) = {
import draw: *
if right == auto {
if left != none {
right = left; right.is-mirror = true
} else {
right = none
}
}
if top == auto {
if bottom != none {
top = bottom; top.is-mirror = true
} else {
top = none
}
}
group(name: name, ctx => {
let (w, h) = size
anchor("origin", (0, 0))
let style = style.named()
style = styles.resolve(ctx.style, merge: style, root: "axes",
base: default-style-scientific)
style = _prepare-style(ctx, style)
// Compute ticks
let x-ticks = compute-ticks(bottom, style)
let y-ticks = compute-ticks(left, style)
let x2-ticks = compute-ticks(top, style)
let y2-ticks = compute-ticks(right, style)
// Draw frame
if style.fill != none {
on-layer(style.background-layer, {
rect((0,0), (w,h), fill: style.fill, stroke: none)
})
}
// Draw grid
group(name: "grid", ctx => {
let axes = (
("bottom", (0,0), (0,h), (+w,0), x-ticks, bottom),
("top", (0,h), (0,0), (+w,0), x2-ticks, top),
("left", (0,0), (w,0), (0,+h), y-ticks, left),
("right", (w,0), (0,0), (0,+h), y2-ticks, right),
)
for (name, start, end, direction, ticks, axis) in axes {
if axis == none { continue }
let style = _get-axis-style(ctx, style, name)
let is-mirror = axis.at("is-mirror", default: false)
if not is-mirror {
on-layer(style.grid-layer, {
draw-grid-lines(ctx, axis, ticks, start, end, direction, style)
})
}
}
})
// Draw axes
group(name: "axes", {
let axes = (
("bottom", (0, 0), (w, 0), (0, -1), false, x-ticks, bottom,),
("top", (0, h), (w, h), (0, +1), true, x2-ticks, top,),
("left", (0, 0), (0, h), (-1, 0), true, y-ticks, left,),
("right", (w, 0), (w, h), (+1, 0), false, y2-ticks, right,)
)
let label-placement = (
bottom: ("south", "north", 0deg),
top: ("north", "south", 0deg),
left: ("west", "south", 90deg),
right: ("east", "north", 90deg),
)
for (name, start, end, outsides, flip, ticks, axis) in axes {
let style = _get-axis-style(ctx, style, name)
let is-mirror = axis == none or axis.at("is-mirror", default: false)
let is-horizontal = name in ("bottom", "top")
if style.padding != 0 {
let padding = vector.scale(outsides, style.padding)
start = vector.add(start, padding)
end = vector.add(end, padding)
}
let (data-start, data-end) = _inset-axis-points(ctx, style, axis, start, end)
let path = _draw-axis-line(start, end, axis, is-horizontal, style)
on-layer(style.axis-layer, {
group(name: "axis", {
if draw-unset or axis != none {
path;
place-ticks-on-line(ticks, data-start, data-end, style, flip: flip, is-mirror: is-mirror)
}
})
if axis != none and axis.label != none and not is-mirror {
let offset = vector.scale(outsides, style.label.offset)
let (group-anchor, content-anchor, angle) = label-placement.at(name)
if style.label.anchor != auto {
content-anchor = style.label.anchor
}
if style.label.angle != auto {
angle = style.label.angle
}
content((rel: offset, to: "axis." + group-anchor),
[#axis.label],
angle: angle,
anchor: content-anchor)
}
})
}
})
})
}
// Draw two axes in a "school book" style
//
// - x-axis (axis): X axis
// - y-axis (axis): Y axis
// - size (array): Size (width, height)
// - x-position (number): X Axis position
// - y-position (number): Y Axis position
// - name (string): Object name
// - ..style (any): Style
#let school-book(x-axis, y-axis,
size: (1, 1),
x-position: 0,
y-position: 0,
name: none,
..style) = {
import draw: *
group(name: name, ctx => {
let (w, h) = size
anchor("origin", (0, 0))
let style = style.named()
style = styles.resolve(
ctx.style,
merge: style,
root: "axes",
base: default-style-schoolbook)
style = _prepare-style(ctx, style)
let x-position = calc.min(calc.max(y-axis.min, x-position), y-axis.max)
let y-position = calc.min(calc.max(x-axis.min, y-position), x-axis.max)
let x-y = value-on-axis(y-axis, x-position) * h
let y-x = value-on-axis(x-axis, y-position) * w
let shared-zero = style.shared-zero != false and x-position == 0 and y-position == 0
let x-ticks = compute-ticks(x-axis, style, add-zero: not shared-zero)
let y-ticks = compute-ticks(y-axis, style, add-zero: not shared-zero)
// Draw grid
group(name: "grid", ctx => {
let axes = (
("x", (0,0), (0,h), (+w,0), x-ticks, x-axis),
("y", (0,0), (w,0), (0,+h), y-ticks, y-axis),
)
for (name, start, end, direction, ticks, axis) in axes {
if axis == none { continue }
let style = _get-axis-style(ctx, style, name)
on-layer(style.grid-layer, {
draw-grid-lines(ctx, axis, ticks, start, end, direction, style)
})
}
})
// Draw axes
group(name: "axes", {
let axes = (
("x", (0, x-y), (w, x-y), (1, 0), false, x-ticks, x-axis),
("y", (y-x, 0), (y-x, h), (0, 1), true, y-ticks, y-axis),
)
let label-pos = (
x: ("north", (0,-1)),
y: ("east", (-1,0)),
)
on-layer(style.axis-layer, {
for (name, start, end, dir, flip, ticks, axis) in axes {
let style = _get-axis-style(ctx, style, name)
let pad = style.padding
let overshoot = style.overshoot
let vstart = vector.sub(start, vector.scale(dir, pad))
let vend = vector.add(end, vector.scale(dir, pad + overshoot))
let is-horizontal = name == "x"
let (data-start, data-end) = _inset-axis-points(ctx, style, axis, start, end)
group(name: "axis", {
_draw-axis-line(vstart, vend, axis, is-horizontal, style)
place-ticks-on-line(ticks, data-start, data-end, style, flip: flip)
})
if axis.label != none {
let (content-anchor, offset-dir) = label-pos.at(name)
let angle = if style.label.angle not in (none, auto) {
style.label.angle
} else { 0deg }
if style.label.anchor not in (none, auto) {
content-anchor = style.label.anchor
}
let offset = vector.scale(offset-dir, style.label.offset)
content((rel: offset, to: vend),
[#axis.label],
angle: angle,
anchor: content-anchor)
}
}
if shared-zero {
let pt = (rel: (-style.tick.label.offset, -style.tick.label.offset),
to: (y-x, x-y))
let zero = if type(style.shared-zero) == std.content {
style.shared-zero
} else {
$0$
}
content(pt, zero, anchor: "north-east")
}
})
})
})
}
|
https://github.com/EmileVezinaCoulombe/Planner | https://raw.githubusercontent.com/EmileVezinaCoulombe/Planner/main/planner.typ | typst | //***************************************************************************//
// Imports //
//***************************************************************************//
#import "@preview/splash:0.3.0": tailwind
//***************************************************************************//
// Variables //
//***************************************************************************//
#let cours = (
"Vision",
"Q & M",
"Architecture",
"Réseaux",
"IA",
"PGL",
)
#let checkBox(..x) = box(width: 10pt, height: 10pt, stroke: 1pt + black, radius: 2pt, ..x)
#let underline-thickness = 0.5pt
#let underline-offset = 1pt
#let underline-100(..x) = underline(stroke: underline-thickness, offset: underline-offset, ..x)
#let uInput-100(..box_args) = box(
width: 1fr, stroke: (bottom: underline-thickness), outset: (bottom: underline-offset),
..box_args,
)
#let underline-thickness = 1.5pt
#let underline-offset = -2pt
#let underline-lg(..x) = underline(stroke: underline-thickness, offset: underline-offset, ..x)
#let uInput-lg(..box_args) = box(
width: 1fr, stroke: (bottom: underline-thickness), outset: (bottom: underline-offset),
..box_args,
)
#let uInput-time(..box_args) = box(width: 1em, stroke: (bottom: 0.5pt), outset: (bottom: 5pt), ..box_args)
#let weeksNb = 16
#let weeks-sm = ()
#let weeks-sm-hidden = ()
#let textBox(..x) = box(width: 9pt, height: 9pt, stroke: 0.5pt + black, radius: 2pt, ..x)
#for i in array.range(1, weeksNb) {
weeks-sm.push(align(center + horizon, checkBox()[#text(8pt)[#i]] ))
weeks-sm-hidden.push(checkBox()[])
}
#let topTodoNb = 3
#let topTodos = ()
#for i in range(topTodoNb) {
topTodos.push([#checkBox() #underline-100[]#uInput-100()])
}
#let dailyTodoNb = 11
#let dailyTodos = ()
#for i in array.range(dailyTodoNb) {
dailyTodos.push(
[#pad(left: 12pt, right: 8pt, [#checkBox() #underline[]#uInput-100()])],
)
}
#let weeklyTodoNb = 21
#let weeklyTodos = ()
#for i in array.range(weeklyTodoNb) {
weeklyTodos.push(
[#pad(left: 12pt, right: 8pt, [#checkBox() #underline-100[]#uInput-100()])],
)
}
//***************************************************************************//
// Settings //
//***************************************************************************//
#set document(
title: [Planner], author: "<NAME>", keywords: "habits", date: datetime(year: 2024, month: 2, day: 1),
)
#set text(font: "New Computer Modern", size: 12pt)
#set page(paper: "a4", margin: (x: 1cm, y: 0.5cm))
#set par(justify: true, leading: 0.52em)
#set align(center)
//***************************************************************************//
// Page 1 : Today //
//***************************************************************************//
#grid(
columns: 1, rows: 3, row-gutter: 3em, [= Today],
[
#grid(
columns: (1fr, 1fr), gutter: 1em, [
#grid(columns: 1, rows: 4, row-gutter: 9pt, [== Top 3], ..topTodos)
#let notesNb = 7
#let notes = ()
#for i in range(notesNb) {
notes.push([#underline-100[]#uInput-100()])
}
#grid(columns: 1, rows: notesNb + 1, row-gutter: 19pt, [== Notes], ..notes)
], [
#box(
stroke: (left: 1pt, bottom: 1pt), inset: (bottom: 10pt),
)[
#grid(
columns: 1, rows: dailyTodoNb + 1, row-gutter: 9pt, [
#text(12pt)[#pad(x: 4pt, [#underline-100(extent: 4pt)[TODO]#uInput-100()])]
],
..dailyTodos,
)
]
],
)
], [
== Done this day
#let taskNb = 10
#let tasks = ()
#for i in array.range(taskNb) {
tasks.push(
(
[#underline-100()[]#uInput-time():#underline-100()[]#uInput-time() | #underline-100()[]#uInput-time():#underline-100()[]#uInput-time()],
[], [],
),
)
}
#table(
columns: (7em, 1fr, 3em), rows: taskNb + 1, inset: 8pt, align: (x, y) => (center, center, center, center).at(x),
fill: (_, row) => if row == 0 { tailwind.neutral-100 } else if row > taskNb - 2 { tailwind.teal-100 },
[*Time*], [*Task*], [*C*], ..tasks.flatten(),
)
],
)
#pagebreak()
//***************************************************************************//
// Page 2: Blank //
//***************************************************************************//
#hide[Blank]
#pagebreak()
//***************************************************************************//
// Page 3: Weekly //
//***************************************************************************//
#grid(
columns: 1, rows: 3, row-gutter: 3em, [
= Weekly
],
[
#grid(
columns: (1fr, 1fr), [
#set align(left)
#grid(
columns: (2.9em, 1fr), [#text(12pt)[Week]], [#grid(columns: weeksNb + 1, column-gutter: 1fr, ..weeks-sm)],
)
#v(-0pt)
#for class in cours {
text(12pt, underline()[#class])
text(
10pt, list(
[#grid(
columns: (3em, 1fr), [ex], grid(columns: weeksNb + 1, column-gutter: 1fr, ..weeks-sm-hidden),
)], [#grid(
columns: (3em, 1fr), [cours], grid(columns: weeksNb + 1, column-gutter: 1fr, ..weeks-sm-hidden),
)], [#grid(
columns: (3em, 1fr), [lec.], grid(columns: weeksNb + 1, column-gutter: 1fr, ..weeks-sm-hidden),
)],
),
)
}
], [
#box(
stroke: (left: 1pt, bottom: 1pt), inset: (bottom: 10pt),
)[
#grid(
columns: 1, rows: weeklyTodoNb + 1, row-gutter: 9pt, [
#text(12pt)[#pad(x: 4pt, [#underline-100(extent: 4pt)[TODO]#uInput-100()])]
],
..weeklyTodos,
)
]
],
)
], [
//***************************************************************************//
// Habit tracker //
//***************************************************************************//
#let habitLenght = 8fr
#grid(
columns: 1, rows: 3, [
#align(
center + bottom, text(
12pt, grid(
columns: (habitLenght, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), rows: 20, [#align(left)[#text(12pt)[Habits]]],
[Mon], [Tue], [Wed], [Thur],
[Fri], [Sat], [Sun],
),
),
)
], [
#pad(y: 12pt, [#underline-lg()[]#uInput-lg()])
],
[
#let underline-thickness = 0.5pt
#let underline-offset = 1pt
#let underline-lg(..x) = underline(stroke: underline-thickness, offset: underline-offset, ..x)
#let uInput(..box_args) = box(
width: 1fr, stroke: (bottom: underline-thickness), outset: (bottom: underline-offset),
..box_args,
)
#let underline-thickness = 0.5pt
#let underline-offset = 9pt
#let uEmptyInput(..box_args) = box(
width: 1fr, stroke: (bottom: underline-thickness), outset: (bottom: underline-offset),
..box_args,
)
#set text(12pt)
#grid(
columns: (habitLenght, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), row-gutter: 5pt,
[#underline-lg()[Planner]#uInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#underline-lg()[Top 3 checked]#uInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#underline-lg()[10 Flashcards]#uInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#underline-lg()[1 page AI book]#uInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#underline-lg()[5 words]#uInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#uEmptyInput()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
)
],
)
], [
//***************************************************************************//
// Evaluations //
//***************************************************************************//
== Evaluations
#grid(
columns: 1, rows: 3, align(center + bottom, text(12pt, grid(
columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), rows: 1, [Mon], [Tue],
[Wed], [Thur], [Fri], [Sat],
[Sun],
))), [#pad(y: 6pt, [#underline-lg()[]#uInput-lg()])],
grid(
columns: (1fr, 1fr, 1fr, 1fr, 1fr, 1fr, 1fr), rows: 2, row-gutter: 10pt, [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()], [#checkBox()], [#checkBox()], [#checkBox()],
[#checkBox()],
),
)
],
)
#pagebreak()
//***************************************************************************//
// Page 4: Calendar //
//***************************************************************************//
#import table
#let firstHour = 7
#let lastHour = 18
#let weekHours = ()
#for i in array.range(firstHour, lastHour) {
weekHours.push((table.cell(rowspan: 4, stroke: none, align: horizon)[#text(8pt, [#i:00])], [], [], [], [], [], [], []))
weekHours.push(( [], [], [], [], [], [], []))
weekHours.push(( [], [], [], [], [], [], []))
weekHours.push(( [], [], [], [], [], [], []))
weekHours.push(table.hline(stroke: (thickness: 1pt)))
}
#let dayLenght = 8em
#v(4em)
#rotate(90deg)[
#table(
columns: (3em, dayLenght, dayLenght, dayLenght, dayLenght, dayLenght, dayLenght, dayLenght),
stroke: 0.2pt,
inset: (y: 5.5pt),
fill: (_, row) => if row == 0 { tailwind.neutral-100 },
table.hline(stroke: none),
table.vline(stroke: none),
[Time], [Mon], [Tue], [Wed], [Thur], [Fri], [Sat], table.cell(stroke: none, [Sun]),
table.vline(start: 1, stroke: 1pt),
table.hline(stroke: 1pt),
..weekHours.flatten(),
table.hline(stroke: (thickness: 1pt)),
table.cell(inset: 11pt, align: horizon)[over time], [], [], [], [], [], [], [],
table.hline(stroke: 1pt),
)
]
|
|
https://github.com/cadojo/correspondence | https://raw.githubusercontent.com/cadojo/correspondence/main/src/rolo/rolo.typ | typst | MIT License | #import "src/attributes.typ": *
#import "src/names.typ": *
#import "src/affiliations.typ": *
#import "src/authors.typ": *
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/021%20-%20Battle%20for%20Zendikar/005_Memories%20of%20Blood.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Memories of Blood",
set_name: "Battle for Zendikar",
story_date: datetime(day: 16, month: 09, year: 2015),
author: "<NAME>",
doc
)
#emph[When Kalitas and the Ghet threatened to turn all of the vampires of Malakir into thralls of the Eldrazi, Drana struck back, retaking control of Malakir and driving Kalitas and his traitors away from the city. But Drana's victory was short-lived, and she and her remaining people were driven from the city by ever-growing hordes of Eldrazi.]
#emph[Their numbers have swelled with thousands of mortals who have no choice but to join them or perish in the face of the Eldrazi assault. They are the last remaining bastion of civilization on Guul Draz, and they wander the face of the ravaged continent in search of hope or succor in a world that has vanishingly little of either.]
#figure(image("005_Memories of Blood/01.png", width: 100%), caption: [], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Against a sky the color of dead trees, a flock of birds dropped out of the air. No force impeded them, no arrow or spell punctured their flight. They just stopped and died, their lifeless bodies ceasing to carry on. Drana thought they had simply given up. Perhaps it was the reasonable choice.
Around her, enormous sleds groaned and buckled under the weight of thousands of refugees, vampire and mortal alike. Each sled was tethered to hundreds of the nulls, slavering and gibbering as they moved forward, ever forward. They were no longer moving toward something. Just #emph[away] . Away from the Eldrazi, away from certain death. But each day there were fewer places to go in #emph[away] . The land of #emph[away] , here in Guul Draz, was being replaced by the presence of more Eldrazi.
Drana ascended through the air, a survey she knew would offer no hope, but she flew nonetheless. Six giant sleds, plus small scattered bands of vampire scouts and outriders and the few mortals who were still combat-ready. Fifteen thousand lives, at most, and perhaps a fifth of those worth more in battle than the delicious blood they carried in their veins. Back when they had first liberated Malakir from the traitorous vampires who had succumbed to the Eldrazi's call, back when they still thought this a winnable war, they had over three times that number—the vast majority of them useful vampire warriors.
Drana rose higher to view the large Eldrazi host behind them. She wanted to say there were thousands of them, but she did not like lying to herself. There were many more than thousands of them, a number so much greater that it was not useful to label it. There in the midst of the host was the enormous Eldrazi sire, towering over the neighboring hills, the clear lord of its domain. The sire was not as large or formidable as Ulamog itself, but it was still massive and powerful enough to lay waste to the continent of Guul Draz. Its multiple limbs waved a constant orbit in the high sky. The vampires had lost many to its rending arms in aerial assaults before the futility of such attacks became clear.
#figure(image("005_Memories of Blood/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The Eldrazi host was massive and the host was inexorable and the host was death . . . but at least the host was #emph[slow] . At times the sleds had pulled many miles in front, so that the pursuit was no longer visible. But there were smaller Eldrazi hosts that had come from both left and right, and in the angling back and forth to stay clear, Drana's force had allowed the pursuing host to catch up. Now the vampires were only a couple of miles ahead, and they were running out of room to maneuver. Soon they would be at the coast, and their only hope would be to double-back and . . . #emph[stay alive today] , Drana reminded herself. That was the new goal. The only goal. #emph[Stay alive today] .
The goal grew more difficult every day.
Eldrazi were everywhere, and the land she had known for thousands of years was evaporating underneath. Neither rock nor wood nor life resisted the chalky calcification that was the residue of the Eldrazi assault. Drana thought of the corpse of the land, being drained of essence and blood to feed the insatiable hunger of a merciless predator. #emph[We were made in the shadows of our makers] , she thought, not for the first time. #emph[Not in image but in action] . The painful truth, the essential truth, was the Eldrazi were better vampires than the vampires.
She turned to look toward the coast, their current destination. There, beyond the narrow waters, was Tazeem. Some of the vampires felt there would be refuge there, but more, including Drana, felt there was no reason #emph[there] should be different than #emph[here] . If vampires, the most powerful race on Zendikar, could not defeat the Eldrazi, what chance did lesser beings have? But every day a few more vampires left, carrying a foolish hope that sanctuary existed somewhere.
She spied a dot on the horizon, and the dot split into five dots, ten dots, then more. From the direction of Tazeem they came, and several vampire scouts flew off to get a closer look. An overseer flew up to join her. The dots resolved into clearer pictures. There were maybe a hundred of them. "Those are kitesails. Kor."
"Welcome or kill?" Kan had been one of her personal overseers for millennia. He knew the ways she thought, and she appreciated his laconic efficiency. Still, he sounded tired. She was tired. She had existed for thousands of years, and though she could not remember more than a fraction of that life, she thought she had never been so tired. #emph[A new experience. ] She gave a tight smile. #emph[I should be grateful] .
"Welcome. They come to join us at the end of the world. We will be accommodating."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
#figure(image("005_Memories of Blood/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The leader of the kor delegation was tall, thin, but with a good amount of lean muscle. A warrior, as were the rest. Drana could smell the blood, the delicious scent of the healthy. She had not fed in a few days, and even that sustenance had been the blood of the dying and infirm. These kor smelled beautiful. She smiled widely, and she gave credit to the kor leader when he did not step back, did not even reach for his sword. Brave blood tasted best.
She put the regret of not being able to taste it on her list of regrets since the beginning of the Eldrazi rise. It had become a long list. The leader's name was Enkindi; he and the rest of his band had been sent by Gideon from Sea Gate to find other survivors on Guul Draz and bring them back to join Gideon's army. Drana had heard of Gideon from a few of the recent stragglers to join their camp. The rumors were that Gideon was a powerful human mage and warrior, but when Drana asked if he had defeated the Eldrazi on Tazeem, they could only reply, "No, but he survives." Drana could not see anything special about this Gideon. That's what they all were doing, surviving, until the time came they stopped. #emph[Do not stop today] . But it could be tomorrow.
Still, if this Gideon could afford to send a hundred capable troops looking for allies on other continents, he was doing better than her army. But in the end, that didn't matter. That these kor could fly might.
The giant sleds had stopped. Vampire overseers walked among the nulls chained to the pull-rods, slopping out handfuls of decaying meat from large buckets. The nulls were the easiest to feed; the rest of their entourage less so. Mortals shakily left the sleds and were handed food in slightly better shape than what the nulls were eating. By this point there was no more fighting and rioting from the mortals over food. They were too exhausted to fight. But not too exhausted to stay on the sleds. Everyone who could moved away from the sleds. They had learned.
#figure(image("005_Memories of Blood/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
As her vampires ranged amongst the sleds, getting what little nourishment they could from the dead and dying, she walked the kor through the thousands of refugees. There were still a few mortals who had both reserves and compassion. Mages, healers, warriors, they would walk amongst the huddled groups offering what succor they could. But everyone knew it was the vampires keeping them alive. Hunters and scouts were constantly foraging in a wide radius, bringing back everything resembling food they could. There was diminishing sustenance left in Guul Draz, though. Now when the scouts returned, they brought back little. More often they didn't return at all.
"You are dying, here." Enkindi's voice was rough, clipped.
There was no judgment in his voice, though, just an observation of facts. Still, Drana's voice carried an edge. "We live today." Though as she looked at the dirty faces surrounding them, visages absent hope or spark, she knew she stretched the meaning of "live."
"Yes, today. But to what end? Where does this end? Gideon believes we can make a stand. That if we all stand together, we can. . ."
"Die together?"
"Win. We can win. Many of you are still strong. We know what you can do in battle. Join us."
"And what are we to do with them?" Drana gestured toward various clumps of mortals who huddled with each other, faces turned to the ground until they heard the call to get back on the sled. No faces looked up. The mortals had no desire to gain the attention of any vampire. Drana understood. Eating the dying mortals was the best compromise she could enforce on her people, and if the mortals thought it horrible, it earned her no favor with those she led either.
"I. . ." Enkindi's voice faltered. "I don't know. But they are going to die either way, unless we can beat the Eldrazi." Drana led them toward a large group of small people on the outskirts of the sleds. There were a hundred of them, probably more. Here and only here were there signs of movement not strictly pertaining to survival. Many of the small people were still and huddled but some of them ran and played and shouted.
Only here had Drana posted several guards, her best and most trusted guards, ringing the group—watching for any potential harm. Eldrazi were not the only threat. Though the vampires had not attacked any healthy mortals under their care, at least not after the first transgressors had been punished fatally, she had posted the guards anyway.
"Children. They are. . ." Enkindi's voice had faltered before, but here it broke. #emph[Perfect] .
"No, not children. Warriors. Like you." Drana's voice was languorous, soft and velvety, just as before sinking her teeth into prey. If she could not enjoy actual blood, at least she could enjoy the hunt. "Melindra, come here." She did not shout, but her voice carried.
One of the smaller children broke free from running and came over to Drana and Enkindi. Her hair was clipped short—shorn with a dagger, either by herself or one of the other children. She bore the same angular cheekbones and pale skin as Enkindi, marking her as kor, but there the similarities ended. Her face was filthy, and her clothes torn and ragged. Drana brought out a small piece of meat and palmed it to the child who gulped it down and smiled. Melindra had a beautiful smile.
"Are you children, Melindra?" Drana's voice continued its soft melody.
"No. We're soldiers. We're a brigade, you said. We're the Orphans' Brigade. You said we got to name ourselves, and we did." As she spoke, Melindra whipped out a dagger from a home-made sheathe, all ragged rope and hide. But the dagger was sharp and oiled. "You #emph[said] . We get to choose. We're the Orphans' Brigade."
"And so I did, Melindra. And so you are. The Orphans' Brigade." She patted Melindra on the head, and Melindra looked up at her and smiled again.
Enkindi looked at the child, and back at Drana, tears and anger in his eyes. "They are children! Kor children. . ."
"And humans and merfolk and elves. All mortals are mortal. Becoming a parent does not seem to provide adequate protection against death."
"Do you actually use them to fight? How evil are you? They are. . ."
#figure(image("005_Memories of Blood/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
"Children, yes." She continued to stroke Melindra's rough-hewn hair. "Being a child seems no more protection against death than being a parent. This is war. In my experience, wars are usually very effective at killing children. Perhaps that's the point of war, to kill children."
Enkindi's hand started to flex and tremble, just a bit. His eyes tightened as his tears stopped. Drana had to be very careful here. She could not provoke him so far yet.
"Except in this war, Enkindi, against the Eldrazi, we are all children."
Enkindi's shoulders slumped, and his hand stopped flexing. He looked up at her, clearly lost. How do you save the unsaveable?
"I will not leave them to the Eldrazi. I will not leave any of them. You ask me to go across the narrow ocean to fight with this Gideon, to kill Eldrazi there instead of Eldrazi here. To save those children, but not save these children. I have a different proposal. I'll leave with you to fight with Gideon at Sea Gate, if you and your warriors fight with me first. Help me kill the Eldrazi behind us, who even now slither closer in their hunger. Help me win my battle, and I'll help you win yours."
She stuck out her hand, in the way mortals do, and successfully resisted the urge to bring his neck close and bite when he offered his hand in return. It was extra flair for Melindra to sheathe her dagger and stick out her hand in the same way, but Drana loved the child a little more for it.
Drana sent her lieutenants to begin preparations, and she arranged to meet with Enkindi in the air. They had a battle to plan.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The sun managed to show itself in the early afternoon, its light wan and pale. The Eldrazi seemingly sucked the energy from #emph[everything] , even light itself. The battle plans had been drawn quickly. One of the few advantages to fighting against innumerable odds and a mindless, inexorable foe was that battle strategies were straightforward. Every day, every hour, her army weakened. Better to strike now. A buzz ran through the masses. After so many days of running and death, here would be a chance at resolution. No matter the outcome, tomorrow's reality would be different than today's fear.
She was not prone to careful introspection, but it was hard not to acknowledge this could be the last day of her existence. She had been alive for many thousands of years. But even several hundred years into that life she realized she had a choice. She could dedicate herself to remembering her past, every new day an exercise in keeping hundreds of years of memories alive, or she could . . . let go. She had chosen to let go.
Memories for the long-lived were a delicate edifice of pebbles. Pebble stacked upon pebble upon pebble. She could roughly trace the largest pebbles, but after so many years, everything in her foundation, in her earliest times, was buried. She wanted those earliest days, knew they would be essential to the vampires surviving this war. Today she would get those memories or she would die. She welcomed the prospect of clarity, regardless of the form in which it arrived.
Her opportunities for clarity were approaching on all three sides. The main Eldrazi host, centered around the enormous sire, came from due east. Two smaller hosts converged from the north and the south. She had placed the bulk of her army to engage the large host. The majority of that contingent was vampires supported by mortals she could trust in battle. Those mortals too fractious to reliably follow her orders were placed in charge of the frail and infirm. She didn't bother giving instructions of what they should do if the army failed. They would find out soon enough in the very short time left to them.
Drana's best overseers managed the few hundred fliers they had left. Her fliers, along with Enkindi and his additional hundred troops, would be key. Drana kept her eyes on the Eldrazi sire. It was both the main challenge and opportunity in this battle. They could kill all the other Eldrazi they wanted, but if they could not find a way to bring the sire down, none of the other deaths would matter. And they had no chance of killing the sire without fliers.
The Eldrazi were close. There were thousands, tens of thousands, more; different shapes and sizes running, crawling, slithering, #emph[slurping ] their way across the rocky ground, here on the outskirts of Guul Draz. Some even flew, their misshapen grotesque bodies an affront to Drana's domain. Occasional ripples surged through the masses and Eldrazi bodies would explode or be swallowed up into the earth. It was Zendikar itself rippling to rid itself of the foreign invaders, using the roil to fight its war.
#figure(image("005_Memories of Blood/06.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
But the weapons of the Eldrazi were more fearsome. Everywhere they touched life, life died. Everywhere they touched matter, matter disintegrated. Everywhere they touched the #emph[world] , the world buckled. #emph[They are the end of all things. ] The Eldrazi came upon them.
Mortal and vampire alike met the initial onslaught with a fierce savagery. They blasted, hacked, and tore their way through the unthinking nodes of hunger embodied in gelatinous, tentacled forms. All the fear and despair of the last few weeks was converted to raw fury and power. If these were their last moments of life, they would be epic moments; moments worth a thousand years of story and song to commemorate.
The Eldrazi did not care. The Eldrazi kept on coming.
An Eldrazi drone lashed a barbed tentacle at her head. She bit through it and caught the free appendage, whipping it around to decapitate another Eldrazi behind her. The headless Eldrazi didn't know it was dead, mauling an open-mouthed mortal, sucking him in and eviscerating him in a single undulating motion. Two other mortals fled in terror before being killed by more pressing Eldrazi. Drana chopped an Eldrazi in half with her sword and then spun to punch through the body of another. Drana snarled as she did it, a feral, manic grin on her face. But no Eldrazi ran in terror. So much of the momentum in battle relied on creating fear and intimidation amongst your opponents; once the mind succumbed, the body followed. That approach was useless against the Eldrazi. The only available tactic was killing.
The Eldrazi broke through the front lines, penetrating deeper into the heart of her forces. More Eldrazi came behind them, and more waves were behind them, always advancing. There were too many. Killing would not be enough. Drana needed to pursue her other path to victory.
#figure(image("005_Memories of Blood/07.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
She rose high into the air, where Enkindi and his troops swooped and glided and tore flying Eldrazi to pieces with their sharp hooks and swords. Drana admired the efficiency and effectiveness of the kor kitesailers. They clearly had much practice killing Eldrazi. Drana hoped they would be competent enough.
"Kan!" Drana shouted at her overseer, whom she had kept close to Enkindi's forces. "Mobilize the Orphans' Brigade. Send them toward the sire!" Kan flew down without a word. Enkindi was also close enough to hear. He veered his kitesail in a wide loop to face Drana. "Monster!" His face contorted in anger and disbelief. He ripped his sword through an attacking Eldrazi, its gelatin droplets torn asunder and falling to the ground below, his face on Drana's throughout.
"You send those children to their deaths!" His screams wanted to rip her apart, but no hand of justice came from the sky to do his bidding. Drana would welcome such a hand, as long as it killed the Eldrazi as well.
"We're all going to die. Better to die while trying to win. We need to kill that sire, or we have no chance. The children will serve as necessary bait to lure the sire where we need it to be." She was calm, peaceful. Every word she said was true. The easiest lies were those that were true.
Fifty feet below, the mass of children moved closer to the front lines, ringed in front by her vampire guards. They had never yet intentionally known combat, though each child had experienced battle; every survivor had by this point. The Eldrazi did not care about intentional combatants.
Enkindi swayed in the air, rocking back and forth. Most of his people had gathered close to their leader, sharing his disgust, fear, and hate. He looked at the Eldrazi sire, one hundred feet tall, limbs coming out of limbs coming out of limbs—an impenetrable fortress in the shape of a single giant Eldrazi. Drana imagined the calculations going through Enkindi's mind. Surely he knew what chance they had against such a being. They all knew.
Hatred and despair warred on Enkindi's face as he came to his decision. She applauded his hatred. He deserved better. His snarling voice rang in the wind. "May your death be painful and long. May your death bring neither peace nor redemption." He turned to his group. "To me! We must take down the sire!" They fanned out as a group, angling their kites up and up to seek their fight with the Eldrazi sire.
Drana followed behind, not too close, preparing herself. She had only started to hope when she first saw the kitesails on the horizon earlier today. They were a possibility, a hope, one she had lost after the very first major battle with the Eldrazi weeks ago on the outskirts of Malakir. Her vampires were fearless, strong, relentless, and ferocious in combat—but thousands of vampires could never contemplate doing what a hundred kor might: sacrifice themselves for the good of others.
Enkindi led the charge directly into the head of the Eldrazi sire. Drana understood the plan. The head and neck of the creature, or at least those appendages most closely resembling those equivalents seemed the most vulnerable to blade and rupture. Though Enkindi and his group were moving fast, the Eldrazi moved faster. A large tentacle from the Eldrazi's head wrapped itself around Enkindi while a smaller attached tentacle wrapped itself around Enkindi's head and squeezed. Enkindi's headless corpse, still attached to its broken kitesail, plummeted uselessly to the ground. The kor were being slaughtered as the Eldrazi sire's numerous appendages lashed and pummeled them out of the skies.
#figure(image("005_Memories of Blood/08.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Drana grabbed one of the falling kor midway before hitting his fatal destination. He was still alive, though unconscious and not long to live. She bit deep through his neck; and his eyes shot open, then closed. It was one of most exquisite tastes she had ever enjoyed, suitable for her last feed. She drained him utterly, letting his desiccated flap of skin waft gently to the ground. She needed every mote of energy for what was to come. She summoned the last of her reserve and cast a spell as she gathered speed toward the Eldrazi sire. Only a few kor were still flying free; the rest were dead or being grappled by the sire. The giant Eldrazi, even distracted by all the kor, could still move blisteringly fast. But this time, Drana moved faster.
She flew straight into the center abdomen of the monster, puncturing gelatin, flesh, and muscle into the very heart of the creature. Her world exploded.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The spell she cast allowed her to see #emph[more] , to see energy and patterns normally invisible, even to one such as her. The energy was odd, alien, with a sickly magenta taint, but it was #emph[everywhere] . #emph[I am the hunter. I am the predator. Everything is prey. Everything is mine. ] She had been so thirsty. She thrust her mouth into the beating magenta heart of this monstrous Eldrazi and she drank. She drank deep. Clarity blossomed.
#emph[In the beginning, in the very beginning, there was hunger. That was all there was, this hunger, this want, this need. Our purpose was to consume. We needed legs and eyes to find prey. Arms and teeth to grab prey. Minds and strength to overcome prey. We consumed and used the energy we gained to consume more.]
The mission was clear. It was not clear in words. The words came later, a poor translation from truth to brain to words, those imperfect messengers of need. It was clear in her bones.#emph[ You will consume. You will scour clean. The remnants of the broken must be consumed and cleansed.]
She didn't know what was meant by #emph[broken] , what the Eldrazi even thought of as #emph[whole] , so they could compare and know what was #emph[broken] . Perhaps to those monstrosities, everything that was real, that was the world, was #emph[broken] .
She drank deeper, deeper. The energy from the large Eldrazi flowed into her, suffused every starved pore in her tightened flesh. The Eldrazi sire had a huge hole in its chest where she had burrowed, but it was still upright, still killing, still marching upon her people. She needed more.
#emph[Consciousness, a sense of ] me #emph[separate from the hunger, took years. Perhaps hundreds of years, though how could I know? The realization of consciousness came in waves, descending streaks of insight separating me from my hunger, me from my master. I was no longer an extension of it, of the consuming force named Ulamog. I was ] me#emph[. Drana.]
#emph[But before separation, there had been an . . . unease. An unease that was part of her because there was no her, only the totality of Ulamog in many different forms. An unease that only later, in those dawn moments between being Eldrazi and being Drana, before she forgot it utterly, she understood a glimpse of a facet of a dream.]
#emph[They were not supposed to be here. They were supposed to be ] away#emph[. Somehow, there was an ] away #emph[from Zendikar. There were many ] aways #emph[from Zendikar, and the Eldrazi knew, in so far as they could know anything, they should be ] there#emph[, and not ] here#emph[.]
#emph[But they were ] here#emph[, and their purpose was to consume, and so they did.]
For a brief second she remembered those dawn moments, the confusing blur of an awakening self, and how strong her purpose had been back then, thousands of years ago. That purpose washed over her, a giant wave of ocean crashing over her and subsuming her entirely.
#emph[You will consume. You will scour clean.]
She was no longer remembering. She was #emph[becoming] . The magenta alien energy she drank from the Eldrazi sire pulsed in her veins, no longer subject to her will. She was not devouring it. It was devouring her.
#figure(image("005_Memories of Blood/09.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#emph[You will consume. You will scour clean.]
Tentacles erupted from her back and shoulders, living matter created instantaneously in the shape of her masters, her makers. #emph[We were made in the shadow of our makers.]
#emph[You will consume. You will scour clean.]
The strange creature residing at the heart of the Eldrazi sire, a misshapen form on the precipice of utter transformation, screamed. It was a scream absent peace or redemption. It was a scream heralding the end of a world.
Somewhere the shadow of a thought briefer than a heartbeat once calling itself Drana clung to a pebble of memory. The pebble said, #emph[I serve no one.]
The pebble glowed black, a proud glow, a glow with gravity, and it attracted other pebbles.
#emph[You will consume. You will scour clean.]
The pebbles were struck by a burst of energy, toppling and scattering them.
#emph[I serve no one. ] The pebbles reformed and coalesced into a shape. That shape emerged from the war between magenta and black light. The voice resonated throughout.
#emph[I serve no one.]
#emph[You will cons—]
#emph[I serve no one! I will be free! ] Drana reformed herself inside the Eldrazi womb.
She drank in everything, every particle of the Eldrazi energy around her. She obliterated it and consumed it and bathed in it. The empty meat surrounding her exploded, leaving nothing but Drana floating in space observing the massacre below her. Her army was being routed, and even with the loss of the sire, the Eldrazi victory was nearly complete.
#emph[This is what it feels like to be a god. ] Energy suffused every fiber in her being. She could obliterate armies, she could destroy the sun. #emph[With this power I could do anything. ] Her vision was boosted tenfold from normal. She could make out every face, every detail below. She saw the Orphans' Brigade, the outer rung of children attacked by the Eldrazi, while some of them fought and some of them ran and some of them died.
She should leave them all. They could not help her. She could go directly to Ulamog and confront it, destroy it. Or she could find this #emph[away ] from Zendikar. Why settle with dominating a world, when there were endless worlds to own? The energy inside her bucked and writhed. Veins split open, too rich with power to be contained by any physical form.
Her people were being destroyed. Should she save them? What matter these mortals, even her vampires, when worlds and gods awaited?
#emph[I belong to no one.]
She saw Melindra run up to an Eldrazi spawn and stab it in the head while she screamed. The Eldrazi spawn sputtered and shook, but still coiled a tentacle in reactive tension, and Drana could see the whiplash intended to shear off its assailant's head.
#emph[I belong to no one. ] Melindra could not see the spawn's reaction, could not see the tentacle coming her way to end her life
#emph[I belong to no one . . . but they belong to me.]
Drana screamed as she let loose the energy stored in her body, becoming a glowing magenta sun in the middle of the day. Rays of purple light struck her people, vampire and mortal alike, healing their wounds, making them stronger, faster, invulnerable.
#figure(image("005_Memories of Blood/10.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The Eldrazi's tentacle struck Melindra in her shoulder and the tentacle shattered. Melindra laughed as she tore the Eldrazi's head off its body. She ran to kill the next Eldrazi. In seconds the battle changed, and what was left of Drana's army began obliterating the Eldrazi forces.
The energy continued to pour from Drana. She had already lost more than half of the Eldrazi energy surge, and still she felt she knew no equal on this world. But her people needed more, and she gave it to them. Wounds closed, sickness fled, strength was restored.
The energy was fading, surges becoming dribbles, each pulse emanating from her slower and weaker than the last. With every pulse she came closer to the ground, unwillingly but obeying laws of exhaustion greater than her ability to fly. There were no more Eldrazi in sight, all had been destroyed by her empowered army. The desiccated chalk patterns on the ground grew closer. #emph[They are beautiful. They are horrible.] Then she hit the ground and found oblivion.
#figure(image("005_Memories of Blood/11.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
"We can retake Guul Draz." In the millennia she had known him, Kan never sounded excited, but he did now. Excitement was the prevailing sentiment amongst the survivors, the two thousand of them that remained. They were healthy and refreshed, a combination of Drana's magic and the first taste of victory any of them had in weeks. Drana did not want to ruin their euphoria, but she knew the means of this victory was unique. She would not risk directly battling any Eldrazi the same way any time soon or ever. This time she had managed to preserve her identity, her very self. Next time, the results could be far different.
"Any of the envoys left alive?" Kan shook his head. Enkindi and the rest of the envoys had served their purpose well. She had no need to honor their sacrifice, nor did she feel guilt about her manipulation. Such were the dealings with prey. But even so. . .
"Make preparations to cross to Tazeem. We are going to Sea Gate." Kan raised an eyebrow for a moment before turning around and barking orders. Several other overseers did the same. There were no dissenting voices. Any desire to reclaim <NAME> was swallowed by their fervent obedience to Drana. She had saved them in their most dire time of need.
Drana walked among her people, and all, vampire and mortal alike, bowed with her passing. Their heads looked up, though, searching for her eyes, their gratitude and pleasure clear. She met their gaze and kept walking until she found what she was looking for.
Melindra was among the other surviving children of the brigade, sharpening her dagger with a whetstone. The child, though still dressed in rags, looked nothing like the ravenous waif she had been. She looked strong, hale, a warrior in truth.
Melindra looked up, her face untouched by guile. Whatever she saw in Drana's face made her smile, and she went back to her whetstone and dagger.
Drana had made the decision before losing consciousness in the aftermath of the battle. She had sought out the Eldrazi sire, sought its energy to unlock her own ancient memories. And she had found what she was searching for. The Eldrazi weren't from #emph[here] . Perhaps they didn't even #emph[want ] to be here, for whatever #emph[want ] meant to them. But most important, there was a #emph[there ] for the Eldrazi to go back to.
She contemplated what she would find at Sea Gate. She looked forward to seeing this magical warrior named Gideon, a strange man in strange clothes whom no one on Zendikar had ever heard of before now. Perhaps he came from this #emph[there] , as well.
#emph[They have a place to go. We can send them away to ] there#emph[. Or we can go away to ] there #emph[ourselves.]
Drana stroked the head of the child, and smiled.
#figure(image("005_Memories of Blood/12.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/gradient-math_05.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test a different direction
#show math.equation: set text(fill: gradient.linear(..color.map.rainbow, dir: ttb))
#show math.equation: box
$ A = mat(
1, 2, 3;
4, 5, 6;
7, 8, 9
) $
$ x_"1,2" = frac(-b +- sqrt(b^2 - 4 a c), 2 a) $
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Courses/计算机组成与设计/processor.typ | typst | ---
order: 4
---
#import "/src/components/TypstTemplate/lib.typ": *
#show: project.with(
title: "计算机组成与设计",
lang: "zh",
)
#let tbl_white(white_row: 1 , content_size: 9pt,..args) = align(center, block[
#show table.cell: it => if it.y <= white_row - 1 {
set text(fill: white, stroke: white)
it
} else {
set text(size: content_size)
it
}
#tbl(..args)
])
#counter(heading).update(3)
= The Processor: part 1
#info(caption: "Contents of Chapter 4")[
1. Introduction & Logic Design Conventions
2. Building a datapath
3. A Simple Implementation Scheme
4. Pipelining
]
== Introduction
- CPU performance factors
- Instruction count: 由 ISA 和 compiler 决定,不太能优化
- CPI and Cycle time: 由 CPU 硬件决定,需要我们优化
- 将介绍两种 RISC-V 实现:simplified version 和 Pipelined version
- 指令执行概述
#block(fill: colors.gray, inset: 4pt)[
- Fetch :
- Take instructions from the instruction memory
- Modify PC to point the next instruction
- Instruction decoding & Read Operand:
- Will be translated into machine control command
- Reading Register Operands, whether or not to use
- Executive Control:
- Control the implementation of the corresponding ALU operation
- Memory access:
- Write or Read data from memory
- Only ld/sd
- Write results to register:
- If it is R-type instructions, ALU results are written to rd
- If it is I-type instructions, memory data are written to rd
- Modify PC for branch instructions
]
- 对每个指令,前两步是一样的
- Fetch the instruction from the memory: 从 memory 中取指令
- Decode and read the registers: 解码指令并读取寄存器
- 接下来的步骤取决于 instruction class: Memory-reference, Arithmetic-logical, branches
- Use ALU to calculate
- Memory address for load/store
- Arithmetic result
- Branch comparison
- 再后面就都不一样了
- Overview
#fig("/public/assets/Courses/计组/img-2024-04-01-09-34-40.png")
- 各个部件
#fig("/public/assets/Courses/计组/img-2024-04-01-09-27-57.png")
- Rigister
- 一个时钟周期内先写后读
- Register Files--Built using D flip-flops
#fig("/public/assets/Courses/计组/img-2024-04-01-09-30-50.png")
- Immediate generation unit
- 两个功能:输入指令产生立即数的逻辑、转移指令偏移量左移位(B和J type末尾添0,lui 左移 12 位)
#fig("/public/assets/Courses/计组/img-2024-04-01-09-35-15.png", width: 90%)
- 只考虑 I-type, S-type, B-type, J-type 指令的话,用 ImmSel (Immediate Select)控制
- 为了 lui 需要再加一位
#tbl_white(
columns: 5,
fill: (x,y) => if y == 0 {rgb(51, 102, 204)} else if y == 7 {rgb(220, 229, 242)},
[Instruction type],[Instruction opcode[6:0]],[Instruction operation],[sign-extend immediate],[ImmSel],
table.cell(rowspan: 3)[I-type],[0000011],[Lw;lbu;lh;lb;lhu],table.cell(rowspan: 3)[sign-extend instr[31:20]],table.cell(rowspan: 3)[00],
[0010011],[Addi;slti;sltiu;xori;ori;andi;],[1100111],[jalr],
[S-type],[0100011],[Sw;sb;sh],[sign-extend instr[31:25],[11:7]],[01],
[B-type],[1100011],[Beq;bne;blt;bge;bltu;bgeu],[sign-extend instr[31],[7],[30:25],[11:8],1'b0],[10],
[J-type],[1101111],[jal],[sign-extend instr[31],[19:12],[20],[30:21],1'b0],[11],
[]
)
- 在先前的 CPU overview 中加入控制组件
#fig("/public/assets/Courses/计组/img-2024-04-03-10-14-10.png", width: 75%)
- 时钟控制方法
- 每个周期内的操作通过 Combinational logic 完成(不能有多步操作)
- 因此像是 Add 这种部件在一个周期内多次用到,就需要复制多个
#fig("/public/assets/Courses/计组/img-2024-04-03-10-20-15.png")
== Building a datapath
- 对六种指令分别解释在上面 CPU overview 中的数据流转(还要加 jalr, lui, bne 等)
#fig("/public/assets/Courses/计组/img-2024-04-03-11-19-52.png", width: 110%)
- 思考不同指令在图中的流转路径
== A Simple Implementation Scheme
- Building Controller
- There are $7+4$ signals
#fig("/public/assets/Courses/计组/img-2024-04-03-11-24-57.png", width: 90%)
- 根据下表中蓝色部分生成控制信号
#tbl_white(
white_row: 2,
columns: 8,
fill: (x,y) => if y == 0 or y == 1 {rgb(0, 174, 239)} else if x >= 1 and x <= 5 {rgb(247, 150, 70)} else if x == 6 {rgb(141, 179, 227)},
[name], table.cell(colspan: 6)[Field], [Comments],
[(Field Size)],[7bits],[5bits],[5bits],[3bits],[5bits],[7bits],[],
[R-type],table.cell(fill: rgb(141, 179, 227))[funct7],[rs2],[rs1],table.cell(fill: rgb(141, 179, 227))[funct3],[rd],[opcode],[Arithmetic instruction format],
[I-type], table.cell(colspan: 2)[imm[11:0]],[rs1],table.cell(fill: rgb(141, 179, 227))[funct3],[rd],[opcode],[Loads & Immediate arithmetic],
[S-type],[imm[11:5]],[rs2],[rs1],table.cell(fill: rgb(141, 179, 227))[funct3],[imm[4:0]],[opcode],[Stores],
[SB-type],[imm[12,10:5]],[rs2],[rs1],table.cell(fill: rgb(141, 179, 227))[funct3],[imm[4:1,11]],[opcode],[Conditional branch format],
[UJ-type],table.cell(colspan: 4)[imm[20,10:1,11,19:12]],[rd],[opcode],[Unconditional jump format],
[U-type],table.cell(colspan: 4)[imm[31:12]],[rd],[opcode],[Upper immediate format]
)
- ALU 控制:两步走
+ 首先根据 opcode 生成 ALUOp 和 七位控制信号
+ 然后根据 ALUOp 和 funct7 生成 ALU control(ALU oepartion)
#tbl(
columns: 7,
[opcode],[ALUop],[Operation],[Funct7],[funct3],[ALU function],[ALU control],
[ld],[00],[load register],[XXXXXXX],[xxx],[add],[0010],
[sd],[00],[store register],[XXXXXXX],[xxx],[add],[0010],
[beq],[01],[branch on equal],[XXXXXXX],[xxx],[subtract],[0110],
table.cell(rowspan: 5)[R-type],table.cell(rowspan: 5)[10],[add],[0#redt[0]00000],[#redt[000]],[add],[0010],
[subtract],[0#redt[1]00000],[#redt[000]],[subtract],[0110],
[AND],[0#redt[0]00000],[#redt[111]],[AND],[0000],
[OR],[0#redt[0]00000],[#redt[110]],[OR],[0001],
[SLT],[0#redt[0]00000],[#redt[010]],[Slt],[0111],
)
#fig("/public/assets/Courses/计组/img-2024-04-03-11-32-05.png")
- 为不同指令解释控制信号(画错了?实现不了 jalr 和 lui)
#fig("/public/assets/Courses/计组/img-2024-04-10-10-30-25.png")
- 性能分析
- 分支指令的计算是并行的,不怎么耗时间
- 假设 memory(200ps), ALU and adders(200ps), register file access(100ps)
- 最耗时间的是 load 指令
#tbl(
columns: 7,
[Instr],[Instr fetch],[Register read],[ALU op],[Memory access],[Register write],[Total time],
[ld],[200ps],[100ps],[200ps],[200ps],[100ps],[800ps],
[sd],[200ps],[100ps],[200ps],[200ps],[],[700ps],
[R-format],[200ps],[100ps],[200ps],[],[100ps],[600ps],
[beq],[200ps],[100ps],[200ps],[],[],[500ps],
)
- 每个周期的时间取决于最慢的 800ps
- 两个解决方法
+ 多周期(instr fetch 一个周期,register read 周期……),这样每个周期时间可以很短
+ 流水线(同一周期多条指令并行计算其不同阶段)
== Exception
- CPU 的工作流改变有两种
+ 可预见的(bne/beq, jal , etc)
+ 不可预见的(Exception and Interruption)
- Exception: Arises within the CPU (e.g., overflow, undefined opcode, syscall)
- Interrupt: From an external I/O controller
- 有的时候会把二者混起来
- 异常不一定是不好的,它是 CPU 指令的异步补充
- 当发生异常的时候,CPU 应该做什么?
+ 保护 CPU 现场(发生异常的指令,异常的原因),进入异常
+ 处理中断事件
+ 退出异常,恢复正常操作
- 有点像 `jal`,跳过去,做完后还要回来
- RISC-V 如何处理异常
- 一组专门处理异常的 CSR 寄存器(Control status registers, 4K 个)
- CSR instructions
- RISC-V Privileged
- Each privilege level has a core set of privileged ISA extensions
#tbl(
columns: 6,
[Level],[Encoding],[Name],[Abbreviation],[Intended Usage],[Description],
[0],[00],[User/Application],[U],[用户模式],[用户操作层面],
[1],[01],[Supervisor],[S],[监督模式],[操作系统],
[2],[10],[Reserved/Hypervisor],[H],[保留],[虚拟机相关],
[3],[11],[Machine],[M],[机器模式],[最底层]
)
- 权限模式的组合
- M 是必要的(处理异常)
- 每种模式有自己的 ISA 扩展
#tbl(
columns: 3,
[Number of levels],[Supported Modes],[Intended Usage],
[1],[M],[Simple embedded systems],
[2],[M, U],[Secure embedded systems],
[3],[M, S, U],[Systems running Unix-like operating systems],
)
- Control and Status Registers (CSRs)
- 12 位 csr 对应 4K 个 CSR 寄存器,其最高一二位指定读写模式,最高三四位指定 privilege mode
#tbl(
columns: 5,
[csr],[rs1],[funct3],[rd],[opcode],
[12bits],[5bits],[3bits],[5bits],[7bits],
)
#tbl_white(
columns: 5,
fill: (x,y) => if y == 0 {rgb(51, 102, 204)},
[CSR],[Privilege],[Abbr.],[Name],[Description],
[0x300],[MRW],[mstatus],[Machine STATUS register\ 机器模式状态寄存器],[MIE、MPIE域标记中断全局使能],
[0x304],[MRW],[mie],[Machine Interrupt Enable register\ 机器模式中断使能寄存器],[控制不同类型中断的局部使能],
[0x305],[MRW],[mtvec],[Machine trap‐handler base address\ 机器模式异常入口基地址寄存器],[进入异常服务程序基地址],
[0x341],[MRW],[mepc],[Machine exception program counter\ 机器模式异常PC寄存器],[异常断点PC地址],
[0x342],[MRW],[mcause],[Machine trap cause register\ 机器模式原因寄存器],[处理器异常原因],
[0x343],[MRW],[mtval],[Machine Trap Value register\ 机器模式异常值寄存器],[处理器异常值地址或指令],
[0x344],[MRW],[mip],[Machine interrupt pending\ 机器模式中断挂起寄存器],[处理器中断等待处理],
)
- mstatus
- xIE 控制全局的中断使能
- xPIE 表示从上层跳过来,原本的中断使能
- xPP 表示从什么调过来
#fig("/public/assets/Courses/计组/img-2024-04-15-08-28-43.png",width:97%)
- mie/mip
- 相比相比 status 是更细粒度的中断控制
- xyIE 表示 x 模式下 y 类型的中断使能(E: exception)
- xyIP 表示 x 模式下 y 类型是否有悬挂着的未处理中断(P: pending)
#fig("/public/assets/Courses/计组/img-2024-04-15-08-32-37.png",width:97%)
- mtvec
- 分两种模式,direct 和 vectored,用低两位指示
- 所有的 exception 使用 direct 模式;只有 interrupt 才会使用 vectored 模式
#fig("/public/assets/Courses/计组/img-2024-04-15-08-35-32.png",width:97%)
- mepc
- 存储处理 exception 或 interrupt 完后的 PC 值
- Exception 是 +0,需要回来前更改 mepc,否则会陷入循环;interrupt 是 +4
#fig("/public/assets/Courses/计组/img-2024-04-15-08-37-01.png",width:97%)
- mcause
#fig("/public/assets/Courses/计组/img-2024-04-15-08-38-50.png")
- 从这张图也可以看出 exception 和 interrupt 的区别
#fig("/public/assets/Courses/计组/img-2024-04-24-20-20-40.png")
- 中断优先级
- 优先级高的先处理,低的 pending 悬挂
- External interrupt > Software interrupt > Timer interrupt
- CSR Instruction
#tbl(
columns: 7,
[Instruction],[csr(12)],[rs1(5)],[funt3(3)],[rd(5)],[opcode(7)],[Description],
[CSRRW],[csr],[rs1],[001],[rd],[1110011],[read and write],
[CSRRS],[csr],[rs1],[010],[rd],[1110011],[read and set],
[CSRRC],[csr],[rs1],[011],[rd],[1110011],[read and clean],
[CSRRWI],[csr],[zimm],[101],[rd],[1110011],[read and write imm],
[CSRRSI],[csr],[zimm],[110],[rd],[1110011],[read and set imm],
[CSRRCI],[csr],[zimm],[111],[rd],[1110011],[read and clean imm],
)
- Interrupts Instruction
- MRET: m-return
#fig("/public/assets/Courses/计组/img-2024-04-15-09-02-29.png")
- 中断处理
- RISC-V处理器检测到异常,开始进行异常处理:
- 停止执行当前的程序流,转而从 CSR 寄存器 mtvec 定义的PC地址开始执行;
- 更新机器模式异常原因寄存器:mcause
- 更新机器模式中断使能寄存器:mie
- 更新机器模式异常PC寄存器:mepc
- 更新机器模式状态寄存器:mstatus
- 更新机器模式异常值寄存器:mtval(以上更新均有硬件完成)
- 异常程序处理完成后,需要从异常服务程序中退出,并返回主程序
- RISCV 中定义了一组退出指令 MRET,SRET,和 URET
- 机器模式下退出异常(MIRET)程序流转而从 csr 寄存器 mepc 定义的 pc 地址开始执行
- 同时硬件更新 csr 寄存器机器模式状态寄存器 mstatus
- 寄存器 MIE 域被更新为当前 MPIE 的值:mie $<-$ mpie
- MPIE 域的值则更新为1:MPIE $<-$ 1
= The Processor: part 2
- 之前说到,一个时钟周期内包含:Instruction memory $->$ register file $->$ ALU $->$ data memory $->$ register file
- 多数时候某些步骤空置且不符合"Making the common case fast",采用流水线解决
#info()[
- Pipelining
- Why pipelining
- Pipelined datapath
- Pipelined control
- Pipeline Hazards
- Pipelining with Exceptions
]
== Pipeline overview
- RISC-V Pipeline: 5 stages
+ IF: Instruction fetch from memory
+ ID: Instruction decode & register read
+ EX: Execute operation or calculate address
+ MEM: Access data memory operand
+ WB: Write result back to register
- 根据资源划分阶段
- 流水线的加速比最大能达到*流水线的阶段数*,即 $5$ 倍(理想情况下)
- 后面会说明,由于流水线之间有 overhead,所以不可能达到这个值,也说明并不是阶段数越多越好
#fig("/public/assets/Courses/计组/img-2024-04-24-10-08-51.png")
- 标蓝表示占用,半标蓝表示占用一半(读右,写左)
#fig("/public/assets/Courses/计组/img-2024-04-24-10-28-46.png")
- Pipelined CPU DataPath
- 用蓝线画出的叫做 hazard(冒险),导致数据依赖,会影响流水线的顺序执行
- 显然是简化的,非所有指令;而且是有错的,比如 load、R-type 指令的写回还需要让 rd 也一起跟着流水线走(后面会改)
#fig("/public/assets/Courses/计组/img-2024-04-24-10-21-46.png")
- 需要 pipeline registers 来存储中间结果,寄存器需要足够宽才能存下所有信息
- PC 也可以看作是一个流水线寄存器
#fig("/public/assets/Courses/计组/img-2024-04-24-10-33-33.png")
- Pipeline的问题
+ Latency
+ Imbalance,如浮点计算所需的时间明显比一般指令长
+ Pipeline hazards
+ Overhead: register delay and clock skew
- Pipeline Diagram 的不同视图
- 单个指令的数据流通
- 多个指令的占用图
- Pipelined 视图
- 控制信号的 pipeline
- 把控制信号分类到各个阶段,跟随 pipeline registers 一起流动
== Hazard 处理
- hazards
- structure hazard: 两个指令同时用到了同一个硬件资源,一般较好解决,不考虑
- 假设 Instr_mem 和 Data_mem 是同一个硬件,那么就会有冲突
- register file 也会有冲突,使用 double bump 技术,上升沿和下降沿各自控制读写
#fig("/public/assets/Courses/计组/img-2024-04-24-11-28-24.png")
- data hazard: 两个指令之间有数据依赖,需要等待前一条指令完成
- 后面的 add 用到前面 add 的结果,需要等待(但是 IM 可以执行)
#fig("/public/assets/Courses/计组/img-2024-04-24-11-35-50.png")
- control hazard: branch 或 jump 指令
- 解决所有 hazard 的最简单方法就是 stall,即等待前一条指令完成
- Control hazard:
- Instruction in IF/ID or ID/EX or EX/MEM is a Branch or JMP
- Data hazard:
- RD of Instruction in EX/MEM == Rs1 or Rs2 of instruction in ID/EX
- RD of Instruction in MEM/WB == Rs1 or Rs2 of instruction in ID/EX
- 如何产生 stall
- 编译器层面添加 nop 指令
- 硬件层面添加 detect unit,检测到 hazard 时,让指令可以继续流动,但是不 update registers
- 考虑 stall 的 pipeline 性能分析
- ...
- 下面讨论更详细的 hazard 处理
=== structural hazard
- Multiple accesses to memory
- Multiple accesses to the register file(double bump)
- fully pipelined function unit
#fig("/public/assets/Courses/计组/img-2024-04-24-12-06-30.png")
- 实际情况下 structural hazard 往往不会被处理
+ To reduce cost
+ To reduce latency of the unit
=== Data Hazard
- 后一条指令用到前一条指令的结果
#fig("/public/assets/Courses/计组/img-2024-05-08-10-08-51.png")
- 使用 forwarding(also called bypassing) 来解决
- 从 EX/MEM 前递
#fig("/public/assets/Courses/计组/img-2024-05-08-10-11-13.png")
- 从 MEM/WB 前递,仍需要一个 stall
#fig("/public/assets/Courses/计组/img-2024-05-08-10-17-47.png")
- 下面是一个略复杂的例子
#grid(
columns: (.7fr, 1fr),
[
#align(center, block(inset: 4pt, fill: colors.gray)[
sub #bluet[x2],x1,x3 \
and x12,#bluet[x2],x5 \
or x13,x6,#bluet[x2] \
add x14,#bluet[x2],#bluet[x2] \
sd x15,100(#bluet[x2]) \
])
- 蓝线往前指说明产生了 Data Hazard;同一层级可以用 double bump 解决;往后指不会产生 hazard
- `and` 和 `or` 可以用 forwarding 解决,红线标出
],
fig("/public/assets/Courses/计组/img-2024-05-08-10-25-08.png")
)
- Detecting the Need to Forward
- Data hazards when
$ cases(reverse: #true, "EX/MEM.RegisterRd = ID/EX.RegisterRs1",
"EX/MEM.RegisterRd = ID/EX.RegisterRs2") #block[Fwd from \ EX/MEM \ pipeline reg] \
cases(reverse: #true, "MEM/WB.RegisterRd = ID/EX.RegisterRs1",
"MEM/WB.RegisterRd = ID/EX.RegisterRs2") #block[Fwd from \ MEM/WB \ pipeline reg] $
- But only if forwarding instruction will write to a register!
- EX/MEM.RegWrite, MEM/WB.RegWrite
- And only if Rd for that instruction is not x0
- EX/MEM.RegisterRd != 0, MEM/WB.RegisterRd != 0
- 并且 EX/MEM 的优先级更高(考虑 Double Data Hazard 的情况)
#align(center, block(inset: 4pt, fill: colors.gray)[
add #bluet[x1],x1,x2 \
add #bluet[x1],#bluet[x1],x3 \
add x1,#bluet[x1],x4
])
- DataPath for forwarding 简图(没画 Imm_Gen 等)
#fig("/public/assets/Courses/计组/img-2024-05-08-10-43-05.png")
- Load-Use Dependency
- Dependence between load and the following instructions
#fig("/public/assets/Courses/计组/img-2024-05-08-11-05-22.png")
- 之前说到,一个 ALU 相关指令的前一条指令是 load 且恰好用到其寄存器时,需要 stall 一个周期,可以 Reorder code to avoid use of load result in the next instruction(编译器优化)
#fig("/public/assets/Courses/计组/img-2024-05-08-10-58-19.png")
- Load-use hazard when
- ID/EX.MemRead and
- ID/EX.RegisterRd = IF/ID.RegisterRs1 or ID/EX.RegisterRd = IF/ID.RegisterRs2
- The performance influence of load stall
- 假设 $30%$ 的指令是 load,其中有一半紧跟着一条用到 load 的 result 的指令,且 hazard 导致 one single cycle delay
- $"CPI" = 1+30% times 50% times 1=1.15$,性能降低 $15%$
- 以上考虑的是 ALU 相关 Data dependency 和 Load 指令 dependency,还有别的,比如 Store-use,不过类似
- How to Stall the Pipeline
- 锁定 pipeline registers,让它们不被更改(相当于下个周期继续做这条指令)
- 这个周期内用到的数据可以用 MUX 设为无效值(即这个周期随便做一做)
#fig("/public/assets/Courses/计组/img-2024-05-08-11-15-15.png")
- DataPath for Hazard-detection and reg-disable
#fig("/public/assets/Courses/计组/img-2024-05-08-11-18-16.png")
=== Control Hazards
- 控制指令依赖于先前的指令,比如 Branches
- 中间的三条指令白做了,需要 flush 掉(流水线*冲掉*流水),相当于 $3$ 次 stall
#fig("/public/assets/Courses/计组/img-2024-05-08-11-23-34.png")
- 解决方法
- stall,碰到 branch 就停 $3$ 拍,简单无脑但比较浪费
- Static Prediction
+ Predict-untaken: treat every branch as not taken
+ Predict-taken: treat every branch as taken
- Reducing Branch Delay
- Dynamic Branch Prediction
- Solution: stall
```verilog
if (Branch_ID=1 or Jump_ID=1) ||
(Branch_IDEX 1 or Jump_IDEX 1) ||
(Branch_EXMem=1 or Jump_EXMem 1)
Control_Stall = 1;
if (Control_Stall) begin
NOP_IFID = 1;
end else begin
NOP_IFID = 10
end
```
- 假设 $30%$ 的指令是 branch,$"CPI" = 1+30% times 3 = 1.9$
- Predict-not-taken
- $"Performance" = 1+ "br"% times "take"% times 3$
- Solution: Reducing Branch Delay
- Move the Branch Computation Forward,用硬件换时间,在 IF/ID 阶段算 branch 结果
- Target address adder & Register comparator
#fig("/public/assets/Courses/计组/img-2024-05-08-11-44-39.png")
- 例子:
- 当前周期为:\<old inst(not taken)\>, beq, sub, before\<1\>, before\<2\>
- 下一个周期为:\<new inst(taken)\>, Bubble(nop), beq, sub, before\<1\>
#fig("/public/assets/Courses/计组/img-2024-05-08-11-48-47.png")
- 然而实际情况会更复杂,考虑 branch 指令跟前面指令的 data hazard
+ branch 是先前指令后的第二第三条,用 forwarding
#fig("/public/assets/Courses/计组/img-2024-05-08-11-54-33.png")
+ branch 是先前 ALU 指令后紧跟的一条或 load 指令后的第二条,要 stall 一个周期
#fig("/public/assets/Courses/计组/img-2024-05-08-11-57-23.png")
+ branch 是先前 load 指令后紧跟的一条,要 stall 两个周期
#fig("/public/assets/Courses/计组/img-2024-05-08-11-58-06.png")
- More-Realistic Branch Prediction
- Static branch prediction
- Based on typical branch behavior; Example: loop and if-statement branches
- Dynamic branch prediction
- Hardware measures actual branch behavior; Assume future behavior will continue the trend
- Predictors
- 1 bit: 每次错了都改变结果,错误率较高(墙头草是这样的)
- 2 bit: 错两次之后改变结果
#fig("/public/assets/Courses/计组/img-2024-05-08-12-05-25.png")
- 为实现时的简单起见,我们假定不跳转,即 predict-not-taken
== Pipelining with Exceptions
- 考虑指令 ```assembly add x1, x2, x1```,我们阻止 x1 被更改
- 完成先前的指令,Flush *add* 指令和之后的指令
- Set Cause and SEPC register values (triky,很困难)
- Transfer control to handler,跟 mispredicted branch 类似
- Multiple Exceptions
- 流水线可以同时发生多个异常,如何定位这些异常是哪条指令产生的?如何去处理这多个异常?
- 如果可以确定异常产生的指令并一一处理,那么就称为 precise exception
- 在更复杂的流水线中(多发射、乱序执行),precise exception 是一个很大的挑战
|
|
https://github.com/Karolinskis/KTU-typst | https://raw.githubusercontent.com/Karolinskis/KTU-typst/main/variables.typ | typst | #let ProjectName = "Projekto pavadinimas"
#let ProjectType = "Baigiamasis bakalauro studijų projektas"
#let ProjectTypeEN = "Final Bachelor's Degree Project"
#let ProjectCity = "Kaunas"
#let ProjectYear = "2024"
#let AuthorName = ("autorius", "<NAME>")
#let ProjectTitle = "Projekto pavadinimas"
#let ProjectTitleEN = "Project Title"
#let ProjectType = "Baigiamasis bakalauro studijų projektas"
#let ProjectTypeEN = "Bachelor's Final Degree Project"
#let ProjectAuthor = "<NAME>"
#let ProjectSupervisor = ("Vadovas", "prof. <NAME>")
#let ProjectSupervisorEN = ("Supervisor", "prof. <NAME>")
#let ProjectReviewer = ("Recenzentė", "prof. <NAME>")
#let ProjectReviewerEN = ("Reviewer", "prof. <NAME>")
#let ProjectYear = "2024"
#let ProjectCity = "Kaunas"
#let ProjectFaculty = "Informatikos fakultetas"
#let ProjectFacultyEN = "Faculty of Informatics"
#let ProjectStudies = "Programų sistemos (6121BX012)"
#let ProjectStudiesEN = "Software Systems (6121BX012)"
#let ProjectStudyFieldAndArea = "Informatikos mokslai, Programų sistemos"
#let ProjectStudyFieldAndAreaEN = "Computer Sciences, Software Systems"
#let ProjectKeywords = ("Raktažodis1, Raktažodis2 Raktažodis3")
#let ProjectKeywordsEN = ("Keyword1, Keuword2, Keyword3, etc") |
|
https://github.com/Le-foucheur/Typst-VarTable | https://raw.githubusercontent.com/Le-foucheur/Typst-VarTable/main/README.md | markdown | MIT License | # VarTable
An easy way to render variation table on typst, built on [fletcher](https://github.com/Jollywatt/typst-fletcher)\
The [documention](https://github.com/Le-foucheur/Typst-VarTable/blob/main/documentation.pdf)
```typ
#import "@preview/Tabvar:0.1.0": tabvar
```
# Few examples
### Trigonometric functions
Turn this :
```js
#import "@preview/Tabvar:0.1.0": tabvar
#tabvar(
init: (
variable: $x$,
label: (
([sign of cos], "Sign"),
([variation of cos], "Variation"),
([sign of sin], "Sign"),
([variation of sin], "Variation"),
),
),
domain: ($0$, $ pi / 2 $, $ pi $, $ (2pi) / 3 $, $ 2 pi $),
content: (
($-$, (), $+$, ()),
(
(top, $1$),
(),
(bottom, $-1$),
(),
(top, $1$),
),
($+$, $-$, (), $+$),
(
(center, $0$),
(top, $1$),
(),
(bottom, $-1$),
(top, $1$),
),
),
)
```
Into this

### hyperbolic function $f(x) = 1/x $
```js
#import "@preview/Tabvar:0.1.0": tabvar
#tabvar(
init: (
variable: $x$,
label: (
([sign of $f$], "Sign"),
([variation of $f$], "Variation"),
),
),
domain: ($ -oo $, $ 0 $, $ +oo $),
content: (
($+$, ("||", $+$)),
(
(center, $0$),
(bottom, top, "||", $-oo$, $+oo$),
(center, $0$),
),
),
)
```

# known issues
- if you put too wide an element for the last value of a variation table, this can create a space between the edge of the table and the lines separating the lines of the table

|
https://github.com/vsheg/intermediate-ml | https://raw.githubusercontent.com/vsheg/intermediate-ml/main/template.typ | typst | #import "@preview/drafting:0.2.0": margin-note, set-page-properties
#import "defs.typ": accent-color
#let note(title: [], content) = {
set text(size: 0.9em, fill: luma(20%))
title = strong(title)
margin-note(side: right, stroke: none, title + content)
}
#let example(content) = {
set text(fill: luma(20%), size: 0.9em)
align(center, rect(width: 90%, stroke: (thickness: 0.1pt, dash: "dashed"))[
#set align(left)
*Example*. #content
])
}
#let draft-pattern = {
let element = text(size: 2em, fill: gray.opacify(-95%))[*DRAFT*]
let pat = pattern(size: (90pt, 40pt), element)
rotate(25deg, rect(width: 150%, height: 150%, fill: pat))
}
#let template(is-draft: true, doc) = {
// page setup
let back = none
if is-draft {
back = draft-pattern
}
let full-width = 600pt
let margin = 10pt
set page(
width: full-width + 2 * margin,
height: 24cm,
margin: (y: margin, left: margin, right: 2 / 5 * full-width),
background: back,
)
// important to margin notes from drafting package
set-page-properties()
// font
set text(size: 9pt, hyphenate: true, font: "New Computer Modern")
// math equations
// set math.equation(numbering: "(1)")
// headings
show heading.where(level: 1): it => box(height: 2em, it)
show heading.where(level: 2): it => box(height: 1em, smallcaps(it))
show heading.where(level: 3): it => text(weight: "bold", style: "italic", it.body)
// Styling
// show strong: it => {
// set text(weight: "semibold", fill: luma(30%))
// highlight(fill: accent-color.lighten(90%), it)
// }
// header
{
set text(style: "italic")
grid(
columns: 2,
column-gutter: 1fr,
)[<NAME>][Updated: #datetime.today().display()]
}
doc
}
|
|
https://github.com/TechnoElf/mqt-qcec-diff-presentation | https://raw.githubusercontent.com/TechnoElf/mqt-qcec-diff-presentation/main/content/introduction.typ | typst | #import "../template/conf.typ": slide
|
|
https://github.com/liuguangxi/erdos | https://raw.githubusercontent.com/liuguangxi/erdos/master/Problems/typstdoc/figures/p218.typ | typst | #import "@preview/cetz:0.2.1"
#cetz.canvas({
import cetz.draw: *
let a = 0.8
line((3*a, 0), (1.5*a, 1.5*calc.sqrt(3)*a), (-1.5*a, 1.5*calc.sqrt(3)*a),
(-3*a, 0), (-1.5*a, -1.5*calc.sqrt(3)*a), (1.5*a, -1.5*calc.sqrt(3)*a), close: true)
line((-3*a, 0), (3*a, 0))
line((-1.5*a, 1.5*calc.sqrt(3)*a), (1.5*a, -1.5*calc.sqrt(3)*a))
line((1.5*a, 1.5*calc.sqrt(3)*a), (-1.5*a, -1.5*calc.sqrt(3)*a))
line((-2*a, calc.sqrt(3)*a), (2*a, calc.sqrt(3)*a))
line((-2.5*a, 0.5*calc.sqrt(3)*a), (2.5*a, 0.5*calc.sqrt(3)*a))
line((-2.5*a, -0.5*calc.sqrt(3)*a), (2.5*a, -0.5*calc.sqrt(3)*a))
line((-2*a, -calc.sqrt(3)*a), (2*a, -calc.sqrt(3)*a))
line((-2.5*a, 0.5*calc.sqrt(3)*a), (-0.5*a, -1.5*calc.sqrt(3)*a))
line((-2*a, calc.sqrt(3)*a), (0.5*a, -1.5*calc.sqrt(3)*a))
line((-0.5*a, 1.5*calc.sqrt(3)*a), (2*a, -calc.sqrt(3)*a))
line((0.5*a, 1.5*calc.sqrt(3)*a), (2.5*a, -0.5*calc.sqrt(3)*a))
line((-0.5*a, 1.5*calc.sqrt(3)*a), (-2.5*a, -0.5*calc.sqrt(3)*a))
line((0.5*a, 1.5*calc.sqrt(3)*a), (-2*a, -calc.sqrt(3)*a))
line((2*a, calc.sqrt(3)*a), (-0.5*a, -1.5*calc.sqrt(3)*a))
line((2.5*a, 0.5*calc.sqrt(3)*a), (0.5*a, -1.5*calc.sqrt(3)*a))
})
|
|
https://github.com/metamuffin/typst | https://raw.githubusercontent.com/metamuffin/typst/main/tests/typ/compiler/methods.typ | typst | Apache License 2.0 | // Test method calls.
// Ref: false
---
// Test whitespace around dot.
#test( "Hi there" . split() , ("Hi", "there"))
---
// Test mutating indexed value.
#{
let matrix = (((1,), (2,)), ((3,), (4,)))
matrix.at(1).at(0).push(5)
test(matrix, (((1,), (2,)), ((3, 5), (4,))))
}
---
// Test multiline chain in code block.
#{
let rewritten = "Hello. This is a sentence. And one more."
.split(".")
.map(s => s.trim())
.filter(s => s != "")
.map(s => s + "!")
.join("\n ")
test(rewritten, "Hello!\n This is a sentence!\n And one more!")
}
---
// Test .at() default values for content.
#test(auto, [a].at("doesn't exist", default: auto))
---
// Error: 2:2-2:15 type array has no method `fun`
#let numbers = ()
#numbers.fun()
---
// Error: 2:2-2:43 cannot mutate a temporary value
#let numbers = (1, 2, 3)
#numbers.map(v => v / 2).sorted().map(str).remove(4)
---
// Error: 2:3-2:19 cannot mutate a temporary value
#let numbers = (1, 2, 3)
#(numbers.sorted() = 1)
---
// Error: 2-5 cannot mutate a constant: box
#box.push(1)
---
// Test content fields method.
#test([a].fields(), (text: "a"))
#test([a *b*].fields(), (children: ([a], [ ], strong[b])))
|
https://github.com/giZoes/justsit-thesis-typst-template | https://raw.githubusercontent.com/giZoes/justsit-thesis-typst-template/main/resources/layouts/preface.typ | typst | MIT License | #import "@preview/anti-matter:0.0.2": anti-matter
// 前言,重置页面计数器
#let preface(
// documentclass 传入的参数
twoside: false,
// 其他参数
spec: (front: "I", inner: "1", back: "I"),
..args,
it,
) = {
// 分页
if (twoside) {
pagebreak() + " "
}
counter(page).update(0)
anti-matter(spec: spec, ..args, it)
} |
https://github.com/jamesrswift/frackable | https://raw.githubusercontent.com/jamesrswift/frackable/main/src/impl.typ | typst | The Unlicense | /// Create vulgar fractions using unicode
/// #example(```typ
/// #frackable(1, 2)
/// #frackable(1, 3)
/// #frackable(9, 16)
/// #frackable(31, 32)
/// #frackable(0, "000")
/// #frackable(whole: 9, 3, 4)
/// ```, scale-preview: 200%)
///
/// - numerator (integer, string): The top part of the fraction.
/// - denominator (integer, string): The bottom part of the fraction.
/// - whole (integer, string): Optional whole number to precede the vulgar
/// fraction, making mixed fraction.
/// -> content
#let frackable(
numerator,
denominator,
whole: none
) = {
show: box
if whole != none {str(whole) + "\u{2064}"}
set text(fractions: true)
str(numerator) + "\u{2044}" + str(denominator)
}
/// Returns a function having the same signature as `frackable`, to be used
/// for typesetting vulgar fractions within fonts that do not support the
/// `frac` feature. Default values are chosen for `Linux Libertine` font.
/// Can be used to display arbitrary strings as a vulgar fraction, rather than
/// just integers or interger-like strings.
/// #example(```typ
/// #set text(font: "Calibri")
/// #let my-frackable = generator(
/// shift-numerator-x: -0.1em,
/// shift-denominator-x: -0.1em,
/// )
///
/// #my-frackable(1, 2)
/// #my-frackable(1, 3)
/// #my-frackable(3, 4, whole: 9)
/// #my-frackable(0, "000")
///
/// ```)
///
/// - font-size (length): Font size with which to display numerator and denominator. Best practice is to use `em` units.
/// - shift-numerator-y (length): Amount of vertical shift to apply to numerator. Best practice is to use `em` units.
/// - shift-numerator-x (length): Amount of horiztonal space *between slash and numerator*. Best practice is to use `em` units.
/// - shift-denominator-y (length): Amount of vertical shift to apply to denominator. Best practice is to use `em` units.
/// - shift-denominator-x (length): Amount of horiztonal space *between slash and denominator*. Best practice is to use `em` units.
#let generator(
font-size: 0.55em,
shift-numerator-x: -0em,
shift-numerator-y: -0.6em,
shift-denominator-x: 0em,
shift-denominator-y: 0.05em,
) = (numerator, denominator, whole: none) => {
show: box
if whole != none {str(whole) + "\u{2064}"}
text(
str(numerator),
size: font-size, baseline: shift-numerator-y,
)
h(shift-numerator-x)
"\u{2044}"
h(shift-denominator-x)
text(
str(denominator),
size: font-size, baseline: shift-denominator-y
)
} |
https://github.com/lvignoli/typst-action-example | https://raw.githubusercontent.com/lvignoli/typst-action-example/main/main.typ | typst | #set page("a4")
#show link: it => underline(text(fill: blue)[#it])
#[
#set align(center)
#set text(32pt, weight: "light")
Example document
]
This document was generated using the Typst GitHub action #link("https://github.com/marketplace/actions/github-action-for-typst")[lvignoli/typst-action].
The action code is
#let action = read(".github/workflows/build.yml")
#raw(action, lang: "yaml")
#v(2em)
And now some cool maths:
$
forall k in NN^*, quad sum_(n=1)^k sum_(m=1)^k (n^2 - m^2) / (n^2+m^2)^2 &= 0, \
"but" quad sum_(n=1)^infinity sum_(m=1)^infinity (n^2 - m^2) / (n^2+m^2)^2 &= pi/4.
$
|
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/strong/strong_inserted.typ | typst | *first*\
#strong[second]\
*third*\
#strong[forth]\
*fifth*\
#strong[sixth] |
|
https://github.com/SeniorMars/tree-sitter-typst | https://raw.githubusercontent.com/SeniorMars/tree-sitter-typst/main/examples/meta/bibliography.typ | typst | MIT License | // Test citations and bibliographies.
---
// Error: 15-25 failed to parse biblatex file: wrong number of digits in line 5
#bibliography("/bad.bib")
---
// Test ambiguous reference.
= Introduction <arrgh>
// Error: 1-7 label occurs in the document and its bibliography
@arrgh
#bibliography("/works.bib")
---
#set page(width: 200pt)
= Details
See also #cite("arrgh", "distress", [p. 22]), @arrgh[p. 4], and @distress[p. 5].
#bibliography("/works.bib")
---
// Test unconventional order.
#set page(width: 200pt)
#bibliography("/works.bib", title: [Works to be cited], style: "author-date")
#line(length: 100%)
#[#set cite(brackets: false)
As described by @netwok],
the net-work is a creature of its own.
This is close to piratery! @arrgh
And quark! @quark
|
https://github.com/gyarab/2023-4e-ruzicka-jako_pavouk | https://raw.githubusercontent.com/gyarab/2023-4e-ruzicka-jako_pavouk/main/src-docs/kapitoly/problemy.typ | typst | = Problematika
== Slovník
Jednou z prvních komplikací bylo najít nějaký dobrý slovník (respektive seznam českých slov, ne jejich významy). Jediný takový seznam, který jsem byl schopen dohledat, byl Český národní korpus SYN2015 o cca 70 000 slovech, který jsem si zatím zredukoval asi na *61 000* a stále čas od času narazím na nějaké cizí nebo zvláštní slovo. Ručně projít tisíce slov totiž není žádný med.
Věty objevující se v testu psaní jsem posbíral z webu Pohádkozem @pohadkozem. Jejich pohádky jsou ze starších knih, jejichž autoři už jsou více než 70 let po smrti.
== Fungování na mobilních zařízeních
Fungování aplikace na výuku psaní všemi deseti na mobilních zařízeních je docela *paradox*. Přestože samotné psaní nedává smysl na malém displeji, musí být stránka přístupná na jakémkoli stroji. V roce 2023 asi 3/4 návštěvnosti webu totiž pocházelo z telefonů. @pc-mobile
Jako Pavouk je tedy responzivní a plně funkční na malých displejích, co se obsahu, přihlašovacího systému, statistik a dalšího týče. Když se ale uživatel pokusí vstoupit do samotného přepisování textů, setká se s hláškou _"Psaní na telefonech zatím neučíme…"_
Aplikace detekuje mobilní zařízení jednoduše podle šířky HTML dokumentu. Druhou největsí modifikací webu je asi menu, které se schovává do strany a je přístupné přes kulaté tlačítko v rohu obrazovky.
== Dvě různá rozložení klávesnice
V České republice jsou běžně používány dvě různá rozložení klávesnice a to QWERTZ a QWERTY. Jedním z problémů, které nevycházely z technického provedení, ale z čistého konceptu, byla implementace těchto dvou rozložení. Nemyslím tím samotnou grafickou klávesnici na frontendu, kde stačilo prohodit Z a Y, ale problém se slovy pro každou lekci zvlášť.
Moje první *nedomyšlené řešení*, které jsem psal ještě v době, kdy stránka disponovala jen texty z náhodně složených písmen, spočívalo v záměně písmenek po vygenerování textu. Tento způsob však logicky fungoval jen pro texty složené z náhodných písmen („ttzz zttt ztzz“) a záměna těchto písmen, ve cvičeních se slovy nebyla ideální („kůylata yůstat důkay“).
#block(breakable: false)[
V databázi máme relaci „slovnik“, která jak název napovídá, obsahuje všechna slova používaná k trénování. V lekci je ale nutné používat pouze slova složená z *již naučených* písmen. Proto jsem si lekce rozdělil na skupiny podle klávesnice, pro kterou jsou vytvořeny a každému slovu přiřadil id lekce, ve které už je možné ho napsat. Níže v ukázce dat vlevo z databáze můžeme vidět jednotlivé lekce a typ klávesnice, ke kterému patří. Potom v druhé tabulce vpravo vidíme slova ze slovníku a „id“ lekcí, do kterých patří v závislosti na rozložení klávesnice.
```asm
lekce | slovnik
¯¯¯¯¯¯¯ | ¯¯¯¯¯¯¯¯¯
id | pismena | klavesnice | slovo | qwertz_id | qwerty_id
----+---------------+------------ | ----------+-----------+-----------
... |
4 | aů | oboje | ...
5 | tz | qwertz | autorství | 17 | 17
6 | ty | qwerty | autorů | 9 | 9
7 | ru | oboje | auty | 13 | 7
... | autory | 13 | 9
12 | cn | oboje | autoři | 16 | 16
13 | yxm | qwertz | ...
14 | zxm | qwerty |
15 | žý | oboje |
... |
```
Jako příklad se můžeme podívat na slovo `auty`, které do množiny již použitelných slov nepřichází ve stejné lekci. U varianty QWERTY totiž už umíme všechna potřebná písmena u 7. lekce. Na druhou stranu u QWERTZ, kde u 7. lekce ještě neumíme písmeno Y, se slovo `auty` objeví až ve 13. lekci, kdy se Y naučíme.
]
#block(breakable: false)[ // aby se to nezalomilo na další stranu
== Optimalizace
*SEO* (Search Engine Optimization) je něco, čemu by se většina vývojářů raději vyhnula. Bohužel se ale bez toho vaše aplikace k nikomu nedostane. Proto jsem se i na tuto stránku vývoje zaměřil a optimalizoval všechny aspekty aplikace tak, aby byly všechny vyhledávače spokojené a aby hladce běžela na jakkoliv starém hardwaru (testováno na Macbooku, 2008, Intel Core 2 Duo, 4GB RAM, linux).
PageSpeed Insights (běžící na open-source Lighthouse)@lighthouse je *nástroj od Google*, který poskytuje statistiku o výkonu a celkové použitelnosti jakékoliv webové stránky. Nejdůležitější jsou ale doporučení a způsoby, jak veškeré problémy se stránkou vyřešit. I to tento nástroj poskytuje. Poté co jsem prošel každý jeden problém a obětoval pár hodin svého času, jsem dosáhl výsledku níže.
#figure(
image("../obrazky/seo.png", width: 90%),
caption: [PageSpeed Insights screenshot],
) <seo>
]
Trošku nešťastné je *jméno "<NAME>"*, které sice hezky vystihuje aplikaci a umožňuje mi používat pavouka jako maskota, ale překrývá se se stejnojmenným filmem, a tak boj o první příčky ve výsledcích hledání není jednoduchý.
Co se týče samotných vyhledávačů, nejpopulárnější Google má v tuto chvíli paradoxně moji aplikaci rád nejméně. Alternativy jako DuckDuckGo, Qwant nebo Bing zobrazují stránku mnohem častěji a jako jednu z prvních. Naštěstí se ale i pozice na Google vyhledávači postupně zlepšuje.
== Výběr jmen uživatelů
Jelikož <NAME> disponuje i přihlašováním pomocí účtů Google, musel jsem se potýkat s otázkou, jaké *unikátní jméno* uživateli přiřadit pro naši databázi, která nemá stejné požadavky na jeho tvar. Od googlu po přihlášení získám kromě e-mailu i jméno a příjmení uživatele, ze kterého mohu vytvořit jméno pro naši aplikaci.
První implementace vypadala tak, že jsem vytáhl jména všech uživatelů z databáze, v lineárním čase je přidal do hashovací tabulky a poté v konstantním čase zkoušel různé kombinace jména a příjmení. Datovou strukturu jsem sice použil, abych se nemusel zbytečně dotazovat do databáze, ale když jsem se podruhé zamyslel, nebylo to nejoptimálnější řešení, jelikož šance, že jméno už bude používáno, je velmi malá. Proto bylo často zbytečné vytvářet hash tabulku jen kvůli jedné jediné kontrole.
#block(breakable: false)[
Způsob, kterým jsem nakonec první řešení nahradil, spočívá v *přidání náhodného čísla za jméno* uživatele. V tomto případě je velmi malá pravděpodobnost kolize v databázi, a ještě menší, že tato kolize nastane vícekrát. Díky tomuto vylepšení není potřeba načítat všechna jména uživatelů a ani na databázi nebude příliš velký nápor.
] |
|
https://github.com/UntimelyCreation/typst-neat-cv | https://raw.githubusercontent.com/UntimelyCreation/typst-neat-cv/main/src/content/en/experience.typ | typst | MIT License | #import "../../template.typ": *
#cvSection("Experience")
#cvEntry(
title: [Senior Software Engineer],
organisation: [ABC Company],
logo: "",
date: [2021 - Present],
location: [France],
description: list(
[#lorem(20)],
[#lorem(20)],
),
tags: ("Go", "TypeScript", "React", "PostgreSQL")
)
#divider()
#cvEntry(
title: [Software Engineer],
organisation: [DEF Corporation],
logo: "",
date: [2018 - 2021],
location: [France],
description: list(
[#lorem(12)],
[#lorem(12)],
),
tags: ("Python", "PostgreSQL")
)
#divider()
#cvEntry(
title: [Software Engineer Intern],
organisation: [XYZ Enterprise],
logo: "",
date: [Summer 2015],
location: [France],
description: list(
[#lorem(16)],
[#lorem(16)],
),
tags: ("TypeScript", "Angular")
)
|
https://github.com/Duolei-Wang/modern-sustech-thesis | https://raw.githubusercontent.com/Duolei-Wang/modern-sustech-thesis/main/template/sections/README.md | markdown | MIT License | # sustech-bachelor-thesis
版本说明:v0.1.0.
TODO:
- [ ] 引用格式 check.
南方科技大学本科毕业设计(论文)模板,论文格式参照 [南方科技大学本科生毕业设计(论文)撰写规范](https://tao.sustech.edu.cn/studentService/graduation_project.html). 如有疏漏敬请谅解,本模板为本人毕业之前自用,如有使用,稳定性请自行负责.
本模板参考了 [iydon](https://github.com/iydon) 仓库的的 $\LaTeX$ 模板 [sustechthesis](https://github.com/iydon/sustechthesis);结构组织参照了 [shuosc](https://github.com/shuosc) 仓库的 [SHU-Bachelor-Thesis-Typst](https://github.com/shuosc/SHU-Bachelor-Thesis-Typst) 模板;图片素材使用了 [GuTaoZi](https://github.com/GuTaoZi) 的同内容仓库里的模板.
本模板、仓库处于个人安利 typst 的需要——在线模板需上传至 typst 官方仓库才能被搜索到,如有开发和接管等需求请务必联系我:
QQ: 782564506
mail: <EMAIL>
## Quickstart
按照毕业设计要求,以 markdown 格式书写你的毕业论文,只需要:
- 在 configs/info 里填入个人信息.
如有标题编译错误(比如我默认了有三行标题),可以自行按照编译器提示把相关代码注释或者修改. 大体语法和内容与基本的编程语言无差别.
- 在 content.typ 里以 typst 特定的 markdown 语法书写你的论文内容.
有关 typst 中 markdown 的语法变更,个人认为的主要变化罗列如下:
- 标题栏使用 '=' 而非 '#','#' 在 typst 里是宏命令的开头.
- 数学公式不需要反斜杠,数学符号可以查阅:https://typst.app/docs/reference/symbols/sym/. 值得注意的是,typst 中语法不通过叠加的方式实现,如 “不等号” 在 LaTex 中是 '\not{=}'. 而在 typst 中,使用 'eq.not' 的方式来调用 'eq'(等号)的 'not'(不等)变体实现.
- 引用标签采用 '@label' 来实现,自定义标签通过 '<label-title>' 来实现. 对于 BibTex 格式的引用(refer.bib),与 LaTex 思路相同,第一个缩略词将会被认定为 label.
- 自定义格式的思路.
如有额外的需要自定义格式的需求,可以自行学习 '#set', '#show' 命令,这可能需要一定的编程语言知识,后续我会更新部分简略教程在我的 github 仓库里:https://github.com/Duolei-Wang/lang-typst.
- 本模板的结构
1. 内容主体. 文章主体内容书写在 content.typ 文件中,附录部分书写在 appendix.typ 文件中.
2. 内容顺序. 文章内容顺序由 main.typ 决定,通过 typst 中 '#include' 指令实现了页面的插入.
3. 内容格式. 内容格式由 /sections/*.typ 控制,body.typ 控制了文章主体的格式,其余与名称一致. cover 为封面,commitment 为承诺书,outline 为目录,abstract 为摘要.
## 有关字体的补充说明
为了 typst/packages 审核方便,我将字体文件上传到了个人版本的仓库里:https://github.com/Duolei-Wang/sustech-thesis-typs. 如有字体使用的需求,请将其中 fonts 文件夹下载后移动到当前根目录下使用.
经个人查阅,论文等要求的“宋体”等字体要求均是一个模糊的概念.
实际上,Windows 系统的宋体指中易宋体等,macOS 采用了华文宋体等. 为了避免不必要的纠纷,建议字体采用完全开源的字体,如:思源宋体、思源黑体、方正宋体、方正黑体、方正楷体、仿宋GB2312 等. 如担心字体审核问题,建议统一采用 GB2312 系列(缺点是部分生僻字缺失). 本模板中使用的字体均为开源字体.
论文字体的选择在 font.typ 里进行了设置,可以修改 SongTi, HeiTi 等自变量的值来决定采用哪一个字体,这些自变量的值应当是字体的标准名称.
如果想查阅当前编译环境内的可选字体,可以通过以下两种方式:
```typst
#set text(
font: ...
)
```
然后将光标悬停在 'font: ' 后,编译器会自动列出当前可用字体.
或者采用命令行指令 'typst fonts' 来查看可选字体.
# 特别鸣谢
- 绘制封面页的时候,参考了 LaTex 版本的 [sustechthesis](https://github.com/iydon/sustechthesis),特此感谢.
- 感谢 [SHU-Bachelor-Thesis](https://github.com/shuosc/SHU-Bachelor-Thesis-Typst) 的结构组织让我学习到了很多,给我的页面组织提供了灵感,
- 在查找图片素材的时候,发现了 GuTaoZi 的 [SUSTech-thesis-typst](https://github.com/GuTaoZi/SUSTech-thesis-typst),发现了自己是闭门造车的事实. 故标注本人的模板为自用版本,此外,校徽等素材使用了咕桃的 svg 素材,特此感谢. |
https://github.com/pku-typst/ichigo | https://raw.githubusercontent.com/pku-typst/ichigo/main/export.typ | typst | MIT License | #import "src/lib.typ": config, prob |
https://github.com/TGM-HIT/typst-thesis-workshop | https://raw.githubusercontent.com/TGM-HIT/typst-thesis-workshop/main/README.md | markdown | Die Folien (ohne Animationen) findest du hier: https://github.com/TGM-HIT/typst-thesis-workshop/blob/main/slides/typst-workshop-handout.pdf
|
|
https://github.com/piepert/philodidaktik-hro-phf-ifp | https://raw.githubusercontent.com/piepert/philodidaktik-hro-phf-ifp/main/src/parts/ephid/ephid.typ | typst | Other | #import "/src/template.typ": *
#make-part([Einführung in die Philosophiedidaktik], subtitle: [Eine Übersicht der philosophiedidaktischen Themen])
#include "grundpositionen/main.typ"
#include "ziele_und_aufgaben/main.typ"
#include "unterrichtsplanung/main.typ"
#include "beurteilen_bewerten/main.typ"
#include "operatoren/main.typ"
#include "rahmenplaene/main.typ"
#include "descartes/main.typ"
#include "klausur/main.typ" |
https://github.com/jamesrswift/journal-ensemble | https://raw.githubusercontent.com/jamesrswift/journal-ensemble/main/src/elements/cetz-plot.typ | typst | The Unlicense | #import "@preview/cetz:0.2.2"
#let plot(
columns: 1,
figure-args: arguments(),
canvas-args: arguments(),
plot-args: arguments(),
body
) = {
set par.line(numbering: none)
figure(
placement: auto,
scope: if columns == 1 {"column"} else {"parent"},
..figure-args,
cetz.canvas(..canvas-args, {
cetz.plot.plot(
size: if columns == 1 {
(8, 4.5)
} else if columns == 2 {
(16, 9)
},
body,
..plot-args
)
})
)
} |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/renderer/react.typ | typst | Apache License 2.0 | #import "/docs/cookery/book.typ": book-page
#import "/docs/cookery/term.typ" as term
#show: book-page.with(title: "React Library")
= React Library
Use #link("https://www.npmjs.com/package/@myriaddreamin/typst.react")[`@myriaddreamin/typst.react`].
```typescript
import { TypstDocument } from '@myriaddreamin/typst.react';
export const App = (artifact: Uint8Array) => {
return (
<div>
<h1>Demo: Embed Your Typst Document in React</h1>
<TypstDocument fill="#343541" artifact={artifact} />
</div>
);
};
```
=== `fill` property
Fill document with color.
```html
<TypstDocument fill="#343541"/>
```
Note: Current typst.ts doesn't support a transparent background color in some browsers.
=== `artifact` property
Render the document with artifact from precompiler.
```html
<TypstDocument artifact={artifact}/>
```
#include "get-artifact.typ"
=== Set renderer initialization option for `TypstDocument`
Retrieve a #term.init-option for initializating the renderer for `TypstDocument`
```ts
TypstDocument.setWasmModuleInitOptions({
getModule: () =>
'http://localhost:20810/typst_ts_renderer_bg.wasm',
});
```
The default value is:
```ts
{
beforeBuild: [],
getModule: () => '/node_modules/@myriaddreamin/typst-ts-renderer/pkg/typst_ts_renderer_bg.wasm',
}
```
=== Example: show document
See #link("https://github.com/Myriad-Dreamin/typst.ts/tree/main/packages/typst.react/src/demo")[typst.react demo] for more details.
|
https://github.com/GYPpro/ACM_res | https://raw.githubusercontent.com/GYPpro/ACM_res/main/2_Notes/PBDS.typ | typst | #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx
// Display inline code in a small box
// that retains the correct baseline.
#set text(font:("Times New Roman","Source Han Serif SC"))
#show raw.where(block: false): box.with(
fill: luma(230),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// #set raw(align: center)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#set page(
// flipped: true,
paper: "a4",
// background: [#image("background.png")]
)
#set text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight: "regular",
size: 13pt,
)
#let nxtIdx(name) = box[ #counter(name).step()#counter(name).display()]
// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill: luma(230),
inset: 7pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#let titlePage(titleName,translatedTitle,Discrib) = [
#set page(footer: [])
#[
#text(
font:("Times New Roman","Source Han Serif SC"),
style:"normal",
weight:"regular",
size: 22pt,
)[
#align(
left+horizon
)[
#heading(level: 1,[#strong(titleName)])
#smallcaps(translatedTitle)
#line(start: (0pt,11pt),end:(300pt,11pt))
#[
#text(Discrib,size:19pt)
]
]
]
]
]
#set heading(
numbering: "1.1.1."
)
= PBDS (Policy-Based Data Structures)中的常用结构
== 基于`tree_policy`
\
*头文件:*
```cpp
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
```
*类型定义:*
```cpp
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
typedef tree<int, null_type, less_equal<int>, rb_tree_tag,
tree_order_statistics_node_update> ordered_multiset;
```
*使用:*
除正常按`set`、`multiset`使用外,有两种特殊成员函数:
```cpp
ordered_multiset o_mset;
ordered_set o_set;
...
o_set.find_by_order(n);//返回第n+1小的元素的迭代器
//即序列增序时下标n对应元素
o_mset.find_by_order(n);//同理
o_set.order_of_key(n);//返回容器中严格小于n的元素的数量
o_mset.order_of_key(n);//同理
``` |
|
https://github.com/maxgraw/bachelor | https://raw.githubusercontent.com/maxgraw/bachelor/main/apps/document/src/5-implementation/rendering.typ | typst | Im vorherigen Kapitel wurden bereits die Grundlagen der Architektur und Technologie der Anwendung beschrieben. Hierbei wurde auch die Grundsätzliche Render Funktion der Anwendung dargestellt. Im Folgenden wird genauer auf die Darstellung der Anwendung eingegangen.
Um die Verschmelzung von realer und virtueller Welt zu verbessern, wird in der Anwendung ein Schattenwurf implementiert. Hierbei wird ein Schattenwurf für die 3D-Objekte in der Szene erstellt, um die Illusion von Tiefe und Realismus zu erhöhen.
Three.js ermöglicht das Aktivieren von Schatten durch die Verwendung von Lichtquellen und Shadow Mapping wie in @figure-initShadow dargestellt. Shadow Mapping beschreibt den Prozess, bei dem Schatten zu einer 3D-Szene hinzugefügt werden. Dabei unterstützt Three.js verschiedene Arten von Shadow Mapping. In der Anwendung wurde "PCFSoftShadowMap" verwendet. Dieser Typ bietet einen weichen Schattenwurf, der besonders bei niedriger Auflösung der Schatten-Map geeignet ist. Obwohl er rechenintensiver als andere Typen ist, wird die Performance aufgrund der begrenzten Anzahl an 3D-Objekten in der Anwendung nicht stark beeinträchtigt.
#let code = ```js
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
```
#figure(
code,
caption: [Initialisierung des Shadow Mapping in Three.js]
) <figure-initShadow>
Im @webxr-lighting-chapter wurde die WebXR Estimated Light API vorgestellt. Diese API ermöglicht es, die Lichtverhältnisse in der realen Welt zu schätzen und diese Informationen in der AR-Anwendung zu verwenden. Dadurch wird eine realistischere Darstellung der 3D-Objekte in der Szene ermöglicht, was zu einer besseren Verschmelzung von realer und virtueller Welt führt. Three.js implementiert diese API und ermöglicht die direkte Verwendung in der Anwendung.
Zunächst muss eine neue Instanz der XREstimatedLight-Klasse initialisiert werden. In @figure-light wird diese Instanz erstellt. Anschließend wird mithilfe von EventListenern auf die Events "estimationstart" und "estimationend" auf die Verfügbarkeit der API gewartet. Sollte die API verfügbar sein und die Schätzung der Lichtverhältnisse beginnen, wird durch das Event "estimationstart" die Lichtquelle der Szene hinzugefügt und die Standardlichtquelle entfernt. Wenn die Schätzung beendet ist, wird durch das Event "estimationend" die Lichtquelle wieder entfernt und die Standardlichtquelle hinzugefügt.
Durch das Abwarten eines Events kann im Sinne des Progressive Enhancement auch ohne Verfügbarkeit der API eine alternative Darstellung gewählt werden. In diesem Fall wird eine vorgefertigte statische Lichtquelle verwendet.
#let code = ```js
const xrLight = new XREstimatedLight(renderer);
xrLight.addEventListener("estimationstart", () => {
scene.add(xrLight);
scene.remove(defaultLight);
});
xrLight.addEventListener("estimationend", () => {
scene.add(defaultLight);
scene.remove(xrLight);
});
```
#figure(
code,
caption: [Integration der WebXR Estimated Light API in Three.js]
) <figure-light>
Wie zuvor definiert verwendet die Anwendung das Stackcube System. Hierbei wurde die 3D-Modelle der einzelnen Möbelstücke bereitgestellt. Um eine realistische Darstellung der Möbelstücke zu ermöglichen, wurden die Modelle und Texturen in Blender importiert und leicht angepasst. Hierbei wurde die Größe sowie Texturskalierung einzelner Modelle angepasst, um eine realistische Darstellung in der Anwendung zu ermöglichen. Anschließend wurden die Modelle in das glTF-Format exportiert. |
|
https://github.com/electratype/electratype | https://raw.githubusercontent.com/electratype/electratype/master/README.md | markdown | # ElectraType


ElectraType is an open-source web based Typst editor built using Svelte.
This project is in very active development stage therefore **stability is not guaranteed**.
This project uses WASM module fount at sister repo [https://github.com/electratype/wasm](https://github.com/electratype/wasm).
## Installation
1. Create parent folder `/parent`
2. Clone this repository into the parent dir folder `/electratype`
3. Clone [https://github.com/electratype/wasm](https://github.com/electratype/wasm) in to the parent dir folder `/electratype-wasm`
4. While inside `/electratype` folder, build WASM module using `yarn run wasm-module`
5. Start app using `yarn run dev --open`
## Roadmap
- [ ] Add font supportgit
- [ ] Add collaboration support
- [ ] Add package support
- [ ] Improve performance on larger documents
- [ ] Add project directories and opening from file system |
|
https://github.com/katamyra/Notes | https://raw.githubusercontent.com/katamyra/Notes/main/Compiled%20School%20Notes/CS3001/Sections/Section5.typ | typst | #import "../../../template.typ": *
#set page(
margin: (x: 1.8cm, y: 1.5cm),
header: align(right)[
<NAME>
]
)
= Social Epistemology
- *Social Epistemology* examines how we form our beliefs and how social factors makeup these beliefs.
== Internal Realism
#definition[
*Internal realism* is a branch of philosophy that arises in response to the debate between scientific realism and anti-realism.
*Scientific Realism* asserts that there exists an objective reality independent of human perception or interpretation, while *anti-realism* denies the existence of such an independent reality.
Specifically in the context of moral actions, *internal realism rejects the idea of a fixed and scientific reality. Instead, that scientific theories are formulated within specific schemes/languages, meaning that moral actions depend on your specific scheme/language.*
In internal realism, one beliefs that while scientific theories and objective reality are not fully 1-1 correlated, scientific theories are still valid in producing descriptions of the world.
]
== Social Construction of Knowledge
#definition[
*The social construction of knowledge* is the idea that knowledge is created not objectively but rather is created within a specific social construct. This means that knowledge is produced/created within communities or institutions. This means that factors such as the language knowledge is learned in, the culture framework within one thinks, or the social norms of that point in time all affect ones knowledge.
#example[
One example of how social constructs influence our social construction of knowledge is the idea of tatoos. Some cultures such as traditional Asian cultures view tatoo's with taboo because of the yakuza, and equate tatoos to crime (this is their knowledge being constructed by their social surroundings). However, other cultures such as polynesian cultures have tatoos as a long standing tradition that are important to their status or cultural heritage.
]
Furthermore, ones knowledge is also impacted by communicating and interactions with others, further showing how you can gain knowledge based on your own social construction.
]
== Internet
+ One thing that the internet does well is that it provides the options to see many unique perspectives from different people that they wouldn't find in their close circles. This means that ones options can be a lot more varied or diverse than that if their social construct was purely formed by their close community.
+ One thing the internet could do better is to help stop echo chambers in social media sites that indirectly "hide" some more unique perspectives sometimes.
+ I would redesign the internet to stop AI algorithms from biasing certain viewpoints so much that they create echo chambers on social media sites.
+ We can also use AI algorithms to fact check information that people put on the internet. This could help eliminate or flag fake knowledge that people put out to be deceiving.
== Intellectual Property
*Trademarks* is a form of IP that specifically protects names, symbols, or any time of identifiers that are used to identify products or services.
*Patents* is a form of IP that specifically gives exclusivity to inventions.
*Copyright* is a form of IP that protects original artwork/mediums that were created by people so they cant simply be copied. |
|
https://github.com/HynDuf/typst-cv | https://raw.githubusercontent.com/HynDuf/typst-cv/master/template/modules_en/certificates.typ | typst | Apache License 2.0 | // Imports
#import "../../lib.typ": cvSection, cvHonor
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#let cvHonor = cvHonor.with(metadata: metadata)
#cvSection("Achievements")
#cvHonor(
date: [2024],
title: [
*Contestant at The 2024 ICPC Asia Pacific Championship* \
Team _rmdir_ - One of twelve Vietnamese teams qualified
],
)
#cvHonor(
date: [2023],
title: [*Second Prize in VNU-level Scienctific Research Competition*],
)
#cvHonor(
date: [2021 - 2022],
title: [
*First Prize at The 2022 (Ho Chi Minh) and The 2021 (Ha Noi) ICPC Asia Regional Contest* \
Team _MariaDB_ (6-th place) and _Nano_ (7-th place)
],
)
#cvHonor(
date: [2021],
title: [
*Second Prize in the Vietnam Olympiad in Informatics* \
Qualified for the International Team Selection Test (TST)
],
)
|
https://github.com/ouuan/cv | https://raw.githubusercontent.com/ouuan/cv/master/template.typ | typst | Apache License 2.0 | /*
* Copyright 2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
#let github(path) = {
return link("https://github.com/" + path)[
#box(image("./icons/github.svg"), baseline: 0.1em, height: 1em)
#h(0.1em)
#path
]
}
#let section-header(title: "", icon: "") = {
v(0.3em)
grid(
columns: (1fr),
row-gutter: 0.6em,
align(left)[
#if icon != "" {
box(align(center, image(icon)), height: 1.3em, width: 2em, baseline: 0.1em)
}
#text(weight: "semibold", 1.4em, title)
],
line(stroke: 0.5pt+gray, length: 100%)
)
}
#let cv(name: "", email: "", birthday: "", github-id: "", body) = {
set document(title: name + " 简历")
set page(paper: "a4", margin: (x: 1.6cm, y: 1.2cm))
set text(font: ("Palatino Linotype", "Noto Serif CJK SC"), 0.9em);
set par(justify: true, linebreaks: "optimized")
[
#block(text(weight: "semibold", 2em, name))
#set box(baseline: 0.1em, height: 1em)
#grid(
columns: (-0.64em, auto, auto, auto, auto, auto),
column-gutter: 0.8em,
"",
link("mailto:" + email)[
#box(image("./icons/envelope.svg"))
#h(0.1em)
#email
],
text(baseline: 0.2em)[·],
github(github-id),
text(baseline: 0.2em)[·],
[
#box(image("./icons/cake-candles.svg"))
#h(0.1em)
#birthday
],
)
]
body
}
#let education(educations) = {
section-header(title: "教育经历", icon: "./icons/building-columns.svg")
set text(1.1em)
grid(
columns: (auto, 1fr, auto, auto),
column-gutter: 1em,
row-gutter: 0.6em,
align: (horizon, horizon, horizon + center, horizon + center),
..for education in educations {
(
text(weight: "semibold", education.school),
education.major,
education.degree,
text(0.9em, weight: "thin", emph(education.date)),
)
}
)
}
#let research(researches) = {
section-header(title: "科研经历", icon: "./icons/flask.svg")
for research in researches {
block[
#text(1.25em, weight: "semibold", research.name)
#h(0.5em)
导师:#research.supervisor
#h(1fr)
#text(weight: "thin", emph(research.date))
#list(..research.points)
#v(0.2em)
]
}
}
#let course-projects(projects) = {
section-header(title: "课程项目", icon: "./icons/code.svg")
for project in projects {
block[
#text(1.25em, weight: "semibold", project.name)
#h(0.5em)
#project.course
#h(1fr)
#project.role
#h(0.5em)
#box(align(center, text(weight: "thin", emph(project.date))), width: 9em)
#if project.tech != "" {
v(-0.5em)
h(0.05em)
text(weight: "thin", 0.8em, project.tech)
v(-0.4em)
}
#list(..project.points)
#v(0.2em)
]
}
}
#let open-source(description, projects) = {
section-header(title: "开源贡献", icon: "./icons/github.svg")
description
v(0.2em)
for project in projects {
block[
#text(1.25em, weight: "semibold", project.name)
#if project.repo != "" {
h(0.5em)
github(project.repo)
}
#if project.star != "" {
h(0.5em)
box(image("./icons/star.svg"), baseline: 0.1em, height: 1em)
h(0.2em)
project.star
}
#if project.tech != "" {
h(0.5em)
text(weight: "thin", 0.9em, project.tech)
}
#h(1fr)
#box(align(center, project.role), width: 5em)
#h(0.5em)
#box(align(center, text(weight: "thin", emph(project.date))), width: 5em)
#project.desc
#v(0.2em)
]
}
}
#let awards(awards) = {
section-header(title: "荣誉奖项", icon: "./icons/award.svg")
grid(
columns: (auto, auto, 1fr),
align: (left, left, right),
gutter: 1em,
..for award in awards {
(
award.name,
text(weight: "semibold", award.prize),
text(weight: "thin", emph(award.date)),
)
}
)
}
#let skills(skills) = {
section-header(title: "专业技能", icon: "./icons/gears.svg")
grid(
columns: (auto, 1fr),
gutter: 1em,
..for skill in skills {
(
text(weight: "semibold", skill.name),
skill.items.join(" / "),
)
}
)
}
|
https://github.com/TGM-HIT/typst-diploma-thesis | https://raw.githubusercontent.com/TGM-HIT/typst-diploma-thesis/main/template/main.typ | typst | MIT License | #import "lib.typ": *
#show: thesis(
title: [Keine Panik!],
subtitle: [Mit Typst durch die Diplomarbeit],
authors: (
// ATTENTION: chapters/vorwort.typ:76 references this list of example authors. When changing
// this list, you need to adjust/remove that line!
(name: "<NAME>", class: [5xHIT], subtitle: [Untertitel des Themengebiets von Ar<NAME>]),
(name: "<NAME>", class: [5xHIT], subtitle: [Untertitel des Themengebiets von Ford Prefect]),
(name: "<NAME>", class: [5xHIT], subtitle: [Untertitel des Themengebiets von Tricia McMillan]),
(name: "<NAME>", class: [5xHIT], subtitle: [Untertitel des Themengebiets von Zaph<NAME>lebrox]),
),
// the German default supervisor label is the non-gendered "Betreuer", so you can override it here
// as necessary
supervisor-label: [Betreuer:in],
supervisor: [DSc MSc Deep Thought],
date: datetime(year: 2018, month: 4, day: 4),
year: [2017/18],
division: [Medientechnik, Systemtechnik],
logo: assets.logo(width: 3cm),
bibliography: bibliography("bibliography.bib"),
// language: "en",
// current-authors: "only",
// strict-chapter-end: true,
)
#include "glossaries.typ"
#declaration(context if text.lang == "de" [
Ich erkläre an Eides statt, dass ich die vorliegende Arbeit selbstständig verfasst, andere als die angegebenen Quellen/Hilfsmittel nicht benutzt und die den benutzten Quellen wörtlich und inhaltlich entnommenen Stellen als solche kenntlich gemacht habe.
Für die Erstellung der Arbeit habe ich auch folgende Hilfsmittel generativer KI-Tools [z. B. ChatGPT, Grammarly Go, Midjourney] zu folgendem Zweck verwendet:
- ChatGPT: eigentlich für eh alles
] else if text.lang == "en" [
I declare that I have authored this thesis independently, that I have not used other than the declared sources and that I have explicitly marked all material which has been quoted either literally or by content from the used sources.
I also used the following generative AI tools [e.g. ChatGPT, Grammarly Go, Midjourney] for the following purpose:
- ChatGPT: for basically everything
] else {
panic("no statutory declaration for that language!")
})
#include "chapters/kurzfassung.typ"
#show: main-matter()
#include "chapters/vorwort.typ"
// in the main-matter, currently all chapters need to have an explicit `#chapter-end()` to ensure
// correct headers and footers. This can hopefully be removed in the future
// (see https://github.com/typst/typst/issues/2722, https://github.com/typst/typst/issues/4438)
#chapter-end()
#include "chapters/danksagung.typ"
#chapter-end()
#include "chapters/einleitung.typ"
#chapter-end()
#include "chapters/studie.typ"
#chapter-end()
#include "chapters/konzept.typ"
#chapter-end()
#include "chapters/implementierung.typ"
#chapter-end()
#include "chapters/retrospektive.typ"
#chapter-end()
#include "chapters/conclusio.typ"
#chapter-end()
|
https://github.com/dashuai009/dashuai009.github.io | https://raw.githubusercontent.com/dashuai009/dashuai009.github.io/main/src/content/blog/040.typ | typst | #let date = datetime(
year: 2022,
month: 11,
day: 28,
)
#metadata((
title: "UE4模块系统",
subtitle: [UnrealEngine],
author: "dashuai009",
description: "详细介绍ue中的模块系统",
pubDate: date.display(),
))<frontmatter>
#import "../__template/style.typ": conf
#show: conf
参考资料
#link("https://www.youtube.com/watch?v=DqqQ_wiWYOw")[UE4 Modules - YouTube]
#link("https://docs.unrealengine.com/4.27/zh-CN/ProductionPipelines/BuildTools/UnrealBuildTool/")[虚幻编译工具 | 虚幻引擎文档 (unrealengine.com)]
== 简介
<简介>
众所周知,c++17及之前中没有modules概念。模块化的代码的优势有#strong[代码分割];、#strong[代码重用];和#strong[加快编译速度];等。
ue中每个模块都被编译为一个dll,据传ue源代码中有一千多个模块\~
ue使用c\#编译构建源代码,而不是vs的sln文件。sln仅仅是为了vs方便。所以,如果新建的模块写进C\#构建文件后,ubt就可以编译构建,即使sln中不显示新建的ue模块。每次更改.build.cs或者更改了文件夹结构,为了生成sln文件,双击项目目录下的GenerateProject.bat。
== 创建一个模块
<创建一个模块>
每个模块位于一个同名文件夹下,一般来说包含一个Public文件夹、Private文件夹和一个C\#构建类。我们创建一个Foo模块,比如说位于Foo文件夹下:
```
Foo
|--Private
|--Public
|--Foo.build.cs
```
Public包含可供其他模块引用的头文件(导出类),Private包含cpp源文件及私有头文件。
每个.buidl.cs中的模块类需要继承自ModuleRules。Foo.build.cs的最基本的实现如下:
```csharp
using UnrealBuildTool;
public class Foo : ModuleRules
{
public FooBar(ReadOnlyTargetRules Target) : base(Target)
{
PrivateDependencyModuleNames.AddRange(new string[] {"Core"});
}
}
```
== build.cs 中的ModuleRules详解
<build.cs-中的modulerules详解>
=== 依赖dependency
<依赖dependency>
`PrivateDependencyModuleNames (List<String>)`
#strong[私有依赖];”:我们的私有代码依赖这些模块,但我们的公共代码不依赖这些模块。
`PublicDependencyModuleNames (List<String>)`
#strong[公共依赖];(不需要路径)(自动执行私有/公共包含)。这些是我们的公共源文件所需要的模块。
- 添加到依赖中的模块:添加引用模块的public目录到includePath,链接对应的dll(相应的导出函数、类等被引入)。
- private依赖不会传递导出的符号:A private/public depends on B,B private depends in C,则A不能看到C的头文件,也不会导入C导出的符号。如果A private/public depends on B,B public depends in C,则A能看到C的头文件,但不会导入C导出的符号。也就是说,B可以public的C的头文件,但始终不能转发链接符号。
- 如果只是private中的cpp/h依赖了外部模块,建议添加到private dependence中,可以加快编译速度。
- Forward declare when you can so you don’t need to mark something as a public dependency.
=== 其他othter
<其他othter>
#link("https://docs.unrealengine.com/4.27/zh-CN/ProductionPipelines/BuildTools/UnrealBuildTool/ModuleFiles/")[模块 | 虚幻引擎文档 (unrealengine.com)]
== 实现一个模块
<实现一个模块>
现在我们有了一个Foo.build.cs,我们需要用cpp实现它。
=== module.h
<module.h>
一般来说,我们要在`[YourModuleName]Module.h`中声明如下代码(以Foo模块为例):
```cpp
#include "Modules/ModuleInterface.h"
class FFooModule : public IModuleInterface
{
public:
/**
* Called right after the plugin DLL has been loaded and the plugin object has been created
*/
virtual void StartupModule();
/**
* Called before the plugin is unloaded, right before the plugin object is destroyed.
*/
virtual void ShutdownModule();
void DoFoo();
}
```
`FFooModule`必须继承自`IModuleInterface`(位于`Modules/ModuleInterface.h`)中
=== module.cpp
<module.cpp>
在`private/FooModule.cpp`中实现以下代码:
```cpp
#include "FooModule.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_MODULE( FFooModule, Foo );
Foo::StartupModule(){
//do sth right after the dll has been loaded and the static object has been created
//可以在module中定义一个单例,并在这里初始化
}
Foo::ShutdownModule(){
// 单例在这析构
}
Foor::DoFoo(){
//自定义函数
}
```
- `IMPLEMENT_MODULE( F[YourModule]Module, Foo)`
宏,一个参数是类名(推荐命名方式`F[YourModule]Module`,第二个是模块名
- #strong[IMPLEMENT\_GAME\_MODULE]
- #strong[IMPLEMENT\_PRIMARY\_GAME\_MODULE]
- "Modules/ModuleManager.h" 和 "Modules/ModuleInterface.h"
位于Core模块中,这是我们最少依赖的模块。
=== 模块的使用方式
<模块的使用方式>
`FModuleManager::Get().LoadModuleChecked<FFooModule>(TEXT("Foo")).DoFoo();`
== PCH(precompiled headers)预编译头文件
<pchprecompiled-headers预编译头文件>
#strong[不推荐使用PCH,初学者可以直接跳过这一节。]
仅适用于代码库比较庞大的情况。
#link("https://learn.microsoft.com/zh-cn/cpp/build/creating-precompiled-header-files?view=msvc-170")[预编译的头文件 | Microsoft Learn]
=== 私有的预编译头文件。
<私有的预编译头文件>
为自己的模块创建的自定义 PCH。使用 PrivatePCHHeaderFile 属性在 Build.cs
文件中定义它。 按照惯例,它应该命名为`[your-module-name]PrivatePCH.h`
```csharp
using UnrealBuildTool;
public class Foo : ModuleRules
{
public FooBar(ReadOnlyTargetRules Target) : base(Target)
{
PrivatePCHHeaderFile = "FooPrivatePCH.h";//每个模块最多一个pch
PrivateDependencyModuleNames.AddRange(new string[] {"Core"});
}
}
```
Unreal Build Tool 会自动为模块中的所有编译文件注入它。
=== 共享的预编译头文件。
<共享的预编译头文件>
共享 PCH
是指一个模块定义了#strong[给其他依赖模块使用的];预编译头文件。模块本身不能使用它。基础虚幻引擎模块中比较常见(UnrealEd, Engine, Slate, CoreUObject, and Core)。只有引擎模块(engine
module可以创建shared PCH)。
您无法选择使用哪一个,虚幻引擎会根据优先级分数从您的模块依赖项之一中为您选择。该优先级分数按模块排序,取决于它依赖的具有共享PCH的其他模块的数量。这是一个有点奇怪的解释,但上面的模块列表已经按优先级排序。例如,如果您的模块依赖于所有五个模块,Unreal将在编译时选择 UnrealEd 的共享 PCH 用于您的模块。
=== 那么什么时候使用哪种预编译头类型呢?
<那么什么时候使用哪种预编译头类型呢>
你实际上有三个选择。
您可以创建自己的私有预编译头文件。
这对于代码库非常大的模块很有用,大型游戏中的主要游戏模块通常就是这种情况。
您必须决定在 PCH 中放入什么以及如何自己平衡它。
您可以使用共享引擎 PCH,这对于所有其他较小的模块来说都是一个不错的选择。
最后,不推荐使用任何 PCH。
这不是很实用,我不知道你为什么要这样做,除非你正在做一些极端的编译调试。
但是你有选择。
因此,让我们看看您在哪里配置这些 PCH 构建设置。
=== 在模块的 Build.cs 文件中设置。
<在模块的-build.cs-文件中设置>
有两个相关的设置来配置它
采用 PCHUsageMode 枚举的 PCHUsage 属性
当您想使用私有 PCH 时,还可以选择 PrivatePCHHeaderFile 属性
这只是标题的字符串路径。
那么,设置PCHUsageMode,我们应该使用哪个设置呢?
嗯,它比 Enum 看起来要简单一些,因为
这三个是遗留的,您应该始终选择 UseExplicitOrSharedPCHs。
该选项默认使用共享 PCH,如果您已通过 PrivatePCHHeaderFile
属性设置,则使用私有 PCH。
从 4.24.2 开始,它实际上已经是默认设置
因此,如果您使用的是在该版本或更高版本上创建的项目,那么您甚至不必设置它。
此设置将来可能会逐步淘汰。
== Include What You Use,通常缩写为 IWYU
<include-what-you-use通常缩写为-iwyu>
遵循四个原则
+ 所有头文件包含其所需的依赖性。
#strong[CoreMinimal];头文件包含了UE核心编程环境的常见类型(包括FString、FName、TArray等)。这样,在头文件中首先include该文件,就可以引入这些东西。
+ Foo.cpp文件首先包含其匹配的Foo.h文件。
否则ubt将发出警告(如要禁用,可在模块的\*.build.cs文件中将
`bEnforceIWYU` 设为 `false`)。
+ PCH文件已不再是显式包含。
+ 不再包含单块头文件(monolithic header,比如Engine.h、UnrealEd.h)。
=== 启用IWYU
<启用iwyu>
在version\<=4.23中,IWYU默认不启用,在 .Build.cs 文件中将 PCHMode
属性设置为 UseExplicitOrSharedPCHs 来打开 IWYU。
在version\>=4.24.2中,默认启用。具体来说,默认启用是通过#strong[DefaultBuildSettings
\= BuildSettingsVersion.V2];设置的。该选项做了三件事
- PCHUsage gets set to PCHUsageMode.UseExplicitOrSharedPCHs;
- #strong[bLegacyPublicIncludePaths] 被设为false,虚幻构建工具会从公共包含路径中省略子文件夹,以减少编译器命令行长度并缩短编译时间。现在必须让每个包含路径都正确。之前你可以只包含Actor.h,现在你必须包含GameFramework/Actor.h。#link("https://docs.unrealengine.com/4.27/zh-CN/ProductionPipelines/BuildTools/UnrealBuildTool/IWYU/IncludeTool/")[包含工具 | 虚幻引擎文档 (unrealengine.com)]
- #strong[ShadowVariableWarningLevel gets set to WarningLevel.Error;]
=== 模块日志
<模块日志>
=== 声明模块日志的类别:
<声明模块日志的类别>
```cpp
DECLARE_LOG_CATEGORY_EXTERN(CategoryName, DefaultVerbosity, CompileTimeVerbosity);
```
- Commonly (Log\[ModuleName\], Display, All), see Logging/LogVerbosity.h
for more.
- Declares a category class that extends FLogCategory.
- Most practical to put it in its own header file.
=== 定义模块日志的类别(方便过滤)
- DEFINE\_LOG\_CATEGORY(CategoryName);
- Instantiates an instance of that log category class, which registers
itself with the log suppression system in the constructor.
- Put it in the same place where you called IMPLEMENT\_MODULE.
=== 使用模块日志
- UE\_LOG(Log\[ModuleName\] Display, TEXT("A wild log appeared!"));
|
|
https://github.com/onomou/typst-examit | https://raw.githubusercontent.com/onomou/typst-examit/main/utilities.typ | typst | MIT License | #import "@preview/cetz:0.2.2"
#let underline-thickness = 0.4pt
#let underline-offset = 1.3pt
#set underline(stroke: underline-thickness, offset: underline-offset)
#let choicebox(choice) = box(
[
// #sym.circle.big
#box(width: 1em, height: 1em, stroke: 0.2mm)
// #sym.square.stroked
#h(0.3em) #box([#move(dy: -0.2em, [#choice])]) #h(0.3em)
]
)
#let writingline(width: 1fr) = box(
width: width,
stroke: (bottom: underline-thickness),
outset: (bottom: underline-offset),
none
)
#let writingbox(height: 1in) = {
box(width: 100%, height: height, stroke: black + 0.2mm)
}
#let graphgrid(width: 10, height: 10, unitlength: 4mm) = {
[
#cetz.canvas(
length: unitlength, {
import cetz.draw: *
grid((0, 0), (width, height), step: 1, stroke: gray + 0.2pt)
}
)
]
}
#let graphpolar(radius: 5, unitlength: 6mm, radials: (15, )) = [
#cetz.canvas(
length: unitlength, {
import cetz.draw: *
// line((0, 0), (width, 0), step: 1, stroke: 0.2pt)
for anglestep in radials {
for ang in range(360,step: anglestep) {
line(stroke:0.2mm+luma(50%), (0,0), (angle: (2 * calc.pi) * ang / 360, radius: radius+0.5))
// draw(stroke:0.2mm+lightgray, (0,0) -- (ang * 180 / 16:4))
}
}
for r in range(radius, step:2) {
circle((0,0),radius: r, stroke: 0.2mm+luma(50%))
}
for r in range(1, radius+1, step:2) {
circle((0,0),radius: r, stroke: 0.2mm+luma(20%))
}
}
)
]
#let graphline(width: 20, unitlength: 4mm) = {
[
#cetz.canvas(
length: unitlength, {
import cetz.draw: *
line((0, 0), (width, 0), step: 1, stroke: 0.2pt, mark: (end: ">", start: ">"))
}
)
]
}
#let img(im, sc: 0.5, align: "b", boxes: false) = style(styles => {
let size = measure(image(im), styles)
set image(width: size.width * sc, height: size.height * sc)
let va = if align == "t" {0.5} else if align == "m" {0.25} else if align == "b" {0}
box(stroke: if boxes {black}, baseline: size.height * va, image(im))
}) |
https://github.com/antonWetzel/Masterarbeit | https://raw.githubusercontent.com/antonWetzel/Masterarbeit/main/arbeit/eigenständigkeitserklärung.typ | typst | #set heading(numbering: none)
= Eigenständigkeitserklärung
Hiermit erkläre ich, dass ich diese Arbeit selbstständig durchgeführt und abgefasst habe. Quellen, Literatur und Hilfsmittel, die von mir genutzt wurden, sind als solche gekennzeichnet.
#v(1em)
#align(center, box(
width: 80%,
grid(
columns: (auto, 1fr),
align: right,
row-gutter: 2em,
column-gutter: 1em,
[Ort:], align(bottom, line(length: 100%)),
[Datum:], align(bottom, line(length: 100%)),
[Unterschrift:], align(bottom, line(length: 100%)),
),
))
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/regression/issue19.typ | typst | Other | #let nums = (1, none, 2)
#nums.map(num => {
if num == none {
return 1
}
return ((str(num)): 1)
})
|
https://github.com/PhilChodrow/cv | https://raw.githubusercontent.com/PhilChodrow/cv/main/src/content/teaching.typ | typst | #import "../template.typ": *
#cvSection("Teaching")
#cvSubSection("Middlebury College")
#pad(left: 0.5cm,
table(
columns: 2,
stroke: none,
align: (right, left),
[Spring 2025], [CSCI 0451: _Machine Learning_ (planned)],
[], [CSCI 0442: _Network Science_ (planned)],
[Winter 2025], [CSCI 0702: _Senior Thesis_],
[Fall 2024], [CSCI 0200: _Mathematical Foundations of Computing_ (x2)],
[], [CSCI 0702: _Senior Thesis_],
[], [CSCI 0500: _Advanced Study_],
[Spring 2024], [CSCI 0451: _Machine Learning_],
[], [CSCI 0702: _Senior Thesis_],
[Winter 2024], [CSCI 0702: _Senior Thesis_],
[Fall 2023], [CSCI 0200: _Mathematical Foundations of Computing_ (x2)],
[Spring 2023], [CSCI 0451: _Machine Learning_ (x2)],
[Fall 2022], [CSCI 0145: _Introduction to Computing_ (x2)],
)
)
#cvSubSection("University of California, Los Angeles")
#pad(left: 0.5cm,
table(
columns: 2,
stroke: none,
align: (right, left),
[Spring 2022], [MATH 168: _Introduction to Networks_],
[Winter 2022], [PIC 16B: _Python Programming with Applications II_],
[Fall 2021], [PIC 16B: _Python Programming with Applications II_],
[], [PIC 16A: _Python Programming with Applications I_],
[Spring 2021], [PIC 16B: _Python Programming with Applications II_],
[], [PIC 16A: _Python Programming with Applications I_],
[Winter 2021], [PIC 16A: _Python Programming with Applications I_],
[Fall 2020], [PIC 16A: _Python Programming with Applications I_],
)
) |
|
https://github.com/liuzhuan/reading-list | https://raw.githubusercontent.com/liuzhuan/reading-list/master/books/programming-with-types/index.md | markdown | # Programming with Types
中文名称:编程与类型系统
阅读本书时尝试使用 Typst 编写读书笔记,详见 [note.typ](note.typ)
|
|
https://github.com/Daillusorisch/HYSeminarAssignment | https://raw.githubusercontent.com/Daillusorisch/HYSeminarAssignment/main/README.md | markdown | # 课程作业
本仓库内的版本对个人信息做了模糊处理。
感谢[武汉大学typst模版项目](https://github.com/Hithereland/whu-typst-template)
|
|
https://github.com/luiswirth/bsc-thesis | https://raw.githubusercontent.com/luiswirth/bsc-thesis/main/src/toc.typ | typst | #show outline.entry.where(
level: 1
): it => {
v(15pt, weak: true)
strong(it.body)
h(1fr)
strong(it.page)
}
#show outline: set heading(outlined: true)
#outline(
title: "Table of Contents",
indent: auto,
fill: line(length: 100%, stroke: 0.1pt),
)
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1980.typ | typst | Apache License 2.0 | #let data = (
("NEW TAI LUE LETTER HIGH QA", "Lo", 0),
("NEW TAI LUE LETTER LOW QA", "Lo", 0),
("NEW TAI LUE LETTER HIGH KA", "Lo", 0),
("NEW TAI LUE LETTER HIGH XA", "Lo", 0),
("NEW TAI LUE LETTER HIGH NGA", "Lo", 0),
("NEW TAI LUE LETTER LOW KA", "Lo", 0),
("NEW TAI LUE LETTER LOW XA", "Lo", 0),
("NEW TAI LUE LETTER LOW NGA", "Lo", 0),
("NEW TAI LUE LETTER HIGH TSA", "Lo", 0),
("NEW TAI LUE LETTER HIGH SA", "Lo", 0),
("NEW TAI LUE LETTER HIGH YA", "Lo", 0),
("NEW TAI LUE LETTER LOW TSA", "Lo", 0),
("NEW TAI LUE LETTER LOW SA", "Lo", 0),
("NEW TAI LUE LETTER LOW YA", "Lo", 0),
("NEW TAI LUE LETTER HIGH TA", "Lo", 0),
("NEW TAI LUE LETTER HIGH THA", "Lo", 0),
("NEW TAI LUE LETTER HIGH NA", "Lo", 0),
("NEW TAI LUE LETTER LOW TA", "Lo", 0),
("NEW TAI LUE LETTER LOW THA", "Lo", 0),
("NEW TAI LUE LETTER LOW NA", "Lo", 0),
("NEW TAI LUE LETTER HIGH PA", "Lo", 0),
("NEW TAI LUE LETTER HIGH PHA", "Lo", 0),
("NEW TAI LUE LETTER HIGH MA", "Lo", 0),
("NEW TAI LUE LETTER LOW PA", "Lo", 0),
("NEW TAI LUE LETTER LOW PHA", "Lo", 0),
("NEW TAI LUE LETTER LOW MA", "Lo", 0),
("NEW TAI LUE LETTER HIGH FA", "Lo", 0),
("NEW TAI LUE LETTER HIGH VA", "Lo", 0),
("NEW TAI LUE LETTER HIGH LA", "Lo", 0),
("NEW TAI LUE LETTER LOW FA", "Lo", 0),
("NEW TAI LUE LETTER LOW VA", "Lo", 0),
("NEW TAI LUE LETTER LOW LA", "Lo", 0),
("NEW TAI LUE LETTER HIGH HA", "Lo", 0),
("NEW TAI LUE LETTER HIGH DA", "Lo", 0),
("NEW TAI LUE LETTER HIGH BA", "Lo", 0),
("NEW TAI LUE LETTER LOW HA", "Lo", 0),
("NEW TAI LUE LETTER LOW DA", "Lo", 0),
("NEW TAI LUE LETTER LOW BA", "Lo", 0),
("NEW TAI LUE LETTER HIGH KVA", "Lo", 0),
("NEW TAI LUE LETTER HIGH XVA", "Lo", 0),
("NEW TAI LUE LETTER LOW KVA", "Lo", 0),
("NEW TAI LUE LETTER LOW XVA", "Lo", 0),
("NEW TAI LUE LETTER HIGH SUA", "Lo", 0),
("NEW TAI LUE LETTER LOW SUA", "Lo", 0),
(),
(),
(),
(),
("NEW TAI LUE VOWEL SIGN VOWEL SHORTENER", "Lo", 0),
("NEW TAI LUE VOWEL SIGN AA", "Lo", 0),
("NEW TAI LUE VOWEL SIGN II", "Lo", 0),
("NEW TAI LUE VOWEL SIGN U", "Lo", 0),
("NEW TAI LUE VOWEL SIGN UU", "Lo", 0),
("NEW TAI LUE VOWEL SIGN E", "Lo", 0),
("NEW TAI LUE VOWEL SIGN AE", "Lo", 0),
("NEW TAI LUE VOWEL SIGN O", "Lo", 0),
("NEW TAI LUE VOWEL SIGN OA", "Lo", 0),
("NEW TAI LUE VOWEL SIGN UE", "Lo", 0),
("NEW TAI LUE VOWEL SIGN AY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN AAY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN UY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN OY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN OAY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN UEY", "Lo", 0),
("NEW TAI LUE VOWEL SIGN IY", "Lo", 0),
("NEW TAI LUE LETTER FINAL V", "Lo", 0),
("NEW TAI LUE LETTER FINAL NG", "Lo", 0),
("NEW TAI LUE LETTER FINAL N", "Lo", 0),
("NEW TAI LUE LETTER FINAL M", "Lo", 0),
("NEW TAI LUE LETTER FINAL K", "Lo", 0),
("NEW TAI LUE LETTER FINAL D", "Lo", 0),
("NEW TAI LUE LETTER FINAL B", "Lo", 0),
("NEW TAI LUE TONE MARK-1", "Lo", 0),
("NEW TAI LUE TONE MARK-2", "Lo", 0),
(),
(),
(),
(),
(),
(),
("NEW TAI LUE DIGIT ZERO", "Nd", 0),
("NEW TAI LUE DIGIT ONE", "Nd", 0),
("NEW TAI LUE DIGIT TWO", "Nd", 0),
("NEW TAI LUE DIGIT THREE", "Nd", 0),
("NEW TAI LUE DIGIT FOUR", "Nd", 0),
("NEW TAI LUE DIGIT FIVE", "Nd", 0),
("NEW TAI LUE DIGIT SIX", "Nd", 0),
("NEW TAI LUE DIGIT SEVEN", "Nd", 0),
("NEW TAI LUE DIGIT EIGHT", "Nd", 0),
("NEW TAI LUE DIGIT NINE", "Nd", 0),
("NEW TAI LUE THAM DIGIT ONE", "No", 0),
(),
(),
(),
("NEW TAI LUE SIGN LAE", "So", 0),
("NEW TAI LUE SIGN LAEV", "So", 0),
)
|
https://github.com/ayoubelmhamdi/typst-phd-AI-Medical | https://raw.githubusercontent.com/ayoubelmhamdi/typst-phd-AI-Medical/master/chapters/resume.typ | typst | MIT License | #import "../functions.typ": heading_center, images, italic
#let finchapiter = text(fill:rgb("#1E045B"),[■])
= RÉSUMÉ.
Les images médicales jouent un rôle important dans le diagnostic et la prise en charge des cancers. Les oncologues analysent des images pour déterminer les différentes caractéristiques de la tumeur, pour proposer un traitement adapté et suivre l'évolution de la maladie.
L'objectif de ce rapport est d'évaluer la détection automatique des nodules pulmonaire cancéreuse dans le contexte de la radiothérapie, à partir des images de CT scan.
Nous utilisons les nodules candidats qui sont segmentés par un réseau neuronal convolutif entraîné sur des images de scanner segmentées par des experts. Notant que celles-ci sont faiblement annotées, et sont souvent disponibles en quantités très limitées du fait de leur coût.
Nous créons un modèle basé sur un CNN (Convolutional Neural Network) pour diagnostiquer ces nodules. Les expériences réalisées sur des scanners pulmonaires de haute qualité ont démontré une détection assez bonne des nodules cancéreux du poumon.
En outre, nous avons également utilisé un autre modèle pour classer les nodules comme probablement normaux ou anormaux à l'aide du LIDC-IDRI/TRPMLN DATASET. Ce modèle a également été confronté à des défis similaires en termes de diversité des nodules et de distribution inégale dans l'ensemble de données.
*Mots clés*: Réseau neuronal convolutif, CNN, ResNET, apprentissage profond, CT scan, TDM, radiothérapie, Caner, Nodules pulmonaire, lésions pulmonaires.#finchapiter
|
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/label.typ | typst | Apache License 2.0 | #set heading(numbering: "1.")
= <test>
@test
= <test->
@test-
= <test:>
@test:
= <test.>
@test.
= <test.1>
@test.1
= <test:1>
@test:1
= <test::>
@test::
= <typst::World>
@typst::World
= <test::.>
@test::. e
= <test: :.>
@test: :. e
A @netwok @arrgh.
@fib:
|
https://github.com/knuesel/typst-minideck | https://raw.githubusercontent.com/knuesel/typst-minideck/main/themes/README.md | markdown | MIT License | # minideck themes
A theme is implemented through a configuration function that has the following positional input:
- `minideck.slide` function
and must accept at least the following named input:
- `page-size`: a dictionary with absolute lengths `width` and `height`
and return as output a dictionary of theme functions including at least
- `template`: a template for the whole document
- `slide`: the input `slide` function or a wrapper for it
- `title-slide`: the input `slide` function or a wrapper for it
The configuration function can accept additional parameters and return additional values in the output dictionary.
The theme functions in the output dictionary can also accept non-standard parameters.
The theme functions that make slides (`slide`, `title-slide` and possibly others) should be wrappers around the `slide` function given as input.
For example an `ocean` theme from a `fancy-themes` package could be used like this:
```typst
#import "@preview/minideck:0.2.1"
#import "@preview/fancy-themes:0.1.0" // hypothetical package
#let (template, slide, title-slide) = minideck.config(theme: fancy-themes.ocean)
#show: template
```
or when theme configuration is required:
```typst
#import "@preview/minideck:0.2.1"
#import "@preview/fancy-themes:0.1.0" // hypothetical package
#let (template, slide, title-slide) = minideck.config(
theme: fancy-themes.ocean.with(variant: "dark"),
)
#show: template
```
|
https://github.com/TypstApp-team/typst | https://raw.githubusercontent.com/TypstApp-team/typst/master/docs/reference/scripting.md | markdown | Apache License 2.0 | ---
description: Automate your document with Typst's scripting capabilities.
---
# Scripting
Typst embeds a powerful scripting language. You can automate your documents and
create more sophisticated styles with code. Below is an overview over the
scripting concepts.
## Expressions
In Typst, markup and code are fused into one. All but the most common elements
are created with _functions._ To make this as convenient as possible, Typst
provides compact syntax to embed a code expression into markup: An expression is
introduced with a hash (`#`) and normal markup parsing resumes after the
expression is finished. If a character would continue the expression but should
be interpreted as text, the expression can forcibly be ended with a semicolon
(`;`).
```example
#emph[Hello] \
#emoji.face \
#"hello".len()
```
The example above shows a few of the available expressions, including
[function calls]($function), [field accesses]($scripting/#fields), and
[method calls]($scripting/#methods). More kinds of expressions are
discussed in the remainder of this chapter. A few kinds of expressions are not
compatible with the hash syntax (e.g. binary operator expressions). To embed
these into markup, you can use parentheses, as in `[#(1 + 2)]`.
## Blocks
To structure your code and embed markup into it, Typst provides two kinds of
_blocks:_
- **Code block:** `{{ let x = 1; x + 2 }}` \
When writing code, you'll probably want to split up your computation into
multiple statements, create some intermediate variables and so on. Code blocks
let you write multiple expressions where one is expected. The individual
expressions in a code block should be separated by line breaks or semicolons.
The output values of the individual expressions in a code block are joined to
determine the block's value. Expressions without useful output, like `{let}`
bindings yield `{none}`, which can be joined with any value without effect.
- **Content block:** `{[*Hey* there!]}` \
With content blocks, you can handle markup/content as a programmatic value,
store it in variables and pass it to [functions]($function). Content
blocks are delimited by square brackets and can contain arbitrary markup. A
content block results in a value of type [content]($content). An
arbitrary number of content blocks can be passed as trailing arguments to
functions. That is, `{list([A], [B])}` is equivalent to `{list[A][B]}`.
Content and code blocks can be nested arbitrarily. In the example below,
`{[hello]}` is joined with the output of `{a + [ the ] + b}` yielding
`{[hello from the *world*]}`.
```example
#{
let a = [from]
let b = [*world*]
[hello ]
a + [ the ] + b
}
```
## Bindings and Destructuring { #bindings }
As already demonstrated above, variables can be defined with `{let}` bindings.
The variable is assigned the value of the expression that follows the `=` sign.
The assignment of a value is optional, if no value is assigned, the variable
will be initialized as `{none}`. The `{let}` keyword can also be used to create
a [custom named function]($function/#defining-functions). Let bindings can be
accessed for the rest of the containing block or document.
```example
#let name = "Typst"
This is #name's documentation.
It explains #name.
#let add(x, y) = x + y
Sum is #add(2, 3).
```
Let bindings can also be used to destructure [arrays]($array) and
[dictionaries]($dictionary). In this case, the left-hand side of the
assignment should mirror an array or dictionary. The `..` operator can be used
once in the pattern to collect the remainder of the array's or dictionary's
items.
```example
#let (x, y) = (1, 2)
The coordinates are #x, #y.
#let (a, .., b) = (1, 2, 3, 4)
The first element is #a.
The last element is #b.
#let books = (
Shakespeare: "Hamlet",
Homer: "The Odyssey",
Austen: "Persuasion",
)
#let (Austen,) = books
Austen wrote #Austen.
#let (Homer: h) = books
Homer wrote #h.
#let (Homer, ..other) = books
#for (author, title) in other [
#author wrote #title.
]
```
You can use the underscore to discard elements in a destructuring pattern:
```example
#let (_, y, _) = (1, 2, 3)
The y coordinate is #y.
```
Destructuring also work in argument lists of functions ...
```example
#let left = (2, 4, 5)
#let right = (3, 2, 6)
#left.zip(right).map(
((a,b)) => a + b
)
```
... and on the left-hand side of normal assignments. This can be useful to
swap variables among other things.
```example
#{
let a = 1
let b = 2
(a, b) = (b, a)
[a = #a, b = #b]
}
```
## Conditionals
With a conditional, you can display or compute different things depending on
whether some condition is fulfilled. Typst supports `{if}`, `{else if}` and
`{else}` expression. When the condition evaluates to `{true}`, the conditional
yields the value resulting from the if's body, otherwise yields the value
resulting from the else's body.
```example
#if 1 < 2 [
This is shown
] else [
This is not.
]
```
Each branch can have a code or content block as its body.
- `{if condition {..}}`
- `{if condition [..]}`
- `{if condition [..] else {..}}`
- `{if condition [..] else if condition {..} else [..]}`
## Loops
With loops, you can repeat content or compute something iteratively. Typst
supports two types of loops: `{for}` and `{while}` loops. The former iterate
over a specified collection whereas the latter iterate as long as a condition
stays fulfilled. Just like blocks, loops _join_ the results from each iteration
into one value.
In the example below, the three sentences created by the for loop join together
into a single content value and the length-1 arrays in the while loop join
together into one larger array.
```example
#for c in "ABC" [
#c is a letter.
]
#let n = 2
#while n < 10 {
n = (n * 2) - 1
(n,)
}
```
For loops can iterate over a variety of collections:
- `{for letter in "abc" {..}}` \
Iterates over the characters of the [string]($str).
(Technically, iterates over the grapheme clusters of the string. Most of the
time, a grapheme cluster is just a single character/codepoint. However, some
constructs like flag emojis that consist of multiple codepoints are still only
one cluster.)
- `{for value in array {..}}` \
Iterates over the items in the [array]($array). The destructuring syntax
described in [Let binding]($scripting/#bindings) can also be used here.
- `{for pair in dict {..}}` \
Iterates over the key-value pairs of the [dictionary]($dictionary).
The pairs can also be destructured by using `{for (key, value) in dict {..}}`.
To control the execution of the loop, Typst provides the `{break}` and
`{continue}` statements. The former performs an early exit from the loop while
the latter skips ahead to the next iteration of the loop.
```example
#for letter in "abc nope" {
if letter == " " {
break
}
letter
}
```
The body of a loop can be a code or content block:
- `{for .. in collection {..}}`
- `{for .. in collection [..]}`
- `{while condition {..}}`
- `{while condition [..]}`
## Fields
You can use _dot notation_ to access fields on a value. The value in question
can be either:
- a [dictionary]($dictionary) that has the specified key,
- a [symbol]($symbol) that has the specified modifier,
- a [module]($module) containing the specified definition,
- [content]($content) consisting of an element that has the specified field. The
available fields match the arguments of the
[element function]($function/#element-functions) that were given when the
element was constructed.
```example
#let dict = (greet: "Hello")
#dict.greet \
#emoji.face
#let it = [= Heading]
#it.body \
#it.level
```
## Methods
A _method call_ is a convenient way to call a function that is scoped to a
value's [type]($type). For example, we can call the [`str.len`]($str.len)
function in the following two equivalent ways:
```example
#str.len("abc") is the same as
#"abc".len()
```
The structure of a method call is `{value.method(..args)}` and its equivalent
full function call is `{type(value).method(value, ..args)}`. The documentation
of each type lists it's scoped functions. You cannot currently define your own
methods.
```example
#let array = (1, 2, 3, 4)
#array.pop() \
#array.len() \
#("a, b, c"
.split(", ")
.join[ --- ])
#"abc".len() is the same as
#str.len("abc")
```
There are a few special functions that modify the value they are called on (e.g.
[`array.push`]($array.push)). These functions _must_ be called in method form.
In some cases, when the method is only called for its side effect, its return
value should be ignored (and not participate in joining). The canonical way to
discard a value is with a let binding: `{let _ = array.remove(1)}`.
## Modules
You can split up your Typst projects into multiple files called _modules._ A
module can refer to the content and definitions of another module in multiple
ways:
- **Including:** `{include "bar.typ"}` \
Evaluates the file at the path `bar.typ` and returns the resulting
[content]($content).
- **Import:** `{import "bar.typ"}` \
Evaluates the file at the path `bar.typ` and inserts the resulting
[module]($module) into the current scope as `bar` (filename without
extension). You can use the `as` keyword to rename the imported module:
`{import "bar.typ" as baz}`
- **Import items:** `{import "bar.typ": a, b}` \
Evaluates the file at the path `bar.typ`, extracts the values of the variables
`a` and `b` (that need to be defined in `bar.typ`, e.g. through `{let}`
bindings) and defines them in the current file. Replacing `a, b` with `*`
loads all variables defined in a module. You can use the `as` keyword to
rename the individual items: `{import "bar.typ": a as one, b as two}`
Instead of a path, you can also use a [module value]($module), as shown in the
following example:
```example
#import emoji: face
#face.grin
```
## Packages
To reuse building blocks across projects, you can also create and import Typst
_packages._ A package import is specified as a triple of a namespace, a name,
and a version.
```example
>>> #let add(x, y) = x + y
<<< #import "@preview/example:0.1.0": add
#add(2, 7)
```
The `preview` namespace contains packages shared by the community. You can find
a searchable list of available community packages in the [packages]($packages)
section.
If you are using Typst locally, you can also create your own system-local
packages. For more details on this, see the
[package repository](https://github.com/typst/packages).
## Operators
The following table lists all available unary and binary operators with effect,
arity (unary, binary) and precedence level (higher binds stronger).
| Operator | Effect | Arity | Precedence |
|:----------:|---------------------------------|:------:|:----------:|
| `{-}` | Negation | Unary | 7 |
| `{+}` | No effect (exists for symmetry) | Unary | 7 |
| `{*}` | Multiplication | Binary | 6 |
| `{/}` | Division | Binary | 6 |
| `{+}` | Addition | Binary | 5 |
| `{-}` | Subtraction | Binary | 5 |
| `{==}` | Check equality | Binary | 4 |
| `{!=}` | Check inequality | Binary | 4 |
| `{<}` | Check less-than | Binary | 4 |
| `{<=}` | Check less-than or equal | Binary | 4 |
| `{>}` | Check greater-than | Binary | 4 |
| `{>=}` | Check greater-than or equal | Binary | 4 |
| `{in}` | Check if in collection | Binary | 4 |
| `{not in}` | Check if not in collection | Binary | 4 |
| `{not}` | Logical "not" | Unary | 3 |
| `{and}` | Short-circuiting logical "and" | Binary | 3 |
| `{or}` | Short-circuiting logical "or | Binary | 2 |
| `{=}` | Assignment | Binary | 1 |
| `{+=}` | Add-Assignment | Binary | 1 |
| `{-=}` | Subtraction-Assignment | Binary | 1 |
| `{*=}` | Multiplication-Assignment | Binary | 1 |
| `{/=}` | Division-Assignment | Binary | 1 |
[semver]: https://semver.org/
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/hydra/0.1.0/src/util.typ | typst | Apache License 2.0 | // assert the element is of the given typ
#let assert-element(element, func) = {
assert.eq(type(element), content, message: "element must be content, was " + repr(type(element)))
assert.eq(element.func(), func, message: "element must be a " + repr(func))
}
// split a selector into a pair of selector and post filter
#let into-sel-filter-pair(sel) = {
if type(sel) in (selector, function) {
(selector(sel), (_, _) => true)
} else if (
type(sel) == array and sel.len() == 2
and type(sel.at(0)) in (selector, function) and type(sel.at(1)) == function
) {
let (sel, func) = sel
(selector(sel), func)
} else {
panic("sel must be a selector or a selector and filter function")
}
}
|
https://github.com/ngyngcphu/tick3d-docs | https://raw.githubusercontent.com/ngyngcphu/tick3d-docs/main/components/latex.typ | typst | Apache License 2.0 | // https://github.com/typst/typst/discussions/1732
#let TeX = style(styles => {
let e = measure(text(1em, "E"), styles)
let T = "T"
let E = text(1em, baseline: e.height / 4, "E")
let X = "X"
box(T + h(-0.1em) + E + h(-0.125em) + X)
})
#let LaTeX = style(styles => {
let l = measure(text(1em, "L"), styles)
let a = measure(text(0.7em, "A"), styles)
let L = "L"
let A = text(0.7em, baseline: a.height - l.height, "A")
box(L + h(-0.3em) + A + h(-0.1em) + TeX)
}) |
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/syntaxes/textmate/tests/unit/basic/control-flow-if.typ | typst | Apache License 2.0 | #if 1
#if {} 1
#if {} else {} 1
#if 1 {} else {} 1
#if [] {} else {} #1
#if {} {} else {} {}
#if () {} else {} # a
#if () {} else {}
1
#if () {} else {}
{}
#if () {} else {}
{
#if () {} else {}
1
# if () {} else {}
1
#if 1 < 2 [
One.
]
#if true == false [
{Bad}, but we {dont-care}!
]
#if {true} [
One.
]
#if [] != none [
Two.
]
#if (
1 + 1
== 1
) [
Nope.
] else {
"Three."
}
#if false [
Bad.
] else {
let point = "."
"Four" + point
}
#{
if content == type[b] [Fi] else [Nope]
if content == type [Nope] else [ve.]
}
#if () () {}
#if () [] {}
#if () {} {}
#if [] () {}
#if [] [] {}
#if [] {} {}
#if {} () {}
#if {} [] {}
#if {} {} {}
#if () == () () {}
#if () == () [] {}
#if () == () {} {}
#if [] == [] () {}
#if [] == [] [] {}
#if [] == [] {} {}
#if {} == {} () {}
#if {} == {} [] {}
#if {} == {} {} {}
#if () and () () {}
#if () and () [] {}
#if () and () {} {}
#if [] and [] () {}
#if [] and [] [] {}
#if [] and [] {} {}
#if {} and {} () {}
#if {} and {} [] {}
#if {} and {} {} {}
#if not () () {}
#if not () [] {}
#if not () {} {}
#if not [] () {}
#if not [] [] {}
#if not [] {} {}
#if not {} () {}
#if not {} [] {}
#if not {} {} {}
|
https://github.com/elteammate/typst-compiler | https://raw.githubusercontent.com/elteammate/typst-compiler/main/src/compile-x86.typ | typst | #import "utils.typ": *
#import "typesystem.typ": *
#import "ir-def.typ": *
#import "utils-asm-highlighting.typ": *
#let registers = (
"rax", "rbx", "rcx", "rdx",
"rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
)
#let fp_registers = (
"xmm0","xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9","xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
)
#let external_function = mk_enum(
debug: true,
"content_join",
"mk_function",
"cast_int_to_content",
)
#let is_register(x) = x in registers
#let compile_function(function_name, function) = {
let code = ()
let constants = (:)
let constant_counter = 0
let free_num_registers = (
"rdi", "rsi", "rdx", "rcx",
"r8", "r9", "rax", "r10", "r11",
)
let allocated_num_registers = (
"rbx", "r12", "r13", "r14", "r15",
)
let locations = (:)
let values_in_registers = (:)
let reserved = ()
for i, reg in allocated_num_registers {
let res = "%%res." + str(i)
locations.insert(res, reg)
values_in_registers.insert(reg, res)
reserved.push(res)
}
let allocated_fp_registers = ()
let param_locations = ()
let int_param_counter = 0
let float_param_counter = 0
let stack_param_counter = 0
for param in function.params {
if int_param_counter < 6 {
param_locations.push(free_num_registers.first())
let _ = { let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
int_param_counter += 1
} else {
param_locations.push("[rbp + " + str(8 * stack_param_counter + 16) + "]")
stack_param_counter += 1
}
}
let labels_by_line = range(function.code.len() + 1).map(x => ())
for label_name, label_line in function.labels {
labels_by_line.at(label_line).push(label_name.replace(".", "_"))
}
let temp_values_occupancy = ()
let temp_var_offset = 8 * function.stack_occupancy.len()
let last_use = (:)
for line, instr in function.code {
for arg in instr.args {
if type(arg) == "string" and arg.len() > 0 and arg.at(0) == "%" {
last_use.insert(arg, line)
}
}
}
for line, instr in function.code {
for label in labels_by_line.at(line) {
code.push(((label).replace("%", "_P_").replace("@", "_A_").replace(".", "_")) + ":")
}
let opcode = instr.instr
let ty = instr.ty
let res = instr.res
let args = instr.args
if opcode == ir_instruction.move_param {
let param_no = args.at(0)
let location = param_locations.at(param_no)
if is_register(location) {
locations.insert(res, location)
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + location))
locations.insert(res, reg)
values_in_registers.insert(reg, res)
}
} else if opcode == ir_instruction.store_fast {
let reg = ({
let val = args.at(1)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
code.push((" " + "mov " + ({
let location = function.locals.at(args.at(0)).stack_pos
"[rbp - " + str(location * 8 + 8) + "]"
})) + ", " + reg)
} else if opcode == ir_instruction.load {
let reg = ({
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
({
locations.insert(res, reg)
values_in_registers.insert(reg, res)
if reg not in allocated_num_registers {
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg
})
})
let location = function.locals.at(args.at(0)).stack_pos
code.push((" " + "mov " + reg + ", " + ({
let location = function.locals.at(args.at(0)).stack_pos
"[rbp - " + str(location * 8 + 8) + "]"
})))
} else if opcode == ir_instruction.const {
if ty == ptype.int {
let reg = ({
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
({
locations.insert(res, reg)
values_in_registers.insert(reg, res)
if reg not in allocated_num_registers {
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg
})
})
code.push((" " + "mov " + reg + ", " + args.at(0)))
} else if ty == ptype.content {
let reg = ({
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
({
locations.insert(res, reg)
values_in_registers.insert(reg, res)
if reg not in allocated_num_registers {
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg
})
})
let name = ({
let c = args.at(0)
let name = (("%%const_" + str(constant_counter) + "_" + function_name).replace("%", "_P_").replace("@", "_A_").replace(".", "_"))
constants.insert(name, "db `" + c.replace("\n", "\\n") + "`, 0")
constant_counter = constant_counter + 1
name
})
code.push((" " + "mov " + reg + ", " + name))
}
} else if opcode == ir_instruction.add {
if ty == ptype.int {
let reg1 = ({
let val = args.at(0)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
let reg2 = ({
let val = args.at(1)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
if last_use.at(args.at(0)) == line {
({
locations.insert(res, reg1)
values_in_registers.insert(reg1, res)
if reg1 not in allocated_num_registers {
let _ = { let r = reg1; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg1
})
code.push((" " + "add " + reg1 + ", " + reg2))
} else {
let reg = ({
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
({
locations.insert(res, reg)
values_in_registers.insert(reg, res)
if reg not in allocated_num_registers {
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg
})
})
code.push((" " + "mov " + reg + ", " + reg1))
code.push((" " + "add " + reg + ", " + reg2))
}
}
} else if opcode == ir_instruction.sub {
if ty == ptype.int {
let reg1 = ({
let val = args.at(0)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
let reg2 = ({
let val = args.at(1)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
if last_use.at(args.at(0)) == line {
({
locations.insert(res, reg1)
values_in_registers.insert(reg1, res)
if reg1 not in allocated_num_registers {
let _ = { let r = reg1; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg1
})
code.push((" " + "sub " + reg1 + ", " + reg2))
} else {
let reg = ({
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
({
locations.insert(res, reg)
values_in_registers.insert(reg, res)
if reg not in allocated_num_registers {
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
reg
})
})
code.push((" " + "mov " + reg + ", " + reg1))
code.push((" " + "sub " + reg + ", " + reg2))
}
}
} else if opcode == ir_instruction.mul {
if ty == ptype.int {
if "rdx" in allocated_num_registers { ({
let reg = "rdx"
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
}) }
if "rcx" in allocated_num_registers { ({
let reg = "rcx"
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
}) }
({
let val = args.at(1)
let reg = "rcx"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
if "rax" in allocated_num_registers { ({
let reg = "rax"
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
}) }
({
let val = args.at(0)
let reg = "rax"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
if last_use.at(args.at(0)) == line {
({
locations.insert(res, "rax")
values_in_registers.insert("rax", res)
if "rax" not in allocated_num_registers {
let _ = { let r = "rax"; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
"rax"
})
code.push((" " + "mul rcx"))
}
}
} else if opcode == ir_instruction.return_ {
if ty != ptype.none_ {
let reg = ({
let val = args.at(0)
if is_register(locations.at(val)) {
let reg = locations.at(val)
if last_use.at(val) == line {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
reg
} else {
let reg = ({
if free_num_registers.len() > 0 {
{ let r = free_num_registers.first(); let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
} else {
let reg = ({
let reg = allocated_num_registers.first()
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
{ let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
})
code.push((" " + "mov " + reg + ", " + locations.at(val)))
if last_use.at(val) != line {
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
}
})
code.push((" " + "mov rax, " + reg))
} else {
code.push((" " + "xor rax, rax"))
}
code.push((" " + "mov rsp, rbp"))
code.push((" " + "pop rbp"))
code.push((" " + "ret"))
} else if opcode == ir_instruction.join {
if ty == ptype.content {
({
for reg in allocated_num_registers {
if reg in ("rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9") {
({
let reg = reg
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
}
}
code.push((" " + "xor rax, rax"))
})
({
let val = args.at(0)
let reg = "rdi"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
({
let val = args.at(1)
let reg = "rsi"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
code.push((" " + "call " + external_function.content_join))
({
locations.insert(res, "rax")
values_in_registers.insert("rax", res)
if "rax" not in allocated_num_registers {
let _ = { let r = "rax"; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
"rax"
})
({
for reg in allocated_num_registers {
if reg in ("rdi", "rsi", "rdx", "rcx", "r8", "r9") {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
}
})
}
} else if opcode == ir_instruction.cast {
if ty == ptype.content {
({
for reg in allocated_num_registers {
if reg in ("rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9") {
({
let reg = reg
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
}
}
code.push((" " + "xor rax, rax"))
})
({
let val = args.at(0)
let reg = "rdi"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
code.push((" " + "call " + external_function.cast_int_to_content))
({
locations.insert(res, "rax")
values_in_registers.insert("rax", res)
if "rax" not in allocated_num_registers {
let _ = { let r = "rax"; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
"rax"
})
({
for reg in allocated_num_registers {
if reg in ("rdi", "rsi", "rdx", "rcx", "r8", "r9") {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
}
})
}
} else if opcode == ir_instruction.mk_function {
({
for reg in allocated_num_registers {
if reg in ("rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9") {
({
let reg = reg
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
}
}
code.push((" " + "xor rax, rax"))
})
let escaped_label = ((args.at(0)).replace("%", "_P_").replace("@", "_A_").replace(".", "_"))
code.push((" " + "mov rdi, " + escaped_label))
code.push((" " + "mov rsi, " + str(args.at(1))))
code.push((" " + "call " + external_function.mk_function))
({
locations.insert(res, "rax")
values_in_registers.insert("rax", res)
if "rax" not in allocated_num_registers {
let _ = { let r = "rax"; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
"rax"
})
({
for reg in allocated_num_registers {
if reg in ("rdi", "rsi", "rdx", "rcx", "r8", "r9") {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
}
})
} else if opcode == ir_instruction.call_fast {
({
let reg = "rbx"
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
({
for reg in allocated_num_registers {
if reg in ("rax", "rdi", "rsi", "rdx", "rcx", "r8", "r9") {
({
let reg = reg
let pos = temp_values_occupancy.position(x => not x)
if pos == none {
pos = temp_values_occupancy.len()
temp_values_occupancy.push(true)
} else {
temp_values_occupancy.at(pos) = true
}
code.push((" " + "mov [rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "], " + reg))
let val = values_in_registers.at(reg)
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.insert(val, "[rbp - " + {str(temp_var_offset + 8 * pos + 8)} + "]")
reg
})
}
}
code.push((" " + "xor rax, rax"))
})
let arg_regs = ("rdi", "rsi", "rdx", "rcx", "r8", "r9")
for arg_no, arg in args.slice(1, calc.min(args.len(), arg_regs.len() + 1)) {
({
let val = arg
let reg = arg_regs.at(arg_no)
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
}
if args.len() > arg_regs.len() + 1 {
for arg in args.slice(arg_regs.len() + 1).rev() {
({
let val = arg
let reg = "rbx"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
code.push((" " + "push rbx"))
{ let r = "rbx"; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
locations.remove(arg)
values_in_registers.remove("rbx")
}
}
({
let val = args.at(0)
let reg = "rbx"
if locations.at(val) != reg {
if is_register(locations.at(val)) {
let _ = { let r = locations.at(val); let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
code.push((" " + "mov " + reg + ", " + locations.at(val)))
let _ = { let r = reg; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
locations.insert(val, reg)
values_in_registers.insert(reg, val)
}
reg
})
code.push((" " + "mov rbx, [rbx]"))
code.push((" " + "call rbx"))
({
locations.insert(res, "rax")
values_in_registers.insert("rax", res)
if "rax" not in allocated_num_registers {
let _ = { let r = "rax"; let _ = free_num_registers.remove(free_num_registers.position(x => x == r));
allocated_num_registers.push(r); r }
}
"rax"
})
if args.len() > arg_regs.len() {
code.push((" " + "add rsp, " + str(8 * (args.len() - arg_regs.len()))))
}
({
for reg in allocated_num_registers {
if reg in ("rdi", "rsi", "rdx", "rcx", "r8", "r9") {
let _ = { let r = reg; let _ = allocated_num_registers.remove(allocated_num_registers.position(x => x == r));
free_num_registers.push(r); r }
}
}
})
}
}
let allocate_on_stack = 8 * (function.stack_occupancy.len() + temp_values_occupancy.len())
if calc.mod(allocate_on_stack, 16) != 0 {
allocate_on_stack += 16 - calc.mod(allocate_on_stack, 16)
}
code = (
(" " + "push rbp"),
(" " + "mov rbp, rsp"),
(" " + "sub rsp, " + str(allocate_on_stack))
) + code
return (code: code, constants: constants)
}
#let compile_x86(functions) = {
let code = ()
let constants = (:)
for function_name, function in functions {
code.push(((function_name.replace(".", "_")).replace("%", "_P_").replace("@", "_A_").replace(".", "_")) + ":")
let res = compile_function(function_name, function)
code += res.code
constants += res.constants
}
let externs = external_function.pairs().map(x => " extern " + x.at(1) + "\n").join()
let text_segment = "segment .text\n global entry\n\n" + externs + code.join("\n") + "\n"
let data_segment = (
"segment .data\n" +
constants.pairs().map(x => x.at(0) + ": " + x.at(1)).join("\n")
) + "\n\n"
return data_segment + text_segment
}
#{
import "ir-gen.typ": *
import "pprint.typ": *
set page(height: auto)
let ir = ir_from_ast(parse("#let f(/*int*/x, /*int*/y) = x + y
#f(2, 2)
"))
pprint(ir)
asm_code(compile_x86(ir.functions))
} |
|
https://github.com/GuTaoZi/SUSTech-thesis-typst | https://raw.githubusercontent.com/GuTaoZi/SUSTech-thesis-typst/main/template/abstract_en.typ | typst | MIT License | #import "../utils/style.typ" : *
#let abstract_en(
show_title: true,
anonymous: false,
info: (:),
fonts: (:),
keywords: (:),
body,
) = {
fonts = FONTS + fonts
if show_title {
set align(center)
for line in info.title {
text(size: FSIZE.二号, font: FONTS.黑体,line + "\n")
// text(size: FSIZE.二号, font: FONTS.黑体,line)
}
align(right)[
#text(size: FSIZE.小二, font: "Arial", "---")
#text(size: FSIZE.小二, font: FONTS.黑体, info.subtitle)
]
text(size: FSIZE.四号, font: FONTS.宋体)[
#info.author
]
text(size: FSIZE.小四, font: FONTS.楷体)[
(#info.department Thesis Advisor:#info.supervisor)\
\
\
]}
align(left)[
#par(first-line-indent: 0em)[
#text(size: FSIZE.三号, font: FONTS.黑体, "[Abstract]: ")
#text(size: FSIZE.四号, font: FONTS.宋体,body)
]
]
align(left+bottom)[
#par(first-line-indent: 0em)[
#text(size: FSIZE.三号, font: FONTS.黑体,"[Key Words]: ")
#text(size: FSIZE.四号, font: FONTS.宋体)[
#(("",)+ keywords.intersperse(", ")).sum()
]
]
]
} |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/tgm-hit-thesis/0.1.0/template/lib.typ | typst | Apache License 2.0 | #import "@preview/tgm-hit-thesis:0.1.0": *
#import "assets.typ"
|
https://github.com/alimitedgroup/alimitedgroup.github.io | https://raw.githubusercontent.com/alimitedgroup/alimitedgroup.github.io/main/verbali/interni/2024-10-15.typ | typst | // VI 15-10-2024
#import "../../lib.typ": *
#set text(lang: "it")
#show: doc => verbale(
data: [15-10-2024],
regmodifiche: (
/*("1.0.0", "2024-10-15", "Sam<NAME>", "-", "Approvazione documento"),*/
("0.1.0", "17-10", "<NAME>", "-", "Modifica e verifica documento"),
("0.0.2", "16-10", "<NAME>", "-", "Redazione documento"),
("0.0.1", "15-10", "Sam<NAME>", "-", "Creazione struttura e template documento"),
),
versione: [0.1.0],
stato: [Verificato],
presenze: (
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
),
odg: [Prima riunione di _ALimitedGroup_: vengono proposte le prime _task_ da portare a termine],
doc,
)
= Informazioni generali
#inizio-verbale-interno([*virtuale*], [*15 Ottobre 2024*], [*14.30*], [*15.34*])
1. Decisione del nome del gruppo
2. Realizzazione del logo del gruppo
3. Definizione dell'email del gruppo
4. Definizione dei canali di comunicazione
5. Definizione struttura generale dei verbali
6. Valutazione dei capitolati disponibili
Data l'assenza di un componente eventuali correzioni alle decisioni riportate in questo documento saranno debitamente verbalizzate a seguito di
nuova riunione.
#pagebreak()
= Dettaglio riunione
== Decisione del nome del gruppo
Durante la riunione è stato proposto _*ALimitedGroup*_ come nome di
rappresentanza del nostro gruppo.
== Realizzazione del logo del gruppo
Successivamente l'approvazione da parte di tutti i presenti del nuovo nome, è stato creato un logo che rappresentava appieno i valori del gruppo:
#figure(
image("../../assets/altd.png", width: 40%, format: "png"),
caption: [Logo scelto dati presenti],
)<logo>
Dopo aver discusso internamente, si è deciso ufficialmente di utilizzare l'immagine in @logo come logo per rappresentare il nostro gruppo.
== Definizione dell'email del gruppo
Per tutte le comunicazioni verso l'esterno da parte del nostro gruppo è stato proposto l'utilizzo della seguente mail:\
#align(center)[#emph[#link("mailto:<EMAIL>")]]
== Definizione dei canali di comunicazione
Durante la riunione è stato per il momento proposto di utilizzare i seguenti
canali di comunicazione interne:
- _Telegram_ è stato proposto di utilizzare un gruppo _Telegram_ per comunicare
di informazioni generali riguardante le attività del gruppo (ad esempio, per
proporre nuove riunioni)
- _Discord_: è stato proposto di utilizzare un server _Discord_ per
realizzare riunioni virtuali
== Definizione della struttura generale dei verbali
Durante la riunione è stato concordato l'utilizzo di un _template standard_
per la redazione dei verbali di riunioni interne ed esterne.
#pagebreak()
== Valutazione dei capitolati disponibili
Durante la riunione è stato proposto che, in base ai comuni interessi e alle
conoscenze attuali, i seguenti capitolati, nell'ordine di preferenza, potrebbero
essere di interesse per lo sviluppo:
1. C6 = *Sistema di Gestione di un Magazzino Distribuito* avente
come proponente *M31*
2. C2 = *<NAME>* avente come proponente *VIMAR*
3. C7 = *LLM: Assistente Virtuale* avente come proponente *Ergon*
È stato proposto, inoltre, di contattare il proponente _M31_ per porre alcune
ulteriori domande riguardanti il capitolato, tra cui:
- Richiesta maggiori dettagli in merito alla gestione della concorrenza
- Richiesta maggiori dettagli in merito allo svolgimento degli _Unit Test_
- Richiesta ulteriori dettagli riguardo la divisione architetturale proposta
= Esiti della riunione
In seguito al termine della riunione, il gruppo decide di conocordare una
nuova riunione da svolgersi il prima possibile per confermare quanto
proposto nel seguente documento con tutti i membri.
Ha altresì proposto di concordare l'invio, quanto prima, di una mail per richiedere un colloquio con _M31_. |
|
https://github.com/arthurcadore/eng-telecom-workbook | https://raw.githubusercontent.com/arthurcadore/eng-telecom-workbook/main/models/model.typ | typst | MIT License | #import "@preview/klaro-ifsc-sj:0.1.0": report
#import "@preview/codelst:2.0.1": sourcecode
#show heading: set block(below: 1.5em)
#show par: set block(spacing: 1.5em)
#set text(font: "Arial", size: 12pt)
#set page(
footer: "Engenharia de Telecomunicações - IFSC-SJ",
)
#show: doc => report(
title: "Nome do Relatório",
subtitle: "Disciplina / Área de atuação",
authors: ("<NAME>",),
date: "DD de Mês de YYYY",
doc,
)
= Exemplo de instânciação de componentes:
== Imagem de exemplo:
#figure(
figure(
image("./pictures/timeDomain.png"),
numbering: none,
caption: [Sinal de entrada no domínio do tempo]
),
caption: figure.caption([Elaborada pelo Autor], position: top)
)
== Tabela de exemplo:
#table(
columns: (1fr, 1fr, 1fr),
table.header[Implementacao][Área][Tempo de propagação],
[Parte 1], [], [],
[Parte 2], [], [],
)
== Trecho de código de exemplo:
#sourcecode[```vhd
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity bin2bcd is
port (
A : in std_logic_vector (7 downto 0);
sd, su, sc : out std_logic_vector (3 downto 0)
);
end entity;
```]
= Introdução
Seção I - Descrição do que será desenvolvido/abordado no relatório
= Fundamentação teórica
Seção II - Conceitos teóricos utilizados no relatório
= Análise dos resultados
Seção III - Apresentação e comentários dos gráfios/figuras das etapas de desenvolvimento do relatório
= Scripts e Códigos Utilizados:
Seção IV - Scripts e Codigos
= Conclusão
Seção V - Conclusões
= Referências
Para o desenvolvimento deste relatório, foi utilizado o seguinte material de referência:
- #link("https://www.researchgate.net/publication/287760034_Software_Defined_Radio_using_MATLAB_Simulink_and_the_RTL-SDR")[Software Defined Radio Using MATLAB & Simulink and the RTL-SDR, de <NAME>] |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/util.typ | typst | Apache License 2.0 | #import "matrix.typ"
#import "vector.typ"
// Multiplies the vector by the transform matrix
#let apply-transform(transform, vec) = {
matrix.mul-vec(
transform,
vector.as-vec(vec, init: (0, 0, 0, 1))
).slice(0, 3)
}
// Reverts the transform of the given vector
#let revert-transform(transform, vec) = {
apply-transform(matrix.inverse(transform), vec)
}
#let bezier-quadratic-pt(a, b, c, t) = {
// (1-t)^2 * a + 2 * (1-t) * t * c + t^2 b
return vector.add(
vector.add(
vector.scale(a, calc.pow(1-t, 2)),
vector.scale(c, 2 * (1-t) * t)
),
vector.scale(b, calc.pow(t, 2))
)
}
#let bezier-cubic-pt(a, b, c1, c2, t) = {
// (1-t)^3*a + 3*(1-t)^2*t*c1 + 3*(1-t)*t^2*c2 + t^3*b
vector.add(
vector.add(
vector.scale(a, calc.pow(1-t, 3)),
vector.scale(c1, 3 * calc.pow(1-t, 2) * t)
),
vector.add(
vector.scale(c2, 3*(1-t)*calc.pow(t,2)),
vector.scale(b, calc.pow(t, 3))
)
)
}
#let resolve-number(ctx, num) = {
if type(num) == "length" {
if repr(num).ends-with("em") {
float(repr(num).slice(0, -2)) * ctx.em-size.width / ctx.length
} else {
float(num / ctx.length)
}
} else {
float(num)
}
}
#let resolve-radius(radius) = {
return if type(radius) == "array" {radius} else {(radius, radius)}
}
|
https://github.com/frectonz/the-pg-book | https://raw.githubusercontent.com/frectonz/the-pg-book/main/book/120.%20discover.html.typ | typst | discover.html
Persuade xor Discover
September 2009When meeting people you don't know very well, the convention is
to seem extra friendly. You smile and say "pleased to meet you,"
whether you are or not. There's nothing dishonest about this.
Everyone knows that these little social lies aren't meant
to be taken literally, just as everyone knows that
"Can you pass the salt?" is only grammatically a question.I'm perfectly willing to smile and say "pleased to meet you"
when meeting new people. But there is another set of
customs for being ingratiating in print that are not so
harmless.The reason there's a convention of being ingratiating in print
is that most essays are written to persuade.
And as any politician could tell
you, the way to persuade people is not just to baldly state the
facts. You have to add a spoonful of sugar to make the medicine
go down.For example, a politician announcing the cancellation of
a government program will not merely say "The
program is canceled." That would seem offensively
curt. Instead he'll spend most of his time talking about the
noble effort made by the people who worked on it.The reason these conventions are more dangerous is that they
interact with the ideas. Saying "pleased to meet you" is just
something you prepend to a conversation, but the sort of spin
added by politicians is woven through it. We're starting to
move from social lies to real lies.Here's an example of a paragraph from an essay I wrote about
labor unions. As written,
it tends to offend people who like unions.
People who think the labor movement was the creation of heroic
union organizers have a problem to explain: why are unions shrinking
now? The best they can do is fall back on the default explanation
of people living in fallen civilizations. Our ancestors were
giants. The workers of the early twentieth century must have had
a moral courage that's lacking today.
Now here's the same paragraph rewritten to please instead of
offending them:
Early union organizers made heroic sacrifices to improve conditions
for workers. But though
labor unions are shrinking now, it's not because present union
leaders are any less courageous. An employer couldn't get away
with hiring thugs to beat up union leaders today, but if they
did, I see no reason to believe today's union leaders would shrink
from the challenge. So I think it would be a mistake to attribute
the decline of unions to some kind of decline in the people who
run them. Early union leaders were heroic, certainly, but we
should not suppose that if unions have declined, it's because
present union leaders are somehow inferior. The cause must be
external.
[1]
It makes the same point: that it can't have been the personal
qualities of early union organizers that made unions successful,
but must have been some external factor, or otherwise present-day
union leaders would have to be inferior people. But written this
way it seems like a defense of present-day union organizers rather
than an attack on early ones. That makes it more persuasive to
people who like unions, because it seems sympathetic to their cause.I believe everything I wrote in the second version. Early union
leaders did make heroic sacrifices. And
present union leaders probably would rise to the occasion if
necessary. People tend to; I'm skeptical about the idea of "the
greatest generation."
[2]If I believe everything I said in the second version, why didn't I
write it that way? Why offend people needlessly?Because I'd rather offend people than pander to them,
and if you write about controversial topics you have to choose one or the other. The degree of
courage of past or present union leaders is beside the point; all
that matters for the argument is that they're the same.
But if you want to please
people who are mistaken, you can't simply tell the truth. You're
always going to have to add some sort of padding to protect their
misconceptions from bumping against reality.Most writers do. Most writers write to persuade, if only out of
habit or politeness. But I don't write to persuade; I write to
figure out. I write to persuade a hypothetical perfectly unbiased
reader.Since the custom is to write to persuade the actual reader, someone
who doesn't will seem arrogant. In fact, worse than arrogant: since
readers are used to essays that try to please someone, an essay
that displeases one side in a dispute reads as an attempt to pander
to the other. To a lot of pro-union readers, the first paragraph
sounds like the sort of thing a right-wing radio talk show host
would say to stir up his followers. But it's not. Something that
curtly contradicts one's beliefs can be hard to distinguish from a
partisan attack on them, but though they can end up in the same
place they come from different sources.Would it be so bad to add a few extra words, to make people feel
better? Maybe not. Maybe I'm excessively attached to conciseness.
I write code the same way I write essays,
making pass after pass
looking for anything I can cut. But I have a legitimate reason for
doing this. You don't know what the ideas are until you get them
down to the fewest words.
[3]The danger of the second paragraph
is not merely that it's longer. It's that you start to lie to
yourself. The ideas start to get mixed together with the spin
you've added to get them past the readers' misconceptions.I think the goal of an essay should be to discover
surprising things. That's my goal, at least.
And most surprising means most different from what people currently
believe. So writing to persuade and writing to discover are
diametrically opposed. The more your conclusions disagree with
readers' present beliefs, the more effort you'll have to expend on
selling your ideas rather than having them. As you accelerate,
this drag increases, till eventually you reach a point where 100%
of your energy is devoted to overcoming it and you can't go any
faster.It's hard enough to overcome one's own misconceptions without having
to think about how to get the resulting ideas past other people's.
I worry that if I wrote to persuade, I'd start to shy away unconsciously
from ideas I knew would be hard to sell. When I notice something
surprising, it's usually very faint at first. There's nothing more
than a slight stirring of discomfort. I don't want anything to get
in the way of noticing it consciously.
Notes[1]
I had a strange feeling of being back in high school writing
this. To get a good grade you had to both write the sort of pious
crap you were expected to, but also seem to be writing with conviction.
The solution was a kind of method acting. It was revoltingly
familiar to slip back into it.[2]
Exercise for the reader:
rephrase that thought to please the same people the first version
would offend.[3]
Come to think of it, there is one way in which I deliberately
pander to readers, because it doesn't change the number of words:
I switch person. This flattering distinction seems so natural to
the average reader that they probably don't notice even when I
switch in mid-sentence, though you tend to notice when it's done
as conspicuously as this.Thanks to <NAME> and <NAME>
for reading drafts of this.Note: An earlier version of this essay began by talking
about why people dislike <NAME>. I now believe that
was mistaken, and that most people don't dislike him for the
same reason I did when I first met him, but simply because
he writes about controversial things.
|
|
https://github.com/Doublonmousse/pandoc-typst-reproducer | https://raw.githubusercontent.com/Doublonmousse/pandoc-typst-reproducer/main/color_issues/mix.typ | typst | #block(fill: red.mix(blue)) |
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2006/WS-10.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [ZHANG Yining], [CHN], [3036],
[2], [WANG Nan], [CHN], [2721],
[3], [GUO Yue], [CHN], [2692],
[4], [GUO Yan], [CHN], [2673],
[5], [LI Xiaoxia], [CHN], [2640],
[6], [TIE Yana], [HKG], [2627],
[7], [JIANG Huajun], [HKG], [2559],
[8], [NIU Jianfeng], [CHN], [2554],
[9], [KIM Kyungah], [KOR], [2534],
[10], [WANG Yuegu], [SGP], [2515],
[11], [FUKUHARA Ai], [JPN], [2471],
[12], [FUJII Hiroko], [JPN], [2456],
[13], [LI Jiawei], [SGP], [2440],
[14], [CAO Zhen], [CHN], [2439],
[15], [PARK Miyoung], [KOR], [2427],
[16], [BOROS Tamara], [CRO], [2404],
[17], [CHANG Chenchen], [CHN], [2386],
[18], [GAO Jun], [USA], [2379],
[19], [LIN Ling], [HKG], [2374],
[20], [LI Jiao], [NED], [2373],
[21], [WU Xue], [DOM], [2346],
[22], [STEFF Mihaela], [ROU], [2344],
[23], [FUKUOKA Haruna], [JPN], [2344],
[24], [CHEN Qing], [CHN], [2335],
[25], [<NAME>], [HUN], [2334],
[26], [FAN Ying], [CHN], [2333],
[27], [<NAME>ling], [ITA], [2329],
[28], [PAVLOVICH Viktoria], [BLR], [2327],
[29], [KIM Mi Yong], [PRK], [2310],
[30], [GANINA Svetlana], [RUS], [2308],
[31], [SHEN Yanfei], [ESP], [2295],
[32], [KANAZAWA Saki], [JPN], [2280],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [FUJINUMA Ai], [JPN], [2275],
[34], [GRUNDISCH Carole], [FRA], [2271],
[35], [HIRANO Sayaka], [JPN], [2266],
[36], [ODOROVA Eva], [SVK], [2261],
[37], [SUN Beibei], [SGP], [2258],
[38], [LIU Jia], [AUT], [2258],
[39], [LIU Shiwen], [CHN], [2252],
[40], [LEE Eunhee], [KOR], [2243],
[41], [JEON Hyekyung], [KOR], [2242],
[42], [#text(gray, "KIM Bokrae")], [KOR], [2240],
[43], [<NAME>], [HKG], [2239],
[44], [KOMWONG Nanthana], [THA], [2238],
[45], [STEFANOVA Nikoleta], [ITA], [2226],
[46], [KWAK Bangbang], [KOR], [2225],
[47], [<NAME>], [CHN], [2225],
[48], [XU Yan], [SGP], [2208],
[49], [<NAME>], [HKG], [2206],
[50], [#text(gray, "RYOM Won Ok")], [PRK], [2205],
[51], [<NAME>], [UKR], [2196],
[52], [<NAME>], [FRA], [2195],
[53], [<NAME>], [HKG], [2194],
[54], [<NAME>], [SGP], [2193],
[55], [PAVLOVICH Veronika], [BLR], [2190],
[56], [HIURA Reiko], [JPN], [2189],
[57], [LI Nan], [CHN], [2186],
[58], [<NAME>], [KOR], [2171],
[59], [<NAME>], [CHN], [2168],
[60], [KOTIKHINA Irina], [RUS], [2166],
[61], [SCHALL Elke], [GER], [2165],
[62], [IVANCAN Irene], [GER], [2164],
[63], [STRBIKOVA Renata], [CZE], [2159],
[64], [ZAMFIR Adriana], [ROU], [2148],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [LI Qiangbing], [AUT], [2148],
[66], [#text(gray, "LEE Eunsil")], [KOR], [2134],
[67], [STRUSE Nicole], [GER], [2131],
[68], [<NAME>], [JPN], [2127],
[69], [WANG Chen], [CHN], [2125],
[70], [POTA Georgina], [HUN], [2121],
[71], [<NAME>], [SGP], [2116],
[72], [WU Jiaduo], [GER], [2111],
[73], [<NAME>], [JPN], [2108],
[74], [UMEMURA Aya], [JPN], [2108],
[75], [LU Yun-Feng], [TPE], [2106],
[76], [DVORAK Galia], [ESP], [2101],
[77], [MOLNAR Cornelia], [CRO], [2093],
[78], [LOVAS Petra], [HUN], [2091],
[79], [PASKAUSKIENE Ruta], [LTU], [2090],
[80], [<NAME>], [SWE], [2089],
[81], [SHIM Serom], [KOR], [2086],
[82], [TERUI Moemi], [JPN], [2086],
[83], [<NAME>], [CRO], [2076],
[84], [<NAME>], [AUS], [2076],
[85], [<NAME>], [ESP], [2072],
[86], [MIROU Maria], [GRE], [2071],
[87], [<NAME>], [THA], [2071],
[88], [<NAME>], [GER], [2066],
[89], [<NAME>], [ISR], [2063],
[90], [<NAME>], [AUS], [2059],
[91], [<NAME>], [GER], [2058],
[92], [<NAME>], [GER], [2058],
[93], [KIM Kyungha], [KOR], [2040],
[94], [XU Jie], [POL], [2038],
[95], [<NAME>], [ROU], [2033],
[96], [<NAME>], [KOR], [2031],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [KIM Jong], [PRK], [2030],
[98], [HEINE Veronika], [AUT], [2022],
[99], [<NAME>], [BUL], [2019],
[100], [<NAME>], [GER], [2017],
[101], [LI Chunli], [NZL], [2015],
[102], [#text(gray, "<NAME>")], [HUN], [1998],
[103], [#text(gray, "BATORFI Csilla")], [HUN], [1988],
[104], [NEVES Ana], [POR], [1985],
[105], [K<NAME>], [RUS], [1985],
[106], [<NAME>], [JPN], [1981],
[107], [<NAME>], [BLR], [1980],
[108], [<NAME>], [GER], [1977],
[109], [BADESCU Otilia], [ROU], [1969],
[110], [<NAME>], [JPN], [1968],
[111], [<NAME>], [GER], [1966],
[112], [<NAME>], [MDA], [1958],
[113], [<NAME>], [TPE], [1957],
[114], [<NAME>], [PRK], [1954],
[115], [<NAME>], [COL], [1951],
[116], [<NAME>], [POR], [1949],
[117], [#text(gray, "<NAME>")], [HUN], [1947],
[118], [<NAME>], [HUN], [1944],
[119], [NTOULAKI Ekaterina], [GRE], [1944],
[120], [<NAME>], [RUS], [1943],
[121], [WANG Yu], [ITA], [1942],
[122], [<NAME>], [GER], [1942],
[123], [VACENOVSKA Iveta], [CZE], [1938],
[124], [#text(gray, "<NAME>")], [SWE], [1938],
[125], [ETSUZAKI Ayumi], [JPN], [1935],
[126], [JANG Hyon Ae], [PRK], [1934],
[127], [#text(gray, "<NAME>")], [JPN], [1930],
[128], [#text(gray, "<NAME>")], [SRB], [1925],
)
) |
|
https://github.com/jLevere/resume | https://raw.githubusercontent.com/jLevere/resume/main/resume.typ | typst | #import "template.typ": *
#show: doc => conf(doc)
== Education
#chiline()
#degree("The Ohio State University", "Bachelor of Arts in Computer and Information Science", "Expected May 2025")
== Experience
#chiline()
#entry(
"IBM X-Force Red",
"Pentest Intern",
"Austin, Texas",
"May-August 2024",
(
"Shadowed experienced pentesters during engagements, gaining insights and experience",
"Worked in small team to engineer a custom solution for stealthy LDAP enumeration and writing by designing and implementing Windows Communication Foundation framework in Python. The project, encompassing nearly 7,000 lines of code, involved reversing and implementing eight protocol layers and authentication mechanisms from scratch. Conducted extensive research and review of Windows protocol documentation, ensuring full interoperability with the Impacket toolset. Produced a standalone tool and presented it to IBM executives",
),
)
#entry(
"IBM X-Force Red",
"Pentest Intern",
"Austin, Texas",
"May-August 2023",
(
"Shadowed experienced pentesters on web app, external, and internal network penetration tests, gaining valuable insights",
"Completed comprehensive internal training in internal network penetration, web application security, cryptography, social engineering, and mobile application security",
"Worked in team to develop a C2 system using ETW for opportunistic traffic sniffing on Windows devices, enabling command execution and communication without direct socket use. Created and presented a proof of concept to IBM executives",
),
)
#entry(
"The Ohio State University Athletics Department",
"IT Student Intern",
"Columbus, Ohio",
"May 2022 - August 2022",
(
"Develop processes to track and document vulnerability remediation across four thousand devices",
"Worked with the myriad of tools used to secure and manage large enterprise environments including CrowdStrike, Qualys, and the SolarWinds suite",
),
)
== Extracurricular
#chiline()
#entry(
"OSU Cyber Security Club",
"Vice President / Member",
"Columbus, Ohio",
"August 2020 - Present",
(
"Member of the winning RIT ISTS 2022 team. Competed in ISTS 2022-2024",
"Participated in the Cyber Truck Challenge 2022, working in a six-person team to map and attack heavy truck engine control units, communication networks, and cyber-physical systems. Presented findings and vulnerabilities to OEMs",
"Collaborated with the Truck Cybersecurity Research Group to develop attack methodologies for Engine Control Units",
"Design Python network support for J1939 intelligent fuzzers and J1939 Transport Protocol",
),
)
#entry(
"Athletics Experience, Target Pistol Shooting",
"US National Team",
"OSU Varsity Athlete",
"August 2016 - 2024",
(
"Dedicate 20+ hours a week to training and practice while maintaining a full academic course load",
"Communicate with teammates of various demographic backgrounds to establish a positive team environment",
"2021, 2022, 2023, 2024 All-American, OSU Scholar Athlete",
"2018 CAT Games Mexico, 2018 South Korea World Championship team, 2019 Pan-American Games Lima, 2020 Tokyo Olympian, Rapid Fire Pistol",
),
)
|
|
https://github.com/zurgl/typst-resume | https://raw.githubusercontent.com/zurgl/typst-resume/main/templates/commun.typ | typst | #import "../metadata.typ": *
/* Utility Functions */
#let hBar() = [
#h(5pt) | #h(5pt)
]
#let autoImport(file) = {
include { "../resume/" + varLanguage + "/" + file + ".typ" }
}
#let languageSwitch(dict) = {
for (k, v) in dict {
if k == varLanguage {
return v
break
}
}
panic("i18n: language value not matching any key in the array")
}
/* Styles */
#let fontList = (
"Source Sans Pro",
"Font Awesome 6 Brands",
"Font Awesome 6 Free",
)
#let headerFont = ("Roboto", "")
#let awesomeColors = (
skyblue: rgb("#0395DE"),
red: rgb("#DC3522"),
nephritis: rgb("#27AE60"),
concrete: rgb("#95A5A6"),
darknight: rgb("#131A28"),
)
#let regularColors = (
subtlegray: rgb("#5cb6e0"),
lightgray: rgb("#343a40"),
darkgray: rgb("#212529"),
)
#let accentColor = {
if type(awesomeColor) == color {
awesomeColor
} else {
awesomeColors.at(awesomeColor)
}
}
/* Layout */
#let layout(doc) = {
set text(font: fontList, weight: "regular", size: 9pt)
set align(left)
set page(
paper: "a4",
margin: (left: 1.4cm, right: 1.4cm, top: .8cm, bottom: .4cm),
)
doc
}
#let beforeSectionSkip = 1pt
#let beforeEntrySkip = 1pt
#let beforeEntryDescriptionSkip = 1pt
#let footerStyle(str) = { text(size: 8pt, fill: rgb("#999999"), smallcaps(str)) }
|
|
https://github.com/AnsgarLichter/hka-thesis-template | https://raw.githubusercontent.com/AnsgarLichter/hka-thesis-template/main/common/settings.typ | typst | #let fontBody = "New Computer Modern"
#let fontBodySize = 12pt;
#let fontFiguresSubtitleSize = 0.85em;
// At the moment only used on the title page
#let fontHeading = "New Computer Modern Sans"
#let fontHeadingSize = 16pt
#let headingsNumberingStyle = "1.1."
#let headingsSpacing = (
below: 0.85em,
above: 1.75em
)
#let citationStyle = "../bibliography/ieee.csl"
#let spaceBeforeParagraph = 24pt
#let distanceBetweenLines = 1em
#let listIdentation = 2.5em |
|
https://github.com/goshakowska/Typstdiff | https://raw.githubusercontent.com/goshakowska/Typstdiff/main/tests/test_working_types/strong/strong.typ | typst | *first*\
#strong[second]\
*third*\
#strong[forth] |
|
https://github.com/EricWay1024/Homological-Algebra-Notes | https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/libs/template.typ | typst | #import "@preview/commute:0.2.0": node, arr, commutative-diagram
#let color_style = "./color.typ"
#let link_color = rgb(0, 0, 255)
#if color_style == "./bw.typ" {
link_color = rgb(0, 0, 0)
}
#let textwidth = 100%;
#let img(path, width: textwidth) = {
align(center, image("../imgs/cat/" + path + ".jpg", width: width))
}
#let bd(term) = [ $bold(#term)$]
#let veck = [$bold("Vect")_k$]
#let homk = [$op("Hom")_k$]
#let hom = [$op("Hom")$]
#let Hom(c) = [$op("Hom")_cal(#c)$]
#let end = [$op("End")$]
#let End(c) = [$op("End")_cal(#c)$]
#let tp = [$times.circle$]
#let ds = [$plus.circle$]
#let iso = [$tilde.equiv$]
#let bij = [$attach(->, t: tilde)$]
#let tpk = [$times.circle_k$]
#let tpr = [$times.circle_R$]
#let tpz = [$times.circle_ZZ$]
#let tpzg = [$times.circle_(ZZ G)$]
#let cA = [$cal(A)$]
#let cB = [$cal(B)$]
#let cC = [$cal(C)$]
#let cD = [$cal(D)$]
#let ob = [$"ob"$]
#let Set = [$bd("Set")$]
#let Cat = [$bd("Cat")$]
#let RMod = [$R$-$bd("Mod")$]
#let kMod = [$k$-$bd("Mod")$]
#let GMod = [$G$-$bd("Mod")$]
#let ZGMod = [$ZZ G$-$bd("Mod")$]
#let ZMod = [$ZZ$-$bd("Mod")$]
#let SMod = [$S$-$bd("Mod")$]
#let ModR = [$bd("Mod")$-$R$]
#let ModS = [$bd("Mod")$-$S$]
#let homr = [$op("Hom")_R$]
#let homg = [$op("Hom")_G$]
#let endr = [$op("End")_R$]
#let Mod = [$bd("Mod")$]
#let Ab = [$bd("Ab")$]
#let Grp = [$bd("Grp")$]
#let Top = [$bd("Top")$]
#let Id = [$op("Id")$]
#let colim = [$op("colim")$]
#let coim = [$op("coim")$]
#let Coim = [$op("Coim")$]
#let IM = [$op("Im")$]
#let Eq = [$op("eq")$]
#let EQ = [$op("Eq")$]
#let Fun = [$op("Fun")$]
#let Coeq = [$op("coeq")$]
#let COeq = [$op("Coeq")$]
#let coker = [$op("coker")$]
#let Coker = [$op("Coker")$]
#let Ker = [$op("Ker")$]
#let ses(A, B, C, f: "", g: "") = [$0 -> #A ->^#f #B ->^#g #C -> 0$]
#let rgt(A) = [$attach(->, t: #A)$]
#let lft(A) = [$attach(<-, t: #A)$]
#let over = [$\/$]
#let lrm = [left $R$-module]
#let rrm = [right $R$-module]
#let lrms = [left $R$-modules]
#let rrms = [right $R$-modules]
#let oo = [$compose$]
#let mapsto = [$|->$]
#let prshv = [$"Psh"$]
#let Psh = [$"Psh"$]
#let cx = [$circle.filled.small$]
#let Ccx = [$C_cx$]
#let Dcx = [$D_cx$]
#let Cco = [$C^cx$]
#let Dco = [$D^cx$]
#let Ch = [$"Ch"$]
#let sest = [short exact sequence]
#let lest = [long exact sequence]
#let sess = [short exact sequences]
#let less = [long exact sequences]
#let iff = [if and only if]
#let Ext = [$"Ext"$]
#let Tor = [$"Tor"$]
#let cone = [$"cone"$]
#let cyl = [$"cyl"$]
#let Tot = [$"Tot"$]
#let triv = [$"triv"$]
#let fJ = [$frak(J)$]
#let Der = [$"Der"$]
#let PDer = [$"PDer"$]
// #let endlec(n) = [_This is the end of lecture #n._]
#let endlec(n) = []
#let TODO = text(blue)[TODO]
#let fw(doc) = box(width: 100%)[#doc]
#let proof(title: "Proof", term) = block(width: 100%, breakable: true)[_#title._ #term #h(1fr) $qed$]
#let project(title: "", authors: (), date: none, body) = {
// Set the document's basic properties.
set document(author: authors, title: title)
set page(numbering: "1", number-align: center)
set text(font: "Linux Libertine", lang: "en")
// Title row.
align(center)[
#block(text(weight: 700, 1.75em, title))
#v(1em, weak: true)
#date
]
// Author information.
pad(
top: 0.5em,
bottom: 0.5em,
x: 2em,
grid(
columns: (1fr,) * calc.min(3, authors.len()),
gutter: 1em,
..authors.map(author => align(center, author)),
),
)
// Main body.
set par(justify: true)
set heading(numbering: "1.1.")
set enum(numbering: "(1)")
show ref: set text(link_color)
show link: set text(link_color)
body
}
#import color_style : *
|
|
https://github.com/linhduongtuan/BKHN-Thesis_template_typst | https://raw.githubusercontent.com/linhduongtuan/BKHN-Thesis_template_typst/main/template/font.typ | typst | Apache License 2.0 | // Setting font and font sizes that are similar as LaTeX
#let arial = ("New Computer Modern Sans")
#let font_size = (
Huge: 26pt,
huge: 24pt,
LARGE: 22pt,
Large: 18pt,
large: 16pt,
normalsize: 15pt,
small: 14pt,
footnotesize: 12pt,
scriptsize: 10.5pt,
tiny: 9pt,
) |
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/007%20-%20Theros/002_Prince%20Anax%2C%20Part%201.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Prince Anax, Part 1",
set_name: "Theros",
story_date: datetime(day: 18, month: 09, year: 2013),
author: "<NAME>",
doc
)
Anax ran around the edge of the gymnasium. The scalding summer sun was getting high in the sky. He was sweating and his lungs burned, but it felt good.
He ran past the rack of spears and swords, past the stand of weighted practice shields, past the leather aprons and piles of stones. He ran past armored soldiers drilling shield walls, past men throwing weights in the sand pit.
#figure(image("002_Prince Anax, Part 1/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Once, he ran through the garden, for a few minutes of shade. One was not supposed to run through there; Anax was, however, the first son of King Athanas, and so no one stopped him.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The bathhouse was crowded this particular early afternoon. It was early for the crowd to hit under normal circumstances, but Father's final audience with the Setessans was only an hour away. Everyone was expected to be there, both to be part of the display and to see what would happen.
Anax lingered in the tub, savoring the cool water on his skin. Before too long, the water felt cold, and he began to shiver. He climbed out and dried himself. His younger brother's voice came from behind him, with only barely concealed reproach. "So what did you do this morning?"
Anax turned to regard Timoteus. Anax was the elder by two years, but he had never been large, and his brother had never been small. Now they were the same size, although perhaps Timoteus's arms were a little bigger. Naked as they were, they were on display for everyone to see. No one made a show of looking, but there was no shortage of sideways glances from the men who would follow them into battle in half a decade.
"I finished Archaelos's #emph[Effective Rhetoric] and ran eleven laps around the gymnasium," Anax said.
Timoteus snorted. "I threw the thirty-mina weight three feet farther than my previous best and did spear drills with a Lukos commander."
#figure(image("002_<NAME>, Part 1/02.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Anax walked to the stool where his clothes were folded and began to dress. Timoteus turned to leave, but looked back over his shoulder. "When the Setessan army is bored of talking, is your plan to run away?"
A few men nearby stifled chuckles. Anax's face burned.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The Setessan ambassador entered the audience chamber with her entourage, wearing rich green linens. The chamber was filled to the brim with Akroan warriors lined up in formation. The ambassador approached the dais and bowed to Father with a flourish. "King Athanas, it is most unfortunate that we could not come to an accord."
Mother and Father stood tall and proud, their red cloaks trimmed with gold. Anax, Timoteus, and their sister Pelagia stood next to them. Father glared daggers at the ambassador. A few gray hairs had snuck into his beard. "You know my position. You are free to dispute it on the battlefield if you wish."
The envoy smiled mirthlessly. "The Setessan council is patient and our memory is long." She limply pointed an arm at Timoteus. "We may take this up with your heir."
Father put his right arm on Anax's shoulder and scowled. "This is Anax, my eldest."
The ambassador looked Anax up and down appraisingly, then frowned. "Your adherence to tradition is admirable, your majesty."
Father dropped his right arm to the hilt of his sword. "And you are a council of cowards. It is time for you to leave."
The ambassador bowed with a flourish and led her entourage out of the room without another word. Attendants closed the door behind them, and Father spoke. "I offered the Setessans what I thought was fair in return for the grievances they brought, and that was not enough. They will bring an army, or they will not." He drew his sword and raised it above his head. "But if they do, we will crush them."
#figure(image("002_Prince Anax, Part 1/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The soldiers roared their approval.
"You are dismissed," he bellowed to the room, and the soldiers filed out. When they were gone, Father squatted and regarded his sons. He looked at the two of them together, as if he were seeing them for the first time. His eyes shone with pride as he looked at Timoteus. When he moved to Anax, his brow furrowed, and he did nothing to conceal his contempt.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Anax sat across from Georgios, the aging man who served as the personal tutor to King Athanas's children. His smile pulled at the wrinkles around his eyes and mouth. "Are you ready to begin?"
Anax nodded. "Thesis: Father doesn't like me."
Georgios jumped back in surprise. "What makes you say that?"
"He scowled at me today, and looked at my brother with pride. It happened in the open, and I'm sure many people were watching."
Georgios composed himself again. "Do you think it is truly you that he does not like?"
"I do not have another explanation."
The old man smiled. "Thesis: a king should value his realm's welfare above the individual preferences of himself or any of his subjects."
Anax thought. "That makes sense."
"Thesis: the most important decision a king makes is choosing his heir."
"Are the inheritance laws not clear?"
"Does the king have the authority to change laws?"
Anax's eyes went wide. "I'm going to the gymnasium."
Georgios gave him a disapproving look. "That is neither a thesis nor a question."
The student stood. "And I am the Prince of Akros. Thank you for the lesson, teacher Georgios."
Georgios pulled himself to his feet with a smile. "You're quite welcome."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The sun was already setting by the time Anax got to the gymnasium. He made his way to the sand pit, where the weights were. There was another boy in the pit as well; he was taller and stronger than Anax, and likely a few years older.
#figure(image("002_Prince Anax, Part 1/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The other boy looked up at him with a slight smile, then at the setting sun. "A bit late to start working out, don't you think?"
Anax deflated for a moment, then fire began to burn in his belly. He drew himself up and walked toward the other boy with purpose.
Recognition and horror took over his face, and he recoiled. "Oh no. I'm sorry. Uh, hello there, I'm Zotikos. I haven't seen you use these before, but I could show you how."
Anax walked into the sand pit. "I would like that."
The older boy took one of the smaller weights in one hand and motioned for Anax to do the same. "Okay. Plant your feet at shoulder width. Hold the weight with both hands. Push out with your hips like this, and the weight should swing forward. Try to get it up to your chest, but without using your arms too much." He demonstrated a few repetitions, then stood. "That's about all you should do to start. You can throw them too, but you shouldn't do that until you're used to them."
Anax nodded. He hoisted the weight and tried to mimic the other boy's movements. After several repetitions, his shoulders, back, and hips were killing him.
Zotikos watched him struggle. "You should stop."
Anax dropped the weight and grunted. "I could keep going."
Zotikos nodded. "And then you would not be able to come back tomorrow. Stop and save your strength. You'll grow faster in the long run that way."
Anax nodded.
"One other thing. I often see you running around the track." Zotikos pointed at the pile of leather next to the weapon stands. "That's what the aprons over there are for. You put one on, put some rocks in the pocket, and go. A lot of kids don't like doing it because it's hell on your legs, but you seem to like running, so it might be good for you. It could give you a leg up on them." He chuckled at his own joke.
Anax nodded. "If you wouldn't mind, I would like to meet you here at about this time every day. I may start late, but I promise you I work hard." He flashed his best princely grin.
Zotikos considered for a moment too long, and gave a calculating smile. "I would be happy to."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The next day, Anax tried the aprons with the weights, just like Zotikos had said.
It made sense that the other boys didn't like it, because it was difficult. But he kept at it during his morning workouts, and it did make him stronger. He never got as far with the apron on, but the running itself was not the point anymore. The evening sessions with Zotikos continued too, although it quickly became clear that the older boy was quite a bit more skilled than Anax was.
One evening, Anax pressed him. "Why are you helping me?"
"You're the prince." Zotikos had not so much as blinked before answering.
Anax dropped his weight in the sand. "You don't have to, though, just like you don't have to come here every night. Why keep doing it?"
Zotikos sighed. "My father is a common foot soldier, and he has no ambition to rise higher. I train so I can surpass his station." He put his weight down and stretched. "And it seemed like you were looking for a friend."
Anax walked closer and put on his sternest face. "Am I a friend? Or am I just the prince?"
The older boy went down on one knee and stared at the sand. "I'm sorry, your highness..."
"Anax." The prince extended his hand, palm up. "Stand up." The older boy looked up and stood. "In the hallways of the palace, when I wear a laurel crown, then you may use my titles. But not here." He walked back toward the weight he had been using. "Here—" and he hefted it— "I am Anax."
Zotikos didn't say much for the rest of the evening. The next day, though, he talked quite a bit more.
In the following weeks, Anax expected the soreness and the increased strength. What he did not expect was that the other soldiers began to watch him and his brother with critical interest.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Anax sat across from Georgios in the small classroom. His legs were quite sore, but they felt good, and they were getting wider too. "Thesis: I'm getting stronger."
Georgios smiled and nodded. "Defend the claim."
"You believe it though!"
The older man gave him a sideways look. "I do, but this is a lesson about rhetoric. Convince me."
"I ran eleven laps on the sand track yesterday with four mina of rocks in my apron."
#figure(image("002_Prince Anax, Part 1/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Georgios nodded. "So you can run."
"I threw the thirty-mina weight a foot farther than my best."
He nodded again. "So you are stronger. How do you fight?"
Anax gave a mild pout. "That was not part of the claim."
Georgios chuckled. "Thesis: You will need to convince more people than just yourself that you are ready to rule Akros."
Anax sighed. "I grant your thesis. How do I do that?"
Georgios raised an eyebrow. "I don't know. If I were better at that sort of thing, I might have ended up in a higher position than the personal tutor to the king's children. But I do know that the Iroan Games will take place in four months, and that you will be expected to compete in at least one junior-division event."
"And my brother will too, no doubt." He slumped.
"He has begun training for the pankration, in fact."
Anax frowned. "The most impressive combat sport at the Games. Of course."
Georgios rolled his eyes. "Thesis: four months is a long time."
"That's indefensible! 'Long' is relative."
"Thesis: You understood my point." He glared at his student. "You could train for any event and be ready in time."
Anax shook his head, smiling slightly despite himself. "In Rhode's #emph[The History of the Setessan Wars] , she speaks of the occasional wisdom of attacking the enemy boldly at his strength. If you win, you win utterly."
"If you lose, you also lose utterly."
"Thesis: I am already losing."
Zotikos scratched his head. "You would know that better than I, but this path is risky."
Anax smiled. "I have some ideas."
|
|
https://github.com/Xecades/markdown-it-typst | https://raw.githubusercontent.com/Xecades/markdown-it-typst/main/README.md | markdown | MIT License | # markdown-it-typst
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![bundle][bundle-src]][bundle-href]
[![JSDocs][jsdocs-src]][jsdocs-href]
[![License][license-src]][license-href]
A simple [`typst.ts`](https://github.com/Myriad-Dreamin/typst.ts) wrapper that adds [Typst](https://github.com/typst/typst) support to [`markdown-it`](https://github.com/markdown-it/markdown-it).
**WARNING**: It's NOT recommended to run this plugin on browser side, as it is not optimized for tree-shaking. (See [`typst.ts` Documentation](https://myriad-dreamin.github.io/typst.ts/cookery/guide/all-in-one-node.html)) However, utilizing the browser-side version of `typst.ts` is still possible, any PRs regarding this are welcome.
---
## Usage
```bash
npm install markdown-it-typst
```
```ts
import MarkdownIt from "markdown-it";
import MarkdownItTypst from "markdown-it-typst";
const md = new MarkdownIt().use(MarkdownItTypst);
const code = `
\`\`\`typst
#set text(font: "New Computer Modern")
Let $a$, $b$, and $c$ be the side
lengths of right-angled triangle.
Then, we know that:
$ a^2 + b^2 = c^2 $
Prove by induction:
$ sum_(k=1)^n k = (n(n+1)) / 2 $
\`\`\`
`;
const html = md.render(code);
console.log(html);
// Output:
//
// <div class="typst">
// <svg class="typst-doc" [...]>
// [...]
// </svg>
// </div>
```
The code above will render the following web page (Without additional styling):

---
## Features
- **Able to import packages**:
~~~md
**Normal** *Markdown* code :-)
```typst
#import "@preview/cetz:0.2.2": canvas, draw, tree
#canvas(length: 2.5cm, {
import draw: *
tree.tree(
draw-node: (node, ..) => {
if node.content == [] { return none }
circle((), radius: .35, stroke: black)
content((), [#node.content])
},
draw-edge: (from, to, pa, child) => {
if child.content == [] { return none }
tree.default-draw-edge(from, to, pa, child)
},
([15], ([13], [12], [14]), ([17], [16], ([18], [], [18])))
)
})
```
~~~

- **Able to import external files**:
~~~md
```typst
#figure(
image("./images/cat.png", width: 200pt),
caption: [`/bin/cat`],
)
```
~~~

---
## Options
Default options:
```ts
const md = new MarkdownIt().use(MarkdownItTypst, {
identifier: "typst",
typstWrapper: (code: string) =>
"#set page(width: auto, height: auto, margin: 5pt)\n" +
"#set text(size: 18pt)\n" +
code,
svgWrapper: (svg: string) => '<div class="typst">\n' + svg + "\n</div>",
});
```
### `identifier`
- Type: `string | string[]`
- Default: `"typst"`
The language identifier(s) of the Typst code block. Only code blocks with the specified identifiers will be processed.
### `typstWrapper`
- Type: `(code: string) => string`
- Default: `(code: string) => "#set page(width: auto, height: auto, margin: 5pt)\n#set text(size: 18pt)\n" + code`
Typst code will be wrapped with this function before being compiled.
### `svgWrapper`
- Type: `(svg: string) => string`
- Default: `(svg: string) => '<div class="typst">\n' + svg + "\n</div>"`
The SVG output will be wrapped with this function during rendering.
---
## Examples
The probably most handy application is to render CeTZ graphs in Markdown:
```ts
const md = new MarkdownIt().use(MarkdownItTypst, {
typstWrapper: (code: string) =>
"#set page(width: auto, height: auto, margin: 5pt)\n" +
'#import "@preview/cetz:0.2.2": canvas, draw, vector, matrix\n' +
"#canvas(length: 1cm, {\n" +
" import draw: *\n" +
code +
"})",
identifier: "cetz",
});
```
~~~md
Electromagnetic waves are **transverse** waves:
```cetz
// Code borrowed from CeTZ: https://typst.app/universe/package/cetz/
// Set up the transformation matrix
set-transform(matrix.transform-rotate-dir((1, 1, -1.3), (0, 1, .3)))
scale(x: 1.5, z: -1)
grid((0,-2), (8,2), stroke: gray + .5pt)
// Draw a sine wave on the xy plane
let wave(amplitude: 1, fill: none, phases: 2, scale: 8, samples: 100) = {
line(..(for x in range(0, samples + 1) {
let x = x / samples
let p = (2 * phases * calc.pi) * x
((x * scale, calc.sin(p) * amplitude),)
}), fill: fill)
let subdivs = 8
for phase in range(0, phases) {
let x = phase / phases
for div in range(1, subdivs + 1) {
let p = 2 * calc.pi * (div / subdivs)
let y = calc.sin(p) * amplitude
let x = x * scale + div / subdivs * scale / phases
line((x, 0), (x, y), stroke: rgb(0, 0, 0, 150) + .5pt)
}
}
}
group({
rotate(x: 90deg)
wave(amplitude: 1.6, fill: rgb(0, 0, 255, 50))
})
wave(amplitude: 1, fill: rgb(255, 0, 0, 50))
```
~~~

The option `typstWrapper` can serve as a way to inject the necessary imports and setup code for typst. However, it may appear ugly to have such long code in the wrapper function. A better way it to utilize the `#import` directive in the Typst code block:
```ts
const md = new MarkdownIt().use(MarkdownItTypst, {
typstWrapper: (code: string) =>
'#import("./preset.typ")\n' + code,
});
```
---
## License
[MIT](./LICENSE) License © 2024 [Xecades](https://github.com/xecades)
<!-- Badges from markdown-it-mdc -->
[npm-version-src]: https://img.shields.io/npm/v/markdown-it-typst?style=flat&colorA=080f12&colorB=1fa669
[npm-version-href]: https://npmjs.com/package/markdown-it-typst
[npm-downloads-src]: https://img.shields.io/npm/dm/markdown-it-typst?style=flat&colorA=080f12&colorB=1fa669
[npm-downloads-href]: https://npmjs.com/package/markdown-it-typst
[bundle-src]: https://img.shields.io/bundlephobia/minzip/markdown-it-typst?style=flat&colorA=080f12&colorB=1fa669&label=minzip
[bundle-href]: https://bundlephobia.com/result?p=markdown-it-typst
[license-src]: https://img.shields.io/github/license/xecades/markdown-it-typst.svg?style=flat&colorA=080f12&colorB=1fa669
[license-href]: https://github.com/xecades/markdown-it-typst/blob/main/LICENSE
[jsdocs-src]: https://img.shields.io/badge/jsdocs-reference-080f12?style=flat&colorA=080f12&colorB=1fa669
[jsdocs-href]: https://www.jsdocs.io/package/markdown-it-typst
|
https://github.com/grnin/Zusammenfassungen | https://raw.githubusercontent.com/grnin/Zusammenfassungen/main/Bsys2/Bsys2_Zusammenfassung_FS24_NG_JT.typ | typst | // Compiled with Typst 0.11.1
#import "../template_zusammenf.typ": *
#show: project.with(
authors: ("<NAME>", "<NAME>"),
fach: "BSys2",
fach-long: "Betriebssysteme 2",
semester: "FS24",
tableofcontents: (enabled: true, columns: 2, depth: 2),
language: "de",
)
// Umfangreiche Zusammenfassung aller Folien
// Für eine Zusammenfassung für die Prüfung siehe
// Bsys2_Spick_FS24_NG_JT.typ
#include "01_Betriebssystem_API.typ"
#include "02_Dateisystem_API.typ"
#include "03_Prozesse.typ"
#include "04_Programme_Bibliotheken.typ"
#include "05_Threads.typ"
#include "06_Scheduling.typ"
#include "07_Mutexe_Semaphore.typ"
#include "08_Signale_Pipes_Sockets.typ"
#include "09_Message_Passing.typ"
#include "10_Ext2_Unicode.typ"
#include "11_Ext4.typ"
#include "12_X_Window_System.typ"
#include "13_Meltdown.typ"
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/silky-slides-insa/0.1.0/slides-template.typ | typst | Apache License 2.0 | #import "@preview/touying:0.5.2": *
// CONSTANTS:
#let heading-fonts = ("League Spartan", "Arial", "Liberation Sans")
#let normal-fonts = ("Source Serif", "Source Serif 4", "Georgia")
#let insa-colors = (
primary: rgb("#e42618"),
secondary: rgb("#f69f1d"),
tertiary: rgb("#f5adaa"),
)
// UTILITIES:
#let _footer(self, color: black) = {
utils.call-or-display(self, self.page.footer)
place(right + bottom, box(width: 1.75cm, height: 1.75cm, align(center + horizon, text(font: normal-fonts, fill: color, weight: "bold", context utils.slide-counter.display()))))
}
// SLIDES:
#let title-slide(..args) = touying-slide-wrapper(self => {
let info = self.info + args.named()
let visual = info.title-visual != none
self = utils.merge-dicts(
self,
config-page(
background: image(if visual {"assets/slide-title-visual.svg"} else {"assets/slide-title.svg"}),
margin: (left: 0pt, top: 0pt),
footer: _footer(self)
)
)
touying-slide(self: self, {
let titles-width = 16cm
if visual {
titles-width = 11.8cm
place(dx: 13.95cm, dy: 1.9cm, block(width: 12cm, height: 11cm, align(center + horizon, info.title-visual)))
}
place(dx: 2.02cm, dy: 1.89cm, block(width: 4.94cm, info.logo))
place(dx: 2.02cm, dy: 4cm, block(width: titles-width, height: 5.81cm, align(bottom, text(font: heading-fonts, size: 40pt, fill: white, weight: "bold", info.title))))
place(dx: 2.02cm, dy: 12.8cm, block(width: titles-width, height: 2.3cm, align(top, text(font: heading-fonts, size: 20pt, fill: black, info.subtitle))))
})
})
#let _section-slide-internal(section, section-description: none, add-heading: false) = touying-slide-wrapper(self => {
self = utils.merge-dicts(
self,
config-page(
background: image("assets/slide-section.svg"),
margin: (left: 0pt, top: 0pt),
footer: _footer(self)
),
)
touying-slide(self: self, {
if add-heading {
show heading: {}
heading(level: 1, section)
}
place(dx: 2.02cm, dy: 4.1cm, block(width: 20cm, height: 6.8cm, align(bottom, text(font: heading-fonts, size: 40pt, weight: "bold", fill: black, section))))
place(dx: 2.02cm, dy: 11.5cm, block(width: 17cm, height: 4cm, align(top, text(font: heading-fonts, size: 24pt, fill: black, section-description))))
})
})
#let section-slide(section, section-description) = _section-slide-internal(section, section-description: section-description, add-heading: true)
#let slide(..args) = touying-slide-wrapper(self => {
self = utils.merge-dicts(
self,
config-page(
background: {
place(bottom + right, image("assets/footer.png", width: 3.5cm))
},
footer: _footer(self, color: white)
)
)
touying-slide(self: self, ..args)
})
#let insa-slides(
title: "Titre à définir",
title-visual: none,
subtitle: "Sous-titre à définir",
insa: "rennes",
..args,
body
) = {
show: touying-slides.with(
config-page(
paper: "presentation-16-9",
//footer: _footer,
margin: (x: 2.02cm, y: 1.71cm)
),
config-common(
slide-level: 1,
new-section-slide-fn: _section-slide-internal,
slide-fn: slide
),
config-info(
title: title,
title-visual: title-visual,
subtitle: subtitle,
logo: image("assets/" + insa + "/logo-white.png"),
),
config-colors(
..insa-colors
),
config-methods(
init: (self: none, body) => {
set text(font: normal-fonts, size: 22pt)
show heading: set text(font: heading-fonts)
show heading.where(level: 2): it => {
pagebreak()
text(size: 30pt, it)
v(.5em)
}
set list(marker: (sym.circle.filled.tiny, sym.plus))
// TODO: change sublist color to primary (impossible for now)
body
}
),
..args
)
title-slide()
body
} |
https://github.com/noahjutz/AD | https://raw.githubusercontent.com/noahjutz/AD/main/notizen/algorithmen/ggt_primes_step1.typ | typst | #import "@preview/cetz:0.2.2": canvas, draw
#show math.equation: set text(fill: gray)
#show math.equation: box.with(inset: (x: 10pt))
#show table.cell.where(y: 0): strong
#table(
columns: 5,
stroke: (x, y) => {
let border = (
top: none, left: none, right: none, bottom: none
)
if x == 3 {border.left = 1pt}
if y == 0 and x > 0 and x < 4 {border.bottom = 1pt}
if y == 5 and x > 0 and x < 4{border.top = 1pt}
border
},
"", "a", "b", "ggT", "",
$div 2$, "528", "3780", "1", $dot 2$,
$div 2$, "1764", "1890", "2", $dot 2$,
$div 9$, "882", "945", "4", $dot 9$,
$...$, "98", "105", "45", $...$,
"", "14", "15", "252", ""
)
|
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/let-04.typ | typst | Other | // Ref: false
#let (a,) = (1,)
#test(a, 1)
|
https://github.com/Lelidle/Q12-cs-scripts | https://raw.githubusercontent.com/Lelidle/Q12-cs-scripts/main/synchronization.typ | typst | #import "template.typ": *
#import "@preview/tablex:0.0.6": tablex, cellx, rowspanx, colspanx
#import "@preview/codelst:2.0.0": sourcecode
#show: setup
#set enum(numbering: (..args) => strong(numbering("1.", ..args))) // in Aufzählungen Zahlen fett
#set heading (
numbering: "1."
)
#let hm = h(1mm)
#v(1fr)
#align(center)[#text(32pt)[Synchronisation \ #align(center)[#image("images/synchronisation.png", width: 80%)] ] \ Stable Diffusion Art "Synchronisation"]
#v(1fr)
#pagebreak()
#outline(title: "Inhaltsverzeichnis", indent: auto)
#pagebreak()
#set page(
header: align(right)[
Synchronisation Skript 2inf1 \
],
numbering: "1"
)
= Nebenläufige Prozesse und Parallelität
== Grundbegriffe
In diesem Kapitel beschäftigen wir uns mit dem Problem, dass manche Prozesse lange dauern können und gegebenenfalls andere Prozesse "warten" müssen. Im Sinne der Effizienz (also der Rechengeschwindigkeit) ist das natürlich suboptimal und muss optimiert werden. Wenn Teile eines Programms unabhängig vom Rest "out of order" ausgeführt werden können (und man dies auch macht!), so spricht man von *nebenläufigen* Prozessen. In diesem Kontext taucht auch häufig der Begriff der *Parallelität* von Prozessen auf.
#merke[Die beiden Begriffe sind nicht vollständig deckungsgleich. Bei reiner *Nebenläufigkeit* gehen wir in der Regel nur von einem CPU-Kern aus, der die Abläufe so optimiert, dass möglichst wenig "Leerlauf" entsteht. Ist diese Nebenläufigkeit gegeben, so ist auch Parallelität möglich. Bei der *Parallelität* gehen wir dagegen von mehehreren Kernen aus, die tatsächlich gleichzeitig arbeiten - häufig an Teilproblemen eines größeren Problems.]
Bevor wir allerdings tiefer in technische Details eintauchen, sollen einige "alltägliche" Probleme unter diesem Gesichtspunkt betrachten.
1. *Hausbau*: Hier finden sich beide Konzepte: einerseits kann ein einzelnes Bauarbeity seine Abläufe optimieren und beispielsweise nach dem Bearbeiten des Bodens (was den Raum unbetretbar macht) einfach in einem anderen Raum weiterarbeiten statt darauf zu warten, dass der Boden wieder betretbar ist (um dann etwas anderes in diesem Zimmer zu erledigen). Andererseits gibt es aber natürlich auch paralleles Arbeiten, wenn mehrere Handwerkys gleichzeitig auf der Baustelle arbeiten, was natürlich die Norm ist!
2. *Kochen*: Die Reihenfolge ist auch hier entscheidend, um Prozesse zu optimieren. Hat man das Hauptgericht vollständig gekocht, aber vergessen die Beilage zuzubereiten wird entsteht am Ende ein Zeitproblem (das sich hier sogar negativ auf die Produktqualität auswirken kann). Auch hier ist das Organisieren der nebenläufigen Prozesse also entscheidend. Gleichzeitig können auch hier natürlich mehrere Personen parallel arbeiten (auch wenn zu viele Köche bekanntlich den Brei verderben).
3. *Landwirtschaft*: Auch hier kann es die parallele Bearbeitung mehrerer Felder durch verschiedene Personen geben (beispielsweise beim Silieren). Nebenläufige Prozesse sind aber genauso vorhanden - so ist es wenig sinnvoll nach dem Melken der Kühe neben ihnen stehen zu bleiben und zu warten, dass sie wieder Milch geben.
All diese Beispiele verdeutlichen, dass der Umgang mit Nebenläufigkeit und Parallelität im "realen" Leben in der Regel durch den Einsatz des berühmten *gesunden Menschenverstandes* gereglt wird. Niemand würde sich einfach neben seine Kühe setzen und darauf warten, dass sie wieder Milch geben (außer man schaut gerne Kühe an!).
Leider (?) besitzen Computer keinen gesunden Menschenverstand, d.h. der Umgang mit Nebenläufigkeit und Parallelität muss in irgendeiner Form im Rahmen der Programmierung implementiert werden. Die folgenden Kapitel beschäftigen sich mit der technischen Umsetzung in Java, sowie Lösungen für die dabei auftretenden Probleme.
#pagebreak()
== Threads
Im Gegensatz zu eigenständigen Prozessen, die voneinander abgeschirmt sind (z.B. sind für jeden Prozess ein eigener Adressraum und eigene Betriebsmittel reserviert), teilen sich die einzelnen Threads eines Prozesses ihre Ressourcen (Speicherbereich, Netzwerkverbindung, andere Betriebsmittel) - wir können einen Prozess also in mehrere Threads aufteilen und das Betriebssystem entscheidet welche davon auf welchem Kern ausgeführt werden.
So ergibt sich der Vorteil, dass beim Wechsel von Threads nicht der vollständige Prozesskontext gewechselt werden muss und somit ein schnellerer Wechsel von einzelnen Programmsträngen möglich ist. Das ermöglicht mehr "Gleichzeitigkeit" (oder zumindest schnellen und koordinierten Wechsel). Außerdem können Threads z.B. durch die Verwendung eines gemeinsamen Speicherbereichs leichter miteinander kommunizieren und Daten austauschen, auch wenn sich dadurch einige Probleme ergeben.
Handelt es sich um einen Mehr-Kern-Rechner, so können mehrere Threads auch tatsächlich von mehreren Kernen gleichzeitig abgearbeitet werden und "echte" Parallelität erreicht werden.
In Java können Threads auf zwei Arten realisiert werden:
1. *Custom Threads* als Unterklasse der bereits vordefinierten Klassen _Thread_. Hier muss nur die _run_- Methode überschrieben werden, die definiert, was ein einzelner Thread tun soll.
2. Alternativ kann die Klasse, die die Arbeit eines einzelnen Threads definiert auch das Interface *Runnable* implementieren (dies wird beim Erben von Thread ebenfalls implizit gefordert!).
Beides soll im Folgenden beispielhaft thematisiert werden.
=== Konsolenausgabe mit Runnable
Das folgende Programm macht noch nichts "sinnvolles", sondern soll nur das Prinzip veranschaulichen. Es werden $10$ Threads erzeugt und jeder dieser Threads schreibt $10$ mal etwas auf die Konsole:
#align(center)[
```java
public class RunnableExample {
public static void main(String[] args) {
//Standard-Thread-Klasse von Java
Thread[] t = new Thread[10];
for (int i = 0; i < t.length; i++) {
// Das Arbeitspaket wird übergeben
t[i]=new Thread(new MyRunnable(i));
}
for (int i = 0; i < t.length; i++) {
//Die Threads werden gestartet und parallel ausgeführt.
t[i].start();
}
for (int i = 0; i < t.length; i++) {
/*Der Main-Thread wartet bis die gestarteten Threads fertig sind.
join() darf nie im selben for wie start() stehen! Es wäre für
unser Minimalbeispiel auch gar nicht notwendig, wenn man aber
Ergebnisse aller Threads abwarten möchte, muss sichergestellt
werden, dass alle Threads fertig sind! */
try {
t[i].join();
//Notwendig damit das Programm nicht "abstürzt",
// falls ein Thread interrupted/unterbrochen wird.
} catch (InterruptedException e) {
e.printStackTrace();
}
}//Ende des Programms
}
}
class MyRunnable implements Runnable {
int number;
//Die übergebenen Daten müssen in Attributen "gespeichert" werden
public MyRunnable(int number){
this.number = number;
}
//Die run-Methode spezifiziert, was der Thread "tun" soll.
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("Hello from Thread " + number);
}
}
}
```
]
Die zweite Klasse _MyRunnable_ definiert unser Arbeitspaket, d.h. in der _run_ Methode werden die "Aufgaben" definiert, was in diesem Fall nur einem zehnmaligem Schreiben auf die Konsole entspricht. Da in der Ausgabe die "Nummer" des Threads mit ausgegeben werden soll, muss diese Information im Konstruktor übergeben und in einem Attribut "abgespeichert" werden.
Die Klasse _RunnableExample_ enthält nur eine einzige main-Methode, die 10 der standardmäßigen Java Thread-Objekte erzeugt und in einem Array speichert.
Anschließend wird jedem Thread seine *workload*, also ein Objekt unserer _MyRunnable_-Klasse übergeben.
Zu diesem Zeitpunkt passiert allerdings noch gar nichts, da die Threads erst *gestartet* werden müssen.
#grid(
columns:(70%, 30%),
rows: 1,
gutter: 12pt,
[Am Ende müssen die Threads auch wieder *"eingefangen"* werden, deswegen wird auf jedem die _join_-Methode aufgerufen - diese führt die Threads und ihre Ergebnisse wieder zusammen (in unserem Fall ist das nicht entscheidend, da wir bereits "unterwegs" auf der Konsole ausgegeben haben, wir benötigen den Befehl trotzdem zum sauberen Beenden der Threads).
Führt man das Programm aus, so ergibt sich beispielsweise die nebenstehende Ausgabe. Insgesamt sind es natürlich 100 Zeilen auf der Konsole, da 10 Threads jeweils 10 mal ihre Hallo-Nachricht schreiben.
Man kann deutlich erkennen, dass die Reihenfolge wild durchgemischt ist, beispielsweise schreibt Thread Nummer 6 zweimal in Folge, Thread Nummer 4 dagegen kommt in der Liste gar nicht vor. Die genaue Struktur der Ausgabe lässt sich nicht vorhersagen.
], [
```terminal
Hello from Thread 8
Hello from Thread 3
Hello from Thread 8
Hello from Thread 0
Hello from Thread 6
Hello from Thread 6
Hello from Thread 5
Hello from Thread 2
Hello from Thread 7
Hello from Thread 7
Hello from Thread 1
Hello from Thread 9
Hello from Thread 9
```]
)
Die _join_-Methode muss in einem _try-catch_-Block stehen, da der Thread *unterbrochen* werden könnte (oder hängen bleibt)und dann keine Rückmeldung mehr gibt.
#hinweis(customTitle:"Hinweise")[
1. Beim Start eines Java-Programms führt ein Thread die _main_-Methode aus. Auf diesen Thread kann man via *Thread.currentThread()* zugreifen. Es laufen auch noch weitere Threads, z.B. für den *Garbage Collector*.
2. Mit der Methode *_interrupt_* kann ein Thread "manuell" beendet werden.
3. Mit *_sleep_* kann ein Thread sich selbst (aber nicht einen anderen Thread!) pausieren lassen.
]
Ein Thread (auch *Aktivitätsfaden* genannt) kann die folgenden Zustände haben:
#align(center)[
#image("images/thread_diagramm.png", width:90%)
]
Das obige Zustandsdiagramm soll nur einen Überblick verschaffen, es ist für uns im Detail nicht relevant.
#v(1cm)
=== Custom Threads
Wir betrachten wieder dasselbe Beispiel wie vorher:
#align(center)[
```java
public class ThreadExample {
public static void main(String[] args) {
MyThread[] t = new MyThread[10];
for (int i = 0; i < t.length; i++) {
//Daten, die der Thread für die Berechnungen benötigt
// müssen übergeben werden, hier: Threadnummer.
t[i]=new MyThread(i);
}
//Der Rest verläuft analog
for (int i = 0; i < t.length; i++) {
t[i].start();
}
for (int i = 0; i < t.length; i++) {
try {
t[i].join();Thread interrupted/unterbrochen wird.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
]
#align(center)[
```java
class MyThread extends Thread {
int nummer;
//Die übergebenen Daten müssen in Attributen "gespeichert" werden
public MyThread(int nummer){
this.nummer = nummer;
}
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("Hello from Thread " + nummer);
}
}
}
```
]
Die beiden Varianten sind fast vollständig deckungsgleich, letztendlich gibt es in diesem Fall keinen deutlichen Vorteil einer Methode. Der Vorteil eines Custom Threads liegt jedoch darin, dass wir leichter an die berechneten Werte kommen, wenn wir sie nach dem Abschluss brauchen sollten.
#hinweis(customTitle: "Hinweis für Experten")[Es gibt natürlich noch mehr Varianten, wie man in Java mit Threads umgehen kann, eine allgemeinere bzw. abstraktere Variante wäre die Verwendung des *ExecutorService*.]
Bislang hat unsere Implementierung noch keine sinnvolle Arbeit verrichtet. Das soll sich jetzt ändern. Nehmen wir an für eine größere Rechnung müssen sehr große Fakultäten berechnet werden.
#hinweis(customTitle:"Zur Erinnerung")[$ n! = n dot (n-1) dot (n-2) dots.c 3 dot 2 dot 1 $]
Der Schultaschenrechner gibt bereits bei $70!$ auf und zeigt einen MathError an. Auch in Java müssen wir einige Vorkehrungen treffen, weder der Datentyp _Integer_ noch _long_ sind groß genug um Zahlen wie $50000!$ zu fassen. Für große Zahlen gibt es in Java eine eigene Klasse, den *_BigInteger_*.
#pagebreak()
Zunächst eine sequentielle Implementierung, die die Fakultät einiger großer Zahlen berechnet:
#align(center)[
```java
import java.math.BigInteger;
public class FactorialsBasic {
public static void main(String[] args) {
// Um die Implementierungen vergleichen zu können, wird die
// Systemzeit vor und nach dem Aufruf der Berechnung gemessen...
long startTime = System.nanoTime();
calculateFactorials();
long endTime = System.nanoTime();
// und anschließend in Sekunden ausgegeben
System.out.println("Execution took: " +
(endTime - startTime)*Math.pow(10,-9) + " seconds");
}
private static void calculateFactorials() {
int[] numbersToFactorial = {50000, 50001, 50002, 50003, 50004};
// Für jede oben definierte Zahl wird die Fakultät berechnet
for(int i : numbersToFactorial) {
// und ausgegeben
System.out.println("Factorial of " + i + " is: " + factorial(i));
}
}
private static BigInteger factorial(int number) {
// BigInteger benutzt ein Enum, um auf die 1 zuzugreifen
// Eine implizite Umwandlung ist hier nicht möglich.
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= number; i++) {
// Ähnliches gilt für alle anderen Zahlen, hier wird jeweils
// der int-Wert in einen BigInteger umgewandelt
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
```
]
Um diese Berechnungen zu beschleunigen können wir jetzt mehrere Threads verwenden und jedem Thread die Aufgabe geben, jeweils eine Fakultät zu berechnen.
#task[Nutzen Sie die obige Vorlage (Schreiben auf die Konsole) und verändern Sie sie so, dass die Fakultäten parallel berechnet werden. Die Lösung findet sich auf der nächsten Seite.]
#pagebreak()
Es muss nicht viel am ursprünglichen Programm geändert werden. Der Thread bekommt weiterhin eine Zahl, dieses Mal wird aber die Fakultät berechnet und ausgegeben, statt nur die Zahl auf die Konsole zu schreiben:
#align(center)[
```java
import java.math.BigInteger;
public class FactorialsParallel {
//Hier hat sich nichts verändert
public static void main(String[] args) {
long startTime = System.nanoTime();
calculateFactorials();
long endTime = System.nanoTime();
System.out.println("Execution took: " +
(endTime - startTime)*Math.pow(10,-9) + " seconds");
}
private static void calculateFactorials() {
int[] numbersToFactorial = {50000, 50001, 50002, 50003, 50004};
//Wir benötigen so viele Threads wie Zahlen
FactorialThread[] threads = new FactorialThread[numbersToFactorial.length];
// Die Threads werden erzeugt und die Zahl übergeben, deren
// Fakultät berechnet werden soll
for (int i = 0; i < threads.length; i++) {
threads[i] = new FactorialThread(numbersToFactorial[i]);
}
// Analoges Vorgehen mit Starten und "einfangen".
for (FactorialThread thread : threads) {
thread.start();
}
// Wir warten darauf, dass alle Threads fertig werden
for (FactorialThread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/* Die Threads können ihre Ergebnisse nicht direkt zurückgeben
* (run ist eine void Methode!) aber wir können mit einem getter
* das Ergebnis vom Thread erfragen:*/
for (int i = 0; i < threads.length; i++) {
System.out.println("Factorial of " + numbersToFactorial[i] + " is: "
+ threads[i].getResult());
}
}
}
```
#pagebreak()
```java
class FactorialThread extends Thread {
// Das Ergebnis wird als Attribut gespeichert, damit nach Beendigung der
// Berechnung darauf zugegriffen werden kann.
private final int number;
private BigInteger result;
public FactorialThread(int number) {
this.number = number;
this.result = BigInteger.ONE;
}
// Die eigentliche Berechnung verläuft analog zur sequentiellen Implementierung.
public void run() {
for (int i = 1; i <= number; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
}
// Ein simpler getter zum "Auslesen" der berechneten Daten.
public BigInteger getResult() {
return result;
}
}
```
]
Dieses Beispiel nutzt zwar die Parallelität - die Komplexität lässt aber noch zu Wünschen übrig. Insbesondere wurden verschiedene Probleme noch umgangen - alle Threads hatten eine Aufgabe, die komplett unabhängig von den anderen Threads war. Das ist natürlich wenig realistisch, da häufig auf den gleichen Daten operiert wird, bzw. die Aufgaben der Threads (teilweise) voneinander abhängen.
#pagebreak()
== Synchronisation
Bei nebenläufigen Prozessen kommt es häufig dazu, dass *gemeinsame Ressourcen* genutzt werden müssen. Um bei einem der obigen Einleitungsbeispiele zu bleiben: ein Koch kann nicht ein weiteres Gericht zubereiten (auch wenn er Zeit hätte), wenn bereits alle Töpfe und Pfannen im Einsatz sind oder - realistischer - alle Herdplatten belegt sind. Die Verwendung einer Pfanne zur gleichzeitigen Herstellung von gegartem Hackfleisch und Karamell ist dabei sicher auch keine gute Lösung.
#merke[Wird der Zugriff auf *gemeinsame Ressourcen* geregelt, so spricht man in der Informatik von *Synchronisation*.]
In diesem Zusammenhang sind drei weitere Begriffe von Bedeutung:
#definition[
1. *Ununterbrechbare Ressource*: diese kann durch einen Prozess erst verändert werden, wenn ein ggf. vorhandener vorheriger Prozess mit dieser Ressource "fertig ist", sie ist also gewissermaßen "gesperrt".
2. *Kritischer Abschnitt*: soll ein Teilbereich des Codes nur von einem Prozess gleichzeitig "betreten werden" (sinnvollerweise innerhalb eines größeren Algorithmusses), dann spricht man von einem kritischen Abschnitt im Code.
3. *Gegenseitiger Ausschluss*: So wird das konkrete *Verfahren* bezeichnet, dass die obigen Bedingungen sicherstellt. In unserem Fall wird das Konzept der *Semaphore* und das *Monitor-Prinzip* wichtig werden.
]
=== Bankkonto mit Semaphor
Nach dem mathematischen Beispiel aus den vorherigen Kapiteln widmen wir uns nun einer anderen Situation: der Modellierung eines Kontos.
Ein Konto benötigt dabei nicht viele Eigenschaften: man muss Geld abheben und einzahlen können, der Konstruktor soll bereits ein gewisses "Startkapital" als Eingabe nehmen.
#task[Implementieren Sie eine Klasse _UnsafeBankAccount_ mit einem Attribut _balance_, sowie die beiden Methoden _deposit_ (einzahlen) und _withdraw_ (abheben) passend. Geben Sie die Informationen zu Einzahlung und Abheben auch auf der Konsole aus (inklusive des aktuellen Guthabens.)]
Eine mögliche Lösung findet sich auf der nächsten Seite. #pagebreak()
```java
public class UnsafeBankAccount {
private double balance;
public UnsafeBankAccount(double initialBalance) {
balance = initialBalance;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", Current Balance: " + balance);
}
public void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount + ",
Current Balance: " + balance);
} else {
System.out.println("Insufficient funds.");
}
}
}
```
So weit könnte es sich auch um eine Modellierungsaufgabe aus der Mittelstufe handeln. Testet man die beiden Methoden ausgiebig, so funktioniert das "Konto" so einwandfrei.
Interessant wird es erst, wenn wir die Parallelität ins Spiel bringen - es ist naheliegend anzunehmen, dass eine Transaktion von Geld von einem Thread "verwaltet" wird. Wenn es irgendein Problem mit einer Transaktion gibt, soll natürlich nicht das gesamte Online-Überweisungsportal einer Bank lahmgelegt sein.
Um den Prozess zu vereinfachen betrachten wir keinen ausführlichen Login, Sicherheitsabfragen oder sonstigen Schnickschnack und lassen auch den Transaktionspartner weg - unsere Threads sollen einfach nur Geld einzahlen, bzw. ausgeben können.
Da es sich dabei um sehr einfache Threads handelt soll an dieser Stelle eine weitere Möglichkeit der Thread-Definition vorgestellt werden, die mit wesentlich weniger Schreibarbeit verbunden ist:
```java
// Der Pfeil steht hier für eine "anonyme Funktion"
new Thread(() -> {
/* Der hier definierte code block repräsentiert die run() Methode des Threads
Wir sparen uns also die explizite Definition des "runnables" und geben
dem Thread eine "anonyme" Implementierung mit. Das hat natürlich den Nachteil,
dass wir sie nicht mehr anderswo verwenden können!*/
}).start();
```
#hinweis[Hier tauchen wir eine kleine Zehe in eine ganz andere Welt des Programmierens. Man spricht bei anonymen Funktionen auch von #link("https://de.wikipedia.org/wiki/Anonyme_Funktion")[Lambda-Funktionen].]
#pagebreak()
In unserem Fall könnten wir das Konto z.B. so testen:
```java
public class AccountTransactions {
//Festlegen der Threadanzahl
final static int NUM_THREADS = 10;
//Festlegen unserer Startkapitals
final static double INITIAL_BALANCE = 1000;
private static void useUnsafe() {
//Erzeugen eines neuen Kontos
UnsafeBankAccount unsafeAccount = new UnsafeBankAccount(INITIAL_BALANCE);
System.out.println("Unsafe Bank Account Transactions:");
//Erzeugen und starten der Threads
for (int i = 0; i < NUM_THREADS; i++) {
new Thread(() -> {
unsafeAccount.deposit(100);
unsafeAccount.withdraw(200);
}).start();
}
}
```
Wir beginnen also mit 1000 Euro (oder Dollar, oder Yen..) auf dem Konto und starten 10 Threads, die alle 100 Euro einzahlen und direkt danach wieder 200 Euro abheben.
Führen wir diese Methode aus, so steht auf der Konsole z.B. das folgende:
#grid(
rows: auto, columns:(60%, 40%), gutter: 2pt,
[```
Unsafe Bank Account Transactions:
Deposited: 100.0, Current Balance: 1700.0
Deposited: 100.0, Current Balance: 1900.0
Deposited: 100.0, Current Balance: 1400.0
Deposited: 100.0, Current Balance: 1200.0
Deposited: 100.0, Current Balance: 1800.0
Deposited: 100.0, Current Balance: 1500.0
Deposited: 100.0, Current Balance: 2000.0
Deposited: 100.0, Current Balance: 1300.0
Deposited: 100.0, Current Balance: 1100.0
Deposited: 100.0, Current Balance: 1600.0
Withdrawn: 200.0, Current Balance: 200.0
Withdrawn: 200.0, Current Balance: 400.0
Withdrawn: 200.0, Current Balance: 600.0
Withdrawn: 200.0, Current Balance: 800.0
Withdrawn: 200.0, Current Balance: 1000.0
Withdrawn: 200.0, Current Balance: 1200.0
Withdrawn: 200.0, Current Balance: 1400.0
Withdrawn: 200.0, Current Balance: 1600.0
Withdrawn: 200.0, Current Balance: 1800.0
Withdrawn: 200.0, Current Balance: 0.0
```],
[Grundsätzlich kommt zwar am Ende das richtige Ergebnis heraus, denn nach dem letzten Abheben haben wir tatsächlich 0 Euro auf dem Konto - die zeitliche Abfolge scheint aber überhaupt nicht zu passen. D.h. die Ausgabe und der tatsächliche "Zustand" unserer Variable, die den Kontostand speichert passen nicht zueinander. Wir zahlen 100 Euro ein, aber der Kontostand ist zu diesem "Zeitpunkt" bereits bei 1700 Euro.
Stellt man sich nun vor, dass tatsächlich noch weitere Konten an Transaktionen beteiligt sind wird das Problem noch deutlicher: es könnte zu irgendeinem Zeitpunkt Geld abgebucht werden, das eigentlich gar nicht verfügbar ist.
]
)
Umgekehrt könnte es auch sein, dass eine Transaktion abgelehnt wird, obwohl eigentlich genug Guthaben vorhanden ist.
Wir müssen also den Zugriff auf unsere Ressource _balance_ (die *ununterbrechbare Ressource*) also limitieren. Hier kommt der *Semaphor* ins Spiel.
#definition(customTitle: "Semaphor")[Ein Semaphor ist eine Variable, deren Wert ausdrückt, ob der Zugriff auf eine gemeinsame Ressource aktuell verboten ist, weil ein anderer Prozess (oder mehrere andere Prozesse, je nachdem wie viele durch den Semaphor erlaubt sind, für uns immer 1!) sie momentan benutzt, oder erlaubt ist, weil kein anderer Prozess sie gerade nutzt.]
Der Ablauf sieht also wie folgt aus:
1. Der Thread prüft, ob der Semaphor "frei" ist.
2. Wenn "belegt" ist, dann wird gewartet und ggf. erneut geprüft.
3. Ist der Semaphor frei, wird er auf "belegt" gesetzt und die Ressource verwendet. Danach wird der Semaphor wieder frei gegeben.
#task[Übertragen Sie diese Idee auf unser Beispiel und verändern Sie die _UnsafeBankAccount_ Klasse so, dass eine "sichere" _SemaphorBankAccount_-Klasse daraus wird.
Recherchieren Sie dazu, wie die Java-Klasse _Semaphor_ funktioniert.]
Eine mögliche Lösung findet sich auf der nächsten Seite.
#pagebreak()
Wir benutzen ein Semaphor, dass nur einem Thread Zugriff auf einmal erlaubt (wird auch als *binärer Semaphor* bezeichnet).
```java
import java.util.concurrent.Semaphore;
class SemaphorBankAccount {
private double balance;
//Bei Erstellung eines Kontos wird auch ein Semaphor erstellst
private Semaphore lock = new Semaphore(1);
public SemaphorBankAccount(double initialBalance) {
this.balance = initialBalance;
}
public void deposit(double amount) {
/*Hier muss "try" verwendet werden, da die Möglichkeit besteht, dass der
Thread, der gerade auf dem Konto arbeitet durch irgendetwas unterbrochen
wird.*/
try {
//Der Semaphor wird für den Thread reserviert und es wird gearbeitet.
lock.acquire();
balance += amount;
System.out.println("Deposited: " + amount + ",
Current Balance: " + balance);
} catch (InterruptedException e) {
//Ausgabe der Fehlermeldung bei Unterbrechung
e.printStackTrace();
} finally {
//Wenn alles geklappt hat wird der Semaphor wieder freigegeben.
lock.release();
}
}
//Hier läuft alles analog ab!
public void withdraw(double amount) {
try {
lock.acquire();
//Wir nehmen an, dass kein Überziehen möglich ist
while (balance < amount) {
System.out.println("Insufficient funds. Waiting for deposit.");
Thread.sleep(100);
}
balance -= amount;
System.out.println("Withdrawn: " + amount + ",
Current Balance: " + balance);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.release();
}
}
}
```
#pagebreak()
Testen können wir diese Implementierung z.B. mit der folgenden Methode:
```java
private static void useSemaphor() {
SemaphorBankAccount semaphorAccount = new SemaphorBankAccount(INITIAL_BALANCE);
System.out.println("Semaphor Bank Account Transactions:");
for (int i = 0; i < NUM_THREADS; i++) {
new Thread(() -> {
semaphorAccount.deposit(100);
semaphorAccount.withdraw(200);
}).start();
}
}
```
#grid(
rows:1, columns:(50%, 50%), gutter:8pt,
[```
Semaphor Bank Account Transactions:
Deposited: 100.0, Current Balance: 1100.0
Withdrawn: 200.0, Current Balance: 900.0
Deposited: 100.0, Current Balance: 1000.0
Withdrawn: 200.0, Current Balance: 800.0
Deposited: 100.0, Current Balance: 900.0
Withdrawn: 200.0, Current Balance: 700.0
Deposited: 100.0, Current Balance: 800.0
Withdrawn: 200.0, Current Balance: 600.0
Deposited: 100.0, Current Balance: 700.0
Withdrawn: 200.0, Current Balance: 500.0
Deposited: 100.0, Current Balance: 600.0
Withdrawn: 200.0, Current Balance: 400.0
Deposited: 100.0, Current Balance: 500.0
Withdrawn: 200.0, Current Balance: 300.0
Deposited: 100.0, Current Balance: 400.0
Withdrawn: 200.0, Current Balance: 200.0
Deposited: 100.0, Current Balance: 300.0
Withdrawn: 200.0, Current Balance: 100.0
Deposited: 100.0, Current Balance: 200.0
Withdrawn: 200.0, Current Balance: 0.0
```],[#v(2mm)Führen wir diese Methode aus, so ergeben sich die - jetzt schön sortierten - nebenstehenden Transaktionen.
Damit stellen wir sicher, dass immer nur eine Transaktion auf einmal abläuft und unsere Geldflüsse laufen wieder geordnet ab. Es gibt jedoch einen Nachteil (gerade in unserem speziellen Fall): durch das "Bestehen" auf der Ordnung haben wir im Wesentlichen alle parallele Verarbeitung aus diesem System genommen. Da es primär um das handling verschiedener Transaktionen ging, ist das nicht so schlimm, da im Zweifel viele verschiedene Konten (alle mit ihrem eigenen Semaphor) betroffen sind und nicht nur das eine.
Trotzdem muss immer hinterfragt werden, ob sich durch die Verwendung von Parallelität wirklich eine Performance-Verbesserung ergibt (das Erzeugen der Threads benötigt z.B. auch Ressourcen!)
]
)
#v(0.5cm)
=== Bankkonto mit Monitor
Die Grundidee bei einem Monitor besteht darin, dass wir *kritische Abschnitte* explizit definieren, die "am Stück" von einem Prozess ausgeführt werden müssen. In Java kann so ein kritischer Abschnitt mit dem Schlüsselwort *synchronized* definiert werden. Dabei können sowohl ganze Methoden synchronisiert werden als auch nur Teile einer Methode.
Der Ablauf sieht dann wie folgt aus:
1. Ein Thread ruft eine synchronisierte Methode auf.
2. Falls der Monitor nicht frei ist, dann wartet der Thread, bis er vom Monitor benachrichtigt wird.
3. Falls der Monitor frei ist führt der Thread die Methode aus. Nach Beendigung werden die wartenden Threads vom Monitor benachrichtigt.
#pagebreak()
Wir setzen das Konzept für das obige Beispiel um:
```java
class MonitorBankAccount {
private double balance;
public MonitorBankAccount(double initialBalance) {
this.balance = initialBalance;
}
//Wir definieren den Monitor mit dem synchronized Schlüsselwort
public synchronized void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount + ", Current Balance: " + balance);
}
public void withdraw(double amount) {
/*Statt in der Signatur, könnte auch nur innerhalb der Methode
ein Block definiert werden, in diesem Fall umspannt er die ganze Methode,
ist also äquivalent zur obigen Variante.
Wir geben dem synchronized block eine Referenz auf "this", da
für die Umsetzung der "Sperre" hier immer ein Objekt benötigt wird
*/
synchronized (this) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount + ",
Current Balance: " + balance);
} else {
System.out.println("Insufficient funds.");
}
}
}
}
```
#hinweis[Beide Konzepte - Monitor und Semaphor - setzen letztendlich dasselbe Prinzip um - den "Schutz" der gemeinsamen Ressource. Für unsere Zwecke ist die Verwendung des Monitors meistens zu bevorzugen, da es wesentlich weniger Schreibaufwand bedeutet.]
#pagebreak()
=== Parallelität im Abitur
Die Abituraufgaben halten sich in Bezug auf Implementierung stark zurück, häufig werden eher die Konzepte "Semaphor" und "Monitor" in "anschaulichen" Situationen abgefragt. Für die Aufgaben im Abitur sind auch *Sequenzdiagramme* wieder wichtig. Es folgen deshalb einige Aufgaben in diesem Stil.
Als Erstes betrachten wir einen *Monitor im Straßenverkehr*(*Rechts-vor-Links-Kreuzung*)
#grid(rows:1, columns:(70%, 30%), gutter: 15pt,
[#v(3mm)In unserem informatischen Modell sind die Autos nebenläufige Prozesse und die Kreuzung ist eine gemeinsame Ressource. Der Einfachheit halber gehen wir nur von Autos aus, die so eine Kreuzung in gerader Richtung überqueren wollen.
Wenn z.B. bei B ein Auto ankommt und bei A auch, dann "sperrt" B für A die Kreuzung. A darf erst dann fahren, wenn B die Kreuzung durchfahren und gewissermaßen "freigegeben" hat. Das hat eine gewisse Ähnlichkeit mit einem Semaphor.
],[#align(center)[#image("images/monitor.png", width: 85%)]]
)
#task(customTitle: "Aufgabe 1")[Angenommen, man implementiert in einer Simulation die Regelung, welches Auto losfahren darf (abweichend von der tatsächlichen Rechts-vor-Links-Regel) mit Hilfe eines Monitors, der den Kreuzungsbereich schützt. Beschreiben Sie, was so eine Regelung in der Realität für den Verkehrsfluss bedeuten würde. Gehen Sie auf ggf unerwünschte Auswirkungen ein.
]
#task(customTitle: "Aufgabe 2")[Stellen Sie in wenigen Sätzen den Zusammenhang zwischen den folgenden Begriffen dar:
1. Semaphor
2. kritischer Abschnitt
3. nebenläufige Prozesse
4. gemeinsame Ressourcen
]
#task(customTitle: "Aufgabe 3")[In einem Zug gibt es mehrere, fortlaufend nummerierte Plätze, die von Kunden online gebucht werden können. Dabei wird eine Methode _bookSeat()_ aufgerufen.
Diese Methode prüft, welche der jeweis nächste freie Sitz ist, markiert diesen als besetzt und schickt dem Kunden seine Reservierungsnummer zu.
Stellen Sie die Vorgänge in einem Sequenzdiagramm für den Fall dar, dass
- auf Parallelität nicht geachtet wurde und zwei Kunden nahezu gleichzeitig reservieren wollen.
- das Monitor-Konzept korrekt umgesetzt wurde.
_Hinweis: Sie können davon ausgehen, dass die Plätze/Sitze in der Zug-Klasse als boolean-Array implementiert wurden und keine eigenen Objekte darstellen_
]
#task(customTitle:"Aufgabe 3: Abitur 2023")[#image("images/abi23monitor.png")]
#pagebreak()
== Erzeuger-Verbraucher Systeme
Das obige Konto-Beispiel eignet sich nicht nur für die Analyse der verschiedenen Implementierung der verschiedenen Parallelitätskonzepte, sondern ist im weitesten Sinne auch ein Beispiel für ein sogenanntes *Erzeuger-Verbraucher-Problem*.
Diese sind durch folgende Punkte gekennzeichnet.
- Ein oder mehrere *Erzeuger* legen eine produzierte Ware auf den Weg zu einem Lagerplatz, um dort die Ware abzuladen. Erst nach dem Ablegen der Waren kehren sie wieder zurück.
- Ein oder mehrere *Verbraucher* machen sich auf den Weg zum Lagerplatz, um dort eine Ware abzuholen. Erst wenn sie eine Ware aufgenommen haben, kehren sie zurück.
- Der *Lagerplatz* besitzt *maximale Kapazität* an Waren.
- Die Beteiligten benötigen eine gewisse (zufällige) Zeit für das Abladen bzw. Aufladen am Lagerplatz, sowie eine (zufällige) Zeit für das Erzeugen bzw. Verbrauchen einer Ware.
Der dritte Punkt ist für unser Konto-Beispiel problematisch, da es eher eine *minimale Kapazität* des Kontos gibt, nämlich 0€. Deswegen betrachten wir einige andere Beispiele:
#align(center)[
#tablex(rows:(auto,)*5, columns:(auto,)*3, align: center,
[*Erzeuger*], [*Verbraucher*],[*Lagerplatz*],
[Pizzabäcker], [Kellner],[Theke],
[Holzfäller], [LKW-Fahrer], [Holzstapel],
[Wasserbombenauffüller], [Wasserbombenwerfer], [Wanne],
[Liefernder Roboterarm] ,[Abholender Roboterarm], [Abstellplatz]
)]
Etwas abstrakter und informatischer formuliert:
1. Mehrere Prozesse nutzen eine gemeinsame Datenstruktur (*Speicher!*).
2. Erzeugerprozesse fügen Objekte hinzu und Verbraucherprozesse entnehmen Objekte.
3. Das Hinzufügen ist nur möglich, wenn die maximale Kapazität der Datenstruktur noch nicht erreicht ist und das Entnehmen ist nur möglich, wenn es mindestens ein Objekt gibt.
Es gibt natürlich viele Möglichkeiten dies zu implementieren. Im einfachsten Fall ist der *Speicher* einfach nur eine ganzzahlige Variable, deren Wert gewisse Grenzen nicht über- oder unterschreiten darf.
Für uns relevant ist der Fall natürlich wieder, wenn der Zugriff auf den gemeinsamen Speicher nicht gleichzeitig erfolgen darf. Die Lösungen für dieses Problem haben wir aber bereits im vorangehenden Kapitel gefunden!
Es fehlen allerdings noch einige Begriffe, die weiter ausdifferenziert werden müssen.
#pagebreak()
=== Aktives Warten
Allgemein könnte der Code für die _insert_ Methode, also das Ablegen in unserem Stapel, naiv wie folgt aussehen, wenn wir davon ausgehen, dass die Attribute _amount_ und _maximum_ in unserer Klasse definiert sind.
```java
// Wir verwenden einen Monitor:
public synchronized void insert() {
if(amount == maximum) {
System.out.println("Storage is full! Waiting.");
//Wir prüfen jede halbe Sekunde, ob der Stapel noch voll ist, oder nicht
while(amount == maximum) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//Falls der Stapel nicht mehr voll ist:
try {
//Wir warten eine zufällige Zeit, um das Ablegen zu simulieren
Thread.sleep((int) (Math.random()*1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
//Wir erhöhen den Zähler
amount += 1;
}
}
```
#task[Beschreiben Sie, welches Problem sich aus dieser Implementierung ergibt.]
Die Lösung findet sich auf der nächsten Seite.
#pagebreak()
Der Monitor ist für die gesamte Methode definiert, d.h. unsere Ressource _amount_ ist durch den Thread gesperrt, der darauf wartet (via _Thread.sleep()_), dass wieder Platz freigeschaufelt wird. Man spricht hier auch vom *aktiven Warten*, da immer wieder aktiv geprüft wird, ob die Bedingung noch gilt, anstatt ein Signal abzuwarten, dass die genutzte Ressource wieder frei ist. In unserem Fall kann kein anderes Objekt die _insert_ oder die _remove_ Methode aufrufen, da wir _Thread.sleep()_ innerhalb des Monitors aufrufen. Es wird also nie Platz auf unserem Stapel frei werden.
Folglich müssen dafür sorgen, dass die Methode nicht nur einfach innerhalb des Monitors "schläft" und diesen aufrecht erhält, sondern wieder *freigibt* (und trotzdem noch auf das freigeben wartet).
Möchte man weiterhin das *aktive Warten* benutzen, so muss das Warten in die Erzeuger-Klasse (also die Klasse der Objekte, die "ablegen" wollen) ausgelagert werden. Damit können dann andere Objekte weiterhin konsumieren, d.h. aufnehmen, um Platz zu schaffen.
#task[Geben Sie allgemeinen Quellcode für diese Umsetzung des aktiven Wartens an. Im Fall der Erzeuger Klasse genügt der Abschnitt des Codes, der für das Warten verantwortlich ist.]
Die Lösung findet sich auf der nächsten Seite.
#pagebreak()
```java
//In unserer Speicher-Klasse
public synchronized boolean insert() {
if (amount == maximum) {
return false;
}
try {
Thread.sleep((int) (Math.random*1000))
} catch (InterruptedException e) {
e.printStackTrace();
}
amount += 1;
return true;
}
//In der Erzeuger-Klasse wird das Warten analog zur vorherigen Variante eingebaut:
while(!storage.insert()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
```
Noch einmal grob zusammengefasst kann das aktive Warten wie folgt implementiert werden.
1. In der *Erzeuger*-Klasse wird die _produce_ Methode immer wieder _insert_ auf dem *Speicher*-Objekt aufrufen, bis dieses den Wert *true* zurückgibt.
2. Analog wird in der *Verbraucher*-Klasse in der _consume_ Methode immer wieder _remove_ aufgerufen, bis der Wert des Aufrufs nicht *null* zurückgibt (wenn wir annehmen, dass ein *Objekt* "abgelegt" wird).
3. In der *Speicher*-Klasse gibt es einerseits die _sychronized insert_-Methode, die das Objekt einfügt, falls noch Platz ist und den Zähler inkrementiert. Andererseits gibt es die _synchronized remove_-Methode, die ein Objekt zurückgibt und den Zähler dekrementiert.
#hinweis[Die Implementierungen der _remove_ Methoden sind völlig analog zur _insert_ Methode und sind deshalb dem geschätzten Lesy zur Übung selbst überlassen.]
#pagebreak()
=== Passives Warten
Man sprich von *passivem Warten*, wenn nach einmaligem Versuch das aufrufende Objekt (also der entsprechende Thread) darauf wartet, dass er benachrichtigt wird, dass die Ressource frei ist.
Unser obiges Problem kann auch durch die Verwendung von passivem Warten gelöst werden, da Java eine eingebaute Methode *_wait_* hat, die den aktuell aktiven Thread warten lässt, im Gegensatz zu _sleep_ gibt diese Methode aber den Monitor wieder frei.
Die _wait_ Methode ist bereits in der _Object_ Klasse implementiert und somit kann jedes Objekt diese aufrufen. Wir benötigen wieder einen _try-catch_-Block, da auch hier unterbrochen werden könnte.
#align(center)[
```java
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
```
]
Damit der Thread wieder an diese Stelle zurückkommen kann muss er von einem anderen Thread via der Methode _notifyAll()_ "geweckt" bzw. benachrichtigt werden.
Mit diesen Informationen können wir wiederum den Code allgemein angeben:
#align(center)[
```java
public synchronized void insert() {
if(amount == maximum) {
System.out.println("Storage is full! Waiting.")
try {
//Wir verwenden wait() statt sleep()
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep((int) (Math.random*1000))
} catch (InterruptedException e) {
e.printStackTrace();
}
amount += 1;
//Alle anderen Threads werden ggf. aufgeweckt
notifyAll();
}
}
```
]
#task[Auch diese Implementierung ist noch nicht ideal, es gibt ein weiteres Problem. Beschreiben Sie, welches!]
Wie immer gibt es die Lösung auf der nächsten Seite.
#pagebreak()
Diese Variante kann zu *Inkonsistenzen* führen, also in unserem Fall zu einer Belegung über die Maximalanzahl hinaus. Das liegt daran, dass ein Erzeuger nach dem Aufwecken nicht noch einmal prüft, ob die Anzahl am Maximum angekommen ist. Ein anderer Thread hätte aber schneller sein können und der ursprünglich frei gewordene Platz ist schon wieder belegt.
Das Problem lässt sich allerdings sehr leicht beheben: anstatt nur einmal mit *if* zu prüfen, ob wir bereits einen vollen Stapel verwenden wir ein while und zwingen damit beim "Zurückkehren" den Thread dazu erneut zu prüfen:
#align(center)[
```java
public synchronized void insert() {
while(amount == maximum) {
System.out.println("Storage is full! Waiting.")
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep((int) (Math.random*1000))
} catch (InterruptedException e) {
e.printStackTrace();
}
amount += 1;
notifyAll();
}
}
```
]
Auch für das passive Warten hier noch einmal zusammengefasst:
1. In der *Erzeuger*-Klasse wird die _produce_ Methode aufgerufen.
2. In der *Verbraucher*-Klasse wird die _consume_ Methode aufgerufen.
3. Im Speicher passiert die Synchronisationsarbeit, sowohl die _insert_, als auch die _remove_ Methode sind hier _synchronized_ und steuern via _wait_ und _notifyAll_ die Zugriffe der einzelnen Threads.
=== Abituraufgaben
Größere Aufgaben dieser Art finden sich in den letzten Jahren quasi nicht. Aus dem Jahr 2012 gibt es aber eine recht ausführliche Aufgabe zum aktiven Warten und dem Monitor.
#task(customTitle: "Abitur 2012")[#image("images/abi12ev.png")]
#pagebreak()
== Verklemmungen (deadlocks)
Mit Hilfe der Semaphore und Monitore haben wir die meisten Probleme gelöst - es bleibt dennoch die Möglichkeit bestehen, dass es zu einer sogenannten *Verklemmung* kommt (wenn die Konzepte nicht korrekt umgesetzt werden). Ein Ähnliches Problem hatten wir beispielsweise schon beim aktiven Warten: der Thread, der wartet, dass etwas vom Stapel entfernt wird vs. alle anderen Threads, die warten, dass dieser den Stapel wieder freigibt.
In diesem Kapitel beleuchten wir *Verklemmungen* noch etwas genauer.
#grid(rows:1, columns:(70%, 30%), gutter: 15pt,
[#v(3mm)
Das klassische "reale" Beispiel für eine Verklemmung hatten wir schon weiter oben: die Kreuzung bei der 4 Autos nahezu gleichzeitig ankommen.
Auch hier könnte bei der Implementierung des Monitors einiges schief gehen - wenn wir die Rechts-Vor-Links Regel wörtlich nehmen könnte der Ablauf so aussehen: Auto A möchte die Kreuzung sperren, bemerkt aber Auto B und wartet, Auto B aber wartet auf Auto C, C wartet auf D und D auf A.
],[#align(center)[#image("images/deadlock.jpg", width: 85%)]]
)
#hinweis[Es gibt keinen "leichten" Weg aus dieser Situation wieder herauszukommen: deswegen ist in der Fahrschule hier auch *Kommunikation* angesagt!]
*Weiteres Beispiel*
Wir erweitern gedanklich das Beispiel unserer Konten aus den vorherigen Kapiteln. Eigentlich sind an einer Überweisung ja zwei Kontent beteiligt.
Wir nehmen folgendes Szenario an:
#align(center)[
#hinweis(customTitle: "Szenario", color: rgb("95FF80"), border-color: rgb("116600"))[
Es gibt die Personen Meike und Nadja mit ihren Konten $M$ (Kontostand 500€) und $N$ (600€)
Meike schuldet Nadja 400€ und Nadja schuldet Meike umgekehrt 300€. Sie sprechen sich deswegen nicht ab, sondern überwisen sich das Geld einfach gegenseitig und auch noch nahezu gleichzeitig!
Nach den Überweisungen sollten also auf Meikes Konto $M$ 400€ sein und auf Nadjas Konto $N$ 700€.
]]
#align(center)[
#tablex(rows:(auto,)*9, columns: (auto,)*3, outset: 3pt,
[*Schritt*], [*Prozess $M -> N$*], [*Prozess $N -> M$*],
[1], [Zugriff auf $N$] , [-],
[2], [$M' = 100€$ und $N'=1000€$ werden berechnet], [-],
[3], [Zuweisung von $M = M' = 100€$], [-],
[4], [setzt aus], [Zugriff auf $M$],
[5], [-], [$M'=400€$ und $N'=300€$ werden berechnet],
[6],[-], [Zuweisung von $M=M'=400€$],
[7], [-], [Zuweisung von $N=N'=300€$],
[8], [Zuweisung von $N=N'=1000€$], [fertig]
)]
Wir haben so Geld vermehrt, da die Kontostände $M = 400€$ und $N=1000€$ betragen. Gut für uns, aber schlecht für die Bank. Bei einer "naiven" parallelen Ausführung kommt es also zu Inkonsistenzen!
Wir müssen also sicherstellen, dass der Zugriff auf $M$ bzw. $N$ wieder durch einen Semaphor oder Monitor geregelt wird. Leider kann damit immer noch z.B. folgendes Szenario auftreten:
#align(center)[
#tablex(rows:(auto,)*6, columns: (auto,)*3, outset: 3pt,
[*Schritt*], [*Prozess $M -> N$*], [*Prozess $N -> M$*],
[1], [Zugriff auf $N$, Reservierung] , [-],
[2], [-], [Zugriff auf $M$, Reservierung],
[3], [-], [Warten auf $N$],
[4], [Warten auf $M$], [-],
[5], [Warten], [Warten],
)]
Die beiden Prozesse warten also darauf, dass die Ressource auf der jeweils anderen Seite wieder freigegeben werden.
Der Prozess $M -> N$ hat $N$ gesperrt und wartet auf $M$, was wiederum vom Prozess $N -> M$ gesperrt ist, das auf $N$ wartet.
Etwas allgemeiner:
#definition[Eine *Verklemmung* kann auftreten, wenn die folgenden drei Voraussetzungen gegeben sind:
1. Die gemeinsame Ressource kann nur durch den Prozess freigegeben werden, dass diese besitzt (Beim Semaphor kann auch ein anderer Prozess freigeben!)
2. Jeder beteiligte Prozess muss versuchen mindestens zwei Sperren auf einmal zu bekommen.
3. Es muss zu einer *zirkulären Abhängigkeit* kommen. Bei zwei beteiligten Prozessen also ein wechselseitiges Warten, bei mehr Prozessen können sich aber auch "Ringe" ergeben (wie bei den Autos weiter oben!)
]
Nachdem das Problem nun identifiziert ist bleibt natürlich noch die Frage:
#align(center)[*Wer löst Verklemmungen auf und wie?*]
Die beiden Prozesse können sich nicht "von selbst" aus diesem Problem befreien, außer wir haben einen sogenannten *Timeout* implementiert: ein Prozess verzichtet nach einer bestimmten Wartezeit auf die Ressource (auch wenn nicht klar ist, ob es sich um eine Verklemmung oder nur eine lange Wartezeit handelt).
Alternativ kann die Verklemmung von einer *übergeordneten Instanz* (also üblicherweise dem Betriebssystem) aufgelöst werden, die brachial entscheidet einen der Prozesse zu unterbrechen.
#task(customTitle: "Aufgabe 1")[Begründen Sie, ob es in der folgenden Situation zu einer Verklemmung kommt ($\P1$ bis $\P5$ sind Prozesse, alles andere sind Ressourcen):
1. $\P1$ besetzt $A$ und wartet auf $C$ und $D$
2. $\P2$ besetzt nichts und wartet auf $A$, $B$ und $E$
3. $\P3$ besetzt $C$ und wartet auf $E$ und $D$
4. $\P4$ besetzt $B$ und $E$ und wartet auf $A$
5. $\P5$ besetzt $D$ und wartet auf $C$
_Tipp: Stellen Sie die Situation mit Hilfe eines Graphen dar!_
]
#task(customTitle: "Aufgabe 2")[Beim klassischen Problem der *speisenden Philosophen* haben wir folgende Situation: 8 Philosophen sitzen an einem runden Tisch. Es gibt für jeden einen Teiller und einen Löffel.
#image("images/philosophen.png")
Ein Philosoph hat jetzt folgendes Verhaltensmuster:
1. Er denkt
2. greift nach einem Löffel rechts oder links von ihm
3. Denkt weiter
4. Greift (zerstreut) nach dem anderen Löffel links oder rechts von ihm
5. Isst mit beiden Löffeln (schnell! Er muss weiter denken)
6. Legt die Löffel wieder ab.
Wie kann es in dieser Situation zu einer Verklemmung kommen?
]
#task(customTitle:"Aufgabe 3")[Beurteilen Sie die folgenden Aussagen:
Um Verklemmungen zu vermeiden, kann man...
1. Semaphore verwenden
2. Monitore verwenden
3. auf gemeinsame Ressourcen verzichten
4. den gleichzeitigen Zugriff auf gemeinsame Ressourcen immer erlauben
5. eine Art Timeout-Funktion einbauen]
#task(customTitle: "Aufgabe 4 - Abi 23")[#image("images/abi23verklemmung.png")]
|
|
https://github.com/VinEdw/physics-equation-sheets | https://raw.githubusercontent.com/VinEdw/physics-equation-sheets/master/phys-2ag/phys-2ag-equations.typ | typst | #import "@preview/cetz:0.2.2"
#set text(size: 12pt)
#set par(leading: 1.00em)
= PHYS 2AG Equations
Having the equations is a start.
The next step is understanding what the equations mean, when to use them, and how to use them.
#let units(body) = {
$space upright(body)$
}
#show: rest => columns(2, rest)
== SI Prefixes
#table(
columns: 3,
table.header([Name], [Symbol], [Factor]),
[Quetta], [Q ], $10^(30)$ ,
[Ronna ], [R ], $10^(27)$ ,
[Yotta ], [Y ], $10^(24)$ ,
[Zetta ], [Z ], $10^(21)$ ,
[Exa ], [E ], $10^(18)$ ,
[Peta ], [P ], $10^(15)$ ,
[Tera ], [T ], $10^(12)$ ,
[Giga ], [G ], $10^(9)$ ,
[Mega ], [M ], $10^(6)$ ,
[Kilo ], [k ], $10^(3)$ ,
[Hecto ], [h ], $10^(2)$ ,
[Deka ], [da], $10^(1)$ ,
[\- ], [\-], $10^(0)$ ,
[Deci ], [d ], $10^(-1)$ ,
[Centi ], [c ], $10^(-2)$ ,
[Milli ], [m ], $10^(-3)$ ,
[Micro ], [μ ], $10^(-6)$ ,
[Nano ], [n ], $10^(-9)$ ,
[Pico ], [p ], $10^(-12)$,
[Femto ], [f ], $10^(-15)$,
[Atto ], [a ], $10^(-18)$,
[Zepto ], [z ], $10^(-21)$,
[Yocto ], [y ], $10^(-24)$,
[Ronto ], [r ], $10^(-27)$,
[Quecto], [q ], $10^(-30)$,
)
== Constants
- $g = 9.8 units(m/s^2)$
- $G = 6.674 times 10^(-11) units((N dot m^2) / "kg"^2)$
- $M_"Earth" = 5.97 times 10^(24) units("kg")$
- $R_"Earth" = 6.38 times 10^(6) units(m)$
- $1 "rev" = 2 pi "rad" = 360 degree$
== Geometry
- Angle addition postulate
- $theta_1 + theta_2 = theta_3$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw three lines
line((0, 0), (1, 3), name: "a")
line((0, 0), (4, 1), name: "b")
line((0, 0), (3, 2), name: "c")
// Draw the angles between them
cetz.angle.angle((0, 0), "a.end", "c.end", label: $theta_1$, radius: 0.75, label-radius: 180%, stroke: red)
cetz.angle.angle((0, 0), "b.end", "c.end", label: $theta_2$, radius: 1, label-radius: 180%, stroke: blue)
cetz.angle.angle((0, 0), "a.end", "b.end", label: $theta_3$, radius: 2.5, label-radius: 120%, stroke: green)
})
- Complementary angles
- $theta_1 + theta_2 = 90 degree$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines that form a right angle
line((0, 0), (0, 2), name: "a")
line((0, 0), (2, 0), name: "b")
// Draw a line cutting through
line((0, 0), (1, 2), name: "c")
// Label the angles
cetz.angle.angle((0, 0), "a.end", "c.end", label: $theta_1$, radius: 1, label-radius: 150%, stroke: red)
cetz.angle.angle((0, 0), "b.end", "c.end", label: $theta_2$, radius: 0.75, label-radius: 150%, stroke: blue)
})
- Supplementary angles
- $theta_1 + theta_2 = 180 degree$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines that form a right angle
line((0, 0), (-2, 0), name: "a")
line((0, 0), (2, 0), name: "b")
// Draw a line cutting through
line((0, 0), (1, 2), name: "c")
// Label the angles
cetz.angle.angle((0, 0), "a.end", "c.end", label: $theta_1$, radius: 1, label-radius: 150%, stroke: red)
cetz.angle.angle((0, 0), "b.end", "c.end", label: $theta_2$, radius: 0.75, label-radius: 150%, stroke: blue)
})
- Vertical angles
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines that intersect
set-style(mark: (symbol: ">"))
line((-2, -1), (2, 1), name: "a")
line((-2, 1), (2, -1), name: "b")
// Draw the top and bottom angles
set-style(mark: (symbol: none))
cetz.angle.angle((0, 0), "a.start", "b.end", label: $theta$, radius: 1)
cetz.angle.angle((0, 0), "b.start", "a.end", label: $theta$, radius: 1)
})
- Parallel lines cut by transversal
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw parallel lines cut by transversal
set-style(mark: (symbol: ">"))
line((0, 0), (4, 0), name: "a")
line((0, 2), (4, 2), name: "b")
line((1, -1), (3, 3), name: "c")
// Find the intersection points
intersections("i", "c", "a", "b")
// Draw first set of angle labels
set-style(mark: (symbol: none))
set-style(angle: (stroke: red))
for (i, a, b) in (
(0, "a.start", "c.end"),
(0, "a.end", "c.start"),
(1, "b.end", "c.start"),
(1, "b.start", "c.end"),
) {
cetz.angle.angle("i." + str(i), a, b, label: $theta_1$, radius: 0.75, label-radius: 150%)
}
// Draw second set of angle labels
set-style(angle: (stroke: blue))
for (i, a, b) in (
(0, "a.end", "c.end"),
(0, "a.start", "c.start"),
(1, "b.start", "c.start"),
(1, "b.end", "c.end"),
) {
cetz.angle.angle("i." + str(i), a, b, label: $theta_2$, radius: 0.5, label-radius: 150%)
}
})
- Triangles
- $A = 1/2 b h$
#cetz.canvas({
import cetz
import cetz.draw: *
// Set the points
let A = (0, 0)
let B = (1, 2)
let C = (3, 0)
// Draw a triangle
line(A, B, name: "AB")
line(B, C, name: "BC")
line(C, A, name: "CA")
// Draw a dashed height line
line((B.at(0), 0), B, name: "height", stroke: (dash: "dashed"))
// Label the sides
content("CA.mid", anchor: "north", padding: 0.2, $b$)
content("height.mid", anchor: "west", padding: 0.2, $h$)
})
- $theta_1 + theta_2 + theta_3 = 180 degree$
- $A/sin(theta_1) = B/sin(theta_2) = C/sin(theta_3)$ (law of sines)
- $C^2 = A^2 + B^2 - 2 A B cos(theta_3)$ (law of cosines)
#cetz.canvas({
import cetz
import cetz.draw: *
// Set the points
let A = (0, 0)
let B = (1, 2)
let C = (3, 0)
// Draw a triangle
line(A, B, name: "AB")
line(B, C, name: "BC")
line(C, A, name: "CA")
// Label the angles
let i = 1
let points = (A, B, C)
while i <= 3 {
cetz.angle.angle(..points, label: $theta_#i$, label-radius: 160%)
let last_point = points.remove(0)
points.push(last_point)
i += 1
}
// Label the edges
content("BC.mid", anchor: "south-west", padding: 0.2, $A$)
content("CA.mid", anchor: "north", padding: 0.2, $B$)
content("AB.mid", anchor: "south-east", padding: 0.2, $C$)
})
- Right triangles
- $A^2 + B^2 = C^2$
- $theta_1 + theta_2 = 90 degree$
- $sin(theta_1) = cos(theta_2) = B/C$
- $cos(theta_1) = sin(theta_2) = A/C$
- $tan(theta_1) = 1/tan(theta_2) = B/A$
#cetz.canvas({
import cetz
import cetz.draw: *
// Set the points
let A = (0, 0)
let B = (3, 4)
let C = (3, 0)
// Draw a triangle
line(A, B, name: "C")
line(B, C, name: "B")
line(C, A, name: "A")
// Label the edges
content("C.mid", anchor: "south-east", padding: 0.2, $C$)
content("B.mid", anchor: "west", padding: 0.2, $B$)
content("A.mid", anchor: "north", padding: 0.2, $A$)
// Label the angles
cetz.angle.angle(A, B, C, label: $theta_1$, label-radius: 160%)
cetz.angle.angle(B, A, C, label: $theta_2$, label-radius: 160%)
cetz.angle.right-angle(C, A, B, label: none)
})
- Rectangles
- $A = b h$
- $P = 2b + 2h$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw a rectangle
rect((0, 0), (2, 1), name: "rect")
// Label the edges
content("rect.south", anchor: "north", padding: 0.2, $b$)
content("rect.east", anchor: "west", padding: 0.2, $h$)
})
- Trapezoid
- $A = 1/2 (b_1 + b_2) h$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw a trapezoid
let A = (0, 0)
let B = (1, 2)
let C = (3, 2)
let D = (4, 0)
line(A, B)
line(B, C, name: "b1")
line(C, D)
line(D, A, name: "b2")
// Add a dashed height line
line((B.at(0), 0), B, name: "height", stroke: (dash: "dashed"))
// Label the edges
content("b1.mid", anchor: "south", padding: 0.2, $b_1$)
content("b2.mid", anchor: "north", padding: 0.2, $b_2$)
content("height.mid", anchor: "west", padding: 0.2, $h$)
})
- Inclined plane
- Inclined planes are typically described by their angle above horizontal
- The tilted coordinate axes are rotated that angle relative to the standard coordinate axes
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw the incline and ground
line((0, 0), (4, 3), name: "incline")
line((0, 0), (4, 0), name: "floor")
// Make the lines dashed
set-style(line: (stroke: (dash: "dashed")))
set-style(angle: (mark: (end: ">")))
// Label the angle with respect to horizontal
cetz.angle.angle((0, 0), "floor.end", "incline.end", label: $theta$, radius: 1, label-radius: 130%)
// Draw the standard axes
set-style(line: (stroke: (paint: blue)))
line((0, 1.5), (4, 1.5), name: "x-standard")
line((2, 0), (2, 3), name: "y-standard")
// Draw the rotated axes
set-style(line: (stroke: (paint: red)))
line((0, 0), (4, 3), name: "x-rotated")
line((3.125, 0), (0.875, 3), name: "y-rotated")
// Label the angle between the axes
let intersection = (2, 1.5)
for axis in ("x", "y") {
for side in ("start", "end") {
let a = axis + "-standard." + side
let b = axis + "-rotated." + side
cetz.angle.angle(intersection, a, b, label: $theta$, radius: 1, label-radius: 130%)
}
}
})
- Circles
- $C = 2 pi r$
- $A = pi r^2$
#cetz.canvas({
import cetz
import cetz.draw: *
circle((0, 0), radius: 1, name: "c")
circle("c.center", radius: 0.05, fill: black)
line((0, 0), (1/calc.sqrt(2), 1/calc.sqrt(2)), name: "r", mark: (end: ">"))
content("r.mid", anchor: "south-east", padding: 0.1, $r$)
})
- Spheres
- $A = 4 pi r^2$
- $V = 4/3 pi r^3$
== Algebra
- Quadratic formula
- $a x^2 + b x + c = 0$
- $x = (-b plus.minus sqrt(b^2 - 4 a c))/(2a)$
- Properties of logarithms
- $log_b (a) = p <==> b^p = a$
- $log_b (a c) = log_b (a) + log_b (c)$
- $log_b (a/c) = log_b (a) - log_b (c)$
- $log_b (a^p) = p log_b (a)$
- Sum and difference trig identities
- $sin(A plus.minus B) = sin(A)cos(B) plus.minus cos(A)sin(B)$
- $cos(A plus.minus B) = cos(A)cos(B) minus.plus sin(A)sin(B)$
== Kinematics
- Note: $x$ can be replaced with $y$ depending on the direction being analyzed
- $v_"avg" = d / (Delta t)$ (average speed)
- $v_"avg,x" = (Delta x) / (Delta t)$ (average velocity, x-component)
- $a_"avg,x" = (Delta v_x) / (Delta t)$
- If $a = "constant"$:
- $v_x = v_(0x) + a_x t$
- $x = x_0 + v_(0x) t + 1/2 a_x t^2$
- $v_x^2 = v_(0x)^2 + 2 a_x (x - x_0)$
- Knows and Unknowns
- #box(grid(
columns: 2,
align: center,
inset: 5pt,
grid.cell(colspan: 2, underline[Point 1 #sym.arrow.r Point 2]),
$x_0$ ,$y_0$,
$x$ ,$y$,
$v_(0x)$,$v_(0y)$,
$v_x$ ,$v_y$,
$a_x$ ,$a_y$,
grid.cell(colspan: 2, $t$),
))
== Forces
- Newton's laws of motion
1. $arrow(a) = 0 <==> Sigma arrow(F) = 0$
2. $Sigma arrow(F) = m arrow(a)$
3. $arrow(F)_(b "on" a) = - arrow(F)_(a "on" b)$
- Gravitational force ($F_g$)
- $F_g = m g$
- $F_g = G (m_1 m_2)/r^2$
- Points straight down towards the center of the Earth
- Normal force ($n$, $N$, or $F_n$)
- No general formula
- Pushes perpendicular to surfaces in contact
- Applied force ($F_"app"$)
- Push or pull in a specified direction
- Tension ($T$ or $F_T$)
- No general formula
- Pulls along rope/chain/cable
- Kinetic friction ($f_k$)
- $f_k = mu_k n$
- Acts opposite relative motion of surfaces
- Static friction ($f_s$)
- $f_s <= mu_s n$
- $f_(s,"max") = mu_s n$
- Direction and magnitude change based on the situation
- Acts when there is no relative motion between surfaces
- Tries to stop relative motion between surfaces
- Spring force ($F_s$)
- $F_s = k s$
- Points in the direction opposite the squish or stretch
- Pivot force ($P$)
- No general formula
- Usually broken into $P_x$ and $P_y$
- Force from pin that keeps attached object from translating away
- Free body diagram (FBD) reminders
- Identify your system
- Identify the direction of the acceleration
- Identify the direction of the velocity
- Choose a coordinate system
- Draw all external forces acting on the system
- Note the angle for any forces acting at an angle relative to the chosen axes
- Centripetal acceleration ($a_c$)
- $a_c = v^2/r = r omega^2$
- Points towards the center of the circular path
== Work and Energy
- Work ($W$)
- Energy transferred via forces
- $W = F d cos(theta)$
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines
set-style(line: (mark: (end: ">")))
line((0, 0), (1, 2), name: "F")
line((0, 0), (3, 1), name: "d")
// Draw the angle between them
cetz.angle.angle((0, 0), "F.end", "d.end", label: $theta$, radius: 1, label-radius: 150%)
// Label the lines
content("F.end", anchor: "south", padding: 0.3, $arrow(F)$)
content("d.end", anchor: "south", padding: 0.3, $arrow(d)$)
})
- External heat ($Q_"ext"$)
- Thermal energy transferred from the environment to/from the system
- Power ($P$)
- $P = (Delta E)/(Delta T)$
- Kinetic energy ($K$)
- Energy of motion
- $K = 1/2 m v^2$
- Kinetic energy ($K_"rot"$)
- Energy of rotational motion
- $K = 1/2 I omega^2$
- Gravitational potential energy ($U_g$)
- Energy due to position in a gravitational field
- $U_g = m g h$
- Make sure to choose a reference level
- Elastic potential energy ($U_s$)
- Energy due to squishing/stretching a spring from its natural length
- $U_g = 1/2 k s^2$
- Internal energy ($U_"int"$)
- $Delta U_"th" = m c Delta T$ (due to temperature)
- $Delta U_"p" = plus.minus m L$ (due to phase change)
- All the substance must reach the phase change temperature before the transition occurs
- Temperature remains constant until all the substance has undergone the phase change
- Sound energy ($U_"sound"$)
- Energy of sound waves
- Conservation of energy
- $E_i + W_"nc" + Q_"ext" = E_f$
- $K_i + U_(g i) + U_(s i) + ... + W_"nc" + Q_"ext" = K_f + U_(g f) + U_(s f) + ... + Delta U_"int"$
== Momentum
- $arrow(p) = m arrow(v)$ (momentum)
- $arrow(J) = arrow(F)_"net,avg" Delta t = Delta arrow(p)$ (impulse-momentum theorem)
- Conservation of momentum
- If $arrow(F)_"net" = 0$, then $p_i = p_f$
- Applies to pretty much all collisions & explosions
- Collision types
- Perfectly inelastic
- "Sticky"
- $v_(1f) = v_(2f) = ... = v_f$
- Inelastic
- In between perfectly inelastic and perfectly elastic
- Perfectly elastic
- "Bouncy"
- $K_i = K_f$
== Rotational Kinematics
- Switching between linear (tangential) and angular quantities
- Angles must be in radians
- $s = r theta$
- $v_t = r omega$
- $a_t = r alpha$
- $omega_"avg" = (Delta theta) / (Delta t)$
- $alpha_"avg" = (Delta omega) / (Delta t)$
- If $alpha = "constant"$:
- $omega = omega_0 + alpha t$
- $x = x_0 + omega_0 t + 1/2 alpha t^2$
- $omega^2 = omega_0^2 + 2 alpha (theta - theta_0)$
== Rotational Dynamics
- Torque ($tau$)
- $tau = plus.minus F r sin(theta)$
- $sin(theta) = sin(theta')$, so either angle can be used
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines
set-style(line: (mark: (end: ">")))
line((3, 1), (4, 3), name: "F")
line((0, 0), (3, 1), name: "r")
// Extend the r vector
line((3, 1), (5, 5/3), name: "e", mark: none, stroke: (dash: "dashed"))
// Label the angles between them
cetz.angle.angle("r.end", "F.end", "r.start", label: $theta'$, radius: 0.5, label-radius: 150%)
cetz.angle.angle("r.end", "F.end", "e.end", label: $theta$, radius: 0.75, label-radius: 150%)
// Label the lines
content("F.end", anchor: "south", padding: 0.3, $arrow(F)$)
content("r.end", anchor: "north", padding: 0.3, $arrow(r)$)
})
- $Sigma tau = I alpha$ (Newton's second law rotational)
- $I = Sigma m r^2$
- Moment of inertia formulas are derived by breaking objects up into pieces, then adding up $m r^2$ for each piece
- Implies that moments of inertia can add together
- $I = I_"cm" + M D^2$ (parallel axis theorem)
- When rolling without slipping, $v_"cm" = r omega$
- Rigid body diagram (RBD) reminders
- Identify your system
- Identify the direction of the acceleration or angular acceleration
- Identify the direction of the velocity or angular velocity
- Choose a coordinate system
- Choose an axis of rotation (if it's not rotating)
- Draw all external forces acting on the system at the location where they are acting
- Note the angle for any forces acting at an angle relative to the chosen axes, or relative to a vector pointing from the pivot to where the force acts
- Note how far each force is acting from the axis of rotation
- Angular momentum ($L$)
- $L = m v r sin(theta)$ (point particle)
- $sin(theta) = sin(theta')$, so either angle can be used
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw two lines
set-style(line: (mark: (end: ">")))
line((3, 1), (4, 3), name: "v")
line((0, 0), (3, 1), name: "r")
// Extend the r vector
line((3, 1), (5, 5/3), name: "e", mark: none, stroke: (dash: "dashed"))
// Label the angles between them
cetz.angle.angle("r.end", "v.end", "r.start", label: $theta'$, radius: 0.5, label-radius: 150%)
cetz.angle.angle("r.end", "v.end", "e.end", label: $theta$, radius: 0.75, label-radius: 150%)
// Label the lines
content("v.end", anchor: "south", padding: 0.3, $arrow(v)$)
content("r.end", anchor: "north", padding: 0.3, $arrow(r)$)
})
- $L = I omega$ (not universal, but works for most cases in the class)
- $tau_"net,avg" Delta t = Delta L$
== Static Equilibrium
- If $arrow(a) = 0$ and $alpha = 0$:
- $Sigma F_x = 0$
- $Sigma F_y = 0$
- $Sigma tau = 0$
- Since it is not rotating, any axis of rotation can be chosen for the purpose of calculating torques
== Simple Harmonic Motion
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw the wave plot
cetz.plot.plot(size: (6, 4),
name: "plot",
axis-style: "school-book",
x-label: $t$,
y-label: $x$,
x-tick-step: none,
y-tick-step: none,
{
cetz.plot.add(domain: (0, 4 * calc.pi),
t => (t, calc.cos(t)))
cetz.plot.add-anchor("a", (0, 1))
cetz.plot.add-anchor("b", (2 * calc.pi, 1))
cetz.plot.add-anchor("c", (2 * calc.pi, 0))
})
// Label the period and amplitude
set-style(mark: (symbol: ">"))
line("plot.a", "plot.b", name: "T")
content("T.mid", anchor: "south", padding: 0.2, $T$)
line("plot.b", "plot.c", name: "A")
content("A.mid", anchor: "west", padding: 0.1, $A$)
})
- Oscillation terms
- Period ($T$)
- Frequency ($f$)
- Angular frequency ($omega$)
- $T = 1/f$ or $f = 1/T$
- $omega = (2 pi)/T = 2 pi f$
- Amplitude ($A$)
- Mass on a spring
- $omega = sqrt(k / m)$
- Simple pendulum
- $omega = sqrt(g / L)$
- Assumes $theta < ~15 degree$ so that $theta approx sin(theta)$
- Kinematics
- $x(t) = A cos(omega t + phi.alt)$
- $x_"max" = A$
- $v(t) = -A omega sin(omega t + phi.alt)$
- $v_"max" = A omega$
- $a(t) = -A omega^2 cos(omega t + phi.alt)$
- $a_"max" = A omega^2$
== Waves
#cetz.canvas({
import cetz
import cetz.draw: *
// Draw the wave plot
cetz.plot.plot(size: (6, 4),
name: "plot",
axis-style: "school-book",
x-tick-step: none,
y-tick-step: none,
{
cetz.plot.add(domain: (0, 4 * calc.pi),
t => (t, calc.cos(t)))
cetz.plot.add-anchor("a", (0, 1))
cetz.plot.add-anchor("b", (2 * calc.pi, 1))
cetz.plot.add-anchor("c", (2 * calc.pi, 0))
})
// Label the wavelength and amplitude
set-style(mark: (symbol: ">"))
line("plot.a", "plot.b", name: "lambda")
content("lambda.mid", anchor: "south", padding: 0.2, $lambda$)
line("plot.b", "plot.c", name: "A")
content("A.mid", anchor: "west", padding: 0.1, $A$)
})
- $v = f lambda$
- Wave speed depends on properties of the medium, not on wavelength and frequency
- $v = sqrt(F_T/mu)$ (speed of wave in a string)
- $v = (331.5 units(m/s)) + (0.6 units((m\/s)/degree.c)) T$ (speed of sound in air)
- Wave function
- $y(x, t) = A cos(k x plus.minus omega t)$
- Plus when moving in the $-x$ direction
- Minus when moving in the $+x$ direction
- Focus on a single point, $x = 0$, over time
- $y(0, t) = A cos(plus.minus omega t)$
- Focus on the shape of the wave at a single point in time, $t = 0$
- $y(x, 0) = A cos(k x)$
- Could add a phase angle $phi.alt$ inside the $cos()$ if needed
- $y(x, t) = A cos(k x plus.minus omega t + phi.alt)$
- Intensity ($I$)
- $I = P / A$
- Can be total power divided by the total area spread over
- Can be power delivered divided by the area of a detector
- Sound intensity level ($beta$)
- $beta = (10 units(d B)) log(I/I_0)$
- $I_0 = 10^(-12) units(W/m^2)$ (threshold of hearing)
- $beta_2 - beta_1 = (10 units(d B)) log(I_2/I_1)$
- Doppler effect for sound
- $f_o = f_s (v plus.minus v_o)/(v minus.plus v_s)$
- $v$: speed of sound
- $o$: observer
- $s$: source
- Use the upper sign if the observer/source is moving towards the other
- Use the lower sign if the observer/source is moving away from the other
== Fluids
- $rho = m/V$ (density)
- $P = F/A$ (pressure)
- $P = P_0 + rho g h$ (pressure at a depth in a fluid)
- Buoyant force ($B$ or $F_B$)
- $B = rho_"fluid" V_"displaced" g$
- Points opposite $arrow(g)$
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/chic-hdr/0.1.0/chic-hdr.typ | typst | Apache License 2.0 | /*
* Chic-header - A package for Typst
* <NAME> (c) 2023
*
* chic-hdr.typ -- The package's main file containing
* the public functions
*
* This file is under the MIT license. For more
* information see LICENSE on the package's main folder.
*/
#import "internal.typ": *
/*
* chic-header
*
* Sets the header content
*
* Parameters:
* - 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(left-side: none, center-side: none, right-side: none) = {
return (
chic-type: "header",
value:[
#chic-grid(left-side, center-side, right-side)
]
)
}
/*
* chic-footer
*
* Sets the footer content
*
* Parameters:
* - 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(left-side: none, center-side: none, right-side: none) = {
return (
chic-type: "footer",
value:[
#chic-grid(left-side, center-side, right-side)
]
)
}
/*
* chic-separator
*
* Sets the separator for either the header, the footer or both
*
* Parameters:
* - on: Where to apply the separator: "header", "footer" or "both"
* - gutter: Space arround 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", gutter: .65em, sep) = {
if on in ("both", "header", "footer") {
if type(sep) == "content" { // It's a custom separator
return (
chic-type: "separator",
on: on,
value: block(width: 100%, 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%, spacing: gutter, line(length: 100%, stroke: sep))
)
}
}
// Return nothing if happens a type mismatch
}
/*
* 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 length") {
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 length") {
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 previous heading name. If there’s no previous
* headings, it returns the next heading name. Finally, if
* there’s no headings ahead, it returns nothing.
*/
#let chic-heading-name() = {
return locate(loc => {
// Search for previous headings
let headings = query(selector(heading).before(loc), loc)
if headings != () {
return headings.last().body
} else {
// Search for next headings
let headings = query(selector(heading).after(loc), loc)
if headings != () {
return headings.first().body
} else {
// There's no headings
return
}
}
})
}
/*
* chic
*
* Chic-header package main function. It receives all the
* parameters to modify the header and the footer of the document
*
* Parameters:
* - width: Width of headers and footers
* - skip: Which pages must not have a header and footer
* - even: Header and footer for even pages
* - odd: Header and footer for odd pages
* - options: Header and footer for all non-specified pages, and
* general header and footer options for all pages.
*/
#let chic(width: 100%, skip: (), even: none, odd: none, ..options) = {
// both-options is used in case `even` is sepcified or `odd` is specified, but not both, or when none of them are specified
let both-options = chic-generate-props(width, options.pos())
let even-options = none
let odd-options = none
// Final properties
let page-options = (
header: none,
footer: none,
margin: both-options.margin,
header-ascent: both-options.header-ascent,
footer-descent: both-options.footer-descent
)
// Load even and odd properties
if even != none {
even-options = chic-generate-props(width, even)
}
if odd != none {
odd-options = chic-generate-props(width, odd)
}
// Load header and footer
for option in ("header", "footer") {
page-options.at(option) = locate(loc => {
if loc.page() not in skip { // Skip given pages
if calc.odd(loc.page()) { // Odd pages
if odd != none {
odd-options.at(option)
} else {
both-options.at(option)
}
} else { // Even pages
if even != none {
even-options.at(option)
} else {
both-options.at(option)
}
}
}
})
}
set page(
..page-options
)
// Rest of the document
options.pos().last()
} |
https://github.com/sitandr/mdbook-typst-highlight | https://raw.githubusercontent.com/sitandr/mdbook-typst-highlight/main/example-book/src/chapter_1.md | markdown | MIT License | # Chapter 1
```typ
= Hello there!
This is a test
```
# Render&Preamble
```typ-norender
This will not be rendered.
And that way?
```
```typ-nopreamble
This will be default doc
```
This is some `#inline` code.
```
This is code without any lang specified.
```
````typ
Typst and some Rust inside
```rust
fn main() {
todo!();
}
```
```` |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.