repo
stringlengths 26
115
| file
stringlengths 54
212
| language
stringclasses 2
values | license
stringclasses 16
values | content
stringlengths 19
1.07M
|
---|---|---|---|---|
https://github.com/GYPpro/DS-Course-Report | https://raw.githubusercontent.com/GYPpro/DS-Course-Report/main/Rep/09.typ | typst | #import "@preview/tablex:0.0.6": tablex, hlinex, vlinex, colspanx, rowspanx
#import "@preview/codelst:2.0.1": sourcecode
// 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,
)
#show raw: set text(
font: ("consolas", "Source Han Serif SC")
)
#set page(
paper: "a4",
)
#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()]
#set math.equation(numbering: "(1)")
#show raw.where(block: true): block.with(
fill: luma(240),
inset: 10pt,
radius: 4pt,
)
#set math.equation(numbering: "(1)")
#set page(
paper:"a4",
number-align: right,
margin: (x:2.54cm,y:4cm),
header: [
#set text(
size: 25pt,
font: "KaiTi",
)
#align(
bottom + center,
[ #strong[暨南大学本科实验报告专用纸(附页)] ]
)
#line(start: (0pt,-5pt),end:(453pt,-5pt))
]
)
/*----*/
= R-BTree的基本实现
\
#text(
font:"KaiTi",
size: 15pt
)[
课程名称#underline[#text(" 数据结构 ")]成绩评定#underline[#text(" ")]\
实验项目名称#underline[#text(" ") R-BTree的基本实现 #text(" ")]指导老师#underline[#text(" 干晓聪 ")]\
实验项目编号#underline[#text(" 08 ")]实验项目类型#underline[#text(" 设计性 ")]实验地点#underline[#text(" 数学系机房 ")]\
学生姓名#underline[#text(" 郭彦培 ")]学号#underline[#text(" 2022101149 ")]\
学院#underline[#text(" 信息科学技术学院 ")]系#underline[#text(" 数学系 ")]专业#underline[#text(" 信息管理与信息系统 ")]\
实验时间#underline[#text(" 2024年6月13日上午 ")]#text("~")#underline[#text(" 2024年7月13日中午 ")]\
]
#set heading(
numbering: "1.1."
)
= 实验目的
实现RB-tree的基本结构
= 实验环境
计算机:PC X64
操作系统:Windows + Ubuntu20.0LTS
编程语言:C++:GCC std20
IDE:Visual Studio Code
= 程序原理
对于一个二叉搜索树,标记所有叶节点为`NIL`,并在路径上标记红黑节点,使得:
+ `NIL`节点为黑色
+ 红色节点的子节点为黑色
+ 从根节点到`NIL`节点路径上的黑色节点数量相同
定义旋转
#image("091.svg",width: 50%)
对于每次插入与删除,需要基于红黑节点性质进行平衡维护。具体实现见代码。
容易证明,满足红黑性质的红黑树,为近似平衡二叉搜索树。
可得插入复杂度为$OO(log_2 n)$,删除复杂度为$OO(log_2 n)$,随机访问复杂度为$OO(log_2 n)$
#pagebreak()
= 程序代码
== `memDeleteTest.cpp`
#sourcecode[```cpp
#include <iostream>
#include <new>
#include <stdlib.h>
using namespace std;
class testClass{
public:
int a = 0;
testClass(){a=1;};
~testClass(){cout << "Distroy TestClass\n";};
};
int main()
{
testClass * arr = new testClass[10];
cout << "Finish Alloc\n";
for(int i = 0;i < 10;i ++)
arr[i].~testClass();
if(arr)
//delete[] arr;
::operator delete[](arr);
else cout << "nullPtr\n";
cout << "Finish Delete\n";
return 0;
}
```]
== `RB_Tree.h`
#sourcecode[```cpp
#ifndef RBTREE_MAP_HPP
#define RBTREE_MAP_HPP
#ifdef __PRIVATE_DEBUGE
#include <iostream>
#endif
#include <vector>
#include <stdlib.h>
#include "Dev\02\myVector.h"
using std::vector;
namespace myDS
{
template <typename VALUE_TYPE>
class RBtree{
private:
// using int size_t;
enum COLOR {RED,BLACK};
protected:
//节点类
class Node{
public:
VALUE_TYPE value;
COLOR color;
Node *leftSubTree, //左子树根节点指针
*rightSubTree, //右子树根节点指针
*parent; //父节点指针
explicit Node() :
value(VALUE_TYPE()),
color(COLOR::RED),
leftSubTree(nullptr),
rightSubTree(nullptr),
parent(nullptr) { };
//获取父节点指针
inline Node * getParent() {
return parent;
}
//获取祖父节点指针
inline Node * getGrandParent() {
if(parent == nullptr) return nullptr;
else return parent->parent;
}
//获取叔叔节点指针
inline Node * getUncle() {
Node* __gp = this->getGrandParent();
if(__gp == nullptr) return nullptr;
else if(parent == __gp->rightSubTree) return __gp->leftSubTree;
else return __gp->rightSubTree;
}
//获取兄弟节点指针
inline Node * getSibling(){
if(parent == nullptr) return nullptr;
else if(parent->leftSubTree == this) return parent->rightSubTree;
else return parent->leftSubTree;
}
};
class iterator{
friend RBtree;
protected:
Node * ptr;
Node * NIL;
void loop2Begin() {
if(ptr == NIL){ptr = nullptr;return;}
while(ptr->leftSubTree != NIL) ptr = ptr->leftSubTree;
}
void loop2End() {
if(ptr == NIL){ptr = nullptr;return;}
if(ptr->parent == nullptr){ ptr = nullptr;return;}
while(ptr->parent->leftSubTree != ptr) {
ptr = ptr->parent;
if(ptr->parent == nullptr){ ptr = nullptr;return;}
}
ptr = ptr->parent;
}
void getNextNode() {
if(ptr->rightSubTree != NIL){
ptr = ptr->rightSubTree;
loop2Begin();
} else {
loop2End();
}
}
public:
iterator(Node * _ptr,Node * _NIL) {
ptr = _ptr;
NIL = _NIL;
}
const VALUE_TYPE & operator*()
{
return ptr->value;
}
VALUE_TYPE *operator->() //?
{
return ptr;
}
myDS::RBtree<VALUE_TYPE>::iterator operator++() {
auto old = *this;
getNextNode();
return old;
}
myDS::RBtree<VALUE_TYPE>::iterator operator++(int) {
getNextNode();
return (*this);
}
bool operator==( myDS::RBtree<VALUE_TYPE>::iterator _b) {
return ptr == _b.ptr;
}
bool operator!=( myDS::RBtree<VALUE_TYPE>::iterator _b) {
return ptr != _b.ptr;
}
};
public:
//树结构
Node *root, *NIL;
RBtree() {
NIL = new Node();
NIL->color = COLOR::BLACK;
root = nullptr;
};
~RBtree(){
auto DeleteSubTree = [&](auto self,Node *p) -> void{
if(p == nullptr || p == NIL) return;
self(self,p->leftSubTree);
self(self,p->rightSubTree);
delete p;
return;
};
if(!(root == nullptr)) DeleteSubTree(DeleteSubTree,root);
delete NIL;
}
void insert(VALUE_TYPE data) {
if(root == nullptr) {
root = new Node();
root->color = COLOR::BLACK;
root->leftSubTree = NIL;
root->rightSubTree = NIL;
root->value = data;
} else {
if(this->locate(data,root)) return;
subInsert(root,data);
}
}
VALUE_TYPE find(VALUE_TYPE tar) {
if(locate(tar,root) != nullptr) return locate(tar,root)->value;
else return -1;
}
bool erase(VALUE_TYPE data) {
return subDelete(root,data);
}
myDS::RBtree<VALUE_TYPE>::iterator begin(){
auto rt = iterator(root,NIL);
rt.loop2Begin();
return rt;
}
myDS::RBtree<VALUE_TYPE>::iterator end(){
return iterator(nullptr,NIL);
}
#ifdef __PRIVATE_DEBUGE
void printDfsOrder()
{
auto dfs = [&](auto self,Node * p ) -> void {
if(p == nullptr){ std::cout << "ED\n";return;}
if(p->leftSubTree == nullptr && p->rightSubTree == nullptr) {std::cout << "[NIL] \n";return;}
std::cout << "["<< p->value << " : " << (p->color == COLOR::BLACK ?"BLACK":"RED") << "] ";
self(self,p->leftSubTree);
self(self,p->rightSubTree);
return;
};
dfs(dfs,root);
}
vector<int> printList;
void printIterOrder()
{
auto dfs = [&](auto self,Node * p) -> void{
if(p->leftSubTree == nullptr && p->rightSubTree == nullptr) {std::cout << "[NIL] \n";return;}
self(self,p->leftSubTree);
std::cout << "["<< p->value << " : " << (p->color == COLOR::BLACK ?"BLACK":"RED") << "] ";
self(self,p->rightSubTree);
};
dfs(dfs,root);
}
#endif
private:
Node * locate(VALUE_TYPE t,Node * p) {
if(p == NIL) return nullptr;
else if(p->value == t) return p;
else if(p->value > t) return locate(t,p->leftSubTree);
else return locate(t,p->rightSubTree);
}
//右旋某个节点
void rotateRight(Node *p)
{
Node * _gp = p->getGrandParent();
Node * _pa = p->getParent();
Node * _rotY = p->rightSubTree;
_pa->leftSubTree = _rotY;
if(_rotY != NIL) _rotY->parent = _pa;
p->rightSubTree = _pa;
_pa->parent = p;
if(root == _pa) root = p;
p->parent = _gp;
if(_gp != nullptr) if(_gp->leftSubTree == _pa) _gp->leftSubTree = p;
else _gp->rightSubTree = p;
return;
}
//左旋某个节点
void rotateLeft(Node *p)
{
if(p->parent == nullptr){
root = p;
return;
}
Node *_gp = p->getGrandParent();
Node *_pa = p->parent;
Node *_rotX = p->leftSubTree;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
_pa->rightSubTree = _rotX;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
if(_rotX != NIL)
_rotX->parent = _pa;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
p->leftSubTree = _pa;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
_pa->parent = p;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
if(root == _pa)
root = p;
p->parent = _gp;
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
if(_gp != nullptr){
if(_gp->leftSubTree == _pa)
_gp->leftSubTree = p;
else
_gp->rightSubTree = p; //?!
}
#ifdef __DETIL_DEBUG_OUTPUT
printIterOrder();
#endif
}
//插入节点递归部分
void subInsert(Node *p,VALUE_TYPE data)
{
if(p->value >= data){ //1 2
if(p->leftSubTree != NIL) //3
subInsert(p->leftSubTree, data);
else {
Node *tmp = new Node();//3
tmp->value = data;
tmp->leftSubTree = tmp->rightSubTree = NIL;
tmp->parent = p;
p->leftSubTree = tmp;
resetStatus_forInsert(tmp);
}
} else {
if(p->rightSubTree != NIL) //1 2
subInsert(p->rightSubTree, data);
else {
Node *tmp = new Node();
tmp->value = data;
tmp->leftSubTree = tmp->rightSubTree = NIL;
tmp->parent = p;
p->rightSubTree = tmp;
resetStatus_forInsert(tmp);
}
}
}
//插入后的平衡维护
void resetStatus_forInsert(Node *p) {
//case 1:
if(p->parent == nullptr){
root = p;
p->color = COLOR::BLACK;
return;
}
//case 2-6:
if(p->parent->color == COLOR::RED){
//case 2: pass
if(p->getUncle()->color == COLOR::RED) {
p->parent->color = p->getUncle()->color = COLOR::BLACK;
p->getGrandParent()->color = COLOR::RED;
resetStatus_forInsert(p->getGrandParent());
} else {
if(p->parent->rightSubTree == p && p->getGrandParent()->leftSubTree == p->parent) {
//case 3:
rotateLeft(p);
p->color = COLOR::BLACK;
p->parent->color = COLOR::RED;
rotateRight(p);
} else if(p->parent->leftSubTree == p && p->getGrandParent()->rightSubTree == p->parent) { //this
//case 4:
rotateRight(p);
p->color = COLOR::BLACK;
p->parent->color = COLOR::RED;
rotateLeft(p);
} else if(p->parent->leftSubTree == p && p->getGrandParent()->leftSubTree == p->parent) {
//case 5:
p->parent->color = COLOR::BLACK;
p->getGrandParent()->color = COLOR::RED;
rotateRight(p->parent);
} else if(p->parent->rightSubTree == p && p->getGrandParent()->rightSubTree == p->parent) {
//case 6: BUG HERE
p->parent->color = COLOR::BLACK;
p->getGrandParent()->color = COLOR::RED;
rotateLeft(p->parent);
}
}
}
}
//删除时的递归部分
bool subDelete(Node *p, VALUE_TYPE data){
//获取最接近叶节点的儿子
auto getLowwestChild = [&](auto self,Node *p) -> Node*{
if(p->leftSubTree == NIL) return p;
return self(self,p->leftSubTree);
};
if(p->value > data){
if(p->leftSubTree == NIL){
return false;
}
return subDelete(p->leftSubTree, data);
} else if(p->value < data){
if(p->rightSubTree == NIL){
return false;
}
return subDelete(p->rightSubTree, data);
} else if(p->value == data){
if(p->rightSubTree == NIL){
deleteChild(p);
return true;
}
Node *smallChild = getLowwestChild(getLowwestChild,p->rightSubTree);
std::swap(p->value, smallChild->value);
deleteChild(smallChild);
return true;
}else{
return false;
}
}
// //删除入口
// bool deleteChild(Node *p, int data){
// if(p->value > data){
// if(p->leftSubTree == NIL){
// return false;
// }
// return deleteChild(p->leftSubTree, data);
// } else if(p->value < data){
// if(p->rightSubTree == NIL){
// return false;
// }
// return deleteChild(p->rightSubTree, data);
// } else if(p->value == data){
// if(p->rightSubTree == NIL){
// delete_one_child (p);
// return true;
// }
// Node *smallest = getSmallestChild(p->rightTree);
// swap(p->value, smallest->value);
// delete_one_child (smallest);
// return true;
// }else{
// return false;
// }
// }
//删除处理:删除某个儿子
void deleteChild(Node *p){
Node *child = p->leftSubTree == NIL ? p->rightSubTree : p->leftSubTree;
if(p->parent == nullptr && p->leftSubTree == NIL && p->rightSubTree == NIL){
p = nullptr;
root = p;
return;
}
if(p->parent == nullptr){
delete p;
child->parent = nullptr;
root = child;
root->color = COLOR::BLACK;
return;
}
if(p->parent->leftSubTree == p) p->parent->leftSubTree = child;
else p->parent->rightSubTree = child;
child->parent = p->parent;
if(p->color == COLOR::BLACK){
if(child->color == COLOR::RED){
child->color = COLOR::BLACK;
} else
resetStatus_forDelete(child);
}
delete p;
}
//删除后的平衡维护
void resetStatus_forDelete(Node *p){
if(p->parent == nullptr){
//case 0-0:
p->color = COLOR::BLACK;
return;
}
if(p->getSibling()->color == COLOR::RED) {
//case 0-1:
p->parent->color = COLOR::RED;
p->getSibling()->color = COLOR::BLACK;
if(p == p->parent->leftSubTree) rotateLeft(p->parent);
else rotateRight(p->parent);
}
if( p->parent->color == COLOR::BLACK &&
p->getSibling()->color == COLOR::BLACK &&
p->getSibling()->leftSubTree->color == COLOR::BLACK &&
p->getSibling()->rightSubTree->color == COLOR::BLACK) {
//case 1-1:
p->getSibling()->color = COLOR::RED;
resetStatus_forDelete(p->parent);
} else if(p->parent->color == COLOR::RED && p->getSibling()->color == COLOR::BLACK&& p->getSibling()->leftSubTree->color == COLOR::BLACK && p->getSibling()->rightSubTree->color == COLOR::BLACK) {
//case 1-2:
p->getSibling()->color = COLOR::RED;
p->parent->color = COLOR::BLACK;
} else {
if(p->getSibling()->color == COLOR::BLACK) {
if(p == p->parent->leftSubTree && p->getSibling()->leftSubTree->color == COLOR::RED && p->getSibling()->rightSubTree->color == COLOR::BLACK) {
//case 1-3:
p->getSibling()->color = COLOR::RED;
p->getSibling()->leftSubTree->color = COLOR::BLACK;
rotateRight(p->getSibling()->leftSubTree);
} else if(p == p->parent->rightSubTree && p->getSibling()->leftSubTree->color == COLOR::BLACK && p->getSibling()->rightSubTree->color == COLOR::RED) {
//case 1-4:
p->getSibling()->color = COLOR::RED;
p->getSibling()->rightSubTree->color = COLOR::BLACK;
rotateLeft(p->getSibling()->rightSubTree);
}
}
p->getSibling()->color = p->parent->color;
p->parent->color = COLOR::BLACK;
//case 1-5:
if(p == p->parent->leftSubTree){
//case 0-3
p->getSibling()->rightSubTree->color = COLOR::BLACK;
rotateLeft(p->getSibling());
} else {
//case 0-4
p->getSibling()->leftSubTree->color = COLOR::BLACK;
rotateRight(p->getSibling());
}
}
}
};
} // namespace myDS
#endif
```]
== `_PRIV_TEST.cpp`
#sourcecode[```cpp
// #include <d:\Desktop\Document\Coding\C++\ProjectC\myDS\myVector.h>
// #include "myVector.h"
#define __PRIVATE_DEBUGE
// #define __DETIL_DEBUG_OUTPUT
#include "Dev\08\RB_Tree.h"
#include "Dev\08\eg2.h"
#include <iostream>
#include <vector>
using namespace myDS;
int main()
{
// testingVector tc;
int i = 0;
// bst rbt;
RBtree<int> rbt;
while (1)
{
// i++;
char q;
std::cin >> q;
switch (q)
{
case 'i':
{
int t;
std::cin >> t;
rbt.insert(t);
}
break;
case 'p':
std::cout << "===DFS Order===\n";
rbt.printDfsOrder();
std::cout << "===Iter Order===\n";
rbt.printIterOrder();
// std::cout << "===Use Itera===\n";
// for(auto x:rbt) std::cout << x << " ";
// cout << "\n";
std::cout << "===Use Bg Ed===\n";
for(auto x = rbt.begin();x != rbt.end();x ++)
{
auto & y = *x;
std::cout << y << " ";
}cout << "\n";
std::cout << "\n";
// rbt.inorder();
break;
case 'd':
{
int t;
std::cin >> t;
// rbt.delete_value(t);
rbt.erase(t);
}
}
```]
= 测试数据与运行结果
运行上述`_PRIV_TEST.cpp`测试代码中的正确性测试模块,得到以下内容:
```
i 1
i 2
i 3
i 4
i 5
i 6
p
===DFS Order===
[2 : BLACK] [1 : BLACK] [NIL]
[NIL]
[4 : RED] [3 : BLACK] [NIL]
[NIL]
[5 : BLACK] [NIL]
[6 : RED] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[2 : BLACK] [NIL]
[3 : BLACK] [NIL]
[4 : RED] [NIL]
[5 : BLACK] [NIL]
[6 : RED] [NIL]
d 2
p
===DFS Order===
[3 : BLACK] [1 : BLACK] [NIL]
[NIL]
[5 : RED] [4 : BLACK] [NIL]
[NIL]
[6 : BLACK] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[3 : BLACK] [NIL]
[4 : BLACK] [NIL]
[5 : RED] [NIL]
[6 : BLACK] [NIL]
d 5
p
===DFS Order===
[3 : BLACK] [1 : BLACK] [NIL]
[NIL]
[6 : BLACK] [4 : RED] [NIL]
[NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[3 : BLACK] [NIL]
[4 : RED] [NIL]
[6 : BLACK] [NIL]
d 3
p
===DFS Order===
[4 : BLACK] [1 : BLACK] [NIL]
[NIL]
[6 : BLACK] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[4 : BLACK] [NIL]
[6 : BLACK] [NIL]
d 2
p
===DFS Order===
[4 : BLACK] [1 : BLACK] [NIL]
[NIL]
[6 : BLACK] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[4 : BLACK] [NIL]
[6 : BLACK] [NIL]
i 2
p
===DFS Order===
[4 : BLACK] [1 : BLACK] [NIL]
[2 : RED] [NIL]
[NIL]
[6 : BLACK] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[2 : RED] [NIL]
[4 : BLACK] [NIL]
[6 : BLACK] [NIL]
i 1
i 2
i 3
i 5
i 4
p
===DFS Order===
[2 : BLACK] [1 : BLACK] [NIL]
[NIL]
[4 : BLACK] [3 : RED] [NIL]
[NIL]
[5 : RED] [NIL]
[NIL]
===Iter Order===
[NIL]
[1 : BLACK] [NIL]
[2 : BLACK] [NIL]
[3 : RED] [NIL]
[4 : BLACK] [NIL]
[5 : RED] [NIL]
===Use Bg Ed===
1 2 3 4 5
```
可以看出,代码运行结果与预期相符,可以认为代码正确性无误。
运行`_PRIV_TEST.cpp`中的内存测试模块,在保持CPU高占用率运行一段时间后内存变化符合预期,可以认为代码内存安全性良好。
#image("03.png")
|
|
https://github.com/typst-community/valkyrie | https://raw.githubusercontent.com/typst-community/valkyrie/main/tests/schemas/author/test.typ | typst | Other | #import "/src/lib.typ" as z
#import "/tests/utility.typ": *
#show: show-rule.with();
= Integration
== Author schema
#[
#z.parse(
(
name: "<NAME>",
email: "<EMAIL>",
// test: true,
),
z.schemas.author,
ctx: z.z-ctx(strict: true),
)
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/ctheorems/1.0.0/README.md | markdown | Apache License 2.0 | # ctheorems
An implementation of numbered theorem environments in
[typst](https://github.com/typst/typst).
### Features
- Numbered theorem environments can be created and customized.
- Environments can share the same counter, via same `identifier`s.
- Environment counters can be _attached_ (just as subheadings are attached to headings) to other environments, headings, or keep a global count via `base`.
- The depth of a counter can be manually set, via `base_level`.
- Environments can be `<label>`'d and `@reference`'d.
- Awesome presets (coming soon!)
## Manual and Examples
Get acquainted with `ctheorems` by checking out the minimal example below!
You can read the [manual](assets/manual.pdf) for a full walkthrough of functionality offered by this module; flick through [manual_examples](assets/manual_examples.pdf) to just see the examples.

### Preamble
```typst
#import "@preview/ctheorems:1.0.0": *
#show: thmrules
#set page(width: 16cm, height: auto, margin: 1.5cm)
#set heading(numbering: "1.1.")
#let theorem = thmbox("theorem", "Theorem", fill: rgb("#eeffee"))
#let corollary = thmplain(
"corollary",
"Corollary",
base: "theorem",
titlefmt: strong
)
#let definition = thmbox("definition", "Definition", inset: (x: 1.2em, top: 1em))
#let example = thmplain("example", "Example").with(numbering: none)
#let proof = thmplain(
"proof",
"Proof",
base: "theorem",
bodyfmt: body => [#body #h(1fr) $square$]
).with(numbering: none)
```
### Document
```typst
= Prime numbers
#definition[
A natural number is called a #highlight[_prime number_] if it is greater
than 1 and cannot be written as the product of two smaller natural numbers.
]
#example[
The numbers $2$, $3$, and $17$ are prime.
@cor_largest_prime shows that this list is not exhaustive!
]
#theorem("Euclid")[
There are infinitely many primes.
]
#proof[
Suppose to the contrary that $p_1, p_2, dots, p_n$ is a finite enumeration
of all primes. Set $P = p_1 p_2 dots p_n$. Since $P + 1$ is not in our list,
it cannot be prime. Thus, some prime factor $p_j$ divides $P + 1$. Since
$p_j$ also divides $P$, it must divide the difference $(P + 1) - P = 1$, a
contradiction.
]
#corollary[
There is no largest prime number.
] <cor_largest_prime>
#corollary[
There are infinitely many composite numbers.
]
```
## Credits
- [sahasatvik (<NAME>)](https://github.com/sahasatvik)
- [MJHutchinson (<NAME>)](https://github.com/MJHutchinson)
- [rmolinari (<NAME>)](https://github.com/rmolinari)
- [DVDTSB](https://github.com/DVDTSB)
|
https://github.com/Ryoga-itf/numerical-analysis | https://raw.githubusercontent.com/Ryoga-itf/numerical-analysis/main/report1/report.typ | typst | #import "../template.typ": *
#import "@preview/codelst:2.0.1": sourcecode, sourcefile
#show: project.with(
week: 1,
authors: (
(
name: sys.inputs.STUDENT_NAME,
id: sys.inputs.STUDENT_ID,
affiliation: "情報科学類2年"
),
),
date: "2024 年 5 月 20 日",
)
== 課題1
=== (1.1)
作成した関数のソースコードは以下の通り:
#sourcefile(read("src/1-1.jl"), file:"src/1-1.jl")
=== (1.2)
#figure(
image("fig/fig1.svg", width: 60%),
caption: "n の値と差の絶対値の関係のグラフ"
)
コードは以下のようになった:
#sourcefile(read("src/1-2.jl"), file:"src/1-2.jl")
== 課題2
=== (2.1)
/ 残差:
- $x_1$: $-2.2365583777356202 times 10^(-13)$
- $x_2$: $0.0$
/ 絶対誤差:
- $x_1$: $1.8041124150158794 times 10^(-15)$
- $x_2$: $0.0$
/ 相対誤差:
- $x_1$: $2.2369538922194248 times 10^(-13)$
- $x_2$: $0.0$
以下のようなコードを用いて計算をした
#sourcefile(read("src/2-1.jl"), file:"src/2-1.jl")
=== (2.2)
/ 残差:
- $x_1$: $1.360267150654626 times 10^(-16)$
- $x_2$: $0.0$
/ 絶対誤差:
- $x_1$: $0.0$
- $x_2$: $0.0$
/ 相対誤差:
- $x_1$: $0.0$
- $x_2$: $0.0$
以下のようなコードを用いて計算した
#sourcefile(read("src/2-2.jl"), file:"src/2-2.jl")
=== (2.3)
$a, b$ の値と $b$ の値の差が大きいときほど解の公式で求めた結果が悪くなると考えられる。
|
|
https://github.com/rabotaem-incorporated/calculus-notes-2course | https://raw.githubusercontent.com/rabotaem-incorporated/calculus-notes-2course/master/sections/02-measure-theory/06-function-sequences.typ | typst | #import "../../utils/core.typ": *
== Последовательности функций
#let converges = sym.arrows.rr
#remind(label: "def-fn-converge")[
1. $f_n, f: E --> overline(RR)$, $f_n$ поточечно сходится к $f$, если $f(x) = lim_(n -> oo) f_n (x)$ для всех $x in E$.
2. $f_n, f: E --> RR$, $f_n converges f$ на $E$ (равномерно сходится на $E$) если $sup_(x in E) abs(f_n (x) - f(x)) -->_(n->+oo) 0$.
]
#def(label: "def-ae-converge")[
Пусть $f_n, f: E --> overline(RR)$. $f_n$ сходится к $f$ _почти везде по мере $mu$_, если $exists e subset E$, такое, что $mu e = 0$ и $f(x) = lim_(n -> oo) f_n (x)$ для любого $E without e$.
]
#def(label: "def-converge-by-measure")[
$f_n, f: E --> overline(RR)$. $f_n$ сходится к $f$ по мере $mu$, если $ forall eps > 0 space mu E {abs(f_n - f) > eps} -->_(n -> oo) 0. $
]
#notice(label: "convergence-implications")[
#sublabel("uniform-pointwise")
#sublabel("pointwise-ae")
#sublabel("uniform-measure")
Равномерная сходимость влечет поточечную, а поточечная влечет сходимость почти везде. Из равноменой сходимости следует сходимость по мере.
]
#show regex("\bПВ\b"): "почти везде"
#pr(name: "Единственность предела", label: "unique-lim")[
1. Если $f_n$ сходится почти везде#rf("def-ae-converge") к $f$ и $f_n$ сходится почти везде#rf("def-ae-converge") к $g$, то $mu E{f != g} = 0$.
2. Если $f_n$ сходится к $f$ по мере#rf("def-converge-by-measure") $mu$ и $f_n$ сходится к $g$ по мере#rf("def-converge-by-measure") $mu$, то $mu E{f != g} = 0$.
]
#proof[
1. Пусть вне $e_1$, $f_n$ сходится к $f$ поточечно, а вне $e_2$ $f_n$ сходится к $g$ поточечно. Тогда вне $e_1 union e_2$, $f_n --> f$ и $f_n --> g$, значит вне этого объединения, $f = g$. Тогда $f(x) != g(x) ==> x in e_1 union e_2$, и $mu E{e_1 union e_2} = 0$. Значит $mu E{f != g} = 0$.
2. Так как $E{f != g} = Union_(n = 1)^oo E{abs(f - g) > 1/n}$, достаточно доказать, что $mu E {abs(f - g) > 1/n} = 0$.
$ forall k quad E{abs(f - g) > 1/n} subset E{abs(f_k - f) > 1/(2n)} union E{abs(f_k - g) > 1/(2n)}. $
А $mu E{abs(f_k - f) > 1/(2n)} -->_(k->oo) 0$. Значит $mu E{abs(f - g) > 1/n} = 0$. Получили что $mu E{f != g} = 0$.
]
#denote(label: "def-Ll")[
$ Ll(E, mu) = {f: E --> overline(RR) space "измеримые"^rf("def-mfn"): mu E {f = plus.minus oo} = 0} $
]
#th(name: "Лебега", label: "lebesgue-convergence")[
Пусть $mu E < +oo$ и $f_n, f in Ll(E, mu)$#rf("def-Ll"). Если $f_n$ сходится к $f$ ПВ, то $f_n$ сходится к $f$ по мере $mu$.
]
#proof[
Поменяем функции (занулим, например) на всех неприятных точках: там где нет сходимости, на бесконечностях, и т.д. (это множество нулевой меры, так как $f in Ll(E, mu)$#rf("def-Ll")), что все функции станут конечными, и сходимость станет поточечной.
Рассмотрим случаи.
1. $f_n arrow.br 0$. Пусть $A_n := E{f_n > eps}$. По определению#rf("def-converge-by-measure"), надо доказать, что $mu A_n --> 0$. Тогда $A_n supset A_(n + 1)$. $eps < f_(n + 1) <= f_n$. Посмотрим на $sect.big_(n = 1)^oo A_n$. Это пустое множество, так как если какой-то $x$ лежит во всех $A_n$, то $f(x) > 0$, чего быть не может. Значит, из непрерывности меры сверху#rf("top-down-continious"), $lim mu A_n = 0$.
2.
Общий случай. $f_n$ произвольное. $lim_(n->oo) abs(f_n - f) = 0$. Тогда и верхний предел равен 0: $ limsup_(n -> oo) abs(f_n - f) = 0 = lim_(n->oo) underbrace(sup_(k >= n) abs(f_k - f), g_n). $
Тогда $g_n arrow.br 0$, следовательно $mu E {g_n > eps} --> 0$. Так как $ E {g_n > eps} = E {sup_(k >= n) abs(f_k - f) > eps} supset E{abs(f_n - f) > eps}. $
Отсюда получили то что нужно.
]
#notice[
1. Условие $mu E < +oo$ существенно. Например, $E = RR$, $mu = lambda_1$, $f_n = bb(1)_[n, +oo)$. $f_n$ сходится к 0 поточечно, но по мере не сходится.
2. Обратное неверно. Например, $E = [0, 1)$, $mu = lambda_1$, $f_n$ выглядит как
$
&bb(1)_[0, 1), \ &bb(1)_[0, 1/2), bb(1)_[1/2, 1), \ &bb(1)_[0, 1/3), bb(1)_[1/3, 2/3), bb(1)_[2/3, 1), \ &bb(1)_[0, 1/4), bb(1)_[1/4, 2/4), bb(1)_[2/4, 3/4), bb(1)_[3/4, 1), \ &dots
$
Сейчас мы заведем теорему, которая будет говорить что на самом деле обращать теорему можно, но только для подпоследовательности, а не для всей последовательности. Здесь, например, подойдет подпоследовательность
$
bb(1)_[0, 1), bb(1)_[0, 1/2), bb(1)_[0, 1/3), bb(1)_[0, 1/4), dots
$
]
#th(name: "Рисса", label: "riesz")[
Пусть $f_n, f in Ll(E, mu)$, $f_n$ сходится к $f$ по мере $mu$#rf("def-converge-by-measure"). Тогда существует $f_n_k$, сходящееся к $f$ почти везде#rf("def-ae-converge").
]
#proof[
$forall eps > 0 space mu E{abs(f_n - f) >= eps} -->_(n-->oo) 0$#rf("def-converge-by-measure"). Берем $n_k > n_(k - 1)$ так, что $ mu underbrace(E{abs(f_n_k - f) >= 1/k}, := A_k) <= 1/2^k $
Пусть $B_n := Union_(k = n + 1)^oo A_k$. $mu B_n <=^rf("volume-props", "monotonous''") sum_(k = n+1)^oo mu A_k <= 1/2^n$. Положим $B := sect.big_(n = 1)^oo B_n$. Тогда $ mu B <= mu B_n <= 1/2^n --> 0 ==> mu B = 0. $
Проверим, что вне $B$ будет поточечная сходимость. $B_1 supset B_2 supset B_3 supset ... $. Если $x in.not B$, то $x in.not B_n$ для некоторого $n$. Значит $x in.not A_k space forall k > n$, и $abs(f_(n_k) - f) < 1/k space forall k > n ==> lim f_(n_k) (x) = f(x).$
]
#follow(label: "inequality-in-converge-by-measure")[
Если $f_n <= g_n$ ПВ и $f_n$ сходится по мере $mu$ к $f$, $g_n$ сходится по мере $mu$ к $g$, то $f <= g$ ПВ.
]
#proof[
Выберем#rf("riesz") подпоследовательность $f_(n_k) --> f$ ПВ и $g_(n_k) --> g$ ПВ. Тогда $f_(n_k) <= g_(n_k)$ ПВ, значит $f <= g$ ПВ.
]
#th(name: "Фреше", label: "frechet")[
Пусть $f: RR^n --> RR$ и $f$ измерима#rf("def-mfn") относительно меры Лебега. Тогда существует последовательность $f_n$ непрерывных функций, сходящаяся к $f$ почти везде#rf("def-ae-converge").
]
#proof[Без доказательства.]
#th(name: "Егорова", label: "egorov")[
Пусть $f_n, f in Ll(E, mu)$#rf("def-Ll"), $mu E < +oo$ и $f_n$ сходится к $f$ ПВ#rf("def-ae-converge"). Тогда $forall eps > 0 space exists e subset E space mu e < eps$ и $f_n converges f$#rf("def-fn-converge") на $E without e$.
]
#proof[Без доказательства.]
#th(name: "Лузина", label: "luzin")[
Пусть $f: E subset RR^m --> RR$ измерима#rf("def-mfn") относительно меры Лебега $lambda$. Тогда для любого $eps > 0$ существует $A subset E$, такое что $lambda (E without A) < eps$ и $f bar_A$ непрерывна.
]
#proof[
Пусть $lambda E < +oo$. Продолжим $f$ нулем вне $E$. Получим измеримую функцию во всем пространстве#rf("non-integral-mfn-props", "mfn-is-mfn-restriction"). По теореме Фреше#rf("frechet") построим последовательность $f_n in C(RR^m)$, такую что $f_n --> f$ ПВ, в частности ПВ на $E$. По теореме Егорова#rf("egorov") найдется $e in E$ такое, что $lambda e < eps$ такое, что $f_n converges f$ на $E without e$. Значит $f bar_(E without e)$ непрерывна (так как при равномерной сходимости сохраняется непрерывность).
Если $lambda E = +oo$, можно разрезать $E$ на куски конечной меры (например, на кубики) и применить предыдущее рассуждение. Надо потребовать от кусочков, чтобы они пересекались с соседями, чтобы непрерывность сохранялась на границах. Если $ E_n = E sect "кубик со стороной 2 по целочисленной решетке" ==> \ exists e_n subset E_n space lambda e_n < eps / 2^n and f bar_(E_n without e_n) "непрерывна". $
]
|
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/common-software/lightburn.typ | typst |
= LightBurn
<software-lightburn>
LightBurn is layout, editing, and control software for the large format lasers:
https://lightburnsoftware.com/
LightBurn is only available on the desktops dedicated for use with the lasers.
LightBurn is capable of handling all stages of a laser project, from art design through to running the job on the laser.
LightBurn can also import vector and raster art from other sources: you can work on your project in other software and then import it into LightBurn when you're ready to run the job.
== Help and Tutorials
LightBurn software has a YouTube page (https://www.youtube.com/@lightburnsoftware7189/) with lots of content to help with projects. For those new to laser cutting and etching, these videos are a good place to start:
- Getting Started With LightBurn: Set up & First Project \
https://www.youtube.com/watch?v=v3RDzOrlCTM
- LightBurn UI Walkthrough \
https://www.youtube.com/watch?v=uzFsrUwONbw
- LightBurn Cut Settings \
https://www.youtube.com/watch?v=nybhYtjElQU
|
|
https://github.com/RhenzoHideki/dlp2 | https://raw.githubusercontent.com/RhenzoHideki/dlp2/main/relatorio-01/relatorio-01.typ | typst | #import "../typst-ifsc/template/article.typ": article
#show: doc => article(
title: "Relatorio 01",
subtitle: "DISPOSITIVOS LÓGICOS PROGRAMÁVEIS II (DLP029007 )",
// Se apenas um autor colocar , no final para indicar que é um array
authors:("<NAME>",),
date: "20 de Setembro de 2023",
doc,
)
= Caminho crítico dos operadores
Faça a implementação de um somador para valores de 16 bits sem sinal. Escreva 5 implementações em VHDL para as operações abaixo. Sintetize usando o Quartus e o dispositivo da DE2-115.
a) a+b
b) a + "0000000000000001"
c) a + "0000000010000000"
d) a + "1000000000000000"
e) a + "1010101010101010"
Verifique a área (LE) e atraso (ns) para cada implementação.
Discussão:
Qual implementação usou menos área? Por quê? Como o delay se comportou?
Comente as diferenças entre os valores de área e delay obtidos nas operações a), b) e c).
#pagebreak()
= Resultados
== Código
```vhdl
library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
entity AP1 is
generic
(
DATA_WIDTH : natural := 16
);
port
(
a : in std_logic_vector((DATA_WIDTH-1) downto 0);
b : in std_logic_vector((DATA_WIDTH-1) downto 0);
s : out std_logic_vector((DATA_WIDTH-1) downto 0)
);
end entity;
architecture rtl of AP1 is
signal soma : unsigned(DATA_WIDTH-1 downto 0);
--constant b: std_logic_vector(DATA_WIDTH-1 downto 0):= "0000000000000001";
--constant b: std_logic_vector(DATA_WIDTH-1 downto 0):= "0000000010000000";
--constant b: std_logic_vector(DATA_WIDTH-1 downto 0):= "1000000000000000";
--constant b: std_logic_vector(DATA_WIDTH-1 downto 0):= "1010101010101010";
begin
soma <= unsigned(a) + unsigned(b);
s <= std_logic_vector(soma);
end rtl;
```
#pagebreak()
== Tabela
#align(center)[
#table(
columns: (auto,auto,auto,auto),
align: center,
[],[Área(LE)],[Delay Completo (ns)],[Delay sem IO (ns)],
[A],[16 / 114,480 ( < 1 % )],[12.853],[9.24],
[B],[15 / 114,480 ( < 1 % )],[11.263],[6.966],
[C],[8 / 114,480 ( < 1 % )],[9.474],[5.803],
[D],[0 / 114,480 ( 0 % )],[8.510],[3.455],
[E],[14 / 114,480 ( < 1 % )],[11.932],[7.515],
)
]
== Qual implementação usou menos área? Por quê? Como o delay se comportou?
A implementação com menos área e delay é a implementação _D_. Isso ocorre pois ela é uma implementação que pode acontecer com somadores localizados nos buffers de IO da placa , isso se deve pois no IO buffers são encontrados somadores de 1 bits e a soma ocorre com o valor de b fixo de "1000000000000000". Por esse motivo , não aparece no relatorio gerado pelo Quartus nenhum elemento lógico sendo utilizado e também por não depender de nenhum somador seu delay acaba sendo baixo.
== Comente as diferenças entre os valores de área e delay obtidos nas operações a), b) e c)
A diferenças das operações de _A_, _B_ e _C_ se devem ao fato das diferentes posições possiveis com o valor de bit 1. A operação _A_ tem a maior área pois é necessária garantir que a soma cubra todos o valores de bits, pois existem 2 entradas aleatórias. A operação _B_ tem o valor de _b_ fixo de "0000000000000001" , dessa forma foi utilizado 1 somador a menos , pois ainda é necessário garantir a soma do carry caso ocorra. Por fim a operação c tem como valor "0000000010000000", como os bits que precedem o 1 são 0 não irão gerar nenhum Carry para a soma então é apenas necessário garantir somadores apartir do bit 1. |
|
https://github.com/storopoli/Bayesian-Statistics | https://raw.githubusercontent.com/storopoli/Bayesian-Statistics/main/slides/00-tools.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "@preview/polylux:0.3.1": *
#import themes.clean: *
#import "utils.typ": *
#new-section-slide("Tools")
#slide(title: "Recommended References")[
- #cite(<geTuringLanguageFlexible2018>, form: "prose") - Turing paper
- #cite(<carpenterStanProbabilisticProgramming2017>, form: "prose") - Stan paper
- #cite(<pymc3>, form: "prose") - PyMC paper
- #link("https://storopoli.github.io/Bayesian-Julia/pages/01_why_Julia/")[
Bayesian Statistics with Julia and Turing - Why Julia?
]
]
#focus-slide(background: julia-purple)[
#quote(
block: true,
attribution: [<NAME>-West],
)[A man and his tools make a man and his trade]
#quote(
block: true,
attribution: [<NAME>],
)[We shape our tools and then the tools shape us]
]
#focus-slide(background: julia-purple)[
#align(center)[#image("images/memes/standards.png")]
]
#slide(title: "Tools")[
- #link("https://mc-stan.org")[Stan] (BSD-3 License)
- #link("https://turinglang.org")[Turing] (MIT License)
- #link("https://www.pymc.io/")[PyMC] (Apache License)
- #link("https://mcmc-jags.sourceforge.io/")[JAGS] (GPL License)
- #link("https://www.mrc-bsu.cam.ac.uk/software/bugs/")[BUGS] (GPL License)
]
#slide(title: [Stan #footnote[#cite(<carpenterStanProbabilisticProgramming2017>, form: "prose")]])[
#side-by-side(columns: (4fr, 1fr))[
#text(size: 16pt)[
- High-performance platform for statistical modeling and statistical computation
- Financial support from
#link("https://numfocus.org/")[NUMFocus]:
- AWS Amazon
- Bloomberg
- Microsoft
- IBM
- RStudio
- Facebook
- NVIDIA
- Netflix
- Open-source language, similar to C++
- Markov Chain Monte Carlo (MCMC) parallel sampler
]
][
#image("images/logos/stan.png")
]
]
#slide(title: [Stan Code Example])[
#fit-to-height(1fr)[```cpp
data {
int<lower=0> N;
vector[N] x;
vector[N] y;
}
parameters {
real alpha;
real beta;
real<lower=0> sigma;
}
model {
alpha ~ normal(0, 20);
beta ~ normal(0, 2);
sigma ~ cauchy(0, 2.5);
y ~ normal(alpha + beta * x, sigma);
}
```
]
]
#slide(title: [Turing #footnote[#cite(<geTuringLanguageFlexible2018>, form: "prose")]])[
#side-by-side(columns: (4fr, 1fr))[
#text(size: 18pt)[
- Ecosystem of Julia packages for Bayesian Inference using probabilistic
programming
- #link("https://www.julialang.org")[Julia] is a fast dynamic-typed language that
just-in-time (JIT) compiles into native code using LLVM:
#link("https://www.nature.com/articles/d41586-019-02310-3")[
#quote[runs like C but reads like Python]
]\;
meaning that is _blazing_ fast, easy to prototype and read/write code
- Julia has Financial support from
#link("https://numfocus.org/")[NUMFocus]
- Composability with other Julia packages
- Several other options of Markov Chain Monte Carlo (MCMC) samplers
]
][
#image("images/logos/turing.png")
]
]
#slide(title: [Turing Ecosystem])[
#text(size: 16pt)[
We have several Julia packages under Turing's GitHub organization
#link("https://github.com/TuringLang")[TuringLang], but I will focus on 6 of
those:
- #link("https://github.com/TuringLang/Turing.jl")[Turing]: main package that we
use to *interface with all the Turing ecosystem* of packages and the backbone of
everything
- #link("https://github.com/TuringLang/MCMCChains.jl")[MCMCChains]: interface to
*summarizing MCMC simulations* and has several utility functions for
*diagnostics* and *visualizations*
- #link("https://github.com/TuringLang/DynamicPPL.jl")[DynamicPPL]: specifies a
domain-specific language for Turing, entirely written in Julia, and it is
modular
- #link("https://github.com/TuringLang/AdvancedHMC.jl")[AdvancedHMC]: modular and
efficient implementation of advanced Hamiltonian Monte Carlo (HMC) algorithms
- #link("https://github.com/TuringLang/DistributionsAD.jl")[DistributionsAD]:
defines the necessary functions to enable automatic differentiation (AD) of the
log PDF functions from
#link("https://github.com/JuliaStats/Distributions.jl")[Distributions]
- #link("https://github.com/TuringLang/Bijectors.jl")[Bijectors]: implements a set
of functions for transforming constrained random variables (e.g. simplexes,
intervals) to Euclidean space
]
]
#slide(title: [Turing #footnote[
I believe in Julia's potential and wrote a whole set of
#link("https://storopoli.github.io/Bayesian-Julia")[
Bayesian Statistics tutorials using Julia and Turing
] @storopoli2021bayesianjulia
] Code Example])[
#v(1em)
```julia
@model function linreg(x, y)
α ~ Normal(0, 20)
β ~ Normal(0, 2)
σ ~ truncated(Cauchy(0, 2.5); lower=0)
y .~ Normal(α .+ β * x, σ)
end
```
]
#slide(title: [PyMC #footnote[#cite(form: "prose", <pymc3>)]])[
#side-by-side(columns: (4fr, 1fr))[
- Python package for Bayesian statistics with a Markov Chain Monte Carlo sampler
- Financial support from #link("https://numfocus.org/")[NUMFocus]
- Backend was based on Theano
- Theano *died*, but PyMC developers create a fork named Aesara
- We have no idea what will be the backend in the future. PyMC developers are
still experimenting with other backends: TensorFlow Probability, NumPyro,
BlackJAX, and so on ...
][
#v(2em)
#image("images/logos/pymc.png")
]
]
#slide(title: [PyMC Code Example])[
```python
with pm.Model() as model:
alpha = pm.Normal("Intercept", mu=0, sigma=20)
beta = pm.Normal("beta", mu=0, sigma=2)
sigma = pm.HalfCauchy("sigma", beta=2.5)
likelihood = pm.Normal("y",
mu=alpha + beta * x1,
sigma=sigma, observed=y)
```
]
#slide(title: [Which Tool Should You Use?])[
#side-by-side(columns: (1fr, 1fr))[
#align(center)[#image("images/logos/turing.png", width: 80%)
Turing]
][
#align(center)[#image("images/logos/stan.png", width: 55%)
Stan]
]
]
#slide(title: [Why Turing])[
- *Julia* all the way down...
- Can *interface/compose* _any_ Julia package
- Decoupling of *modeling DSL, inference algorithms and data*
- Not only HMC-NUTS, but a whole *plethora of MCMC algorithms*, e.g.
Metropolis-Hastings, Gibbs, SMC, IS etc.
- Easy to *create/prototype/modify inference algorithms*
- *Transparent MCMC workflow*, e.g. iterative sampling API allows step-wise
execution and debugging of the inference algorithm
- Very easy to *do stuff in the GPU*, e.g. NVIDIA's CUDA.jl, AMD's AMDGPU.jl,
Intel's oneAPI.jl, and Apple's Metal.jl
- Very easy to do *distributed model inference and prediction*.
]
#slide(title: [Why _Not_ Turing])[
- *Not as fast*, but pretty close behind, as Stan.
- *Not enough learning materials*, example models, tutorials. Also documentation
is somewhat lacking in certain areas, e.g. Bijectors.jl.
- *Not as many citations as Stan*, although not very far behind in GitHub stars.
- *Not well-known in the academic community*.
]
#slide(title: [Why Stan])[
- API for R, Python and Julia.
- Faster than Turing.jl in 95% of models.
- *Well-known in the academic community*.
- *High citation count*.
- *More tutorials, example models, and learning materials available*.
]
#slide(title: [Why _Not_ Stan])[
- If you want to try *something new*, you'll have to do in *C++*.
- Constrained *only to HMC-NUTS* as MCMC algorithm.
- *Cannot decouple model DSL from data* (and also from inference algorithm).
- *Does not compose well with other packages*. For anything you want to do, it has
to "exist" in the Stan world, e.g. bayesplot.
- A *not so easy and intuitive ODE interface*.
- *GPU interface depends on OpenCL*. Also not easy to interoperate.
]
|
https://github.com/hongjr03/shiroa-page | https://raw.githubusercontent.com/hongjr03/shiroa-page/main/DIP/template.typ | typst | // TODO: 1. Make sure no page breaks between the blocks and their titles
#let font = (
main: "IBM Plex Sans",
mono: "IBM Plex Mono",
cjk: "Noto Sans SC",
quote: ("IBM Plex Serif", "Noto Serif SC"),
)
#let principle_class(body) = {
grid(columns: (1em, body.len() / 3 * 1em, 1fr), column-gutter: 8pt)[
#v(4pt) #line(length: 100%, stroke: 0.7pt)
][
*#body*
][
#v(4pt) #line(length: 100%, stroke: 0.7pt)
]
}
/* Blocks */
// Pls add or remove elements in this array first,
// if you want to add or remove the class of blocks
#let classes = ("Definition", "Lemma", "Theorem", "Corollary", "Principle")
#let h1_marker = counter("h1")
#let h2_marker = counter("h2")
#let note_block(body, class: "Block", fill: rgb("#FFFFFF"), stroke: rgb("#000000")) = {
let block_counter = counter(class)
locate(loc => {
// Returns the serial number of the current block
// The format is just like "Definition 1.3.1"
let serial_num = (h1_marker.at(loc).last(), h2_marker.at(loc).last(), block_counter.at(loc).last() + 1)
.map(str)
.join(".")
let serial_label = label(class + " " + serial_num)
v(2pt + 6pt)
text(12pt, weight: "bold")[#serial_label]
// serial_num
block_counter.step()
v(-8pt)
block(fill: fill, width: 100%, inset: 8pt, radius: 4pt, stroke: stroke, body)
})
}
// You can change the class name or color here
#let definition(body) = note_block(body, class: "定义", fill: rgb("#EDF1D6"), stroke: rgb("#609966"))
#let theorem(body) = note_block(body, class: "定理", fill: rgb("#FEF2F4"), stroke: rgb("#EE6983"))
#let lemma(body) = note_block(body, class: "引理", fill: rgb("#FFF4E0"), stroke: rgb("#F4B183"))
#let corollary(body) = note_block(body, class: "推论", fill: rgb("#F7FBFC"), stroke: rgb("#769FCD"))
#let principle_block(name, body, class: "Principle", fill: rgb("#fafffb"), stroke: rgb("#76d195")) = {
let block_counter = counter(class)
locate(loc => {
// Returns the serial number of the current block
// The format is just like "Definition 1.3.1"
let serial_num = str(block_counter.at(loc).last() + 1)
let serial_label = label(name)
v(2pt)
text(12pt, weight: "bold")[#class #serial_num #serial_label #block_counter.step()]
text(12pt, weight: "black")[#name]
v(-8pt)
block(fill: fill, width: 100%, inset: 8pt, radius: 4pt, stroke: stroke, body)
})
}
#let principle(name, body) = principle_block(name, body, class: "原理")
/* Figures */
// The numbering policy is as before, and the default display is centered
#let notefig(path, width: 100%) = {
let figure_counter = counter("Figure")
locate(loc => {
let serial_num = (h1_marker.at(loc).last(), h2_marker.at(loc).last(), figure_counter.at(loc).last() + 1)
.map(str)
.join(".")
let serial_label = label("Figure" + " " + serial_num)
block(width: 100%, inset: 8pt, align(center)[#image(path, width: width)])
set align(center)
text(12pt, weight: "bold")[图 #serial_num #serial_label #figure_counter.step()]
})
}
/* Proofs */
#let proof(body) = {
[*#smallcaps("Proof"):*]
[#body]
align(right)[*End of Proof*]
}
/* References of blocks */
// Automatically jump to the corresponding blocks
// The form of the input should look something like "Definition 1.3.1"
#let refto(class_with_serial_num, alias: none) = {
if alias == none {
link(label(class_with_serial_num), [*#class_with_serial_num*])
} else {
link(label(class_with_serial_num), [*#alias*])
}
}
/* Headings of various levels */
// Templates support up to three levels of headings,
// and notes with more than three headings are usually mess :)
#let set_headings(body) = {
set heading(numbering: "1.1.1")
// 1st level heading
show heading.where(level: 1): it => [
// Under each new h1, reset the sequence number of the blocks
#for class in classes {
counter(class).update(0)
}
#counter("h2").update(0)
#counter("Figure").update(0)
// Start a new page unless this is the first chapter
// #locate(loc => {
// let h1_before = query(heading.where(level: 1).before(loc), loc)
// if h1_before.len() != 1 {
// pagebreak()
// }
// })
// Font size and white space
#set text(20pt, weight: "bold")
#block[Chapter #counter(heading).display(): #it.body]
#v(25pt)
#h1_marker.step()
]
// 2st level heading
show heading.where(level: 2): it => [
#set text(17pt, weight: "bold")
#block[#it]
#h2_marker.step()
]
// 3st level heading
show heading.where(level: 3): it => [
#set text(14pt, weight: "bold")
#block[#it]
]
body
}
/* Cover page */
// Create a note cover with the course name, author, and time
// Modify parameters here if you want to add or modify information item
#let cover_page(title, author, professor, creater, time, abstract) = {
set page(paper: "a4", header: align(right)[
#smallcaps[#title]
#v(-6pt)
#line(length: 40%)
], footer: locate(loc => {
align(center)[#loc.page()]
}))
block(height: 25%, fill: none)
align(center, text(18pt)[*Lecture Notes: #title*])
align(center, text(12pt)[*By #author*])
align(center, text(11pt)[_Taught by Prof. #professor _])
v(7.5%)
abstract
block(height: 35%, fill: none)
align(center, [*#creater, #time*])
}
/* Outline page */
// Defualt depth is 2
#let outline_page(title) = {
// set page(
// paper: "a4",
// // Headers are set to right- and left-justified
// // on odd and even pages, respectively
// header: locate(loc => {
// if calc.odd(loc.page()) {
// align(right)[
// #smallcaps[#title]
// #v(-6pt)
// #line(length: 40%)
// ]
// } else {
// align(left)[
// #smallcaps[#title]
// #v(-6pt)
// #line(length: 40%)
// ]
// }
// }),
// footer: locate(loc => {
// align(center)[#loc.page()]
// }),
// )
show outline.entry.where(level: 1): it => {
v(12pt, weak: true)
strong("§ " + it)
}
align(center, text(18pt, weight: "bold")[#title])
v(15pt)
outline(title: none, depth: 2, indent: auto)
}
/* Body text page */
// Format the headers and headings of the body
#let body_page(title, body) = {
// set page(paper: "a4", header: locate(loc => {
// let h1_before = query(heading.where(level: 1).before(loc), loc)
// let h1_after = query(heading.where(level: 1).after(loc), loc)
// // Right- and left-justified on odd and even pages, respectively
// // Automatically matches the nearest level 1 title
// if calc.odd(loc.page()) {
// if h1_before == () {
// align(right)[_ #h1_after.first().body _ #v(-6pt) #line(length: 40%)]
// } else {
// align(right)[_ #h1_before.last().body _ #v(-6pt) #line(length: 40%)]
// }
// } else {
// if h1_before == () {
// align(left)[_ #h1_after.first().body _ #v(-6pt) #line(length: 40%)]
// } else {
// align(left)[_ #h1_before.last().body _ #v(-6pt) #line(length: 40%)]
// }
// }
// }), footer: locate(loc => {
// align(center)[#loc.page()]
// }))
set_headings(body)
}
/* All pages */
// Organize all types of pages
// If you want to add or modify other global Settings, please do so here
#let note_page(title, author, professor, creater, time, abstract, body) = {
set text(font: (font.main, font.cjk), lang: "zh", region: "cn", weight: 350)
set document(title: title, author: author)
set par(justify: true)
show math.equation.where(block: true) :it=>block(width: 100%, align(center, it))
set raw(tab-size: 4)
show raw: set text(font: (font.mono, font.cjk))
// Display inline code in a small box
// that retains the correct baseline.
show raw.where(block: false): box.with(fill: luma(240), inset: (x: 3pt, y: 0pt), outset: (y: 3pt), radius: 2pt)
let cjk-markers = regex("[“”‘’.,。、?!:;(){}[]〔〕〖〗《》〈〉「」【】『』─—_·…\u{30FC}]+")
show cjk-markers: set text(font: font.cjk)
show raw: it => {
show cjk-markers: set text(font: font.cjk)
it
}
// Display block code in a larger block
// with more padding.
// and with line numbers.
// Thank you @Andrew15-5 for the idea and the code!
// https://github.com/typst/typst/issues/344#issuecomment-2041231063
let style-number(number) = text(gray)[#number]
show raw.where(block: true): it => block(
fill: luma(240),
inset: 10pt,
radius: 4pt,
width: 100%,
)[#grid(
columns: (1em, 1fr),
align: (right, left),
column-gutter: 0.7em,
row-gutter: 0.6em,
..it.lines.enumerate().map(((i, line)) => (style-number(i + 1), line)).flatten(),
)]
// cover_page(title, author, professor, creater, time, abstract)
// outline_page("Outline")
body_page(title, body)
} |
|
https://github.com/LilNick0101/Bachelor-thesis | https://raw.githubusercontent.com/LilNick0101/Bachelor-thesis/main/content/appendix.typ | typst | = Appendice
== Lista requisiti <requirements-list>
I requisiti sono classificati con la seguente codifica:
#align(
center
)[
*R[Tipo]-numero*
]
- *R*: Acronimo di _Requisito_
- *Tipo*: Tipo di requisito, può essere:
- *F*: _Funzionale_
- *V*: _Vincolo_
- *Q*: _Qualità_
#let RFcounter = counter("RFcounter")
#let printRF() = block[
#RFcounter.step()
*RF-#RFcounter.display()*
]
#let RVcounter = counter("RVcounter")
#let printRV() = block[
#RVcounter.step()
*RV-#RVcounter.display()*
]
#let RQcounter = counter("RQcounter")
#let printRQ() = block[
#RQcounter.step()
*RQ-#RQcounter.display()*
]
#show figure: set block(breakable: true)
#figure(
table(
fill: (_, row) => if calc.odd(row) { luma(240) } else { white },
columns: (0.3fr, 1fr, 0.3fr),
align: horizon,
[*Requisito*], [*Descrizione*], [*Funzionalità*],
[#printRF()],[L'utente vuole visualizzare la lista dei luoghi], [F1], //
[#printRF()],[L'utente vuole selezionare un luogo dalla lista per vederne i dettagli], [F1], //
[#printRF()],[L'utente vuole visualizzare i dettagli di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare la posizione geografica un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare i contatti di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare le caratteristiche di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare gli orari di apertura di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare le immagini di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare il numero di recensioni di un luogo], [F3], //
[#printRF()],[L'utente vuole visualizzare la mappa dei luoghi],[F2], //X
[#printRF()],[L'utente vuole selezionare un luogo dalla mappa per vederne i dettagli],[F2], //X
[#printRF()],[L'utente visualizza un messaggio a causa di un errore nel caricamento dei dati], [F1, F2, F3], //
[#printRF()],[L'utente visualizza un messaggio che indica che la lista dei luoghi è vuota], [F1], //
[#printRF()],[L'ospite vuole effettuare il login all'suo profilo utente], [F5], //X
[#printRF()],[L'ospite vuole effettuare il login all'suo profilo utente utilizzando un Account _Google_], [F5], //X
[#printRF()],[L'ospite vuole creare un nuovo account per registrarsi sull'applicazione], [F7],
[#printRF()],[L'ospite inserisce un nome utente per registrarsi], [F7],
[#printRF()],[L'ospite inserisce una e-mail per registrarsi], [F7],
[#printRF()],[L'utente vuole effettuare il logout dal suo profilo utente], [F6], //X
[#printRF()],[L'utente registrato vuole visualizzare il suo profilo utente], [F6], //X
[#printRF()],[L'utente registrato visualizza i suoi dati personali], [F6], //X
[#printRF()],[L'utente registrato vuole caricare un nuovo luogo], [F4], //X
[#printRF()],[L'utente registrato inserisce il nome del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce una descrizione del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce la posizione geografica del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce le caratteristiche del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce gli orari di apertura del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce i contatti del luogo da caricare], [F4], //X
[#printRF()],[L'utente registrato inserisce una o più immagini del luogo da caricare], [F4], //X
[#printRF()],[L'utente visualizza un messaggio che indica che non ha inserito tutte le informazioni richieste del luogo da caricare], [F4], //X
[#printRF()],[L'utente visualizza un messaggio a causa di un errore nel caricamento del nuovo luogo], [F4], //X
[#printRF()],[L'utente registrato vuole salvare un luogo nei preferiti], [F1, F2, F3],
[#printRF()],[L'utente registrato vuole rimuovere un luogo dai preferiti], [F1, F2, F3],
[#printRF()],[L'utente registrato vuole visualizzare la lista dei luoghi preferiti salvati], [F6], //X
[#printRF()],[L'utente registrato vuole selezionare un luogo dalla lista dei luoghi preferiti salvati], [F6], //X
[#printRF()],[L'utente vuole visualizzare la lista dei luoghi caricati da lui], [F6], //X
[#printRF()],[L'utente vuole selezionare un luogo dalla lista dei luoghi caricati da lui], [F6], //X
[#printRF()],[L'utente vuole visualizzare la lista delle recensioni di un luogo], [F8],
[#printRF()],[L'utente registrato vuole caricare una nuova recensione di un luogo], [F9],
[#printRF()],[L'utente registrato vuole inserire il testo di una nuova recensione], [F9],
[#printRF()],[L'utente registrato vuole inserire una valutazione insieme alla recensione], [F9],
[#printRF()],[L'utente registrato visualizza un messaggio a causa di un errore nel caricamento della nuova recensione], [F9],
[#printRF()],[L'utente vuole ordinare la lista dei luoghi per distanza], [F1], //
[#printRF()],[L'utente vuole ordinare la lista dei luoghi per valutazione], [F1], //
[#printRF()],[L'utente vuole ordinare la lista dei luoghi per data di caricamento], [F1], //
[#printRF()],[L'utente vuole filtrare la lista o la mappa dei luoghi per nome], [F1, F2], //X
[#printRF()],[L'utente vuole filtrare la lista o la mappa dei luoghi per prezzo], [F1, F2], //X
[#printRF()],[L'utente vuole filtrare la lista o la mappa dei luoghi per le caratteristiche scelte], [F1, F2], //X
[#printRF()],[L'utente vuole filtrare la lista o la mappa dei luoghi per orario di apertura], [F1, F2] //X
),
caption: [Requisiti funzionali dell'applicazione _Android_.]
)
#pagebreak()
#figure(
table(
fill: (_, row) => if calc.odd(row) { luma(240) } else { white },
columns: (0.3fr, 1fr),
align: horizon,
[*Requisito*], [*Descrizione*],
[#printRV()], [L'applicazione deve essere sviluppata utilizzando il toolkit UI _Jetpack Compose_], //
[#printRV()], [L'applicazione deve essere sviluppata utilizzando il linguaggio _Kotlin_], //
[#printRV()], [L'applicazione finale deve essere utilizzabile da dispositivi _Android_ dalla versione 13.0], //
[#printRV()], [Le componenti sviluppate devono essere documentate]
),
caption: [Requisiti di vincolo dell'applicazione _Android_.]
)
#figure(
table(
fill: (_, row) => if calc.odd(row) { luma(240) } else { white },
columns: (0.3fr, 1fr),
align: horizon,
[*Requisito*], [*Descrizione*],
[#printRQ()], [L'applicazione deve essere fruibile anche in assenza di connessione ad Internet],
[#printRQ()], [Il codice dell'applicazione deve essere presente nel repository _Bitbucket_ aziendale], //
[#printRQ()], [Il codice del progetto deve passare tutte le _Pull requests_]
),
caption: [Requisiti di qualità dell'applicazione _Android_.]
)
== Tabella requisiti soddisfatti <requisiti-soddisfatti>
In seguito, viene riportata la tabella dei requisiti con il seguente grado di soddisfazione:
- *S*: Soddisfatto
- *NS*: Non soddisfatto
#figure(
table(
fill: (_, row) => if calc.odd(row) { luma(240) } else { white },
columns: (80pt, 80pt),
align: horizon,
[*Requisito*], [*S/NS*],
[RF-1],[S],
[RF-2],[S],
[RF-3],[S],
[RF-4],[S],
[RF-5],[S],
[RF-6],[S],
[RF-7],[S],
[RF-8],[S],
[RF-9],[S],
[RF-10],[S],
[RF-11],[S],
[RF-12],[S],
[RF-13],[S],
[RF-14],[S],
[RF-15],[S],
[RF-16],[NS],
[RF-17],[NS],
[RF-18],[NS],
[RF-19],[S],
[RF-20],[S],
[RF-21],[S],
[RF-22],[S],
[RF-23],[S],
[RF-24],[S],
[RF-25],[S],
[RF-26],[S],
[RF-27],[S],
[RF-28],[S],
[RF-29],[S],
[RF-30],[S],
[RF-31],[S],
[RF-32],[S],
[RF-33],[S],
[RF-34],[S],
[RF-35],[S],
[RF-36],[S],
[RF-37],[S],
[RF-38],[NS],
[RF-39],[NS],
[RF-40],[NS],
[RF-41],[NS],
[RF-42],[NS],
[RF-44],[S],
[RF-45],[S],
[RF-46],[S],
[RF-47],[S],
[RF-48],[S],
[RF-49],[S],
[RV-1],[S],
[RV-2],[S],
[RV-3],[S],
[RV-4],[NS],
[RQ-1],[S],
[RQ-2],[S],
[RV-3],[S],
),
caption: [Tabella requisiti soddisfatti e non soddisfatti.]
)
== MainActivity <main-activity>
```kt
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var amplifyManager: AmplifyManager
@OptIn(ExperimentalAnimationApi::class, ExperimentalMaterialNavigationApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SmartOfficesTheme() {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
val navController = rememberAnimatedNavController()
val navHostEngine = rememberAnimatedNavHostEngine(
/**
...
*/
)
DestinationsNavHost(
navGraph = NavGraphs.root,
navController = navController,
engine = navHostEngine
){
composable(AccountRedirectRouteDestination){
AccountRedirectRoute(
navigator = destinationsNavigator,
amplify = amplifyManager
)
}
}
}
}
}
}
}
```
Classe che estende `ComponentActivity` ed è la prima classe che genera contenuti a schermo: inizializza il tema dell'applicazione ed inizializza il `NavHost` e il `NavController` che gestiscono la navigazione tra i vari schermi. Ho implementato solamente la funzione `onCreate` che viene chiamata quando il processo viene creato, tenendo il comportamento di default per le altre funzioni. L'annotazione `@AndroidEntryPoint` permette di iniettare le dipendenze con _Hilt_, in questo caso ho iniettato l'oggetto `AmplifyManager` che gestisce le operazioni di autenticazione utenti per poi passarlo alla schermata di login/profilo utente.
== Destinazione di navigazione <navigation-destination>
```kt
@RootNavGraph(
start = true
)
@Destination
@Composable
fun PlacesListRoute(
viewModel: PlacesListViewModel = hiltViewModel(),
navigator: DestinationsNavigator
) {
val uiState by viewModel.uiState.collectAsState()
/**
...
*/
when(uiState.response){
is ListState.Success -> PlacesListScreen(
filters = uiState.filters,
showFilters = uiState.showFilters,
placesList = uiState.placesList,
onUploadScreenClick = {navigator.navigate(UploadPlaceRouteDestination)},
onFiltersClick = { viewModel.toggleFilters(true) },
onDismissFilters = { viewModel.toggleFilters(false) },
onSearchFilter = { viewModel.updateSearchFilter(it) },
onFilter = { viewModel.updateFilters(it) },
onSelectAccountBox = { navigator.navigate(AccountRedirectRouteDestination) },
onResetAllFilters = viewModel::resetAllFilters,
onApplyFilters = viewModel::applyFilters,
onClickCard = {navigator.navigate(PlacesDetailsRouteDestination(it))},
onAddFavoritesCard = {viewModel.onToggleLocation(it)},
onMapClick = { navigator.navigate(PlacesMapRouteDestination) },
onToggleBottomBar = viewModel::toggleBottomBar,
showBottomBar = uiState.showBottomBar,
onRetry = {
viewModel.resetAllFilters()
viewModel.getLocationList()
},
isLoggedIn = uiState.isLoggedIn
)
is ListState.Loading -> LoadingScreen(
modifier = Modifier
.fillMaxSize()
.size(100.dp)
)
else -> PlacesListErrorScreen(
message = R.string.location_list_error_msg,
onRetry = {
viewModel.resetAllFilters()
viewModel.getLocationList()
},
onAccountBoxClick = {
navigator.navigate(AccountRedirectRouteDestination)
},
onNavigationScreen = {
navigator.navigate(UploadPlaceRouteDestination)
}
)
}
}
```
Una destinazione è una funzione annotata con `@Destination` e prende come parametri il `navigator` usato per navigare da una schermata all'altra e il _ViewModel_ della schermata associata; dal _ViewModel_ poi viene estratto lo stato dell'interfaccia che viene fatto passare al _Composable_ della schermata. Oltre allo stato dell'interfaccia vengono passate anche le funzioni invocate all'input dell'utente. La notazione `@RootNavGraph` indica che si tratta del nodo iniziale, cioè la prima schermata visualizzata avviata l'applicazione.
== Classi ViewModel <view-model>
```kt
@HiltViewModel
class PlaceDetailsViewModel @Inject constructor(
private val getLocalDetailsStreamUseCase: GetLocalDetailsStreamUseCase,
private val toggleSavedLocationUseCase: ToggleSavedLocationUseCase,
private val fetchCurrentUserDataUseCase: FetchCurrentUserDataUseCase
) : ViewModel() {
private val _uiState: MutableStateFlow<PlaceDetailsUiState> =
MutableStateFlow(PlaceDetailsUiState())
val uiState: StateFlow<PlaceDetailsUiState> = _uiState.asStateFlow()
private val mutex = Mutex()
fun toggleGallery(enabled : Boolean){
_uiState.update {
it.copy(showGallery = enabled)
}
}
init {
viewModelScope.launch {
fetchCurrentUserDataUseCase().collect {
_uiState.update { state ->
state.copy(isLoggedIn = it)
}
}
}
}
fun toggleMap(enabled: Boolean){
_uiState.update {
it.copy(showMap = enabled)
}
}
fun toggleTimetable(enabled: Boolean){
_uiState.update {
it.copy(showHours = enabled)
}
}
fun toggleSavedLocation(){
viewModelScope.launch {
if(!mutex.isLocked) {
mutex.lock()
val details = uiState.value.details
details?.let {
val placeId = it.placeDetails.id
toggleSavedLocationUseCase(placeId)
}
mutex.unlock()
}
}
}
fun getLocationDetails(id : String) {
viewModelScope.launch {
getLocalDetailsStreamUseCase(id).collect { loc ->
_uiState.update { state ->
state.copy(response = ListState.Success, details = loc)
}
}
}
}
}
```
Le classi _ViewModel_ sono i titolari di stato di una schermata, estendono la classe `ViewModel` del framework _Android_ e il loro ciclo di vita è regolato dal framework stesso.
Con l'annotazione `@HiltViewModel` è possibile iniettare la classe nell'interfaccia grafica e con l'annotazione `@Inject` nel costruttore è possono iniettare le dipendenze con _Hilt_. In questo esempio la classe gestisce lo stato della schermata di dettaglio di un luogo.
All'interno della classe è contenuto lo stato dell'interfaccia grafica, che è uno `StateFlow`: la sua caratteristica è che ad ogni sua modifica l'interfaccia grafica viene aggiornata. La classe contiene anche metodi per modificare lo stato dell'interfaccia, dato che lo stato è mutabile solo all'interno della classe e all'esterno viene esposto solo lo stato in sola lettura.
== Classi UseCase <use-case>
```kt
@ViewModelScoped
class GetLocalListUseCase @Inject constructor(
private val locationRepository: LocationRepository,
private val savedLocationRepository: SavedLocationRepository,
private val userRepository: UserRepository
) {
suspend operator fun invoke(filters : PlacesListFilters) : Flow<List<PlaceListItemWithSavedModel>> {
return combine(locationRepository.getLocationListStream(filters),userRepository.getLoggedUserFlow()){
locStream, user ->
locStream.map {
PlaceListItemWithSavedModel(
place = it,
isSaved = if(user != null) savedLocationRepository.isLocationSaved(it.id) else false
)
}
}
}
}
```
Le classi `UseCase` sono classi particolari che contengono una sola funzione: vengono usate quando un _ViewModel_ richiede un'elaborazione dei dati più complessa o di dati che provengono da più repository diversi. La loro caratteristica è appunto di avere una sola funzione `invoke`, un operatore di _Kotlin_. In questo esempio il `UseCase` è usato per ottenere la lista dei luoghi, che è composta da dati provenienti da più repository, in questo caso il repository dei luoghi e quello degli utenti: viene usato il metodo `combine` di _Kotlin_ per combinare i dati provenienti da più flussi in un unico flusso. L'annotazione `@ViewModelScoped` permette di iniettare la classe con _Hilt_ e di mantenere lo stesso oggetto per tutta la durata del ciclo di vita del _ViewModel_, sempre con _Hilt_ vengono iniettati i repository con l'annotazione `@inject` nel costruttore.
== Classe Database <database-class>
```kt
@Database(
entities = [
LocationEntity::class,
PhotosEntity::class,
LinksEntity::class,
HourRangeEntity::class,
LoggedUserEntity::class,
UserFavoriteLocations::class,
UserFullNameEntity::class], version = 5)
abstract class SmartOfficesDatabase : RoomDatabase(){
abstract fun locationDao() : LocationDao
abstract fun userDao() : UserDao
}
```
La classe `SmartOfficesDatabase` estende `RoomDatabase` e rappresenta il database locale.
Questa classe contiene i metodi per ottenere i DAO, in questo caso dalla classe si può richiedere due DAO, uno per accedere alle tabelle dei luoghi e uno per accedere alle tabelle degli utenti. L'annotazione `@Database` permette di definire le entità del database.
La classe in sé è astratta, la classe concreta viene implementata tramite una build di _Gradle_.
== Schema ER database locale <db-scheme>
#figure(
image("../resources/images/local_db.svg", width: 80%),
caption: [Schema ER del database locale.]
)
Essendo un database relazionale, il database locale è composto da tabelle che sono collegate tra loro tramite chiavi esterne, queste tabelle sono state progettate per avere una struttura simile alle risposte JSON del API remota, dato che quando vengono prelevati i dati dal back-end remoto, questi vengono salvati nel database locale. in questo caso il database è composto da cinque tabelle, che sono:
- `location`: tabella che contiene i dati dei luoghi, con nome, descrizione, indirizzo, posizione geografica, contatti, caratteristiche, orari di apertura e numero di recensioni;
- `photos`: tabella che contiene i link delle immagini dei luoghi salvate su _Amazon S3_, una `location` ha una relazione uno a molti con `photos`;
- `links`: tabella che contiene i link a siti esterni, una `location` ha una relazione uno a molti con `links`;
- `LoggedUser`: tabella che contiene i dati dell'utente che ha effettuato l'accesso, cioè il nome, cognome, possibile e-mail, possibile numero di telefono e l'immagine del profilo;
- `UserFavoriteLocations`: tabella che contiene i luoghi preferiti salvati dall'utente, `LoggedUser` ha una relazione uno a molti con `UserFavoriteLocations`.
== Interfacce DAO <room-dao>
```kt
@Dao
interface LocationDao {
/*...
*/
@Transaction
@Query("""
SELECT * FROM location
...query lunga...
""")
fun getLocationsStream(
/**
...
*/
) : Flow<List<CompleteLocation>>
@Transaction
@Query("SELECT * FROM location WHERE uploader = :userId")
fun getUserUploadedLocations(userId : String) : Flow<List<CompleteLocation>>
@Transaction
@Query("""SELECT * FROM location INNER JOIN user_favorites ON location_id = id WHERE user_id = :userId """)
fun getUserFavoriteLocations(userId: String) : Flow<List<CompleteLocation>>
@Transaction
@Query("SELECT * FROM location WHERE id IN (:ids)")
fun getLocationsFromIds(ids : Set<String>) : Flow<List<CompleteLocation>>
@Transaction
@Query("SELECT * FROM location WHERE id = :id")
fun getLocationById(id : String) : Flow<CompleteLocation>
@Transaction
@Upsert
fun insertOrUpdateLocations(
locations : List<LocationEntity>,
hours : List<HourRangeEntity> = emptyList(),
photos : List<PhotosEntity> = emptyList(),
links : List<LinksEntity> = emptyList()
)
}
```
Le interfacce DAO di _Room_ vengono utilizzate per implementare il codice effettivo per fare le query dal database locale, il codice delle classi concrete viene generato con una build di _Gradle_. In questo caso la classe `LocationDao` contiene tutte le query necessarie per ottenere i dati dei luoghi. Le query sono scritte in SQL, ma _Room_ permette di scrivere query più complesse, come query che ritornano più tabelle, usando l'annotazione `@Transaction` che permette di eseguire più query in una transazione. Le query ritornano un `Flow`, un flusso di dati che ha la caratteristica che, quando viene aggiornato, chi lo osserva viene notificato. Il tipo di query viene indicato con l'annotazione `@Query`, `@Insert`, `@Delete`, `@Update` e `@Upsert`, quest'ultimo effettua l'_Insert_ se la chiave principale non è presente, altrimenti l'_Update_.
== Classi API <api-classes>
```kt
class LocationApiService(private val ktor: HttpClient) {
suspend fun getLocation(id: String): Result<PlaceDetailsResponse> {
return try {
val response = ktor.get("location/$id")
when (response.status.value) {
200 -> Result.success(response.body())
422 -> Result.failure(ValidationException(response.body<ValidationErrorResponse>().description[0]))
else -> Result.failure(Exception(response.body<ErrorResponse>().message))
}
}catch (ex: Exception){
Result.failure(ex)
}
}
suspend fun getLocationList(
/**
...
*/
): Result<PlacesListResponse> {
try {
val response = ktor.get("location/") {
/**
...
*/
}
return when (response.status.value) {
200 -> {
val responseBody = response.body<PlacesListResponse>()
Result.success(responseBody)
}
422 -> {
val responseBody = response.body<ValidationErrorResponse>()
Result.failure(ValidationException(responseBody.description[0]))
}
else -> {
val responseBody = response.body<ErrorResponse>()
Result.failure(Exception(responseBody.message))
}
}
}catch (ex :Exception) {
return Result.failure(ex)
}
}
suspend fun uploadNewLocation(module: ResponseModule, token: String?): Result<SuccessResponse> {
try {
val response = ktor.post("location/") {
contentType(ContentType.Application.Json)
header(HttpHeaders.Authorization, "Bearer $token")
setBody(module)
}
return when (response.status.value) {
201 -> Result.success(response.body())
422 -> Result.failure(ValidationException(response.body<ValidationErrorResponse>().description[0]))
else -> Result.failure(Exception(response.body<ErrorResponse>().message))
}
}catch (ex: Exception){
return Result.failure(ex)
}
}
}
```
Le classi API sono classi che contengono metodi per effettuare chiamate al API remota. Il client _Ktor_ fa una chiamata all'API remota con l'indirizzo del back-end più l'endpoint interessato. I metodi sono scritti in modo tale da ritornare un oggetto `Result` che è un oggetto che può contenere un valore o un'eccezione, sarà il chiamante poi a gestire i vari casi. Le chiamate sono scritte in modo da essere effetuate in modo asincrono. In questo esempio vengono gestite le chiamate sul endpoint `/location` che permette di ottenere i dati dei luoghi e di caricare nuovi luoghi: il primo metodo ottiene i dati di un luogo, il secondo ottiene la lista dei luoghi, il terzo carica un nuovo luogo, notare come per caricare un luogo bisogna accedere al proprio account così da poter usare un token valido. Le risposte vengono convertite in oggetti serializzabili e per inviare dati al back-end viene convertito un oggetto serializzabile in JSON.
Come per i luoghi, anche per gli utenti esiste una classe API che contiene i metodi per effettuare chiamate al API remota sul endpoint `/user`.
|
|
https://github.com/Error0229/- | https://raw.githubusercontent.com/Error0229/-/main/-.-.%20.-/..__.__._.typ | typst | The Unlicense |
#import "@preview/lovelace:0.2.0": *
#show: setup-lovelace
#set text(font: "New Computer Modern")
#align(center, text(16pt)[
*Design and Analysis of Computer Algorithms Assignment \#5*
])
#align(right, [資工三 110590004 林奕廷])
#set heading(numbering: "1.a.")
#set enum()
=
==
Since the bucket sort use the insertion sort to sort the elements in each
bucket, the worst case will happen when all the elements are in the same bucket.
In this case, the time complexity of the bucket sort will be $O(n^2)$.
==
To make the worst case time complexity of the bucket sort to be $O(n log n)$, we
can use the merge sort to sort the elements in each bucket. Since the quick sort
has the time complexity of $O(n log n)$, the time complexity of the bucket sort
will be $O(n log n)$.
=
To add a cost to the rod-cutting problem, we can simply update the optimal
substructure of the problem. The new optimal substructure is as follows:
$ "CutRod"(n) = max(p_n, max(p_i + "CutRod"(n - i - 1) - c) "for" i in 1... n-1) $
#algorithm(
caption: [Cutting a rod with cost],
pseudocode(
no-number,
[*input:*\ Sequence of prices $p_1, p_2, dots, p_n$,\ Length of the rod $n$, \ Cost
of cutting the rod $c$],
no-number,
[*output:* Maximum revenue that can be obtained by cutting the rod],
no-number,
[*define* $"dp"[0...n]$ as an array],
no-number,
[*function* $"Cutting-Rod-With-Cost"(P, n, c)$],
ind,
[*for* $i = 1$ *to* $n$],
ind,
[*let* $"q" = p_i$],
[*for* $j = 1$ *to* $i - 1$],
ind,
[$"q" = max(q, p_i + "dp"[i - j] - c)$],
ded,
[$"dp"[i] = q$],
ded,
[*return* $"dp"[n]$],
),
)
The time complexity of the above algorithm is $O(n^2)$.
#pagebreak()
=
To find the longest palindromic subsequence, we can construct the longest
palindromic subsequence from 1 to n, and the subsequence can be constructed by
the following rules:
- If the first and last characters are the same, then the longest palindromic
subsequence is the longest palindromic subsequence of the substring from the
second character to the second last character plus 2.
- If the first and last characters are different, then the longest palindromic
subsequence is the maximum of the longest palindromic subsequence of the
substring from the first character to the second last character and the
substring from the second character to the last character.
#algorithm(caption: [Longest palindromic subsequence], pseudocode(
no-number,
[*Input:* string $s$],
no-number,
[*Output:* longest palindromic subsequence],
$l <- "length of" s$,
$"dp is a 2D array of size" l times l$,
[*for* $i$ = 1 *to* $l$],
ind,
$"dp"[i][i] <- 1$,
ded,
[*for* $k = 2$ *to* $l$],
ind,
[*for* $i$ = 1 *to* $l - k + 1$],
ind,
$j <- i + k - 1$,
[*if* $s[i] = s[j]$ *then*],
ind,
$"dp"[i][j] <- "dp"[i + 1][j - 1] + 2$,
ded,
[*else*],
ind,
$"dp"[i][j] <- max("dp"[i + 1][j], "dp"[i][j - 1])$,
ded,
ded,
ded,
no-number,
[*Construct the longest palindromic subsequence*],
[*if* $"dp"[1][l] = 1$ *then*],
ind,
[*return* $s[1]$],
ded,
[*let* $"result" <- "empty string"$],
$i <- 1$,
$j <- l$,
[*repeat*],
ind,
[*if* $"dp"[i][j - 1] = "dp"[i][j]$ *then*],
ind,
$j <- j-1$,
ded,
[*else*],
ind,
$"result" <- s[j] + "result"$,
$i <- i + 1$,
$j <- j - 1$,
[*if* $"dp"[i][j] = 1$ *then*],
ind,
[*if* $"dp"[i - 1][j + 1] = 2$ *then*],
ind,
[*return* $"reverse(result)" + "result"$],
ded,
[*else*],
ind,
[*return* $"reverse(result)" + s[j] + "result"$],
ded,
ded,
ded,
[*end*],
))
The time complexity of the above algorithm is $O(n^2)$.
=
The minimum cost for file placement at server $S_i$ is the minimum cost for file
place at the all the server $S_j$ before $S_i$ plus the cost of accessing file
between $i$ to $j$ plus the file placement cost $c_i$. The algorithm is as
follows:
#algorithm(
caption: [Minimum placement cost],
pseudocode(
no-number,
[*Input:* Size $n$ sequence contains placement cost $c_i$ at server $S_i$, $1 <= i <= n$],
no-number,
[*Output:* Minimum cost for file copies placement],
$"dp is a array with size" n$,
$"dp[1]" <- c_i $,
[*for* $i = 2$ *to* $n$],
ind,
$"dp"[i] =c_i + min("dp"[i] + ((j-i)(j-i-1))/2)_(1 <= i < j)$,
ded,
[*return* $"dp"[n]$],
),
)
The time complexity of the above algorithm is $O(n^2)$.
|
https://github.com/typst-community/guidelines | https://raw.githubusercontent.com/typst-community/guidelines/main/src/chapters/style/modes.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/src/util.typ": *
#import mantys: *
= Mode Switching
Prefer staying in the primary mode of your current context, this avoids unnecessarily frequent use of `#` and unintended leading and trailing whitespace in #mode.mark.
#do-dont[
```typst
// we switched into code mode once and stay in it
#figure(caption: [...],
stack(dir: ltr,
table[...],
table[...],
)
)
```
][
```typst
// we switch back and forth, making writing and reading harder
#figure(caption: [...])[
#stack(dir: ltr)[
#table[...]
][
#table[...]
]
]
```
]
Use the most appropriate mode for your top level scopes, if a function has a lot of statements that don't evaluate to content, #mode.code is likely a better choice than #mode.mark.
#do-dont[
```typc
// we have a high ratio of text to code
let filler = [
// lots of text
]
// we have a high ratio of code to text
let computed = if val {
let x
let y
let z
// ...
}
```
][
```typc
// needless content mode
let func(a, b, c) = [
#let as = calc.pow(a, 2)
#let bs = calc.pow(b, 2)
#let cs = calc.pow(c, 2)
#return calc.sqrt(as + bs + cs)
]
```
]
|
https://github.com/tingerrr/hydra | https://raw.githubusercontent.com/tingerrr/hydra/main/tests/features/footer/test.typ | typst | MIT License | // Synopsis:
// - the query results are correct if an anchor is placed
#import "/src/lib.typ": hydra, anchor
#set page(
paper: "a7",
header: anchor(),
footer: context hydra(),
)
#set heading(numbering: "1.1")
#show heading.where(level: 1): it => pagebreak(weak: true) + it
#set par(justify: true)
= Introduction
#lorem(200)
= Content
== First Section
#lorem(50)
== Second Section
#lorem(150)
|
https://github.com/ukihot/igonna | https://raw.githubusercontent.com/ukihot/igonna/main/articles/algo/order.typ | typst | == 空間計算量
プログラムで問題を処理するとき、条件分岐$italic("if")$や繰り返し$italic("for")$を組み合わせることが多々ある。
問題が解けるまでに要する手順(ステップ)の数を時間計算量といい、かたや問題が解けるまでに必要なメモリサイズを空間計算量という。
空間計算量も時間計算量も少ないアルゴリズムが優れたアルゴリズムであるが、一般的にはメモリを多く費やせば短時間で解け、長時間かければ少ないメモリ容量で済むという「時間と空間のトレードオフ」の関係がある。
同じ問題に対して、複数のアルゴリズムが存在している中、解決したい問題のデータ量が増大しても計算量が膨大に膨れ上がらないアルゴリズムは優秀といえる。
=== ランダウ記法
ランダウ記法$cal(O)()$は、アルゴリズムの時間計算量や空間計算量を大まかに評価するために使われる。
アルゴリズムが入力サイズに対してどの程度の計算時間やメモリを必要とするかを表す。
|
|
https://github.com/MALossov/YunMo_Doc | https://raw.githubusercontent.com/MALossov/YunMo_Doc/main/template/body.typ | typst | Apache License 2.0 | #import "font.typ": *
#import "utils.typ": *
#counter(page).update(1)
// 章节计数器,记录公式层级
// -----------------
// 2023/4/11 update log:
// - 增加计数器,把元素序号转为 `x.x` 的格式
#let counter_chapter = counter("chapter")
#let counter_equation = counter(math.equation)
#let counter_image = counter(figure.where(kind: image))
#let counter_table = counter(figure.where(kind: table))
// 图片和表的格式
// -----------------
// 2023/4/11 update log:
// - 把元素序号转为 `x.x` 的格式
#show figure: it => [
#set text(font_size.wuhao)
#set align(center)
#if not it.has("kind") {
it
} else if it.kind == image {
it.body
[
#textbf("图")
#locate(loc => {
[#counter_chapter.at(loc).first().#counter_image.at(loc).first()]
})
#it.caption
]
} else if it.kind == table {
[
#textbf("表")
#locate(loc => {
[#counter_chapter.at(loc).first().#counter_table.at(loc).first()]
})
#it.caption
]
it.body
} else {
it.body
}
]
// 设置公式格式
// -----------------
// 2023/4/11 update log:
// - 修复为章节号 + 公示编号
#set math.equation(numbering: (..nums) => locate(loc => {
numbering("(1.1)", counter_chapter.at(loc).first(), ..nums)
}))
// 设置引用格式
// -----------------
// 2023/4/11 update log:
// - 原本对公式的引用是 `Equation (x.x)`,改为 `式x.x`
#show ref: it => {
locate(
loc => {
let elems = query(it.target, loc)
if elems == () {
it
} else {
let elem = elems.first()
let elem_loc = elem.location()
if numbering != none {
if elem.func() == math.equation {
link(
elem_loc,
[#textbf("式")
#counter_chapter.at(elem_loc).first().#counter_equation.at(elem_loc).first()
],
)
} else if elem.func() == figure {
if elem.kind == image {
link(
elem_loc,
[#textbf("图")
#counter_chapter.at(elem_loc).first().#counter_image.at(elem_loc).first()
],
)
} else if elem.kind == table {
link(
elem_loc,
[#textbf("表")
#counter_chapter.at(elem_loc).first().#counter_table.at(elem_loc).first()
],
)
}
}
} else {
it
}
}
},
)
}
#set heading(numbering: (..nums) =>
if nums.pos().len() == 1 {
"第" + zhnumbers(nums.pos().first()) + "部分"
} else {
nums.pos().map(str).join(".")
})
#show heading: it => {
if it.level == 1 {
set text(font: songti, size: font_size.sihao, weight: 600)
counter_chapter.step()
counter_equation.update(())
counter_image.update(())
counter_table.update(())
it
par(leading: 0.5em)[#text(size: 0.0em)[#h(0.0em)]]
} else if it.level == 2 {
set text(font: songti, size: font_size.xiaosi, weight: "bold")
it
par(leading: 0.5em)[#text(size: 0.0em)[#h(0.0em)]]
} else if it.level == 3 {
set text(font: heiti, size: font_size.xiaosi, weight: "bold")
it
par(leading: 0.5em)[#text(size: 0.0em)[#h(0.0em)]]
}
else if it.level == 4 {
set text(font: heiti, size: font_size.xiaosi, weight: "regular")
it
par(leading: 0.5em)[#text(size: 0.0em)[#h(0.0em)]]
}
}
// 设置正文格式
#set text(font: songti, size: font_size.xiaosi,weight: "regular",lang:"counter_equation")
#set par(justify: false, leading: 1em, first-line-indent: 2em,)
#show par: it => {
it
v(5pt)
}
#set enum(indent: 2em, body-indent: 0.5em, tight: true)
#set list(indent: 2em, body-indent: 0.5em, tight: true)
#show raw: set text(font: ("JetBrainsMono NF","Noto Sans CJK SC"),size: font_size.xiaowu)
// #show raw: set par(leading: 1em,hanging-indent: 3em)
#include "../contents/1OverView.typ"
#pagebreak()
#include "../contents/2BuildUp.typ"
#pagebreak()
#include "../contents/3FinishPoint.typ"
#pagebreak()
#include "../contents/4Conclusion.typ"
#include "reference.typ"
#pagebreak()
#include "../contents/6Appendix.typ" |
https://github.com/Myriad-Dreamin/tinymist | https://raw.githubusercontent.com/Myriad-Dreamin/tinymist/main/crates/tinymist-query/src/fixtures/type_check/control_flow.typ | typst | Apache License 2.0 | #let x0 = if true {
1
}
#let x1 = if false {
2
}
#let x2 = context if here().page() > 0 {
1
} else {
2
} |
https://github.com/TGM-HIT/typst-diploma-thesis | https://raw.githubusercontent.com/TGM-HIT/typst-diploma-thesis/main/src/utils.typ | typst | MIT License | /// *Internal function.* Returns whether the current page is one where a chapter begins. This is
/// used for styling headers and footers.
///
/// This function is contextual.
///
/// -> bool
#let is-chapter-page() = {
// all chapter headings
let chapters = query(heading.where(level: 1))
// return whether one of the chapter headings is on the current page
chapters.any(c => c.location().page() == here().page())
}
// this is an imperfect workaround, see
// - https://github.com/typst/typst/issues/2722
// - https://github.com/typst/typst/issues/4438
// it requires manual insertion of `#chapter-end()` at the end of each chapter
#let _chapter_end = <thesis-chapter-end>
/// Inserts an invisible marker that marks the end of a chapter. This is used for determining
/// whether a page is empty and thus whether it should have header and footer.
///
/// -> content
#let chapter-end() = [#metadata(none) #_chapter_end]
/// *Internal function.* Returns whether the current page is empty. This is determined by checking
/// whether the current page is between the previous chapter's end and the next chapter's beginning.
/// This is used for styling headers and footers.
///
/// This function is contextual.
///
/// -> bool
#let is-empty-page() = {
// page where the next chapter begins
let next-chapter = {
let q = query(heading.where(level: 1).after(here()))
if q.len() != 0 {
q.first().location().page()
}
}
// page where the current chapter ends
let current-chapter-end = {
let q = query(heading.where(level: 1).before(here()))
if q.len() != 0 {
let current-chapter = q.last()
let q = query(selector(_chapter_end).after(current-chapter.location()))
if q.len() != 0 {
q.first().location().page()
}
}
}
if next-chapter == none or current-chapter-end == none {
return false
}
// return whether we're between two chapters
let p = here().page()
current-chapter-end < p and p < next-chapter
}
/// *Internal function.* Checks whether all chapters and chapter ends are placed properly. The
/// document should contain an alternating sequence of chapters and chapter ends; if a chapter
/// doesn't have an end or vice-versa, this can lead to wrongly displayed/hidden headers and footers.
///
/// The result of this function is invisible if it succeeds.
///
/// -> content
#let enforce-chapter-end-placement() = context {
let ch-sel = heading.where(level: 1)
let end-sel = selector(_chapter_end)
let chapters-and-ends = query(ch-sel.or(end-sel))
let at-page(item) = "on page " + str(item.location().page())
let ch-end-assert(check, message) = {
if not check {
panic(message() + " (hint: set `strict-chapter-end: false` to build anyway and inspect the document)")
}
}
for chunk in chapters-and-ends.chunks(2) {
// the first of each pair must be a chapter
let ch = chunk.first()
ch-end-assert(
ch.func() == heading,
() => "extra chapter-end() found " + at-page(ch)
)
// each chapter must come in a pair
ch-end-assert(
chunk.len() == 2,
() => "no chapter-end() for chapter " + at-page(ch)
)
// the second item in the pair must be a chapter end
let end = chunk.last()
ch-end-assert(
end.func() == metadata,
() => "new chapter " + at-page(end) + " before the chapter " + at-page(ch) + " ended"
)
}
}
/// *Internal function.* This is intended to be called in a section show rule. It returns whether
/// that section is the first in the current chapter
///
/// This function is contextual.
///
/// -> bool
#let is-first-section() = {
// all previous headings
let prev = query(selector(heading).before(here(), inclusive: false))
// returns whether the previous heading is a chapter heading
prev.len() != 0 and prev.last().level == 1
}
|
https://github.com/antran22/typst-cv-builder | https://raw.githubusercontent.com/antran22/typst-cv-builder/main/lib/resume/certification.typ | typst | MIT License | #import "/lib/util.typ": *
#import "./components.typ": *
#let ResumeCertification(certification, date) = {
justified-header(certification, date)
}
#let ResumeCertificationSection(certifications, column_count: 1) = [
#stick_together(
threshold: 40pt,
[= Certifications],
grid(
columns: equal_columns(column_count: column_count),
rows: (auto),
row-gutter: 24pt,
..certifications.map(cert => {
ResumeCertification(cert.name, cert.date)
})
)
)
]
|
https://github.com/Duolei-Wang/modern-sustech-thesis | https://raw.githubusercontent.com/Duolei-Wang/modern-sustech-thesis/main/template/README.md | markdown | MIT License | # modern-sustech-thesis
功能需求、合作开发请移步模板对应的 github 仓库:[modern-sustech-thesis](https://github.com/Duolei-Wang/modern-sustech-thesis).
# 模板使用说明 (Usage)
## typst.app 网页版使用说明 (Use online)
使用步骤:
- 打开 typst.app 从模板新建项目(start from template)
- 论文所需字体需要手动上传到你的项目文件列表.
点击左侧 Explore Files,上传字体文件,上传后的字体文件存储位置没有特殊要求,typst 拥有优秀的内核,可以完成自动搜索.
由于格式渲染引擎的核心需要指定字体的名称,我在模板测试阶段使用了若干标准字体,这些字体可以在我的 github 仓库 [modern-sustech-thesis](https://github.com/Duolei-Wang/modern-sustech-thesis) /template/fonts 里找到.
此外,可以手动更改字体配置,在正文前使用 '#set' 命令即可,由于标题、正文字体不同,此处大致语法如下:
```typst
// headings
show heading.where(level: 1): it =>{
set text(
font: fonts.HeiTi,
size: fonts.No3,
weight: "regular",
)
align(center)[
// #it
#strong(it)
]
text()[#v(0.5em)]
}
show heading.where(level: 2): it =>{
set text(
font: fonts.HeiTi,
size: fonts.No4,
weight: "regular"
)
it
text()[#v(0.5em)]
}
show heading.where(level: 3): it =>{
set text(
font: fonts.HeiTi,
size: fonts.No4-Small,
weight: "regular"
)
it
text()[#v(0.5em)]
}
// paragraph
set block(spacing: 1.5em)
set par(
justify: true,
first-line-indent: 2em,
leading: 1.5em)
```
headings 设定了各个登记标题的格式,其中一级标题需要居中对齐.
'font: fonts.HeiTi' 即为字体的关键参数,参数的值是字体的名称(字符串). typst 将会在编译器内核、项目目录中搜索. typst 内核自带了 Source Sans(黑体)和 Source Serif(宋体)系列,但是中文论文所需的仿宋、楷体仍需自己上传.
# Quickstart of typst template
按照毕业设计要求,以 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 为摘要.
# 版本说明
版本号:0.1.1
- Fixed the fatal bug.
修正了参数传递失败造成的封面等页面无法正常更改信息.
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) 的同内容仓库里的模板.
- 感谢 [SHU-Bachelor-Thesis](https://github.com/shuosc/SHU-Bachelor-Thesis-Typst) 的结构组织让我学习到了很多,给我的页面组织提供了灵感,
- 在查找图片素材的时候,使用了 GuTaoZi 仓库 [SUSTech-thesis-typst](https://github.com/GuTaoZi/SUSTech-thesis-typst) 里的svg 素材,特此感谢.
本模板、仓库处于个人安利 typst 的需要——在线模板需上传至 typst/packages 官方仓库才能被搜索到,如有开发和接管等需求请务必联系我:
QQ: 782564506
mail: <EMAIL> |
https://github.com/timetraveler314/Note | https://raw.githubusercontent.com/timetraveler314/Note/main/Discrete/main.typ | typst | #import "@local/MetaNote:0.0.1" : *
#let detm = math.mat.with(delim: "|")
#show: doc => MetaNote(
title: [
Discrete Mathematics
],
authors: (
(
name: "timetraveler314",
affiliation: "University of Genshin",
email: "<EMAIL>",
),
),
doc,
)
#include "sets.typ"
#include "categories.typ"
#include "logic.typ" |
|
https://github.com/jomaway/typst-gentle-clues | https://raw.githubusercontent.com/jomaway/typst-gentle-clues/main/CHANGELOG.md | markdown | MIT License | # Changelog
## v.1.0.0 (2024/09/04)
- !refactor(predefined): use catppuccin palette as default theme colors.
- fix(predefined): show notify clue correctly now
- refactor(docs): add API docs with tidy
## v.0.9.0 (2024/07/01)
- feat: allow gradient and pattern as color settings.
- feat: add experiment clue
- feat: add idea clue
- feat: add code clue
- feat: set custom image as icon.
- refactor: moved color and icon definitions to a seperate `theme.typ` file.
*BREAKING:*
- refactor: To disable the task-counter `gc-task-counter-enabled.update(false)` needs to be called because moved states to `predefined.typ`
- refactor: change `quote` to `quotation` due to naming conflicts
- refactor: change `example` icon
- refactor: change `conclusion` icon and color
- refactor: change default title weight to a delta of 200
- refactor: change default icon to none.
## v0.8.0 (2024/04/26)
- feat: allow clues without an icon.
- feat: add goal clue
- fix: transparent background for body
- feat: set body-color
- feat: use typst quote function inside quote.
- refactor: update to linguify 0.4.0
- refactor: split into multiple files for better maintainability
## v0.7.1 (2024/03/26)
- fix: bug with linguify.
## v0.7.0 (2024/03/18)
- Use linguify:0.3.0 package to manage different languages.
- lang will be detected from `context text.lang` now.
- Removed `#gc_header-title-lang.update("de")`.
- Removed `#gc_enable-task-counter.update(false)` use `#show: gentle-clues.with(show-task-counter: false)` now.
- **Breaking:** Changed `_color` to `accent-color`. Only type color and gradient are supported.
- Added `border-color` and `header-color` to overwrite default color calculation from the accent-color.
- Added `origin` parameter to `quote`.
## v0.6.0 (2024/01/06)
- Added possibility to define default settings via `#show: gentle-clues.with()` - *lang*, *width*, *stroke-width*, *border-width*, *border-radius*, *breakable* - (See all options in [docs.pdf](docs.pdf))
- **Deprecated:** `#gc_header-title-lang.update("de")` use `#show: gentle-clues.with(lang: "de")` now.
- **Deprecated:** `#gc_enable-task-counter.update(false)` use `#show: gentle-clues.with(show-task-counter: false)` now.
- Added option to show all clues without headers. `#show: gentle-clues.with(headless: true)`
## v0.5.0 (2024/01/05)
- Added option `breakable: true` to make clues breakable .
- Added spanish header titles. Use with `#gc_header-title-lang.update("es")`
- Removed aliases (breaking)
## v0.4.0 (2023/11/17)
- Added french header titles. Use with `#gc_header-title-lang.update("fr")`
- Fixed minor border issues
- Added an task-counter (disable with `gc_enable-task-counter.update(false)`)
*Colors:*
- Changed default color to `navy`
- Fixed bug that the border was sometimes no longer visible after `typst 0.9.0` update.
- Changed default border-color to the same color as `bg-color`
- Added support for gradients: `#clue(_color: gradient.linear(..color.map.crest))`
- **Breaking:** Removed string color_profiles.
- Changed some predefined colors.
## v0.3.0 (2023/10/20)
- Renamed entry files and base template
- Changed default `header-inset`. It's `0.5em` now.
- Added `gc_header-title-lang` state, which defines the language of the title. Accepts `"de"` or `"en"` at the moment.
- Changed `type` checks which requires typst version `0.8.0`
- Renamed parameter `color` to `_color` due to naming conflicts with the color type.
## v0.2.0 (2023/09/26)
- Added option to set the header inset. `#admonish(header-inset: 0.5em)`
- Added custom color: `#admonish(color: (stroke: luma(150), bg: teal))`
- Added predefined example clue: `#example[Testing]`
## v0.1.0 (2023/09/15)
- Initial release
|
https://github.com/adrianvillanueva997/cv | https://raw.githubusercontent.com/adrianvillanueva997/cv/main/modules_en/professional.typ | typst | // Imports
#import "@preview/brilliant-cv:2.0.2": cvSection, cvEntry
#let metadata = toml("../metadata.toml")
#let cvSection = cvSection.with(metadata: metadata)
#let cvEntry = cvEntry.with(metadata: metadata)
#cvSection("Professional Experience")
#cvEntry(
title: [Data Engineer],
society: [Woven by Toyota],
date: [2024 - Present],
location: [Tokyo, Japan],
description: list(
[Leading an engineering team to build a scalable data platform in a data mesh architecture on AWS using Terraform, Terragrunt, and Databricks],
[Implementation of internal libraries and tools for data engineering and data science teams to improve productivity in Python, Java, Typescript, and Rust],
[Design and implement CI/CD pipelines for data engineering and data science projects to deploy and monitor data pipelines and models in Databricks],
),
tags: (
"Databricks",
"Terraform",
"Python",
"Java",
"AWS",
"Terragrunt",
"Typescript",
"GitHub Actions",
"CI/CD",
"Rust",
"kafka",
"Open Telemetry",
),
)
#cvEntry(
title: [Data Engineer],
society: [Ahold Delhaize],
date: [2022 - 2024],
location: [Amsterdam, Netherlands],
description: list(
[Analyze datasets with SQL/Python, collaborate for insights],
[Streamline CI/CD pipelines],
[Develop Python solutions with Kusto for automation/auditing],
[Create ETL pipelines on Databricks],
[Design internal tools for auditing/monitoring with Python],
[Maintain Terraform modules and CI/CD on GitHub Actions],
[Deploy resources on Azure/Kubernetes with ArgoCD],
),
tags: (
"Python",
"SQL",
"Databricks",
"Kusto",
"Terraform",
"GitHub Actions",
"Azure",
"Kubernetes",
"ArgoCD",
"kafka",
),
)
#cvEntry(
title: [Data Engineer],
society: [Dashmote],
date: [2021 - 2022],
location: [Amsterdam, Netherlands],
description: list(
[Infrastructure as Code (IaC) with Terraform on AWS, design and implement scripts for service deployments],
[Maintain and optimize legacy Apache Airflow components in Python],
[Deploy and optimize Docker images using buildkit, caching, and multi-stage builds],
[Collaborate and mentor team, design and deploy production-ready datalake on AWS],
[Redesign and implement DevOps strategies for faster workflows],
),
tags: ("Terraform", "AWS", "Python", "Apache Airflow", "Docker", "DevOps"),
)
#cvEntry(
title: [Software Engineer],
society: [Ernst & Young (EY)],
date: [2019 - 2020],
location: [Madrid, Spain],
description: list(
[Assisted with data cleaning, processing, and analysis using Python and Excel, participated in team meetings and contributed to project planning and execution],
[Contributed to software development for automation and ETL tasks using SQL, Python, Java, and Talend],
[Managed Linux systems, including Ubuntu and CentOS, ensuring stability and security],
[Developed and prototyped machine learning models for predictive analytics and data engineering],
[Full-stack web development],
),
tags: (
"Python",
"Excel",
"SQL",
"Java",
"Talend",
"Linux",
"Machine Learning",
"Full-stack",
),
)
|
|
https://github.com/Kirchoffs/typst-demo | https://raw.githubusercontent.com/Kirchoffs/typst-demo/main/document-hello-world/demo-1.typ | typst | = Introduction
In this report, we will explore the various factors that influence _fluid dynamics_ in glaciers and how they contribute to the formation and behavior of these natural structures.
+ The climate
- Temperature
- Precipitation
+ The topography
+ The geology
Glaciers as the one shown in @glaciers will cease to exist if we don't take action soon!
#figure(
image("resources/glacier.jpeg", width: 50%),
caption: [
_Glaciers_ form an important part
of the earth's climate system.
],
) <glaciers>
|
|
https://github.com/SWATEngineering/Docs | https://raw.githubusercontent.com/SWATEngineering/Docs/main/src/2_RTB/VerbaliEsterni/VerbaleEsterno_231206/content.typ | typst | MIT License | #import "meta.typ": inizio_incontro, fine_incontro, luogo_incontro, company
#import "functions.typ": glossary, team
#let participants = csv("participants.csv")
#let participants_company = csv("participants_company.csv")
= Partecipanti
/ Inizio incontro: #inizio_incontro
/ Fine incontro: #fine_incontro
/ Luogo incontro: #luogo_incontro
== Partecipanti di #team
#table(
columns: (3fr, 1fr),
[*Nome*], [*Durata presenza*],
..participants.flatten()
)
== Partecipanti di #emph[#company]
#for member in participants_company.flatten() [
- #member
]
= Sintesi Elaborazione Incontro
/*************************************/
/* INSERIRE SOTTO IL CONTENUTO */
/*************************************/
== Esposizione dei progressi raggiunti
Nell'incontro con la Proponente, il team ha illustrato in dettaglio l'evoluzione del Proof of Concept, evidenziandone gli importanti progressi compiuti nel corso dello sprint. La Proponente ha manifestato un apprezzamento molto positivo per i risultati raggiunti finora, confermando la validità della direzione intrapresa per il successo del progetto. Inoltre, sono stati dati feedback per migliorare quanto sviluppato, a livello grafico, per rendere più veloce e facile la comprensione dei vari pannelli.
In seguito, la riunione è proseguita con una dettagliata discussione riguardo la parte inerente la documentazione, ponendo particolare enfasi sull'_Analisi dei Requisiti_.
== Avanzamento del codice
Gli obiettivi prefissati comprendevano l'archiviazione dei dati provenienti da Kafka nel database OLAP ClickHouse, nonché lo sviluppo di una dashboard in Grafana. La dashboard avrebbe dovuto visualizzare una mappa della città indicando la posizione dei sensori di temperatura, presentare in modo chiaro le temperature medie rilevate e un grafico che mostrasse l'andamento sinusoidale della temperatura.
== Feedback della Proponente
La Proponente ha sollevato una critica sostanziale in merito alla comprensibilità della dashboard, evidenziando la difficoltà di interpretare il grafico sinusoidale a causa della sovrapposizione di dati. La soluzione proposta è quella di rendere le temperature più singolari e differenziare il modo in cui i sensori generano l'onda sinusoidale, accelerando il ciclo per rappresentare una "giornata" in pochi minuti, aumentando il tasso di generazione dei dati per una rappresentazione più dinamica. È stato inoltre consigliato di aggiungere un pannello descrittivo.
Per ottimizzare le query, è stato suggerito di integrare, ove necessario, le funzioni aggregate di movingAverage e di ridurre l'intervallo per una maggior visuale.
Inoltre, è stata proposta l'implementazione della capacità di filtraggio in Grafana, focalizzata sulla possibilità di effettuare confronti tra sensori.
== Obiettivo del prossimo sprint
La Proponente ha mostrato un forte entusiasmo per i progressi raggiunti in poche settimane, indicando che, dal loro punto di vista, si era già pronti per il PoC. In vista del prossimo sprint, hanno suggerito alcune potenziali migliorie estetiche per rendere più comprensibile il prodotto e la possibilità di aggiungere già un'altra tipologia di sensore.
== Documentazione
La Proponente risultava essere soddisfatta anche della nuova versione dell'_Analisi dei Requisiti_. L'unica perplessità riguardava il numero complessivo della tipologia di sensori, ritenuto eccessivamente elevato anche in termini di visualizzazione sulla dashboard, e alcuni casi d'uso considerati ridondanti.
Da notare che la Proponente ha sottolineato la preferenza per la qualità rispetto alla quantità. In altre parole, si è manifestato un interesse più marcato verso sensori altamente efficaci e pertinenti piuttosto che un vasto assortimento che potrebbe risultare difficile da gestire o che potrebbe includere elementi superflui.
La Proponente ha anche sottolineato che l'individuazione dei casi d'uso risulta essere più complessa a causa del fatto che il sistema è quasi esclusivamente backend.
|
https://github.com/Danmushu/missingSemester | https://raw.githubusercontent.com/Danmushu/missingSemester/main/git%26latex/main.typ | typst | #import "template.typ": *
/***** para *****/
#let title = "Git & Latex"
#let author = "梁子毅"
#let course_id = "系统开发工具基础"
#let instructor = "周小伟,范浩"
#let semester = "2024 Summer"
#let due_time = "Aug 28, 2024"
#let id = "22090001041"
#show: assignment_class.with(title, author, course_id, instructor, semester, due_time, id)
#set enum(numbering: "1.")
= Git
== 课后练习
#cprob[
克隆本课程网站的仓库
][
可以使用`git clone https://github.com/missing-semester-cn/missing-semester-cn.github.io.git`来克隆网站的仓库,运行结果如下@fig1
]
#figure(
image("./figure/img1.png", width: 70%),
caption: [
`git clone`
],
)<fig1>
#cprob[
将版本历史可视化并进行探索
][
可以使用`git log --all --graph --decorate`进行可视化,效果如@fig2
]
#figure(
image("./figure/img2.png", width: 70%),
caption: [
`git log --all --graph --decorate`
],
)<fig2>
#cprob[
探索谁最后修改了README.md 文件?(提示:使用`git log`命令并添加合适的参数)
][
有两种方式:
+ 直接用`git log`打开,会产生一个类似vim的编辑器,使用`/README.md`可以找到这个文件
+ 或者使用`git log -1 README.md`可以读取含有README.md的第一行如图@fig3
]
#figure(
image("./figure/img3.png", width: 70%),
caption: [
探索谁最后修改了README.md 文件
],
)<fig3>
#cprob[
最后一次修改 `_config.yml` 文件中 collections: 行时的提交信息是什么?(提示:使用 `git blame` 和 `git show`)
][
+ 可以使用`git blame _config.yml | grep collections`来显示
+ 也可以使用`git show --pretty=format:"%s" a88b4eac | head -1`
+ 二者运行如下@fig4
]
#figure(
image("./figure/img4.png", width: 70%),
caption: [
最后一次修改 `_config.yml` 文件中 collections: 行时的提交信息
],
)<fig4>
#cprob[
从 GitHub 上克隆某个仓库,修改一些文件。当您使用 `git stash` 会发生什么?通过 `git stash pop` 命令来撤销 `git stash` 操作,什么时候会用到这一技巧?
][
+ 使用`git stash`的时候,会将当前工作区清空,git会将刚刚工作区的文件存起来。
+ 当你完成其他分支的编写(比方说bug处理)再用`git stash pop`取出你之前隐藏的文件(比方说正在开发新功能的文件)
]
#cprob[
当您执行 `git log --all --oneline` 时会显示什么?
][
运行结果如下@fig5,因为输出太长,使用`tail -n 10`和管道来输出最后的10行内容
]
#figure(
image("./figure/img5.png", width: 70%),
caption: [
`git log --all --oneline`的运行结果
],
)<fig5>
#cprob[
与其他的命令行工具一样,Git 也提供了一个名为 ~/.gitconfig 配置文件 (或 dotfile)。请在 ~/.gitconfig 中创建一个别名,使您在运行 git graph 时,您可以得到 `git log --all --graph --decorate --oneline` 的输出结果;
][
+ 用`vim ~/.gitconfig`指令
+ 在其中输入
```shell
[alias]
graph = log --all --graph --decorate --oneline
```
+ 运行结果如下@fig6
]
#figure(
image("./figure/img6.png", width: 70%),
caption: [
通过vim来编辑.gitconfig文件
],
)<fig6>
#figure(
image("./figure/img7.png", width: 70%),
caption: [
起了别名后的运行结果
],
)<fig7>
== 实际运用
+ 连接github
- 我已经连接过了github,连接之后.gitconfig文件中会有如@fig8 的内容,连接的指令如下
```git
git config --global user.name "name"//自定义用户名
git config --global user.email "<EMAIL>"//用户邮箱
```
#figure(
image("./figure/img8.png", width: 70%),
caption: [
配置了过后的.gitconfig文件
],
)<fig8>
+ 建立本地版本库
- 使用`git init`建立,如@fig9
#figure(
image("./figure/img9.png", width: 50%),
caption: [
git init
],
)<fig9>
+ 查看当前状体
- 使用`git status`,如@fig10
#figure(
image("./figure/img10.png", width: 50%),
caption: [
git init
],
)<fig10>
+ 把项目源代码加入仓库
- 使用`git add .`,如@fig11
#figure(
image("./figure/img11.png", width: 50%),
caption: [
git init
],
)<fig11>
+ 提交仓库
- 使用`git commit -m "first commit"`对起脚进行说明,如@fig12
#figure(
image("./figure/img12.png", width: 50%),
caption: [
git init
],
)<fig12>
+ 配置ssh key
- git bash中指令`ssh-keygen -t rsa -C "<EMAIL>"
` 会生成一对ssh密钥,将公钥放到github上(具体内容网上可查,不再赘述)
+ 推送
- 使用`git push -u origin master`
- 如果是fork的别人的仓库,可以发起pull request申请merge
- git实例一共12个
= Latex
- 我已经使用过latex一段时间了,这里根据我之前用latex使用的实验报告作为实例
== 基本结构
- 代码如下:
```tex
\documentclass[12pt]{article}
\usepackage{amsmath,amsthm,amssymb,color,latexsym}%重要别删,对newenvironment有用
\usepackage[a4paper,left=1cm,right=1cm,top=0.5cm,bottom=1cm]{geometry}
\usepackage[all]{xy}
\usepackage{geometry}
\geometry{letterpaper}
\usepackage{graphicx}
\usepackage{url}
\usepackage{ctex}
\usepackage[colorlinks=true, allcolors=blue]{hyperref}
\usepackage{type1cm}
\fontsize{10.5pt}{15.75pt}
\newtheorem{problem}{Problem}
\newenvironment{jielun}[1][\it\bf{结论}]{\textbf{#1. } }{\ }
\newenvironment{taolun}[1][\it\bf{讨论}]{\textbf{#1. } }{\ }
\pagestyle{empty}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{document}
\noindent \CJKfamily{zhkai}class name\hfill 16 \\
HW4.202404\hfill 梁子毅
%顶格 线
\noindent\hrulefill
\CJKfamily{zhkai}
\begin{problem}
\end{problem}
\begin{enumerate}
\item
\end{enumerate}
\begin{quote}
\end{quote}
\begin{problem}
\end{problem}
\end{document}
```
#speci_block[代码解释][
+ `\documentclass[12pt]{article}`: 这行代码定义了文档的类型为article,并且字体大小设置为12pt。
+ `\usepackage`: 这些行引入了多个LaTeX包,用于提供额外的功能,比如数学公式、定理环境、颜色、图形插入等。
+ `\geometry`: 这个命令用于设置页面的尺寸和边距。
+ `\newtheorem`: 定义了一个名为problem的新定理环境,用于标记问题。
+ `\newenvironment`: 定义了两个新的环境jielun和taolun,分别用于标记结论和讨论部分。
+ `\pagestyle{empty}`: 设置页面的样式为无页眉和页脚。
+ `%`: 是注释的符号,我这里用来作为分隔符
+ `\begin{document}`: 这标志着文档内容的开始。
+ `\noindent`: 这行代码防止段落首行缩进。
+ `\CJKfamily{zhkai}`: 这行代码指定了使用中文楷体字体。
+ `class name\hfill 16 \\`: 这行代码设置了文档的标题和日期,\hfill用于水平填充空白,使日期右对齐。
+ `HW4.202404\hfill 梁子毅`: 这可能是作业的编号和作者的名字,同样使用\hfill进行右对齐。
+ `\noindent\hrulefill`: 这行代码在文档中添加了一条水平线。
+ `\begin{problem}`: 开始一个新的问题环境。
+ `\begin{enumerate}`: 开始一个枚举列表。
+ `\end{enumerate}`: 结束枚举列表。
+ `\begin{quote}`: 开始一个引用环境。
+ `\end{quote}`: 结束引用环境。
+ `\begin{problem}`: 开始另一个问题环境。
+ `\end{document}`: 这标志着文档内容的结束。
]
#figure(
image("./figure/latex_1.png", width: 70%),
caption: [
l我的一份latex模板
],
)<latex1>
- 除此之外,常用的还有`\section`,`\title`,`\author`
- 如下@latex2 是我上个学期使用的一份报告模板\
#figure(
image("./figure/latex_2.png", width: 100%),
caption: [
我的一份latex模板
],
)<latex2>
- Latex实例一共20个(20个命令)
= 总结
- Git
+ git工具的思想相当有意思,但是接口的设计相当“丑”,很难记,我上github看了git的源码,感觉文件结构很混乱(大概是因为我功力不到家),看不透。
+ 目前我使用git会用clion等jetbrain的ide中的简便图形界面,当连接好仓库之后,直接点击图形界面的commit和push还是相当方便的
- Latex
+ 上一个学期用了大半个学期的latex来写实验报告,中途挑选了一个tau-book的模板@latex2 这个模板比较好看
+ 使用latex的感觉就是这个工具又臭又长,非常难用,但是确实比markdown的编译效果美观很多
+ 现在使用写报告用的是typst,一个新的排版语言,底层用rust构建,编译速度很快,而且很好配置(latex我配置了大半天都还是报错,最后使用overleaf来写)
+ 总的来说,如果没有一定的必要,推荐使用typst这个新生代来进行编写实验报告或者笔记,工具玩来玩去,轻量和便捷慢慢成为追求,满足需求即是王道 |
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/meppp/0.1.0/template/main.typ | typst | Apache License 2.0 | #import ("@preview/meppp:0.1.0"):*
#let abstract=[
这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。这是摘要。
]
#show: doc => meppp-lab-report(
title: "这是实验标题",
author: "我是作者",
info: "这是作者信息",
abstract: abstract,
keywords:(
"this is keyword1",
"this is keyword2"
),
author-footnote: [<EMAIL>; +86 11451419198],
doc
)
= 引言
这是引言。这是引言。这是引言。这是引言。这是引言。这是引言。这是引言。这是引言。这是引言。这是引言。
= 实验装置
这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。这是实验装置。
== 第一个实验装置
#figure(image("example_fig.png"),caption:[这是第一个实验装置的示意图])<img>
第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。第一个实验装置。
= 结果与讨论
结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。这是结果与讨论。
#meppp-tl-table(table(
columns:4,
rows:2,
table.header([Item1],[Item2],[Item3],[Item4]),
[Data1],[Data2],[Data3],[Data4],
)
)
#lorem(80)
= 结论
这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。这是结论。
@kopka2004guide
= 致谢
#lorem(40)
#bibliography("example_ref.bib") |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/fletcher/0.4.0/src/main.typ | typst | Apache License 2.0 | #import calc: floor, ceil, min, max
#import "utils.typ": *
#import "layout.typ": *
#import "draw.typ": *
#import "marks.typ": *
/// Draw a labelled node in an diagram which can connect to edges.
///
/// - pos (point): Dimensionless "elastic coordinates" `(x, y)` of the node,
/// where `x` is the column and `y` is the row (increasing upwards). The
/// coordinates are usually integers, but can be fractional.
///
/// See the `diagram()` options to control the physical scale of elastic
/// coordinates.
///
/// - label (content): Node content to display.
/// - inset (length, auto): Padding between the node's content and its bounding
/// box or bounding circle. If `auto`, defaults to the `node-inset` option of
/// `diagram()`.
/// - outset (length, auto): Margin between the node's bounds to the anchor
/// points for connecting edges.
///
/// This does not affect node layout, only how edges connect to the node.
/// - shape (string, auto): Shape of the node, one of `"rect"` or `"circle"`. If
/// `auto`, shape is automatically chosen depending on the aspect ratio of the
/// node's label.
/// - stroke (stroke): Stroke style for the node outline. Defaults to the `node-stroke` option
/// of `diagram()`.
/// - fill (paint): Fill of the node. Defaults to the `node-fill` option of
/// `diagram()`.
/// - defocus (number): Strength of the "defocus" adjustment for connectors
/// incident with this node. If `auto`, defaults to the `node-defocus` option
/// of `diagram()` .
/// - extrude (array): Draw strokes around the node at the given offsets to
/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
/// of the stroke's thickness) or lengths.
///
/// The node's fill is drawn within the boundary defined by the first offset in
/// the array.
///
/// #fletcher.diagram(
/// node-stroke: 1pt,
/// node-fill: red.lighten(70%),
/// node((0,0), `(0,)`),
/// node((1,0), `(0, 2)`, extrude: (0, 2)),
/// node((2,0), `(2, 0)`, extrude: (2, 0)),
/// node((3,0), `(0, -2.5, 2mm)`, extrude: (0, -2.5, 2mm)),
/// )
///
/// See also the `extrude` option of `edge()`.
#let node(
..args,
pos: auto,
label: auto,
inset: auto,
outset: auto,
shape: auto,
width: auto,
height: auto,
radius: auto,
stroke: auto,
fill: auto,
corner-radius: auto,
defocus: auto,
extrude: (0,),
) = {
if args.named().len() > 0 {
panic("Unexpected named argument(s):", args)
}
if args.pos().len() == 2 {
(pos, label) = args.pos()
} else if args.pos().len() == 1 {
let arg = args.pos().at(0)
if type(arg) == array {
pos = arg
label = none
} else {
pos = auto
label = arg
}
}
if type(label) == content and label.func() == circle { panic(label) }
metadata((
class: "node",
pos: pos,
label: label,
inset: inset,
outset: outset,
size: (width, height),
radius: radius,
shape: shape,
stroke: stroke,
fill: fill,
corner-radius: corner-radius,
defocus: defocus,
extrude: extrude,
))
}
/// Interpret the positional arguments given to an `edge()`
///
/// Tries to intelligently distinguish the `from`, `to`, `marks`, and `label`
/// arguments based on the types.
///
/// Generally, the following combinations are allowed:
/// ```
/// edge(..<coords>, ..<marklabel>, ..<options>)
/// <coords> = (from, to) or (to) or ()
/// <marklabel> = (marks, label) or (label, marks) or (marks) or (label) or ()
/// <options> = any number of options specified as strings
/// ```
#let interpret-edge-args(args) = {
if args.named().len() > 0 {
panic("Unexpected named argument(s):", args)
}
let is-coord(arg) = type(arg) == array and arg.len() == 2
let is-rel-coord(arg) = is-coord(arg) or (
type(arg) == str and arg.match(regex("^[utdblrnsew]+$")) != none or
type(arg) == dictionary and "rel" in arg
)
let is-arrow-symbol(arg) = type(arg) == symbol and str(arg) in MARK_SYMBOL_ALIASES
let is-edge-option(arg) = type(arg) == str and arg in EDGE_ARGUMENT_SHORTHANDS
let maybe-marks(arg) = type(arg) == str and not is-edge-option(arg) or is-arrow-symbol(arg)
let maybe-label(arg) = type(arg) != str and not is-arrow-symbol(arg)
let pos = args.pos()
let new-args = (:)
let peek(x, ..predicates) = {
let preds = predicates.pos()
x.len() >= preds.len() and x.zip(preds).all(((arg, pred)) => pred(arg))
}
// Up to the first two arguments may be coordinates
if peek(pos, is-coord, is-rel-coord) {
new-args.from = pos.remove(0)
new-args.to = pos.remove(0)
} else if peek(pos, is-rel-coord) {
new-args.to = pos.remove(0)
}
// if peek(pos, is-arrow) {
// new-args.marks = MARK_SYMBOL_ALIASES.at(pos.remove(0))
// }
// accept (mark, label), (label, mark) or just either one
if peek(pos, maybe-marks, maybe-label) {
new-args.marks = pos.remove(0)
new-args.label = pos.remove(0)
} else if peek(pos, maybe-label, maybe-marks) {
new-args.label = pos.remove(0)
new-args.marks = pos.remove(0)
} else if peek(pos, maybe-label) {
new-args.label = pos.remove(0)
} else if peek(pos, maybe-marks) {
new-args.marks = pos.remove(0)
}
while peek(pos, is-edge-option) {
new-args += EDGE_ARGUMENT_SHORTHANDS.at(pos.remove(0))
}
// If label hasn't already been found, broaden search to accept strings as labels
if "label" not in new-args and peek(pos, x => type(x) == str) {
new-args.label = pos.remove(0)
}
if pos.len() > 0 {
panic("Could not interpret `edge()` argument(s):", pos, "Arguments were:", new-args)
}
new-args
}
/// Draw a connecting line or arc in an arrow diagram.
///
/// - from (elastic coord): Start coordinate `(x, y)` of connector. If there is
/// a node at that point, the connector is adjusted to begin at the node's
/// bounding rectangle/circle.
/// - to (elastic coord): End coordinate `(x, y)` of connector. If there is a
/// node at that point, the connector is adjusted to end at the node's bounding
/// rectangle/circle.
///
/// - ..args (any): The connector's `label` and `marks` named arguments can also
/// be specified as positional arguments. For example, the following are equivalent:
/// ```typc
/// edge((0,0), (1,0), $f$, "->")
/// edge((0,0), (1,0), $f$, marks: "->")
/// edge((0,0), (1,0), "->", label: $f$)
/// edge((0,0), (1,0), label: $f$, marks: "->")
/// ```
///
/// - label-pos (number): Position of the label along the connector, from the
/// start to end (from `0` to `1`).
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// ..(0, 0.25, 0.5, 0.75, 1).map(p => fletcher.diagram(
/// cell-size: 1cm,
/// edge((0,0), (1,0), p, "->", label-pos: p))
/// ),
/// )
/// - label-sep (number): Separation between the connector and the label anchor.
///
/// With the default anchor (`"bottom"`):
///
/// #fletcher.diagram(
/// debug: 2,
/// cell-size: 8mm,
/// {
/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s)
/// }
/// })
///
/// With `label-anchor: "center"`:
///
/// #fletcher.diagram(
/// debug: 2,
/// cell-size: 8mm,
/// {
/// for (i, s) in (-5pt, 0pt, .4em, .8em).enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, "->", label-sep: s, label-anchor: "center")
/// }
/// })
///
/// - label (content): Content for connector label. See `label-side` to control
/// the position (and `label-sep`, `label-pos` and `label-anchor` for finer
/// control).
///
/// - label-side (left, right, center): Which side of the connector to place the
/// label on, viewed as you walk along it. If `center`, then the label is place
/// over the connector. When `auto`, a value of `left` or `right` is chosen to
/// automatically so that the label is
/// - roughly above the connector, in the case of straight lines; or
/// - on the outside of the curve, in the case of arcs.
///
/// - label-anchor (anchor): The anchor point to place the label at, such as
/// `"top-right"`, `"center"`, `"bottom"`, etc. If `auto`, the anchor is
/// automatically chosen based on `label-side` and the angle of the connector.
///
/// - stroke (stroke): Stroke style of the edge. Arrows scale with the stroke
/// thickness.
/// - dash (dash type): Dash style for the connector stroke.
/// - bend (angle): Curvature of the connector. If `0deg`, the connector is a
/// straight line; positive angles bend clockwise.
///
/// #fletcher.diagram(debug: 0, {
/// node((0,0), $A$)
/// node((1,1), $B$)
/// let N = 4
/// range(N + 1)
/// .map(x => (x/N - 0.5)*2*100deg)
/// .map(θ => edge((0,0), (1,1), θ, bend: θ, ">->", label-side: center))
/// .join()
/// })
///
/// - marks (pair of strings):
/// The marks (arrowheads) to draw along an edge's stroke.
/// This may be:
///
/// - A shorthand string such as `"->"` or `"hook'-/->>"`. Specifically,
/// shorthand strings are of the form $M_1 L M_2$ or $M_1 L M_2 L M_3$, where
/// $
/// M_i in {#fletcher.MARK_ALIASES.keys().filter(x => x.len() < 4).map(raw.with(lang: none)).join($,$)} union N
/// $
/// is a mark symbol and
/// $L in {#("-", "--", "..", "=", "==").map(raw.with(lang: none)).join($,$)}$
/// is the line style.
/// The mark symbol can also be a name,
/// $M_i in N = {#("hook", "hook'", "harpoon", "harpoon'", "head", "circle").map(raw.with(lang: none)).join($,$), ...}$
/// where a trailing `'` means to reflect the mark across the stroke.
///
/// - An array of marks, where each mark is specified by name or by a
/// dictionary of parameters.
///
/// Shorthands are expanded into other arguments. For example,
/// `edge(p1, p2, "=>")` is short for `edge(p1, p2, marks: (none, "head"), "double")`, or more precisely, `edge(p1, p2, ..fletcher.interpret-marks-arg("=>"))`.
///
///
/// #table(
/// columns: (1fr, 4fr),
/// align: (center + horizon, horizon),
/// [Arrow], [`marks`],
/// ..(
/// "->",
/// ">>-->",
/// "<=>",
/// "==>",
/// "->>-",
/// "x-/-@",
/// "|..|",
/// "hook->>",
/// "hook'->>",
/// "||-*-harpoon'",
/// ("X", (kind: "head", size: 15, sharpness: 40deg),),
/// ((kind: "circle", pos: 0.5, fill: true),),
/// ).map(arg => (
/// fletcher.diagram(edge((0,0), (1,0), marks: arg, stroke: 0.8pt)),
/// raw(repr(arg)),
/// )).join()
/// )
///
/// - mark-scale (percent):
/// Scale factor for marks or arrowheads.
///
/// #fletcher.diagram(
/// label-sep: 10pt,
/// edge-stroke: 1pt,
/// for i in range(3) {
/// let s = (1 + i/2)*100%
/// edge((2*i,0), (2*i + 1,0), label: s, "->", mark-scale: s)
/// }
///)
///
/// Note that the default arrowheads scale automatically with double and triple
/// strokes:
///
/// #fletcher.diagram(
/// label-sep: 10pt,
/// edge-stroke: 1pt,
/// for (i, s) in ("->", "=>", "==>").enumerate() {
/// edge((2*i,0), (2*i + 1,0), s, label: raw(s, lang: none))
/// }
/// )
/// - extrude (array): Draw a separate stroke for each extrusion offset to
/// obtain a multi-stroke effect. Offsets may be numbers (specifying multiples
/// of the stroke's thickness) or lengths.
///
/// #fletcher.diagram({
/// (
/// (0,),
/// (-1.5,+1.5),
/// (-2,0,+2),
/// (-.5em,),
/// (0, 5pt,),
/// ).enumerate().map(((i, e)) => {
/// edge(
/// (2*i, 0), (2*i + 1, 0), [#e], "|->",
/// extrude: e, stroke: 1pt, label-sep: 1em)
/// }).join()
/// })
///
/// Notice how the ends of the line need to shift a little depending on the
/// mark. For basic arrow heads, this offset is computed with
/// `round-arrow-cap-offset()`.
///
/// - crossing (bool): If `true`, draws a backdrop of color `crossing-fill` to
/// give the illusion of lines crossing each other.
///
/// #fletcher.diagram(crossing-fill: luma(98%), {
/// edge((0,1), (1,0), stroke: 1pt)
/// edge((0,0), (1,1), stroke: 1pt)
/// edge((2,1), (3,0), stroke: 1pt)
/// edge((2,0), (3,1), stroke: 1pt, crossing: true)
/// })
///
/// You can also pass `"crossing"` as a positional argument as a shorthand for
/// `crossing: true`.
///
/// - crossing-thickness (number): Thickness of the "crossing" background
/// stroke, if `crossing: true`, in multiples of the normal stroke's thickness.
/// Defaults to the `crossing-thickness` option of `diagram()`.
///
/// #fletcher.diagram(crossing-fill: luma(98%), {
/// (1, 2, 5, 8, 12).enumerate().map(((i, x)) => {
/// edge((2*i, 1), (2*i + 1, 0), stroke: 1pt, label-sep: 1em)
/// edge((2*i, 0), (2*i + 1, 1), raw(str(x)), stroke: 1pt, label-sep:
/// 2pt, label-pos: 0.3, crossing: true, crossing-thickness: x)
/// }).join()
/// })
///
/// - crossing-fill (paint): Color to use behind connectors or labels to give the illusion of crossing over other objects. Defaults to the `crossing-fill` option of
/// `diagram()`.
///
/// #let cross(x, fill) = {
/// edge((2*x + 0,1), (2*x + 1,0), stroke: 1pt)
/// edge((2*x + 0,0), (2*x + 1,1), $f$, stroke: 1pt, crossing: true, crossing-fill: fill)
/// }
/// #fletcher.diagram(crossing-thickness: 5, {
/// cross(0, white)
/// cross(1, blue.lighten(50%))
/// cross(2, luma(98%))
/// })
///
#let edge(
..args,
from: auto,
to: auto,
label: none,
label-side: auto,
label-pos: 0.5,
label-sep: auto,
label-anchor: auto,
stroke: auto,
dash: none,
kind: auto,
bend: 0deg,
corner: none,
marks: (none, none),
mark-scale: 100%,
extrude: (0,),
crossing: false,
crossing-thickness: auto,
crossing-fill: auto,
) = {
let options = (
from: from,
to: to,
label: label,
label-pos: label-pos,
label-sep: label-sep,
label-anchor: label-anchor,
label-side: label-side,
stroke: stroke,
dash: dash,
kind: kind,
bend: bend,
corner: corner,
marks: marks,
mark-scale: mark-scale,
extrude: extrude,
crossing: crossing,
crossing-thickness: crossing-thickness,
crossing-fill: crossing-fill,
)
options += interpret-edge-args(args)
options += interpret-marks-arg(options.marks)
// relative coordinate shorthands
if type(options.to) == str {
let rel = (0, 0)
let dirs = (
"t": ( 0,-1), "n": ( 0,-1), "u": ( 0,-1),
"b": ( 0,+1), "s": ( 0,+1), "d": ( 0,+1),
"l": (-1, 0), "w": (-1, 0),
"r": (+1, 0), "e": (+1, 0),
)
for char in options.to.clusters() {
rel = vector.add(rel, dirs.at(char))
}
options.to = (rel: rel)
}
let stroke = default(as-stroke(options.stroke), as-stroke((:)))
stroke = as-stroke((
paint: stroke.paint,
cap: default(stroke.cap, "round"),
thickness: stroke.thickness,
dash: default(stroke.dash, options.dash),
))
if options.label-side == center {
options.label-anchor = "center"
options.label-sep = 0pt
}
let obj = (
class: "edge",
points: (options.from, options.to),
label: options.label,
label-pos: options.label-pos,
label-sep: options.label-sep,
label-anchor: options.label-anchor,
label-side: options.label-side,
kind: options.kind,
bend: options.bend,
corner: options.corner,
stroke: stroke,
marks: options.marks,
mark-scale: options.mark-scale,
extrude: options.extrude,
is-crossing-background: false,
crossing-thickness: crossing-thickness,
crossing-fill: crossing-fill,
)
assert(type(obj.marks) == array, message: repr(obj))
if options.crossing {
metadata((
..obj,
is-crossing-background: true
))
}
metadata(obj)
}
#let apply-defaults(nodes, edges, options) = {
let to-pt(len) = if type(len) == length {
len.abs + len.em*options.em-size
} else {
len
}
(
nodes: nodes.map(node => {
node.stroke = as-stroke(node.stroke)
node.stroke = default(node.stroke, options.node-stroke)
node.fill = default(node.fill, options.node-fill)
node.corner-radius = default(node.corner-radius, options.node-corner-radius)
node.inset = default(node.inset, options.node-inset)
node.outset = default(node.outset, options.node-outset)
node.defocus = default(node.defocus, options.node-defocus)
node.size = node.size.map(to-pt)
node.radius = to-pt(node.radius)
if node.shape == auto {
if node.radius != auto { node.shape = "circle" }
if node.size != (auto, auto) { node.shape = "rect" }
}
let real-stroke-thickness = if type(node.stroke) == stroke {
default(node.stroke.thickness, 1pt)
} else {
1pt
}
node.extrude = node.extrude.map(d => {
if type(d) == length { d }
else { d*real-stroke-thickness }
}).map(to-pt)
node.inset = to-pt(node.inset)
node.outset = to-pt(node.outset)
node
}),
edges: edges.map(edge => {
edge.stroke = as-stroke(edge.stroke)
edge.stroke = stroke(
paint: default(edge.stroke.paint, options.edge-stroke.paint),
thickness: to-pt(default(edge.stroke.thickness, options.edge-stroke.thickness)),
cap: default(edge.stroke.cap, options.edge-stroke.cap),
join: default(edge.stroke.join, options.edge-stroke.join),
dash: default(edge.stroke.dash, options.edge-stroke.dash),
miter-limit: default(edge.stroke.miter-limit, options.edge-stroke.miter-limit),
)
edge.crossing-fill = default(edge.crossing-fill, options.crossing-fill)
edge.crossing-thickness = default(edge.crossing-thickness, options.crossing-thickness)
edge.label-sep = default(edge.label-sep, options.label-sep)
if edge.is-crossing-background {
edge.stroke = (
thickness: edge.crossing-thickness*edge.stroke.thickness,
paint: edge.crossing-fill,
cap: "round",
)
edge.marks = (none, none)
edge.extrude = edge.extrude.map(e => e/edge.crossing-thickness)
}
if edge.kind == auto {
if edge.corner != none { edge.kind = "corner" }
else if edge.bend != 0deg { edge.kind = "arc" }
else { edge.kind = "line" }
}
// Scale marks
edge.mark-scale *= options.mark-scale
let scale = edge.mark-scale/100%
edge.marks = edge.marks.map(mark => {
if mark == none { return }
for k in ("size", "inner-len", "outer-len") {
if k in mark { mark.at(k) *= scale }
}
mark
})
edge.label-sep = to-pt(edge.label-sep)
edge.extrude = edge.extrude.map(d => {
if type(d) == length { to-pt(d) }
else { d*edge.stroke.thickness }
})
edge
}),
)
}
#let extract-nodes-and-edges-from-equation(eq) = {
assert(eq.func() == math.equation)
let terms = eq.body + []
assert(repr(terms.func()) == "sequence")
let edges = ()
let nodes = ()
let matrix = ((none,),)
let (x, y) = (0, 0)
for child in terms.children {
if child.func() == metadata {
if child.value.class == "edge" {
let edge = child.value
edge.points.at(0) = default(edge.points.at(0), (x, y))
if edge.label != none { edge.label = $edge.label$ } // why is this needed?
edges.push(edge)
} else if child.value.class == "node" {
let node = child.value
node.pos = (x, y)
nodes.push(node)
}
} else if repr(child.func()) == "linebreak" {
y += 1
x = 0
matrix.push((none,))
} else if repr(child.func()) == "align-point" {
x += 1
matrix.at(-1).push(none)
} else {
matrix.at(-1).at(-1) += child
}
}
for (y, row) in matrix.enumerate() {
for (x, item) in row.enumerate() {
nodes.push(node((x, y), $item$).value)
}
}
(
nodes: nodes,
edges: edges,
)
}
#let interpret-diagram-args(args) = {
let nodes = ()
let edges = ()
let prev-coord = (0,0)
let should-set-last-edge-point = false
for arg in args {
if arg.func() == metadata {
if arg.value.class == "node" {
let node = arg.value
nodes.push(node)
prev-coord = node.pos
if should-set-last-edge-point {
// the `to` point of the previous edge is waiting to be set
edges.at(-1).points.at(1) = node.pos
should-set-last-edge-point = false
}
} else if arg.value.class == "edge" {
let edge = arg.value
if edge.points.at(0) == auto {
edge.points.at(0) = prev-coord
}
if edge.points.at(1) == auto {
if should-set-last-edge-point { panic("Cannot infer edge end point. Please specify explicitly.") }
should-set-last-edge-point = true
}
edges.push(edge)
}
} else if arg.func() == math.equation {
let result = extract-nodes-and-edges-from-equation(arg)
nodes += result.nodes
edges += result.edges
} else {
panic("Unrecognised value passed to diagram", arg)
}
}
edges = edges.map(edge => {
let to = edge.points.at(1)
if to == auto {
edge.points.at(1) = vector.add(edge.points.at(0), (1, 0))
} else if type(to) == dictionary and "rel" in to {
// Resolve relative coordinates
// panic(edge)
edge.points.at(1) = vector.add(edge.points.at(0), to.rel)
}
assert(edge.points.at(0) != auto and edge.points.at(1) != auto, message: repr(edge))
assert(type(edge.points.at(1)) != dictionary, message: repr(edge))
edge
})
(
nodes: nodes,
edges: edges,
)
}
/// Draw an arrow diagram.
///
/// - ..objects (array): An array of dictionaries specifying the diagram's
/// nodes and connections.
///
/// The results of `node()` and `edge()` can be joined, meaning you can specify
/// them as separate arguments, or in a block:
///
/// ```typ
/// #fletcher.diagram(
/// // one object per argument
/// node((0, 0), $A$),
/// node((1, 0), $B$),
/// {
/// // multiple objects in a block
/// // can use scripting, loops, etc
/// node((2, 0), $C$)
/// node((3, 0), $D$)
/// },
/// )
/// ```
///
/// - debug (bool, 1, 2, 3): Level of detail for drawing debug information.
/// Level `1` shows a coordinate grid; higher levels show bounding boxes and
/// anchors, etc.
///
/// - spacing (length, pair of lengths): Gaps between rows and columns. Ensures
/// that nodes at adjacent grid points are at least this far apart (measured as
/// the space between their bounding boxes).
///
/// Separate horizontal/vertical gutters can be specified with `(x, y)`. A
/// single length `d` is short for `(d, d)`.
///
/// - cell-size (length, pair of lengths): Minimum size of all rows and columns.
///
/// - node-inset (length, pair of lengths): Default padding between a node's
/// content and its bounding box.
/// - node-outset (length, pair of lengths): Default padding between a node's
/// boundary and where edges terminate.
/// - node-stroke (stroke): Default stroke for all nodes in diagram. Overridden
/// by individual node options.
/// - node-fill (paint): Default fill for all nodes in diagram. Overridden by
/// individual node options.
///
/// - node-defocus (number): Default strength of the "defocus" adjustment for
/// nodes. This affects how connectors attach to non-square nodes. If
/// `0`, the adjustment is disabled and connectors are always directed at the
/// node's exact center.
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// ..(0.2, 0, -1).enumerate().map(((i, defocus)) => {
/// fletcher.diagram(spacing: 8mm, {
/// node((i, 0), raw("defocus: "+str(defocus)), stroke: black, defocus: defocus)
/// for y in (-1, +1) {
/// edge((i - 1, y), (i, 0))
/// edge((i, y), (i, 0))
/// edge((i + 1, y), (i, 0))
/// }
/// })
/// })
/// )
///
/// - label-sep (length): Default value of `label-sep` option for `edge()`.
/// - mark-scale (length): Default value of `mark-scale` option for `edge()`.
/// - crossing-fill (paint): Color to use behind connectors or labels to give
/// the illusion of crossing over other objects. See the `crossing-fill` option
/// of `edge()`.
///
/// - crossing-thickness (number): Default thickness of the occlusion made by
/// crossing connectors. See the `crossing-thickness` option of `edge()`.
///
/// - axes (pair of directions): The directions of the diagram's axes.
///
/// This defines the orientation of the coordinate system used by nodes and
/// edges. To make the $y$ coordinate increase up the page, use `(ltr, btt)`.
/// For the matrix convention `(row, column)`, use `(ttb, ltr)`.
///
/// #stack(
/// dir: ltr,
/// spacing: 1fr,
/// fletcher.diagram(
/// axes: (ltr, ttb),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->"),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ltr, ttb)`),
/// ),
/// move(dy: 0.87em, fletcher.diagram(
/// axes: (ltr, btt),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->"),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ttb, ltr)`),
/// )),
/// fletcher.diagram(
/// axes: (ttb, ltr),
/// debug: 1,
/// node((0,0), $(0,0)$),
/// edge((0,0), (1,0), "->", bend: -20deg),
/// node((1,0), $(1,0)$),
/// node((1,1), $(1,1)$),
/// node((0.5,0.5), `axes: (ttb, ltr)`),
/// ),
/// )
///
/// - render (function): After the node sizes and grid layout have been
/// determined, the `render` function is called with the following arguments:
/// - `grid`: a dictionary of the row and column widths and positions;
/// - `nodes`: an array of nodes (dictionaries) with computed attributes
/// (including size and physical coordinates);
/// - `edges`: an array of connectors (dictionaries) in the diagram; and
/// - `options`: other diagram attributes.
///
/// This callback is exposed so you can access the above data and draw things
/// directly with CeTZ.
#let diagram(
..objects,
debug: false,
axes: (ltr, ttb),
spacing: 3em,
cell-size: 0pt,
node-inset: 12pt,
node-outset: 0pt,
node-stroke: none,
node-fill: none,
node-corner-radius: 0pt,
node-defocus: 0.2,
label-sep: 0.2em,
edge-stroke: 0.048em,
mark-scale: 100%,
crossing-fill: white,
crossing-thickness: 5,
render: (grid, nodes, edges, options) => {
cetz.canvas(
draw-diagram(grid, nodes, edges, options)
)
},
) = {
if type(spacing) != array { spacing = (spacing, spacing) }
if type(cell-size) != array { cell-size = (cell-size, cell-size) }
if objects.named().len() > 0 {
let args = objects.named().keys().join(", ")
panic("Unexpected named argument(s): " + args)
}
let options = (
spacing: spacing,
debug: int(debug),
node-inset: node-inset,
node-outset: node-outset,
node-stroke: node-stroke,
node-fill: node-fill,
node-corner-radius: node-corner-radius,
node-defocus: node-defocus,
label-sep: label-sep,
cell-size: cell-size,
edge-stroke: as-stroke(edge-stroke),
mark-scale: mark-scale,
crossing-fill: crossing-fill,
crossing-thickness: crossing-thickness,
axes: axes,
)
assert(axes.at(0).axis() != axes.at(1).axis(), message: "Axes cannot both be in the same direction.")
// Interpret objects at a sequence of nodes and edges
let positional-args = objects.pos().join() + [] // join to ensure sequence
assert(repr(positional-args.func()) == "sequence")
let (nodes, edges) = interpret-diagram-args(positional-args.children)
box(style(styles => {
let options = options
options.em-size = measure(h(1em), styles).width
let to-pt(len) = len.abs + len.em*options.em-size
options.spacing = options.spacing.map(to-pt)
let (nodes, edges) = (nodes, edges)
// Add dummy nodes at edge terminals
for edge in edges {
nodes.push(node(edge.points.at(0), none).value)
nodes.push(node(edge.points.at(1), none).value)
}
// Swap axes
if options.axes.map(a => a.axis()) == ("vertical", "horizontal") {
nodes = nodes.map(node => {
node.pos = node.pos.rev()
node
})
edges = edges.map(edge => {
edge.points = edge.points.map(array.rev)
edge
})
options.axes = options.axes.rev()
}
let (nodes, edges) = apply-defaults(nodes, edges, options)
let nodes = compute-node-sizes(nodes, styles)
let grid = compute-grid(nodes, options)
let nodes = compute-node-positions(nodes, grid, options)
render(grid, nodes, edges, options)
}))
}
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/hyphenate_03.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test shy hyphens.
#set text(lang: "de", hyphenate: true)
#grid(
columns: 2 * (20pt,),
gutter: 20pt,
[Barankauf],
[Bar-?ankauf],
)
|
https://github.com/danilasar/conspectuses-3sem | https://raw.githubusercontent.com/danilasar/conspectuses-3sem/master/Основы_теории_изучаемого_языка/241001_сложноподчинённые предложения.typ | typst | = Сложноподчинённые предложения
В сложноподчинённом предложени выделяется одно главное предложение, не обусловленное зависимостью от других частей и находящееся на высшем синтаксическом уровне, и один чурка.
== Классификация придаточных предложений
- подлежащные
- предикативные
- дополнительные или изъяснительные
- определительные
- обстоятельственные
=== Подлежащные придаточные
ебать сколько всего упущено...
=== Предикативные придаточные
Предикативные придаточные в функции именной части составного сказуемого отвечают на вопросы: #quote[What is the subject? What is the subjetc like?] Они вводятся теми же союзами и союзными словами, что подлежащные придаточные. Предикативные придаточные обычно стоят после глагола связки.
Например, #quote[The question is #underline[whether they will be able to help us]].
=== Дополнительные придаточные
Дополнительные придаточные отвечают на вопросы #quote[What? What about? For what?] Они вводятся теми же союзами и союзными словами, что и подлежащные, и предикативные придаточные. Союз #quote[that] часто опускается.
Например, #quote[I don't know #underline[where you live]. He said #underline[(that) he felt tired]].
=== Определительные придаточные
Определительные придаточные отвечают на вопросы #quote[What? What kind of? Which?] Они вводятся теми же союзными словами: #quote[whose, what, who, which, when, where, how, why]. Например, #quote[The letter #underline[that I recieved from him yesterday] is very important].
#quote[We have received a letter, #underline[which contains interesting information on the state of the mark of wheat]].
=== Обстоятельственные придаточные
Существуют обстоятельственные придаточные каждого типа обстоятельств:
- времени
- места
- причины
- следствия
- образа действия
- сравнения
- уступки
- цели
- условия
==== Обстоятельственные придаточные времени
Обстоятельственные придаточные времени отвечают на вопросы: #quote[Whene? Since when? How long?] Они вводятся союзами #quote[whene, whenever, while, as, after, before, till, until, as soon as, since, no sooner ...than] и др. Глагол-сказуемое в придаточных времени никогда не употребляются в будущем времени.
Например, #quote[#underline[While there is life] there is hope.]
==== Обстоятельственные придаточные места
Обстоятельственные придаточные места отвечают на вопросы: #quote[Where? From where?] Они вводятся союхными словами #quote[where, wherever].
Например, #quote[He went where the doctor sent him].
==== Обстоятельственные придаточные причины
Обстоятельственные придаточные причины отвечают на вопросы: #quote[Why?] Они вводятся союзами #quote[because, as, since, for, now what] и др.
Например, #quote[#underline[As there were no porters] we have to carry our luggage urselves].
==== Обстоятельственные придаточные следствия
Обстоятельственные придаточные следствия выражают следствие, вытекающиее из содержания придаточного предложения. Они вводятся союзом #quote[so...that].
Например, #quote[She sat behind me #underline[so (that) I could not see her expression]].
==== Обстоятельственные придаточные образа действия
Наиболее часто использующиеося обстоятельственные придаточные --- придаточные образа действия. Они отвечают на вопрос: #quote[How?]. Они вводятся союзами: #quote[as, as if, as though].
Например, #quote[You answer #underline[as...if you did not know this rule]].
==== Обстоятельственные придаточные сравнения
Обстоятельственные придаточные сравнения вводятся союзами #quote[than, as...as, not so...as].
Например, #quote[He is older #underline[than he looks]].
==== Обстоятельственные придаточные уступки
бляяя
==== Обстоятельственные придаточные цели
Обстоятельственные придаточные цели отвечают на вопросы: #quote[What for? For what purpose?]. Они вводятся союзами: #quote[so...that, so, in order that].
Например, #quote[The teacher speaks slowly #underline[so that his pupils may understand him]].
==== Обстоятельственные придаточные условия
Обстоятельтсвенные придаточные условия отвечают на вопрос #quote[On what ondition?] Они вводятся союзами #quote[if, unless, so long as, on condition (that), provided (that)].
Глагол-сказуемое в условных придаточных никогда не употреблятся в будущем времени.
Например, #quote[#underline[If I see him tomorrow], I'll ask him about it].
== Разбор сложноподчинённого предложения
He spoke as if I were a child that needet to be distracted.
He spoke --- главное.
If I were a child и that needed to be distracted --- подчинённые.
Сложноподчинённое предложение с последовательным подчинением, состоящее из двух придаточных. Первое придаточное образа действия вводится союзом#quote[as if] и зависит от сказуемого главного предложения. Второе придаточное определительное и зависит от сказуемого первого придаточного предложения.
=== He spoke
простое предложение, двусоставное, нераспространённое, утвердительное, повествовательное.
he --- простое подлежащее, выраженное личным местоимением.
spoke (speak) --- простое глагольное сказуемое, выраженное глаголом в личной форме.
=== as if I were I child
простое предложение, двусоставное, нераспространённое, утвердительное и повествовательное.
I --- простое подлежащее выражено личным местоимением.
were a child --- составное именное сказуемое выражено глаголом, именная часть выражена существительным в общем падеже
=== that needed to be distracted
простое предложение, двусоставное, нераспространённое, утвердительное, повествовательное.
that --- простое подлежащее, выраженное относительным местимением.
needed to be distracted --- составное глагольное сказуемое, воыраженное гаголом в личной форме и инфинитивом другого глагола.
|
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/input-decimal-markers/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
// Decimal Point
#num[1.2]
#num("1.2")
$num(1.2)$
// Comma
#num[1,2]
#num("1,2")
$num(1\,2)$
// Custom
#metro-setup(input-decimal-markers: (sym.minus,))
#num[1-2]
#num("1-2")
$num(1-2)$ |
https://github.com/voXrey/cours-informatique | https://raw.githubusercontent.com/voXrey/cours-informatique/main/typst/tris.typ | typst | #set text(font: "Roboto Serif")
= Complément sur les Tris <complément-sur-les-tris>
== Introduction <introduction>
Vocabulaire
- Tri #strong[comparatif] : fonctionne pour n’importe quel ensemble $lr((X , lt.eq))$ totalement ordonné.
- Tri #strong[en place] : on trie le tableau d’entrée en place, via le souvent des échanges / interversion / transposition, #strong[sans copier le tableau] et en espace auxiliaire $O lr((1))$.
- Tri #strong[stable] : en pratique on trie des tableaux selon une #strong[clé] mais chaque case du tableau a aussi des #strong[données satellites]. À clés égales, l’ordre initial est préservé.
#figure(
align(
center,
)[#table(
columns: 6,
align: (col, row) => (center, center, center, center, center, center,).at(col),
inset: 6pt,
[Tri],
[Temps],
[Espace],
[En place],
[Stable],
[Comparatif],
[`Bulle`],
[$O lr((n ²))$],
[$O lr((1))$],
[Oui],
[Oui],
[Oui],
[`Sélection`],
[$O lr((n ²))$],
[$O lr((1))$],
[Oui],
[Non],
[Oui],
[`Insertion`],
[$O lr((n ²))$],
[$O lr((1))$],
[Oui],
[Oui],
[Oui],
[`Fusion`],
[$O lr((n l o g lr((n))))$],
[$O lr((n))$],
[Non],
[Oui],
[Oui],
[`Rapide`],
[$O lr((n ²))$~au pire~$O lr((n l o g lr((n))))$~en moyenne],
[$O lr((1))$],
[Oui],
[Si pivot devant],
[Oui],
[`ABR`],
[$O lr((n l o g lr((n))))$~en moyenne],
[$O lr((n))$],
[Non],
[Selon la gestion],
[Oui],
[`Heap`],
[$O lr((n l o g lr((n))))$],
[$O lr((1))$],
[Oui],
[Probablement pas],
[Oui],
[`Comptage`],
[$O lr((n + m a x lr((a))))$],
[$O lr((m a x lr((a))))$],
[Non],
[Oui],
[Non],
[`Sleep`],
[X],
[$O lr((n))$],
[Non],
[Non],
[Non],
)],
)
|
|
https://github.com/eduardz1/Bachelor-Thesis | https://raw.githubusercontent.com/eduardz1/Bachelor-Thesis/main/README.md | markdown | # Design and Development of the Digital Twin of a Greenhouse
The thesis is written in [typst](https://github.com/typst/typst), a new markup-based typesetting system that is meant to replace LaTeX. To compile you need to have typst installed, the project was compiled with `version 0.9`.
# Background
The thesis was written on the basis of the intership I followed in the reaserch centre at the Uiversity of Oslo's Computer Science department during my semester abroad from the University of Turin. The compiled pdf can be found in the [main.pdf](./main.pdf) file, the presentation in the [presentation.pdf](./presentation.pdf) file.
# Abstract
In this thesis, we will talk about what digital twins are and how they can be used in a range of scenarios, we will introduce some concepts of the Semantic Web that will serve as a basis for our work. We will also introduce a novel programming language, SMOL, developed to facilitate the way to interface with digital twins. We will talk about the work of myself and my colleagues in the process of building the physical twin with a focus on the structure and the way the responsibilities of the different components are modularized. Finally, we will talk about the software components that we wrote as part of this project, including the code to interact with the sensors and the actuators - with a focus on the Python code and the way it's structured - and the SMOL code that serves as a proof of concept for the automation of the greenhouse.
|
|
https://github.com/luickk/QuantumGameOfLife | https://raw.githubusercontent.com/luickk/QuantumGameOfLife/main/physics_notes.typ | typst | #let assumption = text(fill: red)[ASSUMPTION]
#let hbar = math.planck.reduce
#let todo = text(fill: red)[TODO]
= Math/ Physics Summary \ \
Src: MIT-Path-Integral-paper.pdf \
- General Prequests
- Lagragian
- Represents the difference between the kinetic and potential energy of a system at given n-dim point in spaced
- The stationary *action principle* requires that the *action* functional of the system derived from L must remain at a stationary point (a maximum, minimum, or saddle) throughout the time evolution of the system.
- $L = K - V$
- In Euclidian (flat) Space
- The Lagrangian is constructed using standard expressions for kinetic and potential energy.
- $L = 1/2 m x^2 − 1/2 k x^2$
- When you need to describe motion of a system you need the Euler Lagragian to analyze the dynamics of physical systems using the principle of least action
- $d/(d t) ((partial L )/(partial dot(q)^i)) - (partial L) / (partial q^i) = 0$
- In more complex Riemann Space
- The Lagrange formalism can be extended using the concept of a Riemannian manifold. In these cases, the kinetic energy term must account for the curvature of the space
- For Particle of mass m moving in D-dimensional Manifold with metric tensor $g_(a b)$ is:
- $L = 1/2 m g_(a b) (q) dot(q)^a dot(q)^b - V(q)$
- The metric tensor defines the curvature of the space
- Greens funciton
- Way to display a inhomogeneous differential equation as an integral
- Vector Represenataion
- Dirac Bra-ket Notation
- 1 dim complex Hilbert space
- is a collection of vectors with n dim basis vectors
- Probability curve of positional dim of 2 dim vector in hilbert space:
- $ phi.alt(x) = angle.l x|Psi angle.r$
- Ket Vecotr state
- $phi.alt angle.r$
- e.g. basis vectors of a 2dim Hilbert space
- $phi.alt_1 angle.r$, $phi.alt_2 angle.r$
- $phi.alt$ scaled by $c_1$
- $c_1 | phi.alt angle.r$
- akin to: $phi.alt$ has an associated probability amplitude or coefficient of $c_1$
- Braket - Complex Dot product
- In this notation, a Bra Ket vector represents the dot product between the two which is equal to the probability curve from one to the other state
- $angle.l phi.alt_1 |phi.alt_2 angle.r = phi.alt_1 dot phi.alt_2$
- Complex dot product:
- $A dot B = sum_i^n a_i overline(b_i)$
- Outer product, creates new Operator
- $hat(A)_n = phi.alt_1 angle.r angle.l phi.alt_2$
- Combining States
- $|phi.alt_1 angle.r |phi.alt_2 angle.r = |phi.alt_1 angle.r times.circle |phi.alt_2 angle.r$
- The resulting combined state contains all possible combinations of the states $|phi.alt_1 angle.r$ and $|phi.alt_2 angle.r$, where the state of each individual system remains unchanged.
- Also called Identity Operator $hat(I) = sum_(i=1)^n |phi.alt_i angle.r angle.l phi.alt_i$
- Operator: $hat(A)$
- $hat(A) | psi angle.r = | phi.alt angle.r $ where $psi$ and $phi.alt$ are in Hilberspace
- Some Eigenmatrix that transforms that's applied on the state vector($psi$) that returns an eigenvalue "the measurement"
- $"measurement" = angle.l psi | hat(A)|psi angle.r$
- Probability Amplitude of a vector $phi.alt$
- $||phi.alt||^2$
- Linear Operations
- $hat(A)[c_1 | phi.alt_1 angle.r + c_2 | phi.alt_2 angle.r] = c_1hat(A)|phi.alt_1 angle.r + c_2hat(A)|phi.alt_2 angle.r$
- Examples of 2 Dim Hilbertspace
- State with momentum: $p |p angle.r$
- State with definite position: $x |x angle.r$
- Probability amplitude for state $phi.alt_1 "to" phi.alt_2$:
- $angle.l phi.alt_1 | phi.alt_2 angle.r = integral_(-infinity)^(+infinity) phi.alt_1 dot phi.alt_2 d x$
- Probability amplitude for a particle to be at position x
- #assumption: in the original version the $Psi$ below also is $phi.alt$ but withou an index
- $phi.alt(x) = angle.l x | Psi angle.r$
- #link("https://quantummechanics.ucsd.edu/ph130a/130_notes/node108.html")[src]
\ \
- Path Integral Formula
- Formula: $|psi(x, t') angle.r = integral_(-infinity)^infinity angle.l psi(x',t')|psi(x_0,t_0)angle.r d x'|psi(x',t')$
- This formulation has proven crucial to the subsequent development of theoretical physics, because manifest Lorentz covariance (time and space components of quantities enter equations in the same way) is easier to achieve than in the operator formalism of canonical quantization. Unlike previous methods, the path integral allows one to easily change coordinates between very different canonical descriptions of the same quantum system. Another advantage is that it is in practice easier to guess the correct form of the Lagrangian of a theory, which naturally enters the path integrals (for interactions of a certain type, these are coordinate space or Feynman path integrals), than the Hamiltonian). _#link("https://en.wikipedia.org/wiki/Path_integral_formulation")[Source]_
- Propagator: $U(x', t'; x_0, t_0) = angle.l psi(x', t') | psi(x_0, t_0) angle.r$
- The Propagator represents the probability amplitude for a particle to travel from one point in space and time to another
- with elapsed time written as: $U(x', t; x_0)$
- Propagator and an initial state Ket can fully describe the evolution of a system over time
- Action: $S[x(t)]$
- An infinite continuum of trajectories $x(t)$(time indipendent) are possible, each with a classical action
- $->$ Every possible path contributes with equal amplitude to the Propagator, but with a phase related to the classical action (action $->$ complex phase). Summing over all possible trajectories $->$ Propagator
-
\ $U(x', t; x_0) = A(t) sum_("all\ntrajectories") exp[i/hbar overbrace(S[x(t)], "action over\ntrajectory") ]$
- This is the heart of the path integral formulation. How the complete formulation is found is subject to the rest of my notes about the path integral.
- Since all actions for every path contribute to the Propagator one would suspect that it would diverge quite fast. This is not the case since every action for every path will cancel the greate the difference in the action $Delta S approx pi hbar$.
Contributions of trajectories far away from the "classical path", in aggregate, cancel.
- Assume the classical trajectory $x_("cl") (t)$ as the trajectory with the minimum value of the action $S[x_("cl")]$, which is stationary to fist order with regard to deciations.
- trajectory can be observed with high probability(same as little uncerainty? #todo)
- trajectories close contribute with coherent phase to the intefral
- trajectories with action $pi hbar$ more than the classical action ar out of phase and intefere destructively with each other. Integrating over more of such destructive trajectories cause their contribution to average out to zero
- $->$ the calssical trajectory is qualitatively imoprtant
- $pi hbar$ is frightinly small making the principal contributions trajectories those in a narrow band around the classical one. On quantum scale though $pi hbar$ is big enough to cause significant deviations from the classical trajectory
- Propagator for a free particle
- For a particle moving in free spcae along one dimension
- Formular 12 in the paper
- $U(x, t; x_0) = sqrt(m/(2pi i hbar t)) exp[(i m)/(2t hbar) (x-x_0)^2]$ |
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2009/MS-04.typ | typst |
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (1 - 32)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[1], [MA Long], [CHN], [3203],
[2], [WANG Hao], [CHN], [3156],
[3], [MA Lin], [CHN], [3126],
[4], [BOLL Timo], [GER], [3048],
[5], [HAO Shuai], [CHN], [2970],
[6], [XU Xin], [CHN], [2934],
[7], [WANG Liqin], [CHN], [2931],
[8], [SAMSONOV Vladimir], [BLR], [2860],
[9], [CHEN Qi], [CHN], [2823],
[10], [JOO Saehyuk], [KOR], [2804],
[11], [ZHANG Jike], [CHN], [2778],
[12], [OH Sangeun], [KOR], [2745],
[13], [SUSS Christian], [GER], [2734],
[14], [MIZUTANI Jun], [JPN], [2645],
[15], [JIANG Tianyi], [HKG], [2639],
[16], [YOON Jaeyoung], [KOR], [2633],
[17], [ZHANG Chao], [CHN], [2622],
[18], [LEE Jungwoo], [KOR], [2613],
[19], [KO Lai Chak], [HKG], [2612],
[20], [HOU Yingchao], [CHN], [2610],
[21], [PERSSON Jorgen], [SWE], [2609],
[22], [SCHLAGER Werner], [AUT], [2605],
[23], [<NAME>], [AUT], [2597],
[24], [CHUANG Chih-Yuan], [TPE], [2595],
[25], [<NAME>], [GRE], [2590],
[26], [OVTCHAROV Dimitrij], [GER], [2590],
[27], [LI Ching], [HKG], [2587],
[28], [RUBTSOV Igor], [RUS], [2565],
[29], [KAN Yo], [JPN], [2555],
[30], [CHEN Weixing], [AUT], [2553],
[31], [RYU Seungmin], [KOR], [2549],
[32], [YOSHIDA Kaii], [JPN], [2544],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [PRIMORAC Zoran], [CRO], [2543],
[34], [MAZE Michael], [DEN], [2541],
[35], [<NAME>], [ROU], [2534],
[36], [KIM Hyok Bong], [PRK], [2531],
[37], [GERELL Par], [SWE], [2531],
[38], [TANG Peng], [HKG], [2529],
[39], [QIU Yike], [CHN], [2528],
[40], [LI Ping], [QAT], [2513],
[41], [CHEUNG Yuk], [HKG], [2495],
[42], [<NAME>], [GER], [2488],
[43], [<NAME>], [KOR], [2486],
[44], [<NAME>], [SGP], [2481],
[45], [KORBEL Petr], [CZE], [2479],
[46], [<NAME>], [CRO], [2466],
[47], [<NAME>], [RUS], [2454],
[48], [<NAME>], [FRA], [2453],
[49], [<NAME>], [KOR], [2449],
[50], [<NAME>], [POL], [2446],
[51], [<NAME>], [GRE], [2434],
[52], [TUGWELL Finn], [DEN], [2431],
[53], [<NAME>], [KOR], [2423],
[54], [<NAME>], [CHN], [2423],
[55], [<NAME>], [GER], [2411],
[56], [<NAME>], [SWE], [2403],
[57], [<NAME>], [KOR], [2402],
[58], [<NAME>], [DOM], [2402],
[59], [<NAME>], [ROU], [2399],
[60], [<NAME>], [CRO], [2395],
[61], [CHT<NAME>], [BLR], [2389],
[62], [KISHIKAWA Seiya], [JPN], [2386],
[63], [<NAME> Man], [PRK], [2382],
[64], [BLASZCZYK Lucjan], [POL], [2382],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [KOSOWSKI Jakub], [POL], [2380],
[66], [LEGOUT Christophe], [FRA], [2380],
[67], [#text(gray, "XU Hui")], [CHN], [2376],
[68], [MATSUDAIRA Kenta], [JPN], [2375],
[69], [<NAME>], [JPN], [2367],
[70], [<NAME>], [SRB], [2362],
[71], [<NAME>], [NGR], [2359],
[72], [<NAME>], [FRA], [2357],
[73], [<NAME>], [SVK], [2351],
[74], [<NAME>], [BRA], [2349],
[75], [<NAME>], [GER], [2348],
[76], [<NAME>], [ITA], [2345],
[77], [<NAME>-Lung], [TPE], [2342],
[78], [#text(gray, "KEEN Trinko")], [NED], [2328],
[79], [<NAME>], [HKG], [2325],
[80], [<NAME>], [SVK], [2312],
[81], [YANG Min], [ITA], [2312],
[82], [<NAME>], [SGP], [2311],
[83], [<NAME>], [ESP], [2309],
[84], [<NAME>], [RUS], [2307],
[85], [<NAME>], [IND], [2306],
[86], [WU Chih-Chi], [TPE], [2301],
[87], [<NAME>], [ROU], [2300],
[88], [SMIRNOV Alexey], [RUS], [2299],
[89], [<NAME>], [SLO], [2293],
[90], [<NAME>], [AUT], [2287],
[91], [SHMYREV Maxim], [RUS], [2286],
[92], [<NAME>], [TPE], [2285],
[93], [<NAME>], [KOR], [2285],
[94], [<NAME>], [POL], [2279],
[95], [<NAME>], [JPN], [2278],
[96], [<NAME>], [FRA], [2277],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Men's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [<NAME>], [PRK], [2276],
[98], [<NAME>], [KOR], [2275],
[99], [<NAME>], [SVK], [2269],
[100], [<NAME>], [BEL], [2260],
[101], [<NAME>], [GER], [2259],
[102], [LIVENTSOV Alexey], [RUS], [2257],
[103], [<NAME>], [JPN], [2253],
[104], [<NAME>], [CHN], [2248],
[105], [LUNDQVIST Jens], [SWE], [2241],
[106], [DIDUKH Oleksandr], [UKR], [2238],
[107], [<NAME>], [JPN], [2233],
[108], [<NAME>], [CRO], [2232],
[109], [<NAME>], [POR], [2231],
[110], [HUANG Sheng-Sheng], [TPE], [2231],
[111], [#text(gray, "<NAME>")], [CZE], [2228],
[112], [CHANG Yen-Shu], [TPE], [2225],
[113], [ERLANDSEN Geir], [NOR], [2221],
[114], [<NAME>], [CZE], [2219],
[115], [<NAME>], [SGP], [2219],
[116], [<NAME>], [EGY], [2216],
[117], [APOLONIA Tiago], [POR], [2216],
[118], [<NAME>], [DEN], [2216],
[119], [BURGIS Matiss], [LAT], [2211],
[120], [KONECNY Tomas], [CZE], [2211],
[121], [SVENSSON Robert], [SWE], [2210],
[122], [<NAME>], [DEN], [2205],
[123], [<NAME>], [HUN], [2204],
[124], [DRINKHALL Paul], [ENG], [2204],
[125], [MONTEIRO Joao], [POR], [2200],
[126], [LIU Song], [ARG], [2196],
[127], [<NAME>], [ESP], [2195],
[128], [MEROTOHUN Monday], [NGR], [2190],
)
) |
|
https://github.com/Quaternijkon/notebook | https://raw.githubusercontent.com/Quaternijkon/notebook/main/theme.typ | typst | // Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
#let std-smallcaps = smallcaps
#let std-upper = upper
// Overwrite the default `smallcaps` and `upper` functions with increased spacing between
// characters. Default tracking is 0pt.
#let smallcaps(body) = std-smallcaps(text(tracking: 0.6pt, body))
#let upper(body) = std-upper(text(tracking: 0.6pt, body))
// Colors used across the template.
#let stroke-color = luma(200)
#let fill-color = luma(250)
// This function gets your whole document as its `body` and formats it as a simple
// non-fiction paper.
#let ilm(
// The title for your work.
title: [Your Title],
// Author's name.
author: "Author",
// The paper size to use.
paper-size: "a4",
// Date that will be displayed on cover page.
// The value needs to be of the 'datetime' type.
// More info: https://typst.app/docs/reference/foundations/datetime/
// Example: datetime(year: 2024, month: 03, day: 17)
date: none,
// Format in which the date will be displayed on cover page.
// More info: https://typst.app/docs/reference/foundations/datetime/#format
date-format: "[month repr:long] [day padding:zero], [year repr:full]",
// An abstract for your work. Can be omitted if you don't have one.
abstract: none,
// The contents for the preface page. This will be displayed after the cover page. Can
// be omitted if you don't have one.
preface: none,
// The result of a call to the `outline` function or `none`.
// Set this to `none`, if you want to disable the table of contents.
// More info: https://typst.app/docs/reference/model/outline/
table-of-contents: outline(),
// The result of a call to the `bibliography` function or `none`.
// Example: bibliography("refs.bib")
// More info: https://typst.app/docs/reference/model/bibliography/
bibliography: none,
// Whether to start a chapter on a new page.
chapter-pagebreak: true,
// Display an index of figures (images).
figure-index: (
enabled: false,
title: "",
),
// Display an index of tables
table-index: (
enabled: false,
title: "",
),
// Display an index of listings (code blocks).
listing-index: (
enabled: false,
title: "",
),
// The content of your work.
body,
) = {
// Set the document's metadata.
set document(title: title, author: author)
// Set the body font.
// Default is Linux Libertine at 11pt
set text(font: ("Libertinus Serif", "Linux Libertine"), size: 12pt)
// Set raw text font.
// Default is Fira Mono at 8.8pt
show raw: set text(font: ("Jetbrains Mono","PingFang SC","Iosevka", "Fira Mono"), size: 9pt)
// Configure page size and margins.
set page(
paper: paper-size,
margin: (bottom: 1.27cm, top: 1.27cm, left: 1.27cm, right: 1.27cm),
)
// Cover page.封面
page(align(left + horizon, block(width: 90%)[
#let v-space = v(2em, weak: true)
#text(3em)[*#title*]
#v-space
#text(1.6em, author)
#if abstract != none {
v-space
block(width: 80%)[
// Default leading is 0.65em.
#par(leading: 0.78em, justify: true, linebreaks: "optimized", abstract)
]
}
#if date != none {
v-space
// Display date as MMMM DD, YYYY
text(date.display(date-format))
}
]))
// Configure paragraph properties.
// Default leading is 0.65em.
set par(leading: 0.7em, justify: true, linebreaks: "optimized")
// Default spacing is 1.2em.
show par: set block(spacing: 1.35em)
// Add vertical space after headings.
show heading: it => {
it
v(2%, weak: true)
}
// Do not hyphenate headings.
show heading: set text(hyphenate: false)
// Show a small maroon circle next to external links.
// show link: it => {
// // Workaround for ctheorems package so that its labels keep the default link styling.
// if type(it.dest) == label { return it }
// it
// h(1.6pt)
// super(box(height: 3.8pt, circle(radius: 1.2pt, stroke: 0.7pt + rgb("#993333"))))
// }
// Display preface as the second page.
if preface != none {
page(preface)
}
// Indent nested entires in the outline.
set outline(indent: auto)
// Display table of contents.
if table-of-contents != none {
table-of-contents
}
// Configure heading numbering.
set heading(numbering: "1.")
// Configure page numbering and footer.
set page(
footer: context {
// Get current page number.
let i = counter(page).at(here()).first()
// Align right for even pages and left for odd.
let is-odd = calc.odd(i)
let aln = if is-odd { right } else { left }
// Are we on a page that starts a chapter?
let target = heading.where(level: 1)
if query(target).any(it => it.location().page() == i) {
return align(aln)[#link((page: 3, x: 0cm, y: 0cm))[#i]]
}
// Find the chapter of the section we are currently in.
let before = query(target.before(here()))
if before.len() > 0 {
let current = before.last()
let gap = 1.75em
let chapter = upper(text(size: 0.68em, current.body))
if current.numbering != none {
if is-odd {
align(aln)[#link((page: 3, x: 0cm, y: 0cm))[#chapter #h(gap) #i]]
} else {
align(aln)[#link((page: 3, x: 0cm, y: 0cm))[#i #h(gap) #chapter]]
}
}
}
},
)
// Configure equation numbering.
set math.equation(numbering: "(1)")
// Display inline code in a small box that retains the correct baseline.
show raw.where(block: false): box.with(
fill: fill-color.darken(2%),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
// Display block code with padding.
show raw.where(block: true): block.with(
inset: (x: 5pt),
)
// Break large tables across pages.
show figure.where(kind: table): set block(breakable: true)
set table(
// Increase the table cell's padding
inset: 7pt, // default is 5pt
stroke: (0.5pt + stroke-color)
)
// Use smallcaps for table header row.
show table.cell.where(y: 0): smallcaps
// Wrap `body` in curly braces so that it has its own context. This way show/set rules will only apply to body.
{
// Start chapters on a new page.
show heading.where(level: 1): it => {
if chapter-pagebreak { pagebreak() }
it
}
body
}
// Display bibliography.
if bibliography != none {
pagebreak()
show std-bibliography: set text(0.85em)
// Use default paragraph properties for bibliography.
show std-bibliography: set par(leading: 0.65em, justify: false, linebreaks: auto)
bibliography
}
// Display indices of figures, tables, and listings.
let fig-t(kind) = figure.where(kind: kind)
let has-fig(kind) = counter(fig-t(kind)).get().at(0) > 0
if figure-index.enabled or table-index.enabled or listing-index.enabled {
show outline: set heading(outlined: true)
context {
let imgs = figure-index.enabled and has-fig(image)
let tbls = table-index.enabled and has-fig(table)
let lsts = listing-index.enabled and has-fig(raw)
if imgs or tbls or lsts {
// Note that we pagebreak only once instead of each each
// individual index. This is because for documents that only have a couple of
// figures, starting each index on new page would result in superfluous
// whitespace.
pagebreak()
}
if imgs { outline(title: figure-index.at("title", default: "Index of Figures"), target: fig-t(image)) }
if tbls { outline(title: table-index.at("title", default: "Index of Tables"), target: fig-t(table)) }
if lsts { outline(title: listing-index.at("title", default: "Index of Listings"), target: fig-t(raw)) }
}
}
}
// This function formats its `body` (content) into a blockquote.
#let blockquote(body) = {
block(
width: 100%,
fill: fill-color,
inset: 2em,
stroke: (y: 0.5pt + stroke-color),
body
)
}
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1D360.typ | typst | Apache License 2.0 | #let data = (
("COUNTING ROD UNIT DIGIT ONE", "No", 0),
("COUNTING ROD UNIT DIGIT TWO", "No", 0),
("COUNTING ROD UNIT DIGIT THREE", "No", 0),
("COUNTING ROD UNIT DIGIT FOUR", "No", 0),
("COUNTING ROD UNIT DIGIT FIVE", "No", 0),
("COUNTING ROD UNIT DIGIT SIX", "No", 0),
("COUNTING ROD UNIT DIGIT SEVEN", "No", 0),
("COUNTING ROD UNIT DIGIT EIGHT", "No", 0),
("COUNTING ROD UNIT DIGIT NINE", "No", 0),
("COUNTING ROD TENS DIGIT ONE", "No", 0),
("COUNTING ROD TENS DIGIT TWO", "No", 0),
("COUNTING ROD TENS DIGIT THREE", "No", 0),
("COUNTING ROD TENS DIGIT FOUR", "No", 0),
("COUNTING ROD TENS DIGIT FIVE", "No", 0),
("COUNTING ROD TENS DIGIT SIX", "No", 0),
("COUNTING ROD TENS DIGIT SEVEN", "No", 0),
("COUNTING ROD TENS DIGIT EIGHT", "No", 0),
("COUNTING ROD TENS DIGIT NINE", "No", 0),
("IDEOGRAPHIC TALLY MARK ONE", "No", 0),
("IDEOGRAPHIC TALLY MARK TWO", "No", 0),
("IDEOGRAPHIC TALLY MARK THREE", "No", 0),
("IDEOGRAPHIC TALLY MARK FOUR", "No", 0),
("IDEOGRAPHIC TALLY MARK FIVE", "No", 0),
("TALLY MARK ONE", "No", 0),
("TALLY MARK FIVE", "No", 0),
)
|
https://github.com/jgm/typst-hs | https://raw.githubusercontent.com/jgm/typst-hs/main/test/typ/compiler/string-14.typ | typst | Other | // Test the `replace` method with `Str` replacements.
#test("ABC".replace("", "-"), "-A-B-C-")
#test("Ok".replace("Ok", "Nope", count: 0), "Ok")
#test("to add?".replace("", "How ", count: 1), "How to add?")
#test("AB C DEF GH J".replace(" ", ",", count: 2), "AB,C,DEF GH J")
#test("Walcemo"
.replace("o", "k")
.replace("e", "o")
.replace("k", "e")
.replace("a", "e"),
"Welcome"
)
#test("123".replace(regex("\d$"), "_"), "12_")
#test("123".replace(regex("\d{1,2}$"), "__"), "1__")
|
https://github.com/dccsillag/moremath.typ | https://raw.githubusercontent.com/dccsillag/moremath.typ/main/moremath.typ | typst | MIT License | // === GENERIC ===
// A handy thing to slightly increase parentheses size. E.g.:
// `big((x - y) - (y - z))` will make the external parentheses a bit bigger
#let big(x) = math.lr(x, size: 150%)
#let bigp(x) = big($(#x)$)
// A wrapper to number a single equation
#let numbered(x) = {
set math.equation(numbering: "(1)")
x
}
// TODO: not implies, not implied by, not iff; generic "not" (like `\not` in LaTeX)?
// Handy cursive letters (only uppercase for now)
#let aa = $cal(A)$
#let bb = $cal(B)$
#let cc = $cal(C)$
#let dd = $cal(D)$
#let ee = $cal(E)$
#let ff = $cal(F)$
#let gg = $cal(G)$
#let hh = $cal(H)$
#let ii = $cal(I)$
#let jj = $cal(J)$
#let kk = $cal(K)$
#let ll = $cal(L)$
#let mm = $cal(M)$
#let nn = $cal(N)$
// #let oo = $cal(O)$
#let pp = $cal(P)$
#let qq = $cal(Q)$
#let rr = $cal(R)$
#let ss = $cal(S)$
#let tt = $cal(T)$
#let uu = $cal(U)$
#let vv = $cal(V)$
#let ww = $cal(W)$
#let xx = $cal(X)$
#let yy = $cal(Y)$
#let zz = $cal(Z)$
// === PROBABILITY THEORY ===
#let indep = $perp #h(-1em) perp$ // Independence relation
#let nindep = $cancel(indep)$ // Non-independence relation FIXME
#let Pr = math.op("Pr") // Alternative notation for probability
#let Ex = math.op("Ex") // Alternative notation for expectation
#let Var = math.op("Var") // Variance
#let Cov = math.op("Cov") // Covariance
#let ind = math.bb($1$) // Indicator
#let iid = math.upright("iid")
// === MISCELANEOUS IDENTITIES ===
#let sign = math.op("sign")
#let argmin = math.op("arg min", limits: true)
#let argmax = math.op("arg max", limits: true)
// === OPTIMIZATION, ANALYSIS and CALCULUS ===
#let dist = math.upright("d") // metric
#let deriv = math.upright("D") // general derivative operator
// Landau notation:
#let oh = $cal(o)$
#let Oh = $cal(O)$
#let ohmega = $cal(omega)$ // hmmm...
#let Ohmega = $cal(Omega)$ // hmmm...
#let Thetah = $cal(Theta)$ // hmmm...
|
https://github.com/litchipi/docgen | https://raw.githubusercontent.com/litchipi/docgen/main/.invoice.typ | typst | #set page(
paper: "a4",
margin: 8%,
)
#set text(font: "Roboto", 13pt)
#let table_color() = rgb(110, 140, 180, 205)
#let horiz_line_color() = rgb(53, 80, 220, 100)
#let sep_par() = 28pt
#grid(
columns: (1fr, auto),
align(left, text(23pt)[Timothée CERCUEIL]),
align(right)[LOGO ICI]
)
#align(left, text(14pt)[
5 rue du Rhin, 44470 Carquefou \
<EMAIL> \
Entrepreneur Individuel \
SIRET: 02340234023402340
])
#v(sep_par())
#grid(columns: (1fr, 1fr), column-gutter: 10%,
align(left)[
#text(17pt)[*Facturé à*] \
Société CASEDI SARL \
24 rue de la Fosse, 44470 Carquefou \
],
align(right)[Numéro de facture *050-3192394* \
Créée le *5 Janvier 2024* \
Date de la prestation: *3 Janvier 2024*],
)
#v(sep_par())
#table(
stroke: table_color(),
columns: (3fr, 1fr, 1fr, 1fr),
[*Prestation*], [*Nombre d'heures*], [*Prix de l'heure*], [*Total HT*],
"Conseil en informatique", "5", "25€", "125€",
"Gestion d'un conflit de version dans la base de donnée ", "3", "30€", "90€"
)
#v(sep_par())
#table(
stroke: table_color(),
columns: (auto, auto),
[*Total HT*], [215€],
[*TVA 20%*], [43€],
// [*TVA non applicable* - article 293B du CGI], [],
[*TOTAL TTC*], [258€]
)
#v(230pt)
#set text(font: "Spectral", 12pt)
#line(length: 100%, stroke: horiz_line_color())
Some terms applicable I think but I'm not sure
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/docs/cookery/guide/all-in-one-inputs.typ | typst | Apache License 2.0 | === Example: get output from input
get output with *single input file*:
```ts
const mainContent = 'Hello, typst!';
// into vector format
await $typst.vector({ mainContent });
// into svg format
await $typst.svg({ mainContent });
// into pdf format
await $typst.pdf({ mainContent });
// into canvas operations
await $typst.canvas(div, { mainContent });
```
With some extra *input file*:
```ts
await $typst.addSource('/template.typ', templateContent);
```
With extra *binary input files*:
```ts
const encoder = new TextEncoder();
// add a json file (utf8)
compiler.mapShadow('/assets/data.json', encoder.encode(jsonData));
// remove a json file
compiler.unmapShadow('/assets/data.json');
// add an image file
const pngData = await fetch(...).arrayBuffer();
compiler.mapShadow('/assets/tiger.png', new Uint8Array(pngData));
```
clean up shadow files for underlying access model:
```ts
compiler.resetShadow();
```
Note: this function will also clean all files added by `addSource`.
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/039_Theros%3A%20Beyond%20Death.typ | typst | #import "@local/mtgset:0.1.0": conf
#show: doc => conf("Theros: Beyond Death", doc)
#include "./039 - Theros: Beyond Death/001_Theros Beyond Death Story Summary.typ"
|
|
https://github.com/7sDream/fonts-and-layout-zhCN | https://raw.githubusercontent.com/7sDream/fonts-and-layout-zhCN/master/chapters/04-opentype/designspace.typ | typst | Other | #import "/lib/draw.typ": *
#import "/template/lang.typ": khmer
#let start = (0, 0)
#let end = (900, 580)
#let graph = with-unit((ux, uy) => {
// mesh((0, 0), (1000, 600), (100, 100), stroke: 1pt + gray)
shape(
((150, 200), (150, 150)),
((150, 400), (150, 350)),
((250, 500), (200, 500)),
((750, 500), (700, 500)),
((850, 400), (850, 450)),
((850, 200), (850, 250)),
((750, 100), (800, 100)),
((250, 100), (300, 100)),
closed: true,
fill: choose(gray.lighten(20%), gray.darken(20%)),
)
point((100, 150), radius: 10)
arrow((100, 150), (100, 480), stroke: 3*ux + theme.main, head-scale: 5)
txt(rotate(-90deg, reflow: true)[字宽], (110, 300), anchor: "lc", size: 30 * ux)
point((500, 70), radius: 10)
arrow((500, 70), (230, 70), stroke: 3*ux + theme.main, head-scale: 5)
arrow((500, 70), (770, 70), stroke: 3*ux + theme.main, head-scale: 5)
txt([字重], (500, 40), anchor: "ct", size: 30*ux)
let xs = (250, 500, 750)
let weights = ((300, [细]), (400, [常规]), (700, [粗]))
let ys = (180, 450)
let widths = ((100%, ""), (50%, [窄]))
for (y, (width, width-desc)) in ys.zip(widths) {
for (x, (weight, weight-desc)) in xs.zip(weights) {
txt(text(weight: weight, stretch: width)[#khmer[\u{179B}]], (x, y), size: 100 * ux)
txt(weight-desc + width-desc + [体], (x, y + 60), size: 32 * ux, anchor: "cb")
}
}
txt([设计空间], (500, 330), size: 32 * ux)
})
#canvas(end, start: start, width: 80%, graph)
|
https://github.com/chendaohan/bevy_tutorials_typ | https://raw.githubusercontent.com/chendaohan/bevy_tutorials_typ/main/08_queries/queries.typ | typst | #set page(fill: rgb(35, 35, 38, 255), height: auto, paper: "a3")
#set text(fill: color.hsv(0deg, 0%, 90%, 100%), size: 22pt, font: "Microsoft YaHei")
#set raw(theme: "themes/Material-Theme.tmTheme")
= 1. 查询
查询可以让你访问实体的组件。使用 Query 系统参数,你可以指定要访问的数据,并可选择额外的过滤器。
你在 Query 中输入的类型,作为你想要访问的实体的“规范”。查询将匹配符合你规范的 ECS 世界中的哪些实体。然后,你可以以不同的方式使用查询,从这些实体中访问相关的数据。
= 2. Query Data
Query 的第一个类型参数是你想要访问的数据。使用 & 进行共享/只读访问,使用 &mut 进行独占/可变访问。
```Rust
fn level_info(levels: Query<&Level>)
fn add_health(mut health: Query<&mut Health>)
```
如果组件不是必须的(有没有这个组件都行的实体),请用 Option 。如果你想要多个组件,请将它们放在一个元组中。
```Rust
fn health_info_my_player_add_marker(health: Query<(&Health, Option<&MyPlayer>)>)
```
如果你想知道你正在访问的实体的 ID,你可以在 Query 中加入 Entity 类型。如果你需要稍后对这些实体执行特定操作,这将非常有用。
```Rust
fn position_entity_info(positions: Query<(Entity, &Position)>)
```
= 3. 迭代
最常见的操作是迭代 Query ,以访问每个匹配实体的组件值。Query 可以通过调用 iter() / iter_mut() 方法转换为迭代器,这样就可以调用迭代器适配器了。
```Rust
fn level_info(levels: Query<&Level>) {
levels.iter().for_each(|level| {
info!("level: {level:?}");
});
}
fn add_health(mut health: Query<&mut Health>) {
health.iter_mut().for_each(|mut health| {
health.0 += 1;
});
}
```
= 4. 访问特定实体
要从一个特定的实体访问组件,你需要知道实体 ID :
```Rust
fn level_info_by_parent(parents: Query<&Parent>, levels: Query<&Level>) {
let parent = parents.single().get();
if let Ok(level) = levels.get(parent) {
info!("parent level: {level:?}");
}
}
```
如果你想要一次访问多个实体的数据,可以使用 many() / many_mut() (在错误时 panic)或 get_many() / get_many_mut() (返回 Result) 或 iter_many() / iter_many_mut() (返回迭代器)。这些方法请确保所有的 Entity 与查询匹配,否则将产生错误。
```Rust
fn health_info_by_children(children: Query<&Children>, health: Query<&Health>) {
let Ok(children) = children.get_single() else {
return;
};
let mut children = children.iter();
let entity_1 = *children.next().unwrap();
let entity_2 = *children.next().unwrap();
let Ok([health_1, health_2]) = health.get_many([entity_1, entity_2]) else {
return;
};
println!("many child health_1: {health_1:?}, health_2: {health_2:?}");
for health in health.iter_many(children) {
info!("child health: {health:?}");
}
}
```
= 5. 独特实体
如果你知道应该只存在一个匹配的实体,你可以使用 single() / single_mut() (在错误时 panic)或 get_single() / get_single_mut() (返回 Result)。这些方法确保存在恰好一个候选实体可以匹配你的查询,否则将产生错误。
```Rust
fn level_info_by_parent(parents: Query<&Parent>, levels: Query<&Level>) {
let parent = parents.single().get();
if let Ok(level) = levels.get(parent) {
info!("parent level: {level:?}");
}
}
fn health_info_by_children(children: Query<&Children>, health: Query<&Health>) {
let Ok(children) = children.get_single() else {
return;
};
for health in health.iter_many(children) {
info!("child health: {health:?}");
}
}
```
= 6. 组合
如果你想遍历 N 个实体的所有可能组合,Bevy 也提供了一个方法。如果实体很多,这可能会变得非常慢!
```Rust
fn level_combinations(levels: Query<&Level>) {
levels.iter_combinations().for_each(|[level1, level2]| {
info!("level 1: {level1:?}, level 2: {level2:?}");
});
}
```
= 7. Query Filter
添加查询过滤器以缩小从查询中获取的实体范围。
这是通过使用 Query 类型的第二个(可选)泛型类型参数来完成的。
注意查询的语法:首先指定你想要访问的数据(使用元组访问多个内容),然后添加任何额外过滤条件(也可以用元组添加多个)。
使用 With 来过滤有某个组件的实体,用 Without 来过滤没有某个组件的实体。
```Rust
fn my_player_health(health: Query<&Health, With<MyPlayer>>) {
health.iter().for_each(|health| {
info!("my player health: {health:?}");
})
}
fn without_my_player_health(health: Query<&Health, Without<MyPlayer>>) {
health.iter().for_each(|health| {
info!("without my player health: {health:?}");
});
}
```
这在你实际上不关心这些组件内部存储的数据时很有用,但你想确保你的查询只查找具有(或不具有)它们的实体。如果你想要数据,那么将组件放在查询的第一部分,而不是使用过滤器。
可以组合多个过滤器:
- 在一个元组中 (与逻辑)
- 用 Or 包装来检测满足其中任一个 (或逻辑)
```Rust
fn my_player_and_player_level(levels: Query<&Level, (With<MyPlayer>, With<Player>)>) {
levels.iter().for_each(|level| {
info!("my player level: {level:?}");
})
}
fn my_player_or_player_level(levels: Query<&Level, Or<(With<MyPlayer>, With<Player>)>>) {
levels.iter().for_each(|level| {
info!("player level: {level:?}");
});
}
``` |
|
https://github.com/fenjalien/metro | https://raw.githubusercontent.com/fenjalien/metro/main/tests/num/digit-group-size/test.typ | typst | Apache License 2.0 | #import "/src/lib.typ": num, metro-setup
#set page(width: auto, height: auto)
#num[1234567890]
#num(digit-group-size: 5)[1234567890]
#num(digit-group-other-size: 2)[1234567890] |
https://github.com/weeebdev/cv | https://raw.githubusercontent.com/weeebdev/cv/main/modules/education.typ | typst | Apache License 2.0 | #import "../brilliant-CV/template.typ": *
#cvSection("Education")
#cvEntry(
title: [Master of Computer Science],
society: [Nazarbayev University, Astana],
date: [2022 - 2024],
location: [Kazakhstan],
logo: "../src/logos/ucla.png",
description: list(
[Thesis: Federated Learning for Wearable Sensor Data],
[GPA: 3.54/4.0],
// [Course: Big Data Systems and Technologies #hBar() Data Mining and Exploration #hBar() Natural Language Processing]
)
)
#cvEntry(
title: [Bachelors of Information Systems],
society: [Suleyman Demirel University, Almaty],
date: [2018 - 2022],
location: [Kazakhstan],
logo: "../src/logos/ucla.png",
description: list(
[Thesis: Development of audio journaling application Memento for people with cognitive impairments],
[GPA: 3.93/4.0],
// [Course: Database Systems #hBar() Computer Networks #hBar() Software Engineering #hBar() Artificial Intelligence]
)
)
|
https://github.com/protohaven/printed_materials | https://raw.githubusercontent.com/protohaven/printed_materials/main/shop-posters/large_format_laser-prohibited_materials.typ | typst | #import "/meta-environments/env-posters.typ": *
#show: doc => large_poster(
title: "Prohibited Materials",
category: "Large Format Laser",
authors: ("<NAME> <<EMAIL>>",),
doc
)
// Content goes here
#block[
#set text(size: 32pt)
#let pro_materials = csv("/data-reference/large_format_laser/prohibited_materials.csv").map(l => l.slice(0,-1))
#let table_header = pro_materials.remove(0)
#table(
columns: (auto, 1fr),
stroke: none,
align: left,
inset: (
x: 48pt,
y: 16pt,
),
fill: (_, y) => if calc.odd(y) { color.tablegrey },
table.header(..table_header.map(h => strong(h))),
table.hline(),
..pro_materials.flatten()
)
] |
|
https://github.com/morrisfeist/cvgen | https://raw.githubusercontent.com/morrisfeist/cvgen/master/template/theme.typ | typst | MIT License | #import "data.typ": data
#let theme = (:)
#{
for (key, value) in json(sys.inputs.THEME).at(data.theme.flavor).colors {
theme.insert(key, rgb(value.hex))
}
theme.insert("primary", theme.at(data.theme.primary))
theme.insert("secondary", theme.at(data.theme.secondary))
}
|
https://github.com/jassielof/typst-templates | https://raw.githubusercontent.com/jassielof/typst-templates/main/upsa-bo/estudio-de-factibilidad/template/estudio-de-factibilidad.typ | typst | MIT License | #import "../lib.typ": *
#show: estudio-de-factibilidad.with(
título: [Estudio de Factibilidad],
materia: [SIGLA: Proyectos],
fecha: [Segundo Semestre, 2024],
docente: [Ing. <NAME>],
estudiantes: [
Estudiante 1 Nombre#super[4] \
Estudiante 2 Nombre#super[5] \
],
facultades-carreras: [
#super[4] FAI: Facultad de Ingeniería, Ingeniería de Sistemas \
#super[5] FAI: Facultad de Ingeniería, Ingeniería Industrial y de Sistemas \
],
abstracto: lorem(50),
resumen-ejecutivo: lorem(50),
bibliografía: "referencias.yml",
)
#[
#show: contenido-principal.with()
#include "capítulos/1.introducción.typ"
#include "capítulos/2.marco teórico.typ"
#include "capítulos/3.diagnóstico interno de la empresa.typ"
#include "capítulos/4.estudio de la materia prima e insumos.typ"
#include "capítulos/5.estudio de mercado.typ"
#include "capítulos/6.localización y tamaño.typ"
#include "capítulos/7.estudio de ingeniería.typ"
#include "capítulos/8.inversiones.typ"
#include "capítulos/9.presupuesto de ingresos y costos.typ"
#include "capítulos/10.financiamiento.typ"
#include "capítulos/11.evaluación social y ambiental.typ"
#include "capítulos/12.diseño de la organización.typ"
#include "capítulos/13.evaluación económica y financiera.typ"
#include "capítulos/14.conclusiones y recomendaciones.typ"
]
#bibliography(
"referencias.yml",
full: true,
title: [Bibliografía],
style: "apa",
)
#show: anexos.with()
= Instrumentos para la Recolección de Información
== Guías de Entrevistas
== Cuestionarios
== Etc.
= Propios de la Investigación
= Cálculos, Tablas, Cotizaciones, Etc.
= Curriculum Vitae
|
https://github.com/LDemetrios/TypstTuringMachine | https://raw.githubusercontent.com/LDemetrios/TypstTuringMachine/main/README.md | markdown | # The Turing Machine in Typst
You all know that Typst is Turing-complete, right?
Well, I wrote an actual Turing Machine!
### But why?
Well, I had a lab in University with task to write several programs in TM language.
And all the interpreters I found on internet are quite slow or have an inconvenient interface,
so I decided to write one myself.
And, when something needs visualization, Typst is the first that comes to my head.
And here we are...
Huge thanks goes out to [@sitandr](https://github.com/sitandr), who helped very much with the layout look and performance!
### OK, show me
You're welcome! Here's a simple program that accepts an even number of zeroes, and rejects an odd one:
```
Start 0 -> Even 0 ^
Even _ -> Accept _ ^
Even 0 -> Odd _ >
Odd 0 -> Even _ >
Odd _ -> Reject _ ^
```
Here `Start`, `Accept` and `Reject` are predefined states. `_` means an empty cell, `<`, `>`, `^` mean "go left", "go right" and "stay" respectively.
Starting with `Even`, the machine alternates its state every step. If it sees an empty cell, it considers the input to be ended,
and changes to accepting state if `Even`, or to rejecting state if `Odd`.
And here's the visualization, with `000` given as input:
<img src="./examples/zero.png" width="300" />
### How do I use it?
There are three functions you need to know about, all described in the `turing.typ` file.
+ `parse-code` — exactly what it says on the package, parses the code.
It accepts a string or a code block, and returns the internal representation of the automaton.
+ `run` — runs the code until the machine accepts the result, rejects it, breaks, or reaches the timelimit.
It accepts the initial state (which is an array of tapes, where tape is an array of symbols, where symbol is a string), and the rules.
The rules should be something that `parse-code` returns.
You can also specify custom starting, accepting and rejecting state names.
Returns the pair of the `data` and the ending state.
The ending state is `none` if the machine broke, or the last state machine was in, otherwise.
Note that if machine broke, there is still data about its evaluation
+ `trace` — displays the evaluation process. Accepts the data received from `run`, and the last state. You can also specify the `break-every` parameter to insert a pagebreak after each couple of state changes.
All the above also support multi-taped Turing Machines,
see `postfixlogic` for the syntax and the logic behind using it.
So, regularly the usage is as follows:
```typ
#let rules = parse-code(read("postfixlogic.tm"))
#let initial-state = (to-arr("01|0&1|"), to-arr("_"))
#let (data, endstate) = run(initial-state, rules, lim-steps: 1000)
#trace(data, endstate, break-every: 10)
```
`to-arr` is a util function which turns a string into array of chars.
### What are those other files?
They are examples of code (`.tm` files) and its evaulation on sample inputs (`.pdf` files).
Unless otherwise stated, all the numbers are in binary format.
+ `aplusb`
Adds two numbers, separated by `+`. For example, it turns `10+11` into `101`.
+ `balanced`
Checks if the input contains only parentheses which are correctly matched. For example, it accepts `(()())` and rejects `())(`.
+ `convertto2`
Converts a number from a ternary form to a binary form.
For example, it turns `102` (ternary for eleven) into `1011`.
+ `less`
Compares two numbers separated by `<`. For example, it rejects `11<10`
+ `mirror`
Appends a reversed number to itself. For example, it turns `10100` into `1010000101`.
+ `tandem`
Checks if a number string consists of two repeating words. For example, it accepts `110110`.
+ `factorial`
This is where I got bored writing for TM with only one tape, so I hardcoded all the factorials from 0! to 30! in base-32 system, and then wrote turning base-32 to binary. It passed all the tests, by the way.
+ `postfixlogic`
And there come multitaped machines.
This one uses a second tape as a stack for evaluating an expression written in Polish notation. For example, it evaluates `01|0&1|` to `1`.
Don't forget to pass extra empty tapes to the `run` function!
+ `infixlogic`
And more of it, this time there is a usual infix notation: `(0|0|1)&1&0` should be evalutated to 0. This almost is the idea of two-stack machine, and the evaluation is divided into three phases: first it eliminates `&`s, then `|`, and then parentheses.
And repeats if there's something left.
+ `sorting`
Yeah, right. It uses the bubble sort, not the in-place merge sort, sorry for that. Yet it anyway required four tapes and countless efforts to avoid getting confused.
|
|
https://github.com/lxl66566/my-college-files | https://raw.githubusercontent.com/lxl66566/my-college-files/main/信息科学与工程学院/电子认识实习/report.typ | typst | The Unlicense | // typst 0.10.0
#import "../template.typ": *
#import "@preview/mitex:0.2.2": *
#import "@preview/tablem:0.1.0": tablem
#let project(
title: "电子认识实习",
authors: ("absolutex"),
body,
) = {
set document(author: authors, title: title)
set text(font: 字体.宋体, size: 字号.小四, lang: "zh", region: "cn")
set page(
numbering: (..nums) => {
"第" + str(nums.pos().at(0)) + "页,共" + str(nums.pos().at(-1)) + "页"
},
number-align: center,
margin: (top: 2.5cm, bottom: 2.5cm, left: 2.5cm, right: 1.5cm),
header: [
#set align(center)
#set text(font: 字体.宋体, size: 字号.小五)
《电子认识实习》报告
],
)
set par(first-line-indent: 2em)
show heading: it => {
it
fake_par
}
// heading,一级标题换页且不显示数字,首行居中
set heading(numbering: (..nums) => if nums.pos().len() == 1 {
中文数字(nums.pos().first()) + "、"
} else {
nums.pos().slice(1).map(str).join(".") + "."
})
show heading: it => {
if it.level == 1 {
text(size: 字号.小三, font: 字体.黑体, it)
} else if it.level == 2 {
text(size: 字号.小四, font: 字体.黑体, it)
} else if it.level == 3 {
text(size: 字号.小四, it)
} else {
text(size: 字号.五号, it)
}
}
// figure(image)
show figure.where(kind: image): it => {
set align(center)
it.body
{
set text(font: 字体.宋体, size: 字号.五号, weight: "extrabold")
h(1em)
it.caption
}
}
// raw with frame
show raw: set text(font: 字体.代码)
show raw.where(block: true): it => frame()[#it]
set enum(numbering: "1.")
show outline: ol => {
show heading: it => {
align(center)[#text(size: 字号.小三, font: 字体.黑体, it)]
}
set par(first-line-indent: 0pt)
ol
}
show outline.entry: it => {
set text(font: 字体.宋体, size: 字号.小四)
it
}
set outline(indent: auto)
outline()
pagebreak()
align(center)[#text(size: 字号.三号, font: 字体.黑体, "数字式交流电压表设计")]
body
}
#let answer(body) = {
text(font: 手写字体, body)
}
#show: project.with(
title: "电子认识实习",
authors: ("absolutex",),
)
= 设计要求
+ 输入交流电压范围:0~200mV(有效值)
+ 要求用三位 LED 数显测得的电压值,分辨率为 1 mV
+ 可用的主要元器件:高阻抗双运放 LF353N、通用运放 LM741、MC14433
+ 实验器材:示波器、万用表、函数信号发生器、交流毫伏表、直流电源
+ 电源电压:±5V
= 设计过程
== 系统功能
本实验要求设计一个数字式交流电压表,其功能是:测量输入交流电压,并在数字显示管上显示测量结果。
== 设计流程
#figure(
image("static/1.png", width: 80%),
caption: [设计流程],
)
== 整流滤波、放大电路
#figure(
image("static/2.png", width: 80%),
caption: [整流滤波、放大电路原理图],
)
由于输入量是交流信号,因此首先必需将交流信号变为直流信号,图 2 电路可以实现上述要求。
设:R1=R3=R4=R7=R8=10K,R2=R5=5.1K,R6=20K,R9=100K。
当 $V_i>0$ 时,$D_2$ 导通,$D_1$反向偏置,$A 1$ 为同向放大器。
此时,$V_(o 1)=(R_1+R_3)/(R_1)V_i=2V_i$,A2 则将反向输入端的 $V_(o 1)$ 及同向输入端的 $V_i$信号同时放大,#mi[`V_{o2}=-\frac{R_6}{R_4}V_{o1}+\frac{R_4+R_6}{R_4}V_i=-V_i`]。
当 $V_i <0$ 时,$D_1$导通,$D_2$反向偏置,A1 为增益等于 1 的跟随器,$V_(o 1)=V_i$。
A2则将反向输入端的$V_(o 1)$及同向输入端的$V_i$信号同时放大,#mi[`\mathrm{V}_{\mathrm{o}2}=-\frac{\mathrm{R}_6}{\mathrm{R}_4+\mathrm{R}_3}\mathrm{V}_{\mathrm{o}1}+\frac{\mathrm{R}_3+\mathrm{R}_4+\mathrm{R}_6}{\mathrm{R}_3+\mathrm{R}_4}\mathrm{V}_i=\mathrm{V}_i`],因此,$V_(o 2) = −V_i$ ,$V_(o 2)$的线性度不受二极管非线性的影响。
A3 作反相放大,将输入信号放大至 0~2V 标准信号。$R_9$、$W_1$、$C_2$ 组成滤波。
== A/D 转换、译码驱动、数字显示
#figure(
image("static/3.png", width: 80%),
caption: [由 MC14433 集成电路组成的 3 位半数字电压表原理图],
)
A/D 转换、译码驱动、数字显示采用 MC14433 组成的 3 位半数字电压表电路,如图 3 所示。
用数字方法处理模拟信号时,必须先将模拟量转换成数字量,这是由模拟—数字转换器(A/D)完成的。
A/D 转换的方法很多,本实验用到的 MC14433是双积分式 A/D 转换器。双积分式 A/D 转换器的特点是线路结构简单,外接元件少,抗共模干扰能力强,但转换速度较慢(3~10次/秒),使用时只要外接两个电阻和两个电容就能执行$3 1/2$位的 A/D 转换。由于它的二—十进制转换码采用数据轮流扫描输出方式,因而只需一块七段译码显示 $3 1/2$位十进制数,大大节省了外部电路的数量和显示电路的功耗,这对 LED 显示的数字表特别有利。
== 设计结果
本次实验分为两个模块,一个是模拟信号处理电路,另一个是A/D转换与数字显示电路。图 4 是模拟信号处理电路的原件排列图:
#figure(
image("static/circuit.png", width: 80%),
caption: [元件排列图],
)
其中,电阻 R1,R3,R4,R7,R8 为 $10K Omega$,电阻 R6 为 $20K Omega$,W1 为 $33K Omega$ 可调电位器,W2 为 $10K Omega$ 可调电位器。
此设计图使用了尽可能少的飞线(共计 4 根),具有较好的物理稳定性。但是这也导致了其余焊点连接较多,锡的使用量较大,并且提高了焊点连接的难度。
= 制作过程
下图为最终焊接的成果:
#figure(
image("static/12.jpg", width: 60%),
caption: [左图为正面,右图为背面],
)
下图为 LM353 1 脚的二倍正弦波波形与 7 脚的全波整流波形:
#figure(
image("static/wave1.jpg", width: 50%),
caption: [1 脚波形],
)
#figure(
image("static/wave2.jpg", width: 50%),
caption: [7 脚波形],
)
调试时,先尝试调零。将电位器 W1 与 W2 均调至极限档位,在交流信号输入幅值为0时有 4.2 mV 的示数。将输入幅值调为200 mV,调整 W1 使数字管显示 199.1 mV,此时调零示数为 4.7 mV。
#figure(
image("static/3.jpg", width: 40%),
caption: [调零示数:4.7 mV],
)
#figure(
image("static/4.jpg", width: 40%),
caption: [最大幅值示数:199.1 mV],
)
= 数据处理
#tablem[
|输入信号有效值(mV)|显示电压有效值(mV)|误差(mV)|输入信号有效值(mV)|显示电压有效值(mV)|误差(mV)|
|---|---|---|---|---|---|
|0|4.7|4.7|110| 108.5|1.5|
|10| 12.9|2.9|120| 118.4|1.6|
|20| 23.0|3.0|130| 127.9|2.1|
|30| 31.6|1.6|140| 137.7|2.3|
|40| 41.2|1.2|150| 147.1|2.9|
|50| 52.5|2.5|160| 157.5|2.5|
|60| 61.9|1.9|170| 170.6|0.6|
|70| 71.7|1.7|180| 180.0|0.0|
|80| 81.2|1.2|190| 190.4|0.4|
|90| 90.5|0.5|200| 199.9|0.1|
|100| 98.9|1.1| | | |
]
输入信号为 0 时,
#figure(
image("static/data1.png", width: 60%),
caption: [输入信号与输出信号的关系],
)
可以看出输入信号与输出信号大致呈线性关系,并且数值基本相同。
#figure(
image("static/data2.png", width: 60%),
caption: [输入信号与误差的关系],
)
误差总体呈下降趋势,但相关性不明显。
= 问题解决
我们组选择自己设计电路,在最初的一个多小时里都在设计。电路的设计目标是尽可能减少飞线的数量。在设计过程中我发现,想要减少飞线数量,核心之处在于巧妙使用电子元件本身跨越电路板里预留的线。
设计完后,开始焊接,刚焊了两个元件,就发现一个设计上的失误:电路板的孔很小,无法穿过两个元件的引脚,也就是说元件贴合处无法重合。于是重新修改设计图,所幸改动并不麻烦。
又焊了几个元件,此时队友需要二极管元件找不到来问我,我才发现我焊错了二极管。本次实验有两种二极管,不同的电路用的是不同的二极管,我用成了队友的二极管。于是只好拆掉重焊。
我这里焊接是先焊所有小元件,包括电阻,贴片电容,然后再焊针座,最后焊电位器和电解电容,这样的好处是电路板可以放平,无需额外操作。我的队友先焊接更高的针座,然后再焊接小元件,这样元件会下坠,需要人手帮忙将元件提高,使其贴合电路板。
元件焊好以后只是个开始,接下来就是连接焊点。指导中说直接用锡连接焊点,但是实际操作时并不容易。锡很容易粘在烙铁上,并且锡中的助焊剂总是倾向于分离焊点,因此需要极大量的锡使其强制粘连。然后过多的锡在高温下成为流体,又会从电路板中的小洞里流下去,上面加得越多,下面漏下去的也越多,造成了不小的困扰。这里我采用了不同的解决办法:对长的焊点连接,使用元件上剪下的铁丝辅助;而短的焊点如果从孔里漏下去了太多的锡,可以从电路板正面继续连接。
使用铁丝辅助也不是简单的事。实验室的镊子太大,铁丝比较小,无法固定,铁丝很容易到处跑。并且实验室中没有夹具夹电路板,需要两个人共同才能完成电路板固定与焊点连接。
后来飞线倒是比较简单,本来这个方案飞线就少,而且飞线比连接焊点简单多了,只要对准,然后跟普通的元件焊接一样即可。
好不容易焊接完成,然后使用万用表测试连通性又发现了几个错连的焊点。由于电路板正反对照比较麻烦,不容易看出连接错误,必须用万用表测试。然后重新清理这些焊点并连接。又发现了电位器用错了,W1 与 W2 的阻值是不同的,不能够混用,于是又重新焊接。
重新焊接时,难免会遇到焊孔被堵住的情况。此时可以将电路板竖直放置,我用烙铁融化,队友使用吸锡器将锡吸出。吸锡器的数量很少,并且很多同学不会将其还回来。遇到焊错后需要尽快处理,否则随着时间的推移,吸锡器会越来越抢手,更难拿到。
在后续调试时,发现芯片的 1 脚是正常的正弦波,而 7 脚理应是全波整流的波形却变成了半波整流。跟着实验指导自查,然后用万用表自查也都无法找到问题。跟其他同学交流后得知应该是漏了线,然而自己检查却检查不出。于是只好找老师,老师的丰富经验很快就定位出了问题所在,LM353 芯片 6 脚和 7 脚的电阻是断路而不是理应的 20K。继续排查发现是被飞线覆盖的一个点漏焊了。在补焊后,电路正常工作,出现了漂亮的全波整流波形。
后来调试也没有遇到太多问题。主要是调零过程并不能使示数真正调到 0,我们原以为是电路问题,后来发现其他的小组也会有这个问题,应该是电子元件本身的误差导致的。
= 实验体会
经历了一天的痛苦并快乐的课程设计实践,我的收获颇丰。
+ 课程设计对我的实践能力和动手能力提出了较高的要求。我们之前只在工程训练中接触了非常基础的焊接技术,而本次实验要求较高,通过设计电路排布、焊接电路板元件等实际操作,将课堂上学到的理论知识应用到实际问题中,培养实践动手能力和解决问题的能力。我在实践中学到了很多课上学不到的焊接经验,培养了我解决实际问题的思维和能力。
+ 课程设计注重团队合作与沟通能力的培养。我和同伴分别负责模拟板和数字板的焊接,通过与小组同伴有效沟通、协调和分工合作,我们的工作能够高效地在一天内完成。其中,团队合作精神和合作能力得以体现。特别是吸锡器的使用一般需要两人共同完成。
+ 在设计过程中,要将模拟电路图设计转换成元件排布图,这锻炼了我的电路设计能力。思考如何能够做得更好是一件很快乐的事,能够给我很大的满足感。
+ 在调试中可能会遇到各种技术难题和困难,需要学生具备独立思考和解决问题的能力。在调试阶段,我们遇到了输出波形错误的问题,通过逐级分析的方法,使用万用表对许多焊点进行测量,最后发现有漏焊的情况。
+ 电子技术课程设计中培养了我的耐心。遇到错焊漏焊情况,不要烦躁,不要抱怨,需要冷静地解决问题。对着电路板发泄只会延缓实验进展。
= 成员分工
- 我负责模拟电路板的设计与焊接,数据记录。
- 队友程煜捷负责数字电路板的焊接与测试。 |
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/features_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test number type.
#set text(number-type: "old-style")
0123456789 \
#text(number-type: auto)[0123456789]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-AB00.typ | typst | Apache License 2.0 | #let data = (
(),
("ETHIOPIC SYLLABLE TTHU", "Lo", 0),
("ETHIOPIC SYLLABLE TTHI", "Lo", 0),
("ETHIOPIC SYLLABLE TTHAA", "Lo", 0),
("ETHIOPIC SYLLABLE TTHEE", "Lo", 0),
("ETHIOPIC SYLLABLE TTHE", "Lo", 0),
("ETHIOPIC SYLLABLE TTHO", "Lo", 0),
(),
(),
("ETHIOPIC SYLLABLE DDHU", "Lo", 0),
("ETHIOPIC SYLLABLE DDHI", "Lo", 0),
("ETHIOPIC SYLLABLE DDHAA", "Lo", 0),
("ETHIOPIC SYLLABLE DDHEE", "Lo", 0),
("ETHIOPIC SYLLABLE DDHE", "Lo", 0),
("ETHIOPIC SYLLABLE DDHO", "Lo", 0),
(),
(),
("ETHIOPIC SYLLABLE DZU", "Lo", 0),
("ETHIOPIC SYLLABLE DZI", "Lo", 0),
("ETHIOPIC SYLLABLE DZAA", "Lo", 0),
("ETHIOPIC SYLLABLE DZEE", "Lo", 0),
("ETHIOPIC SYLLABLE DZE", "Lo", 0),
("ETHIOPIC SYLLABLE DZO", "Lo", 0),
(),
(),
(),
(),
(),
(),
(),
(),
(),
("ETHIOPIC SYLLABLE CCHHA", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHU", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHI", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHAA", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHEE", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHE", "Lo", 0),
("ETHIOPIC SYLLABLE CCHHO", "Lo", 0),
(),
("ETHIOPIC SYLLABLE BBA", "Lo", 0),
("ETHIOPIC SYLLABLE BBU", "Lo", 0),
("ETHIOPIC SYLLABLE BBI", "Lo", 0),
("ETHIOPIC SYLLABLE BBAA", "Lo", 0),
("ETHIOPIC SYLLABLE BBEE", "Lo", 0),
("ETHIOPIC SYLLABLE BBE", "Lo", 0),
("ETHIOPIC SYLLABLE BBO", "Lo", 0),
)
|
https://github.com/CodeHex16/documentazione | https://raw.githubusercontent.com/CodeHex16/documentazione/main/template/documenti.typ | typst | #let documento(
titolo: "Titolo del documento",
email: "<EMAIL>",
data: [],
versione : [0.1.0],
presenze: (
),
contenuto,
) = {
set text(font: "Noto Sans")
set text(size: 12pt)
set par(justify: true, linebreaks: "optimized",first-line-indent:1em)
show link : set text(font:"Jetbrains Mono");
grid(
columns: (1fr, 1fr),
align : horizon,
align(left,
image("images/logo_unipd.svg", height: 6em),
),
align(right,
stack(
align(center)[
#image("images/logo_extended.jpg", width: 13em)
#v(0em)
#text(size: 10pt, fill: rgb("#424242"),
link("mailto:<EMAIL>"))
]
)
)
)
// Titolo
set align(center)
par(
justify: false,
text(28pt, weight: "black", fill: black, hyphenate: false)[#titolo]
)
table(
columns: (auto,auto),
align: left,
inset: 10pt,
stroke: none,
[*Data*], [#data],
table.hline(stroke: 0.5pt),
[*Versione*], [#versione]
)
// Presenze
set align(left)
set align(left)
table(
columns: (auto, auto),
stroke: none,
table.vline(start: 1, x:1, stroke: 0.5pt),
inset: 10pt,
table.header(text(size:14pt)[*Presenze*]),
..presenze
)
// Indice
pagebreak()
set page(
margin: (top: 4cm, bottom: 4cm, left: 2cm, right: 2cm),
header: [
#grid(
align: horizon,
columns: (1fr, 1fr),
align(left)[#image("images/logo.jpg", width: 2em)], align(right)[#titolo],
)
#line(length: 100%, stroke: 0.5pt)
],
numbering: "I",
footer: [
#align(center, line(length: 15%))
#context { align(center, counter(page).display(page.numbering)) }
],
)
counter(page).update(1)
show outline.entry.where(level: 1): it => {
v(1.5em, weak: true)
strong(it)
}
outline(title: [Indice], indent: auto)
pagebreak()
// CONTENUTO
set page(numbering: "1")
set align(left)
set heading(numbering: "1.")
show heading.where(level: 1): set align(center)
show heading : it => [
#it
#v(1em)
]
counter(page).update(1)
contenuto
} |
|
https://github.com/ClazyChen/Table-Tennis-Rankings | https://raw.githubusercontent.com/ClazyChen/Table-Tennis-Rankings/main/history/2005/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], [2946],
[2], [GUO Yue], [CHN], [2686],
[3], [GUO Yan], [CHN], [2667],
[4], [NIU Jianfeng], [CHN], [2554],
[5], [KIM Kyungah], [KOR], [2522],
[6], [LI Xiaoxia], [CHN], [2510],
[7], [WANG Nan], [CHN], [2486],
[8], [LI Jiawei], [SGP], [2467],
[9], [LIN Ling], [HKG], [2465],
[10], [PAVLOVICH Viktoria], [BLR], [2378],
[11], [GAO Jun], [USA], [2369],
[12], [BOROS Tamara], [CRO], [2365],
[13], [#text(gray, "KIM Hyang Mi")], [PRK], [2346],
[14], [WANG Yuegu], [SGP], [2329],
[15], [TIE Yana], [HKG], [2322],
[16], [CHANG Chenchen], [CHN], [2315],
[17], [LAU Sui Fei], [HKG], [2310],
[18], [CAO Zhen], [CHN], [2305],
[19], [FAN Ying], [CHN], [2295],
[20], [#text(gray, "BAI Yang")], [CHN], [2279],
[21], [KIM Bokrae], [KOR], [2259],
[22], [LIU Shiwen], [CHN], [2247],
[23], [<NAME>], [ROU], [2239],
[24], [SONG Ah Sim], [HKG], [2239],
[25], [LI Jiao], [NED], [2238],
[26], [FUKUHARA Ai], [JPN], [2228],
[27], [MO<NAME>yunjung], [KOR], [2219],
[28], [ZHANG Rui], [HKG], [2203],
[29], [SHEN Yanfei], [ESP], [2197],
[30], [TOTH Krisztina], [HUN], [2186],
[31], [LEE Eunsil], [KOR], [2186],
[32], [PENG Luyang], [CHN], [2173],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (33 - 64)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[33], [LIU Jia], [AUT], [2171],
[34], [SUN Beibei], [SGP], [2164],
[35], [UMEMURA Aya], [JPN], [2159],
[36], [JEON Hyekyung], [KOR], [2145],
[37], [FUJII Hiroko], [JPN], [2145],
[38], [SCHALL Elke], [GER], [2143],
[39], [LAY Jian Fang], [AUS], [2136],
[40], [GANINA Svetlana], [RUS], [2119],
[41], [HIRANO Sayaka], [JPN], [2119],
[42], [KWAK Bangbang], [KOR], [2113],
[43], [<NAME>], [ITA], [2111],
[44], [FUJINUMA Ai], [JPN], [2099],
[45], [POTA Georgina], [HUN], [2099],
[46], [<NAME>], [GER], [2089],
[47], [KIM Mi Yong], [PRK], [2084],
[48], [ZHANG Xueling], [SGP], [2083],
[49], [LI Nan], [CHN], [2069],
[50], [STRUSE Nicole], [GER], [2064],
[51], [JIANG Huajun], [HKG], [2057],
[52], [<NAME>], [GER], [2044],
[53], [<NAME>], [GER], [2043],
[54], [<NAME>], [JPN], [2042],
[55], [PAVLOVICH Veronika], [BLR], [2029],
[56], [TASEI Mikie], [JPN], [2022],
[57], [BATORFI Csilla], [HUN], [2019],
[58], [LI Chunli], [NZL], [2015],
[59], [WANG Chen], [CHN], [2015],
[60], [KOMWONG Nanthana], [THA], [2015],
[61], [KOSTROMINA Tatyana], [BLR], [2005],
[62], [FAZEKAS Maria], [HUN], [2004],
[63], [KIM Kyungha], [KOR], [2003],
[64], [YOON Sunae], [KOR], [1997],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (65 - 96)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[65], [<NAME>], [ROU], [1996],
[66], [<NAME>], [JPN], [1992],
[67], [ODOROVA Eva], [SVK], [1989],
[68], [PASKAUSKIENE Ruta], [LTU], [1985],
[69], [STEFANOVA Nikoleta], [ITA], [1971],
[70], [BADESCU Otilia], [ROU], [1969],
[71], [<NAME>], [JPN], [1967],
[72], [<NAME>], [CRO], [1967],
[73], [<NAME>], [KOR], [1965],
[74], [<NAME>], [ISR], [1965],
[75], [<NAME>], [HUN], [1964],
[76], [STRBIKOVA Renata], [CZE], [1960],
[77], [ELLO Vivien], [HUN], [1960],
[78], [XU Jie], [POL], [1957],
[79], [#text(gray, "MELNIK Galina")], [RUS], [1950],
[80], [VACENOVSKA Iveta], [CZE], [1945],
[81], [WATANABE Yuko], [JPN], [1944],
[82], [PALINA Irina], [RUS], [1942],
[83], [KIM Soongsil], [KOR], [1940],
[84], [<NAME>], [SGP], [1937],
[85], [DVORAK Galia], [ESP], [1936],
[86], [HUANG Yi-Hua], [TPE], [1936],
[87], [PAN Chun-Chu], [TPE], [1923],
[88], [NEGRISOLI Laura], [ITA], [1919],
[89], [LU Yun-Feng], [TPE], [1919],
[90], [DOBESOVA Jana], [CZE], [1916],
[91], [<NAME>], [SRB], [1911],
[92], [KO Un Gyong], [PRK], [1907],
[93], [<NAME>], [GER], [1903],
[94], [<NAME>], [GER], [1903],
[95], [LI Qiangbing], [AUT], [1899],
[96], [FUKUOKA Haruna], [JPN], [1894],
)
)#pagebreak()
#set text(font: ("Courier New", "NSimSun"))
#figure(
caption: "Women's Singles (97 - 128)",
table(
columns: 4,
[Ranking], [Player], [Country/Region], [Rating],
[97], [MUANGSUK Anisara], [THA], [1890],
[98], [KO Somi], [KOR], [1888],
[99], [LOVAS Petra], [HUN], [1888],
[100], [XU Yan], [SGP], [1888],
[101], [MIROU Maria], [GRE], [1887],
[102], [IVANCAN Irene], [GER], [1885],
[103], [HEINE Veronika], [AUT], [1883],
[104], [KISHIDA Satoko], [JPN], [1883],
[105], [<NAME>], [ESP], [1882],
[106], [<NAME>], [JPN], [1877],
[107], [KIM Junghyun], [KOR], [1877],
[108], [JEE Minhyung], [AUS], [1876],
[109], [<NAME>], [ROU], [1873],
[110], [<NAME>], [KOR], [1871],
[111], [NI Xia Lian], [LUX], [1871],
[112], [<NAME>], [CRO], [1866],
[113], [<NAME>], [GER], [1864],
[114], [#text(gray, "CADA Petra")], [CAN], [1862],
[115], [#text(gray, "KIM Minhee")], [KOR], [1861],
[116], [<NAME>], [IND], [1860],
[117], [<NAME>], [KOR], [1859],
[118], [ERDELJI Anamaria], [SRB], [1859],
[119], [SHIOSAKI Yuka], [JPN], [1858],
[120], [#text(gray, "TANIGUCHI Naoko")], [JPN], [1854],
[121], [PIETKIEWICZ Monika], [POL], [1852],
[122], [#text(gray, "KOVTUN Elena")], [UKR], [1849],
[123], [<NAME>], [CRO], [1845],
[124], [<NAME>], [SLO], [1844],
[125], [FADEEVA Oxana], [RUS], [1833],
[126], [<NAME>], [PRK], [1833],
[127], [<NAME>], [HUN], [1827],
[128], [<NAME>], [IND], [1826],
)
) |
|
https://github.com/Otto-AA/definitely-not-tuw-thesis | https://raw.githubusercontent.com/Otto-AA/definitely-not-tuw-thesis/main/template/content/main.typ | typst | MIT No Attribution | #import "@preview/definitely-not-tuw-thesis:0.1.0": flex-caption
= Once upon an ipsum
#lorem(100)
= There was a long ipsum
In @tuwi-logo, we can see the TUWI Logo, followed by @some-table and @lorem-ipsum-alg. The algorithm was discussed here: @team2019people.
#figure(
image("../graphics/TUWI-Logo-Code.png", width: 60%),
caption: flex-caption(
[The TUWI Logo, monochrome and colorized.],
[TUWI logo (short description for list of figures)],
),
) <tuwi-logo>
#figure(
table(
columns: (1fr, auto, auto),
inset: 10pt,
align: horizon,
table.header(
[],
[*Area*],
[*Parameters*],
),
[cylinder],
$ pi h (D^2 - d^2) / 4 $,
[
$h$: height \
$D$: outer radius \
$d$: inner radius
],
[tetrahedron], $ sqrt(2) / 12 a^3 $, [$a$: edge length],
),
caption: flex-caption(
[A table copy pasted from #link("https://typst.app/docs/reference/model/table/")[the docs].],
[Some table],
),
) <some-table>
#figure(
kind: "algorithm",
caption: "The Lorem Ipsum algorithm",
)[
```python
def loop():
print("Lorem")
print("Ipsum")
```
] <lorem-ipsum-alg>
#lorem(200)
== With sub ipsums
#lorem(30)
#lorem(30)
== Many sub ipsums
#lorem(200)
== Many many sub ipsums
#lorem(200)
=== Going
==== Deep |
https://github.com/AHaliq/DependentTypeTheoryReport | https://raw.githubusercontent.com/AHaliq/DependentTypeTheoryReport/main/chapters/chapter3/index.typ | typst | #import "../../preamble/dtt.typ": *
#import "../../preamble/catt.typ": *
#import "@preview/curryst:0.3.0": rule, proof-tree
#import "@preview/fletcher:0.5.1" as fletcher: diagram, node, edge
#import "@preview/cetz:0.2.2"
= Intensional Type Theory (ITT)
We now attempt to redefine propositional equality that has the normalization metatheorem.
Instead of propositional equality as $Eq$; _mapping in_ type, we define it as $Id$; _mapping out_ type.
$
{c in Tm(Gamma. Id(A,a,b), C) | jrule }iso { star }
$
$Id$ like equality; besides $refl$, must satisfy $sym, trans, cong$, which is generalized with $subst$.
Thus the elimination rule for $Id$; called $jrule$, indeed exhibits $subst$. Additionally also $uniq$.
== J Rule
Let $[a] = Sigma(b:A,Id(A,a,b))$; points $a$ identifies with, then we can define the following:
#figure(table(columns:3, align:(left,left,left),
[$jrule$ type signature], [$subst$ from $jrule$], [$uniq$ from $jrule$],
$jrule : {A:UU}$,
$subst {a gap b:A} B gap p = jrule$,
$uniq {a:A}(b,p) = jrule$,
$#h(1em) C: &(a gap b:A) -> \ &Id(A,a,b) -> \ &UU$,
$#h(1em) lambda a gap b gap \_. (B gap a -> B gap b)$,
$#h(1em) &lambda x gap y gap p'. Id(\ &gap Sigma (z:A, [z]),\ & gap (x, refl_x), (y,p'))$,
$-> a:A -> C gap a gap a gap refl_a$,
$#h(1em) lambda \_. lambda b. b$,
$#h(1em) lambda x. refl_((x,refl_x))$,
$-> (a gap b:A) gap p:Id(A,a,b)$,
$#h(1em) a gap b gap p$,
$#h(1em) a gap b gap p$,
$-> C gap a gap b gap p$,
figure(cetz.canvas({
import cetz.draw: *
scale(x: 60%, y: 60%)
circle((0,0), name: "L")
circle((3,0), name: "R")
circle((1.5,-2), radius: (2.5,0.7), name: "B")
fill(black)
circle((-0.5,0.3), radius: 0.15, name: "a1")
circle((0.4,-0.5), radius: 0.15, name: "a2")
circle((2.8,-0.5), radius: 0.15, name: "b2")
circle((3,0.3), radius: 0.15, name: "b1")
fill(black)
circle((3.7,-0.2), radius: 0.15)
circle((0,-2), radius: 0.15, name: "a")
circle((3,-2), radius: 0.15, name: "b")
content("L.north", [$B(a)$], anchor: "south")
content("R.north", [$B(b)$], anchor: "south")
content("B.north", $A$, anchor: "south")
stroke(black)
line("a", "b", name: "line3", mark: (end: ">"))
stroke((paint: purple, dash: "dashed"))
line("a1", "b1", name: "line1", mark: (end: ">"))
line("a2", "b2", name: "line2", mark: (end: ">"))
stroke((paint: gray, dash: "dotted"))
line("a", "L.west")
line("a", "L.east")
line("b", "R.west")
line("b", "R.east")
content("a.south", [$a$], anchor: "north")
content("b.south", [$b$], anchor: "north")
content("line3.mid", $p$, anchor: "north")
})),
figure(cetz.canvas({
import cetz.draw: *
scale(x: 60%, y: 60%)
circle((1.5,-2), radius: (2.5,1.3), name: "B")
fill(black)
circle((0,-2), radius: 0.15, name: "a")
circle((3,-2), radius: 0.15, name: "b")
stroke(black)
line("a", "b", name: "line3", mark: (end: (symbol: ">", fill: black)))
content("line3.mid", $p$, anchor: "north")
fill(none)
arc("a", start: 0deg, stop: 300deg, radius: 0.3, mark: (end: (symbol: ">", fill: black)), name: "arc1")
stroke((paint: purple, dash: "dashed"))
bezier("line3.mid", "arc1.north", (0.7,-0.6), mark: (end: (symbol: ">", fill: purple)))
content("a.south", [$a$], anchor: "north")
content("b.south", [$b$], anchor: "north")
content("B.north", $A$, anchor: "south")
})),
sub([description]),
sub([_drag points at $B(a)$ along p_]),
sub([_all ids from $a$ are identified with $refl_a$_]),
))
== Equality Properties
#figure(table(columns: 4, align: (left, left, left, left),
[$subst$ type signature], [$sym$ from $subst$], [$trans$ from $subst$], [$cong$ from $subst$],
$subst : {a gap b:A}$,
$sym gap p = subst$,
$trans gap p gap q = subst$,
$cong gap f gap p = subst$,
$#h(1em) B:A -> UU$,
$#h(1em) lambda x. Id(A,x,a)$,
$#h(1em) lambda x. Id(A,a,x)$,
$#h(1em) lambda x. Id(B,f gap a, f gap x)$,
$-> Id(A,a,b)$, $#h(1em) p$, $#h(1em) q$, $#h(1em) p$,
$-> B gap a$, $#h(1em) refl_a$, $#h(1em) p$, $#h(1em) refl_((f gap a))$,
$-> B gap b$,
figure(cetz.canvas({
import cetz.draw: *
scale(x: 60%, y: 60%)
circle((1.5,-2), radius: (2.5,1.3), name: "B")
fill(black)
circle((0,-2), radius: 0.15, name: "a")
circle((3,-2), radius: 0.15, name: "b")
stroke(black)
fill(none)
bezier("a.east", "b.west", (1.75,-3) ,name: "line3", mark: (end: (symbol: ">", fill: black)))
content("line3.mid", $p$, anchor: "north")
arc("a", start: 0deg, stop: 300deg, radius: 0.3, mark: (end: (symbol: ">", fill: purple)), name: "arc1")
stroke((paint: purple, dash: "dashed"))
bezier("b.north", "a.north", (1.75,-0.6), mark: (end: (symbol: ">", fill: purple)))
stroke((paint: gray, dash: "dotted"))
bezier("a", "b",(1.75,-1.7))
content("a.south", [$a$], anchor: "north")
content("b.south", [$b$], anchor: "north")
content("B.north", $A$, anchor: "south")
})),
figure(cetz.canvas({
import cetz.draw: *
scale(x: 60%, y: 60%)
circle((1.5,-1.5), radius: (2.5,2), name: "B")
fill(black)
circle((0,-2), radius: 0.15, name: "a")
circle((3,-2), radius: 0.15, name: "b")
circle((3,-0.5), radius:0.15, name: "c")
stroke(black)
fill(none)
bezier("b.north", "c.south", (3.5,-1.5), name: "line1", mark: (end: (symbol: ">", fill: black)))
line("a.east", "b.west",name: "line3", mark: (end: (symbol: ">", fill: black)))
content("line3.mid", $p$, anchor: "north")
content("line1.mid", $q$, anchor: "west")
fill(none)
stroke((paint: purple, dash: "dashed"))
line("a", "c.west", mark: (end: (symbol: ">", fill: purple)))
stroke((paint: gray, dash: "dotted"))
bezier("b", "c",(2.1,-1.5))
content("a.south", [$a$], anchor: "north")
content("b.south", [$b$], anchor: "north")
content("c.north", [$c$], anchor: "south")
content("B.north", $A$, anchor: "south")
})),
figure(cetz.canvas({
import cetz.draw: *
scale(x: 60%, y: 60%)
circle((1.5,0.2), radius: (2.5,1), name: "A")
circle((1.5,-2), radius: (2.5,1), name: "B")
fill(black)
circle((0,-2), radius: 0.15, name: "fa")
circle((3,-2), radius: 0.15, name: "fb")
circle((0,0.2), radius: 0.15, name: "a")
circle((3,0.2), radius: 0.15, name: "b")
stroke(black)
line("a.east", "b.west", name: "line1", mark: (end: (symbol: ">", fill: black)))
stroke((paint: purple, dash: "dashed"))
line("fa.east", "fb.west", name: "line3", mark: (end: (symbol: ">", fill: purple)))
stroke((paint: gray, dash: "dotted"))
line("a", "fa", name: "line2", mark: (end: (symbol: ">", fill: gray)))
line("b", "fb", name: "line4", mark: (end: (symbol: ">", fill: gray)))
stroke(black)
fill(none)
arc("fa", start: 0deg, stop: 300deg, radius: 0.3, mark: (end: (symbol: ">", fill: black)), name: "arc1")
content("fa.south", [$f gap a$], anchor: "north-west")
content("fb.south", [$f gap b$], anchor: "north-east")
content("a.north", [$a$], anchor: "south-west")
content("b.north", [$b$], anchor: "south-east")
content("line1.mid", $p$, anchor: "north")
content("B.east", $B$, anchor: "west")
content("A.east", $A$, anchor: "west")
})),
sub([description]),
sub([_drag start of $refl_a$ along $p$_]),
sub([_drag end of $p$ along $q$_]),
sub([_drag end of $refl_((f gap a))$ along $f gap b$_]),
))
_Others_: $upright("symsym") = Id(Id(A,a,b),sym comp sym p, p)$ and dependent version of $cong$ in terms of $jrule$.
== Metatheoretic Consequences
/ Normalization: Using $Id$ we no longer use equality reflection, thus our theory now has normalization.
/ J is Invariant: Moreover, the initial model of ETT supports the initial model of ITT, meaning ETT satisfies the rules of ITT, but not the other way round.
/ Function Extensionality; funext: Because of the lack of equality reflection / trivial $subst$, we can't directly construct a proof / closed term of funext. And adding it as an axiom preserves normalization but breaks canonicity since the empty context is no longer empty.
/ Uniqueness of Identity Proofs; UIP: With $jrule$ as elimination for our propositional equality, we no are no longer guaranteed to have UIP. If we were to use $jrule$ with equality reflection, then all computation of $subst$ would be trivial. The proof by Hoffmann and Streicher via a groupoid model shows that UIP does not hold in ITT. We can then ask if the identity proofs of identity proofs (and so on) are also unique. this is $"U(IP)"^n$. This is the motivation for higher inductive types and homotopy type theory.
/ Conservativity: Lastly the Hoffmann conservativity theorem states that any proposition provable in ETT but not ITT can be reduced to the problem of funext and $"U(IP)"^n$
|
|
https://github.com/wuespace/vos | https://raw.githubusercontent.com/wuespace/vos/main/vo/lizvo.typ | typst | #import "@preview/delegis:0.3.0": *
#show: delegis.with(
logo: image("wuespace.svg"),
title: "Vereinsordnung zu Lizenzen im WüSpace e. V.",
abbreviation: "LizVO",
resolution: "2. Vorstandsbeschluss vom 23.05.2024, 2024/V-27",
draft: false,
in-effect: "23.05.2024"
)
#heading(outlined: false, numbering: none)[Vorbemerkung]
Fußnoten dienen als Erläuterung und sind nicht Teil der Beschlussfassung.
#outline()
= Allgemeine Bestimmungen
§ 1 Geltungsbereich
Diese Vereinsordnung ergänzt die bestehende Satzung des Vereins WüSpace e.~V. und regelt die lizenzrechtliche Einordnung von im Rahmen der Vereinsarbeit entstehenden Erzeugnissen.
§ 2 Definition von Erzeugnissen
Erzeugnisse im Sinne dieser Vereinsordnung sind sämtliche Werke, Produkte, Designs, Software und sonstige kreative oder technische Resultate, die von Mitgliedern im Rahmen der Vereinsarbeit geschaffen werden.
= Rechte an Erzeugnissen
§ 3 Nutzungsrecht und Umfang
(1) Die Mitglieder räumen dem Verein ein einfaches, nicht exklusives Nutzungsrecht an den Erzeugnissen ein.
(2) Das Nutzungsrecht umfasst das Recht zur Nutzung, Bearbeitung, Veröffentlichung und Verbreitung der Erzeugnisse im Rahmen des Vereinszwecks, inklusive digitaler und kommerzieller Nutzung.
§ 4 Nutzung externer Erzeugnisse
Bei Erzeugnissen mit externer Beteiligung muss der Verein äquivalente Nutzungsrechte durch einen Vertrag sicherstellen.
= Sonderregelungen
§ 5 Abweichungen von dieser Vereinsordnung
Der Vorstand kann per Beschluss von den Regelungen dieser Vereinsordnung abweichen, wenn alle am Erzeugnis beteiligten Mitglieder zustimmen.
#footnote[ Diese Regelung ermöglicht Flexibilität in speziellen Fällen, wenn alle Beteiligten zustimmen. Die Vereinsordnung kann nicht alle denkbaren Situationen abdecken, daher ermöglicht dieser Abschnitt, auf individuelle Umstände angemessen zu reagieren.]
= Schlussbestimmungen
§ 6 Übergangsbestimmungen
(1)
Für vor der Einführung dieser Vereinsordnung erbrachte Erzeugnisse, die von einem CLA abgedeckt wurden, gelten deren Regelungen, sofern sie nicht im Widerspruch zu dieser Vereinsordnung steht.
(2)
Für vor der Einführung dieser Vereinsordnung erbrachte Erzeugnisse, die nicht von einem CLA abgedeckt wurden, gelten die Regelungen dieser Vereinsordnung.
#footnote[
Eine rückwirkende Einführung ist hier möglich, nachdem diese nur die explizite Aussprache einer bisher implizit erfolgten Praxis entspricht.
]
(3)
Für nach der Einführung dieser Vereinsordnung erbrachte Erzeugnisse gelten unabhängig der Unterzeichnung eines CLAs die Regelungen dieser Vereinsordnung.
§ 7 Gültigkeit und Änderungen
Diese Vereinsordnung tritt mit Beschluss des Vorstands zum 23.05.2024 in Kraft.
|
|
https://github.com/vaibhavjhawar/typst-cv-template1 | https://raw.githubusercontent.com/vaibhavjhawar/typst-cv-template1/main/README.md | markdown | MIT License | # Typst Resume/CV Template
A Typst Resume/CV template
Inspired by <NAME> Graduate CV LaTex template
## Requires
Compilation of this project requires the following:
- [Typst CLI](https://github.com/typst/typst)
- [Fontin Fonts](https://www.exljbris.com/fontin.html)
## Preview
See [cv1.pdf](https://github.com/vaibhavjhawar/typst-cv-template1/blob/main/cv1.pdf) for redendered PDF output

## Usage
1. Clone the repo
```
git clone https://github.com/vaibhavjhawar/typst-cv-template1.git
```
2. Edit the [cv1.typ](https://github.com/vaibhavjhawar/typst-cv-template1/blob/main/cv1.typ) file
3. Check dependencies and compile it with Typst
```
typst compile cv1.typ
```
It can also be compiled using as Typst project on [Typst app](https://typst.app/)
## License
[MIT](https://github.com/vaibhavjhawar/typst-cv-template1/blob/main/LICENSE)
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/edge_01.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 21-23 expected "ascender", "cap-height", "x-height", "baseline", "bounds", or length, found array
// #set text(top-edge: ()) |
https://github.com/mabeh19/typst.nvim | https://raw.githubusercontent.com/mabeh19/typst.nvim/master/README.md | markdown |
# Typst.nvim
__Very__ small script for automatically watching typst files and viewing them with xdg-open.
|
|
https://github.com/mrcinv/nummat-typst | https://raw.githubusercontent.com/mrcinv/nummat-typst/master/01_julia.typ | typst | #import "admonitions.typ": opomba
#import "julia.typ": jlfb, jlf, repl, code_box, pkg, blk, readlines
= Uvod v programski jezik Julia
V knjigi bomo uporabili programski jezik #link("https://julialang.org/")[Julia]. Zavoljo
učinkovitega izvajanja, uporabe
#link("https://docs.julialang.org/en/v1/manual/types/")[dinamičnih tipov],
#link("https://docs.julialang.org/en/v1/manual/methods/")[funkcij, specializiranih glede na signaturo],
in dobre podpore za interaktivno uporabo, je Julia zelo primerna za programiranje numeričnih metod
in ilustracijo njihove uporabe. V nadaljevanju sledijo kratka navodila, kako začeti z Julio.
Cilji tega poglavja so:
- naučiti se uporabljati Julio v interaktivni ukazni zanki,
- pripraviti okolje za delo v programskem jeziku Julia,
- ustvariti prvi paket in
- ustvariti prvo poročilo v formatu PDF.
Tekom te vaje bomo pripravili svoj prvi paket v Juliji, ki bo vseboval parametrično enačbo
#link("https://sl.wikipedia.org/wiki/Geronova_lemniskata")[Geronove lemniskate], in napisali teste,
ki bodo preverili pravilnost funkcij v paketu. Nato bomo napisali skripto, ki uporabi funkcije iz
našega paketa in nariše sliko Geronove lemniskate. Na koncu bomo pripravili lično
poročilo v formatu PDF.
== Namestitev in prvi koraki
Sledite #link("https://julialang.org/downloads/")[navodilom], namestite
programski jezik Julia in v terminalu poženite ukaz `julia`. Ukaz odpre interaktivno ukazno zanko
(angl. _Read Eval Print Loop_ ali s kratico REPL) in v terminalu se pojavi ukazni pozivnik
#text(green)[`julia>`]. Za ukaznim pozivnikom lahko napišemo posamezne ukaze, ki jih nato
Julia prevede, izvede in izpiše rezultate. Poskusimo najprej s preprostimi izrazi:
#code_box[
#repl("1 + 1", "2")
#repl("sin(pi)", "0.0")
#repl("x = 1; 2x + x^2", "3")
#repl("# vse, kar je za znakom #, je komentar, ki se ne izvede", "")
]
=== Funkcije
Funkcije, ki so v programskem jeziku Julia osnovne enote kode, definiramo na več načinov. Kratke
enovrstične funkcije definiramo z izrazom ```jl ime(x) = ...```.
#code_box[
#repl("f(x) = x^2 + sin(x)", "f (generic function with 1 method)")
#repl("f(pi/2)", "3.4674011002723395")
]
#pagebreak()
Funkcije z več argumenti definiramo podobno:
#code_box[
#repl("g(x, y) = x + y^2", "g (generic function with 1 method)")
#repl("g(1, 2)", "5")
]
Za funkcije, ki zahtevajo več kode, uporabimo ključno besedo ```jl function```:
#code_box[
#repl(
"function h(x, y)
z = x + y
return z^2
end",
"h (generic function with 1 method)",
)
#repl("h(3, 4)", "49")
]
Funkcije lahko uporabljamo kot vsako drugo spremenljivko. Lahko jih podamo kot
argumente drugim funkcijam in jih združujemo v podatkovne strukture, kot so seznami,
vektorji ali matrike. Funkcije lahko definiramo tudi kot anonimne funkcije. To
so funkcije, ki jih vpeljemo brez imena in jih kasneje tudi ne moremo poklicati po imenu.
#code_box[
#repl("(x, y) -> sin(x) + y", "#1 (generic function with 1 method)")
]
Anonimne funkcije uporabljamo predvsem kot argumente v drugih funkcijah. Funkcija
```jl map(f, v)``` na primer zahteva za prvi argument funkcijo `f`, ki jo nato aplicira na vsak
element vektorja:
#code_box[
#repl("map(x -> x^2, [1, 2, 3])", "3-element Vector{Int64}:
1
4
9")
]
Vsaka funkcija v programskem jeziku Julia ima lahko več različnih definicij, glede na kombinacijo tipov argumentov, ki jih podamo. Posamezno
definicijo funkcije imenujemo
#link("https://docs.julialang.org/en/v1/manual/methods/#Methods")[metoda]. Ob klicu funkcije Julia izbere najprimernejšo metodo.
#code_box[
#repl("k(x::Number) = x^2", "k (generic function with 1 method)")
#repl("k(x::Vector) = x[1]^2 - x[2]^2", "k (generic function with 2 methods)")
#repl("k(2)","4")
#repl("k([1, 2, 3])", "-3")
]
=== Vektorji in matrike
Vektorje vnesemo z oglatimi oklepaji ```jl []```:
#code_box[
#repl("v = [1, 2, 3]", "3-element Vector{Int64}:
1
2
3")
#repl("v[1] # vrne prvo komponento vektorja", "1")
#repl("v[2:end] # vrne zadnji dve komponenti vektorja", "2-element Vector{Int64}:
2
3")
#repl(
"sin.(v) # funkcijo uporabimo na komponentah vektorja, če imenu dodamo .",
"3-element Vector{Float64}:
0.8414709848078965
0.9092974268256817
0.1411200080598672",
)
]
Matrike vnesemo tako, da elemente v vrstici ločimo s presledki, vrstice pa s
podpičji:
#code_box[
#repl("M = [1 2 3; 4 5 6]", "2×3 Matrix{Int64}:
1 2 3
4 5 6
")
]
Za razpone indeksov uporabimo ```jl :```, s ključno besedo ```jl end``` označimo zadnji indeks. Julia avtomatično določi razpon indeksov v matriki:
#code_box[
#repl("M[1, :] # prva vrstica", "3-element Vector{Int64}:
1
2
3")
#repl("M[2:end, 1:end-1]", "1×2 Matrix{Int64}:
4 5")
]
Osnovne operacije delujejo tudi na vektorjih in matrikah. Pri tem moramo vedeti,
da gre za matrične operacije. Tako je na primer `*` operacija množenja matrik ali matrike
z vektorjem in ne morda množenja po komponentah.
#code_box[
#repl(
"[1 2; 3 4] * [6, 5] # množenje matrike z vektorjem",
"2-element Vector{Int64}:
16
38",
)
]
Če želimo operacije izvajati po komponentah, moramo pred operator dodati piko, na kar nas Julia opozori z napako:
#code_box[
#repl(
"[1, 2] + 1 # seštevanje vektorja in števila ni definirano ",
"ERROR: MethodError: no method matching +(::Vector{Int64}, ::Int64)
For element-wise addition, use broadcasting with dot syntax: array .+ scalar",)
#repl("[1, 2] .+ 1", "2-element Vector{Int64}:
2
3")
]
Posebej uporaben je operator `\`, ki poišče rešitev sistema linearnih enačb.
Izraz ```jl A\b``` vrne rešitev matričnega sistema $A x = b$:
#code_box[
#repl("A = [1 2; 3 4]; # podpičje prepreči izpis rezultata", "")
#repl(
"x = A \ [5, 6] # rešimo enačbo A * x = [5, 6]",
"2-element Vector{Float64}:
-3.9999999999999987
4.499999999999999",
)
]
Izračun se izvede v aritmetiki s plavajočo vejico, zato pride do zaokrožitvenih napak in
rezultat ni povsem točen. Naredimo še preizkus:
#code_box[
#repl("A * x", "2-element Vector{Float64}:
5.0
6.0")
]
Operator `\` deluje za veliko različnih primerov. Med drugim ga
lahko uporabimo tudi za iskanje rešitve pre-določenega sistema po metodi najmanjših kvadratov:
#code_box[
#repl("[1 2; 3 1; 2 2] \ [1, 2, 3] # rešitev za predoločen sistem", "2-element Vector{Float64}:
0.5999999999999999
0.5111111111111114")
]
=== Moduli
#link("https://docs.julialang.org/en/v1/manual/modules/")[Moduli] pomagajo organizirati
funkcije v enote in omogočajo uporabo istega imena za različne funkcije in tipe. Module definiramo z ```jl module ImeModula ... end```:
#code_box[
#repl("module KrNeki
kaj(x) = x + sin(x)
čaj(x) = cos(x) - x
export kaj
end", "Main.KrNeki")
]
Če želimo funkcije, ki so definirane v modulu ```jl ImeModula```, uporabiti izven modula, moramo modul naložiti z ```jl using ImeModula```. Funkcije, ki so izvožene z ukazom ```jl export ime_funkcije``` lahko kličemo kar po imenu, ostalim funkcijam pa moramo dodati ime modula kot predpono. Modulom, ki niso del paketa in so definirani lokalno, moramo dodati piko, ko jih naložimo:
#code_box[
#repl("using .KrNeki", "")
#repl("kaj(1)", "1.8414709848078965")
#repl("KrNeki.čaj(1)", "-0.45969769413186023")
]
Modul lahko naložimo tudi z ukazom ```jl import ImeModula```.
V tem primeru moramo vsem funkcijam iz modula dodati ime modula in piko kot predpono.
=== Paketi
Nabor funkcij, ki so na voljo v Juliji, je omejen, zato pogosto uporabimo knjižnice, ki vsebujejo dodatne funkcije. Knjižnica funkcij v Juliji se imenuje #link("https://julialang.org/packages/")[paket]. Funkcije v paketu so združene v modul, ki ima isto ime kot paket.
Julia ima vgrajen upravljalnik s paketi, ki omogoča dostop do paketov, ki so del
Julije, kot tudi tistih, ki jih prispevajo uporabniki. Poglejmo si primer, kako
uporabiti ukaz `norm`, ki izračuna različne norme vektorjev in matrik. Ukaz
`norm` ni del osnovnega nabora funkcij, ampak je del modula `LinearAlgebra`, ki je že
vključen v program Julia. Če želimo uporabiti `norm`, moramo najprej uvoziti
funkcije iz modula `LinearAlgebra` z ukazom ```jl using LinearAlgebra```:
#code_box[
#repl("norm([1, 2, 3]", "ERROR: UndefVarError: `norm` not defined")
#repl("using LinearAlgebra", none)
#repl("norm([1, 2, 3])", "3.7416573867739413")
]
Če želimo uporabiti pakete, ki niso del osnovnega jezika Julia, jih moramo
prenesti z interneta. Za to uporabimo modul `Pkg`. Paketom je namenjen poseben
paketni način vnosa v ukazni zanki. Do paketnega načina pridemo, če za pozivnik vnesemo znak `]`.
#opomba(
naslov: [Različni načini ukazne zanke],
)[
Julia ukazna zanka (REPL) pozna več načinov, ki so namenjeni različnim
opravilom.
- Osnovni način s pozivom #text(green.darken(20%))[`julia>`] je namenjen vnosu
kode v Juliji.
- Paketni način s pozivom #text(blue)[`pkg>`] je namenjen upravljanju s paketi. V
paketni način pridemo, če vnesemo znak `]`.
- Način za pomoč s pozivom #text(orange)[`help?>`] je namenjen pomoči. V način za
pomoč pridemo z znakom `?`.
- Lupinski način s pozivom #text(red)[`shell>`] je namenjen izvajanju ukazov v
sistemski lupini. V lupinski način vstopimo z znakom `;`.
- Iz posebnih načinov pridemo nazaj v osnovni način s pritiskom na vračalko(⌫).
]
Za primer si oglejmo, kako namestiti knjižnico za ustvarjanje slik in grafov #link("https://docs.juliaplots.org/latest/")[Plots.jl]. Najprej aktiviramo paketni način z vnosom znaka `]` za pozivnikom. Nato paket dodamo z ukazom `add`.
#code_box[
#pkg("add Plots", "...")
#repl("using Plots # naložimo modul s funkcijami iz paketa", none)
#repl(
blk("scripts/01_julia.jl","# 01plot"),
none,
)
]
#figure(
image("img/01_graf.svg", width: 60%)
)
=== Datoteke s kodo
Kodo lahko zapišemo tudi v datoteke. Vnašanje ukazov v interaktivni zanki je
uporabno za preproste ukaze na primer namesto kalkulatorja, za resnejše delo pa je bolje kodo shraniti v datoteke. Praviloma imajo datoteke s kodo v jeziku Julia končnico
`.jl`.
Napišimo preprost program. Ukaze, ki smo jih vnesli doslej , shranimo v datoteko z
imenom `01uvod.jl`. Ukaze iz datoteke poženemo z ukazom ```jl include``` v ukazni zanki:
#code_box[
#repl("include(\"01uvod.jl\")", "")
]
ali pa v lupini operacijskega sistema:
#code_box[
#raw("$ julia 01uvod.jl")
]
#opomba(
naslov: [Urejevalniki in programska okolja za Julijo],
[
Za lažje delo z datotekami s kodo potrebujemo dober urejevalnik besedila,
ki je namenjen programiranju. Če še nimate priljubljenega urejevalnika,
priporočam #link("https://code.visualstudio.com/")[VS Code] in #link("https://www.julia-vscode.org/")[razširitev za Julio].
Če odprete datoteko s kodo v urejevalniku VS Code, lahko s kombinacijo tipk
`Ctrl + Enter` posamezno vrstico kode
pošljemo v ukazno zanko za Julio, da se izvede. Na ta način združimo prednosti
interaktivnega dela in zapisovanja kode v datoteke `.jl`.
],
)
Priporočam, da večino kode napišete v datoteke. V nadaljevanju bomo spoznali,
kako organizirati datoteke v projekte in pakete tako, da lahko kodo uporabimo na več
mestih.
== Avtomatsko posodabljanje kode
Ko uporabimo kodo iz datoteke v interaktivni zanki, je treba ob vsaki spremembi
datoteko ponovno naložiti z ukazom `include`.
Paket #link("https://timholy.github.io/Revise.jl")[Revise.jl] poskrbi za to, da se
nalaganje zgodi avtomatično vsakič, ko se datoteke spremenijo. Zato najprej namestimo
paket Revise in poskrbimo, da se zažene ob vsakem zagonu interaktivne zanke.
Naslednji ukazi namestijo paket Revise, ustvarijo mapo `$HOME/.julia/config` in datoteko `startup,jl`, ki naloži paket Revise in se izvede ob vsakem zagonu programa `julia`:
#code_box[
#repl("# pritisnemo ], da pridemo v paketni način", none)
#pkg("add Revise", none)
#repl(
"startup = \"\"\"
try
using Revise
catch e
@warn \"Error initializing Revise\" exception=(e, catch_backtrace())
end
\"\"\"",
"...",
)
#repl("path = homedir() * \"/.julia/config\")", none)
#repl("mkdir(path)", none)
#repl("write(path * \"/startup.jl\", startup) # zapišemo startup.jl", none)
]
Okolje za delo z Julio je pripravljeno.
== Priprava korenske mape
Programe, ki jih bomo napisali v nadaljevanju, bomo hranili v mapi `nummat`. Ustvarimo jo z ukazom:
#code_box[
```sh
$ mkdir nummat
```
]
Korenska mapa bo služila kot #link("https://pkgdocs.julialang.org/v1/environments/")[projektno okolje], v katerem bodo zabeleženi vsi paketi, ki jih bomo potrebovali.
#code_box[
```sh
$ cd nummat
$ julia
```
#repl("# s pritiskom na ] vključimo paketni način", none)
#pkg("activate . # pripravimo projektno okolje v korenski mapi", none)
#pkg("", none, env: "nummat")
]
Zgornji ukaz ustvari datoteko `Project.toml` in pripravi novo projektno okolje v mapi `nummat`.
#opomba(
naslov: [Projektno okolje v Juliji],
)[Projektno okolje je mapa, ki vsebuje datoteko `Project.toml` z informacijami o paketih in zahtevanih različicah paketov. Projektno okolje aktiviramo z ukazom ```jl Pkg.activate("pot/do/mape/z/okoljem")``` oziroma v paketnem načinu z:
#code_box[
#pkg("activate pot/do/mape/z/okoljem", none)
]
Uporaba projektnega okolja delno rešuje problem #link(
"https://sl.wikipedia.org/wiki/Obnovljivost",
)[ponovljivosti], ki ga najlepše ilustriramo z izjavo #quote[Na mojem računalniku pa koda dela!]. Projektno okolje namreč vsebuje tudi datoteko `Manifest.toml`, ki hrani različice in kontrolne vsote za pakete iz `Project.toml` in vse njihove odvisnosti. Ta informacija omogoča, da Julia naloži vedno iste različice vseh odvisnosti, kot v času, ko je bila datoteka `Manifest.toml` zadnjič posodobljena.
Projektna okolja v Juliji so podobna #link("https://docs.python.org/3/library/venv.html")[virtualnim okoljem v Pythonu].
]
Projektnemu okolju dodamo pakete, ki jih bomo potrebovali v nadaljevanju. Zaenkrat je to le
paket #link("https://github.com/JuliaPlots/Plots.jl")[Plots.jl], ki ga potrebujemo za risanje grafov:
#code_box[
#pkg("add Plots", "", env: "nummat")
]
Datoteka `Project.toml` vsebuje le ime paketa `Plots` in identifikacijski niz:
#code_box[
```
[deps]
Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80"
```
]
Točna verzija paketa `Plots` in vsi paketi, ki jih potrebuje, so zabeležena v datoteki `Manifest.toml`.
== Vodenje različic s programom Git
Priporočamo uporabo programa za vodenje različic #link("https://git-scm.com/")[Git]. V nadaljevanju bomo opisali, kako pripraviti v korenski mapi `nummat` pripraviti Git repozitorij in vpisati datoteke, ki smo jih do sedaj ustvarili.
#opomba(naslov: [Sistem za vodenje različic Git])[
#link("https://git-scm.com/")[Git] je sistem za vodenje različic, ki je postal _de facto_
standard v razvoju programske opreme pa tudi drugod, kjer se dela s tekstovnimi
datotekami. Priporočamo, da si bralec ustvari svoj Git repozitorij, kjer si uredi
kodo in zapiske, ki jo bo napisal pri spremljanju te knjige.
Git repozitorij lahko hranimo zgolj lokalno na lastnem računalniku, ali pa ga repliciramo na lastnem strežniku ali na enem od javnih spletnih skladišč
programske kode, na primer #link("https://github.com/")[Github] ali
#link("https://gitlab.com/")[Gitlab].]
Z naslednjim ukazom v mapi `nummat` ustvarimo repozitorij za `git` in
registriramo novo ustvarjene datoteke.
#code_box[
```shell
$ git init .
$ git add .
$ git commit -m "Začetni vpis"
```
]
Z ukazoma `git status` in `git diff` lahko pregledamo, kaj se je spremenilo od zadnjega vpisa. Ko smo zadovoljni s spremembami, jih zabeležimo z ukazoma `git add` in `git commit`. Priporočamo redno uporabo ukaza `git commit`. Pogosti vpisi namreč precej olajšajo nadzor nad spremembami kode in spodbujajo k razdelitvi dela na majhne zaključene probleme, ki so lažje obvladljivi.
== Priprava paketa za vajo
Ob začetku vsake vaje bomo v korenski mapi (`nummat`) najprej ustvarili mapo oziroma #link("https://pkgdocs.julialang.org/v1/creating-packages/")[paket],
v katerem bo shranjena koda za določeno vajo. S ponavljanjem postopka priprave
paketa za vsako vajo posebej se bomo naučili, kako hitro začeti s projektom.
Obenem bomo optimizirali način dela (angl. workflow) in odpravili ozka grla v postopkih priprave projekta. Ponavljanje vedno istih postopkov nas prisili, da postopke kar se da poenostavimo in ponavljajoča se opravila avtomatiziramo. Na dolgi rok se tako lahko bolj posvečamo dejanskemu reševanju problemov.
Za vajo bomo ustvarili paket `Vaja01`, s katerim bomo narisali
#link(
"https://sl.wikipedia.org/wiki/Geronova_lemniskata",
)[Geronovo lemniskato].
V mapi `nummat` ustvarimo paket `Vaja01`, v katerega bomo postavili kodo. Nov paket ustvarimo v paketnem načinu z ukazom `generate`:
#code_box[
```shell
$ cd nummat
$ julia
```
#repl(" # pritisnemo ] za vstop v paketni način", none)
#pkg("generate Vaja01", none)
]
Ukaz `generate` ustvari mapo `Vaja01` z osnovno strukturo
#link("https://pkgdocs.julialang.org/v1/creating-packages/")[paketa v Juliji]:
#code_box[
```shell
$ tree Vaja01
Vaja01
├── Project.toml
└── src
└── Vaja01.jl
1 directory, 2 files
```
]
Paket `Vaja01` nato dodamo v projektno okolje v korenski mapi `nummat`, da bomo lahko kodo iz paketa uporabili v programih in ukazni zanki:
#code_box[
#pkg("activate . ", none)
#pkg(
"develop ./Vaja01 # paket dodamo projektnemu okolju",
none,
env: "nummat",
)
]
#opomba(
naslov: [Za obsežnejši projekti uporabite šablone],
)[
Za obsežnejši projekt ali projekt, ki ga želite objaviti, je bolje uporabiti že
pripravljene šablone
#link("https://github.com/JuliaCI/PkgTemplates.jl")[PkgTemplates] ali
#link("https://github.com/tpapp/PkgSkeleton.jl")[PkgSkeleton]. Zavoljo
enostavnosti bomo v sklopu te knjige projekte ustvarjali s `Pkg.generate`.
]
Osnovna struktura paketa je pripravljena. Paketu bomo v nadaljevanju dodali še:
- kodo (@sec:01koda),
- teste (@sec:01testi) in
- dokumentacijo (@sec:01docs).
== Koda <sec:01koda>
Ko je mapa s paketom `Vaja01` pripravljena, lahko začnemo. Napisali bomo funkcije, ki izračunajo koordinate
#link(
"https://sl.wikipedia.org/wiki/Geronova_lemniskata",
)[Geronove lemniskate]:
$
x(t) = (t^2 - 1) / (t^2 + 1) #h(2em)
y(t) = 2t(t^2 - 1) / (t^2 + 1)^2.
$
V urejevalniku odpremo datoteko `Vaja01/src/Vaja01.jl` in vanjo shranimo definiciji:
#figure(
code_box(raw(lang: "jl", block: true, read("Vaja01/src/Vaja01.jl"))),
caption: [Definicije funkcij v paketu `Vaja01`.]
)<pr:Vaja01>
Funkcije iz datoteke `Vaja01/src/Vaja01.jl` lahko uvozimo z ukazom ```jl using Vaja01```, če smo paket `Vaja01` dodali v projektno okolje (`Project.toml`). V mapo `src` sodijo splošno uporabne funkcije, ki jih želimo uporabiti v drugih
programih. V interaktivni zanki lahko sedaj pokličemo novo definirani funkciji:
#code_box[
#repl("using Vaja01", none)
#repl("lemniskata_x(1.2)", "0.180327868852459")
]
V datoteko `Vaja01\doc\01uvod.jl` bomo zapisali preprost program, ki uporabi kodo iz paketa `Vaja01` in nariše lemniskato:
#figure(
code_box(jlf("Vaja01/doc/01uvod.jl", 4, 11)),
)
Program `01uvod.jl` poženemo z ukazom:
#code_box[
#repl("include(\"Vaja01/doc/01uvod.jl\")", none)
]
#opomba(
naslov: [Poganjanje ukaz za ukazom v VS Code],
)[
Če uporabljate urejevalnik #link("https://code.visualstudio.com/")[VS Code] in
#link("https://github.com/julia-vscode/julia-vscode")[razširitev za Julio], lahko ukaze
iz programa poganjate vrstico za vrstico kar iz urejevalnika. Če pritisnete kombinacijo tipk
`Shift + Enter`, se bo izvedla vrstica v kateri je trenutno kazalka.
]
Rezultat je slika lemniskate.
#figure(
image(width: 60%, "img/01_demo.svg"),
caption: [Geronova lemniskata]
)
== Testi <sec:01testi>
Naslednji korak je, da dodamo avtomatske teste, s katerimi preizkusimo pravilnost kode, ki
smo je napisali v prejšnjem poglavju. Avtomatski test je preprost program, ki pokliče določeno funkcijo in preveri rezultat.
#opomba(
naslov: [Avtomatsko testiranje programov],
[Pomembno je, da pravilnost programov preverimo. Najlažje to naredimo "na roke",
tako da program poženemo in preverimo rezultat. Testiranja "na roke" ima veliko
pomankljivosti. Zahteva veliko časa, je lahko nekonsistentno in dovzetno
za človeške napake.
Alternativa ročnemu testiranju programov so avtomatski testi.
To so preprosti programi, ki izvedejo testirani program in
rezultate preverijo. Avtomatski testi so pomemben del #link(
"https://sl.wikipedia.org/wiki/Agilne_metode_razvoja_programske_opreme",
)[agilnega razvoja programske opreme] in omogočajo avtomatizacijo procesov
razvoja programske opreme, ki se imenuje #link(
"https://en.wikipedia.org/wiki/Continuous_integration",
)[nenehna integracija].],
)
Uporabili bomo paket #link("https://docs.julialang.org/en/v1/stdlib/Test/")[Test],
ki olajša pisanje testov. Vstopna točka za teste je datoteka `test\runtests.jl`. Uporabili bomo makroje #link("https://docs.julialang.org/en/v1/stdlib/Test/#Test.@test")[\@test] in #link(
"https://docs.julialang.org/en/v1/stdlib/Test/#Test.@testset",
)[\@testset] iz paketa `Test`.
V datoteko `test/runtests.jl` dodamo teste za obe koordinatni funkciji, ki smo
ju definirali:
#figure(
code_box(
raw(read("Vaja01/test/runtests.jl"), lang: "jl")),
caption: [Rezultat funkcij primerjamo s pravilno vrednostjo.],
)
Za primerjavo rezultatov smo uporabili .
#opomba(
naslov: [Primerjava števil s plavajočo vejico],
[Pri računanju s števili s plavajočo vejico se izogibajmo primerjanju števil z
operatorjem `==`, ki števili primerja bit po bit.
Pri izračunih, v katerih nastopajo števila s plavajočo vejico, pride do zaokrožitvenih napak.
Zato se različni načini izračuna za isto število praviloma razlikujejo na zadnjih
decimalkah. Na primer izraz ```jl asin(sin(pi/4)) - pi/4 ```
ne vrne točne ničle ampak vrednost `-1.1102230246251565e-16`, ki pa je zelo
majhno število. Za približno primerjavo dveh vrednosti `a` in `b` zato uporabimo izraz
$
|a - b| < epsilon,
$
kjer je $epsilon$ večji, kot pričakovana zaokrožitvena napaka. V Juliji lahko za približno primerjavo števil in vektorjev uporabimo operator `≈`, ki je alias za funkcijo #link("https://docs.julialang.org/en/v1/base/math/#Base.isapprox")[isapprox].],
)
Preden lahko poženemo teste, moramo ustvariti testno okolje. Sledimo #link(
"https://docs.julialang.org/en/v1/stdlib/Test/#Workflow-for-Testing-Packages",
)[priporočilom za testiranje paketov]. V mapi `Vaja01/test` ustvarimo novo
okolje in dodamo paket `Test`.
#code_box[
#pkg("activate Vaja01/test", none)
#pkg("add Test", none, env: "test")
#pkg("activate .", none, env: "test")
]
Teste poženemo tako, da v paketnem načinu poženemo ukaz `test Vaja01`.
#code_box[
#pkg("test Vaja01", "Testing Vaja01
Testing Running tests
...
...
Test Summary: | Pass Total Time
Koordinata x | 2 2 0.1s
Test Summary: | Pass Total Time
Koordinata y | 2 2 0.0s
Testing Vaja01 tests passed", env:"nummat")
]
== Dokumentacija <sec:01docs>
Dokumentacija programske kode je sestavljena iz različnih besedil in drugih
virov, npr. videov, ki so namenjeni uporabnikom in razvijalcem programa ali
knjižnice. Dokumentacija vključuje komentarje v kodi, navodila za
namestitev in uporabo programa in druge vire z razlagami ozadja,
teorije in drugih zadev, povezanih s projektom. Dobra dokumentacija lahko veliko
pripomore k uspehu določenega programa. To še posebej velja za knjižnice.
Slabo dokumentirane kode, nihče ne želi uporabljati. Tudi če vemo, da kode ne bo
uporabljal nihče drug razen nas samih, bodimo prijazni do samega sebe v prihodnosti
in pišimo dobro dokumentacijo.
V tej knjigi bomo pisali tri vrste dokumentacije:
- dokumentacijo za posamezne funkcije v sami kodi,
- navodila za uporabnika v datoteki `README.md`,
- poročilo v formatu PDF.
#opomba(
naslov: [Zakaj format PDF],
)[
Izbira formata PDF je mogoče presenetljiva za pisanje dokumentacije programske
kode. V praksi so precej uporabnejše HTML strani. Dokumentacija v obliki HTML
strani, ki se generira avtomatično v procesu #link(
"https://en.wikipedia.org/wiki/Continuous_integration",
)[nenehne integracije], je postala _de facto_ standard. V kontekstu popravljanja domačih nalog in poročil za vaje pa ima format PDF še vedno prednosti, saj ga je lažje pregledovati in popravljati.
]
=== Dokumentacija funkcij in tipov
Funkcije in podatkovne tipe v Juliji dokumentiramo tako, da pred definicijo dodamo niz z
opisom funkcije, kot smo to naredili v programu @pr:Vaja01. Več o tem si lahko preberete #link(
"https://docs.julialang.org/en/v1/manual/documentation/",
)[v poglavju o dokumentacij] priročnika za Julijo.
=== README dokument
Dokument README(preberi me) je namenjen najbolj osnovnim informacijam o paketu. Dokument je vstopna točka za dokumentacijo in navadno vsebuje
- kratek opis projekta,
- povezavo na dokumentacijo,
- navodila za osnovno uporabo in
- navodila za namestitev.
#figure(
code_box(
raw(lang:"md", read("Vaja01/README.md"))
),
caption: [README.md vsebuje osnove informacije o projektu.]
)
=== PDF poročilo
Za pripravo dokumentov v formatu PDF priporočamo uporabo naslednjih programov
- #link("https://tug.org/")[TeX/LaTeX],
- #link("https://pandoc.org/")[pandoc],
- #link("https://asciidoctor.org/")[AsciiDoctor],
- #link("https://typst.app/")[Typst].
V nadaljevanju bomo opisali, kako poročilo pripraviti s paketom #link("https://github.com/JunoLab/Weave.jl")[Weave.jl]. Paket `Weave.jl` omogoča mešanje besedila in programske kode v enem dokumentu: #link("https://en.wikipedia.org/wiki/Literate_programming")[literarnemu programu], kot ga je opisal <NAME> (@knuth84).
Za pisanje besedila bomo uporabili format #link("https://en.wikipedia.org/wiki/Markdown")[Markdown], ki ga bomo dodali kot komentarje v kodi.
Za generiranje PDF dokumentov je potrebno namestiti
#link("https://tug.org/")[TeX/LaTeX]. Priporočam namestitev
#link("https://yihui.org/tinytex/")[TinyTeX] ali #link("https://tug.org/texlive/")[TeX Live], ki pa zasede več prostora na disku.
Po #link("https://yihui.org/tinytex/#installation")[namestitvi] programa
TinyTex moramo dodati še nekaj `LaTeX` paketov, ki jih potrebuje paket Weave. V
terminalu izvedemo naslednji ukaz
#code_box[
```shell
$ tlmgr install microtype upquote minted
```
]
Poročilo pripravimo v obliki literarnega programa. Uporabili bom kar
`Vaja01/doc/01uvod.jl`, ki smo jo ustvarili, da smo pripravili sliko.
V datoteko dodamo besedilo v obliki komentarjev. Komentarje, ki se začnejo z
```jl #'```, paket `Weave` uporabi kot tekst v formatu #link(
"https://weavejl.mpastell.com/stable/publish/#Supported-Markdown-syntax",
)[Markdown], medtem ko se koda in navadni komentarji v poročilu izpišejo kot
koda.
#figure(
code_box[
#raw(lang: "jl", block:true, readlines("Vaja01/doc/01uvod.jl", 1, 13))
],
caption: [Vrstice, ki se začnejo z znakoma `#'`, so v formatu Markdown],
)
Poročilo pripravimo z ukazom ```jl Weave.weave```. Ustvarimo program
`Vaja01\doc\makedocs.jl`, ki pripravi pdf dokument:
#figure(code_box(
raw(read("Vaja01/doc/makedocs.jl"), lang: "jl")
),
caption: [Program za pripravo PDF dokumenta],
)
Program poženemo z ukazom ```jl include("Vaja01/doc/makedocs.jl")``` v Juliji. Preden poženemo program `makedocs.jl`, moramo projektnemu okolju `nummat` dodati paket `Weave.jl`.
#code_box[
#pkg("add Weave", none, env: "nummat")
#repl("include(\"Vaja01/doc/makedocs.jl\")", none)
]
Poročilo se shrani v datoteko `Vaja01/pdf/demo.pdf`.
#figure(
rect(
image("img/01uvod.pdf.png", width: 60%)
),
caption: [Poročilo v PDF formatu]
)
#opomba(
naslov: [Alternativni paketi za pripravo PDF dokumentov],
)[
Poleg paketa `Weave.jl` je na voljo še nekaj programov, ki so primerni za pripravo PDF dokumentov s programi v Juliji:
- #link("https://github.com/JuliaLang/IJulia.jl")[IJulia],
- #link("https://github.com/fredrikekre/Literate.jl")[Literate.jl] in
- #link("https://quarto.org/docs/computations/julia.html")[Quadro].
]
#opomba(naslov: [Povezave, ki so povezane s pisanjem dokumentacije.])[
- #link(
"https://docs.julialang.org/en/v1/manual/documentation/",
)[Pisanje dokumentacije] v jeziku Julia.
- #link("https://docs.julialang.org/en/v1/manual/style-guide/")[Priporočila za stil] za programski jezik Julia.
- #link("https://documenter.juliadocs.org/stable/")[Documenter.jl] je najbolj
razširjen paket za pripravo dokumentacije v Julii.
- #link("https://diataxis.fr/")[Diátaxis] je sistematičen pristop k pisanju
dokumentacije.
- #link(
"https://www.writethedocs.org/guide/docs-as-code/",
)[Dokumentacija kot koda] je ime za način dela, pri katerem z dokumentacijo
ravnamo na enak način kot s kodo.
]
== Zaključek
Ustvarili smo svoj prvi paket, ki vsebuje kodo, avtomatske teste in dokumentacijo. Mapa `Vaja01` bi morala imeti naslednjo strukturo:
#code_box[
```shell
$ tree Vaja01
Vaja01
├── Manifest.toml
├── Project.toml
├── README.md
├── doc
│ ├── 01uvod.jl
│ └── makedocs.jl
├── src
│ └── Vaja01.jl
└── test
├── Manifest.toml
├── Project.toml
└── runtests.jl
```
]
Preden nadaljujete, preverite ponovno, če vse deluje tako kot bi moralo. V Juliji aktivirajte projektno okolje:
#code_box[
#repl("# pritisnite ] za vstop v paketni način", none)
#pkg("activate .", none)
]
Nato najprej poženemo teste:
#code_box[
#pkg("test Vaja01", "...
Testing Vaja01 tests passed", env: "nummat")
]
Na koncu pa poženemo še demo:
#code_box[
#repl("include(\"Vaja01/doc/01uvod.jl\")", none)
]
in pripravimo poročilo:
#code_box[
#repl("include(\"Vaja01/doc/makedocs.jl\")", none)
]
Priporočamo, da si pred branjem naslednjih poglavij vzamete čas in poskrbite, da se zgornji
ukazi izvedejo brez napak. |
|
https://github.com/Sckathach/adversarial-gnn-based-ids | https://raw.githubusercontent.com/Sckathach/adversarial-gnn-based-ids/main/mini-survey/neurips.typ | typst | // Workaround for the lack of an `std` scope.
#let std-bibliography = bibliography
// Metrical size of page body.
#let viewport = (
width: 5.5in,
height: 9in,
)
// Default font sizes from original LaTeX style file.
#let font-defaults = (
tiny: 7pt,
scriptsize: 7pt,
footnotesize: 9pt,
small: 9pt,
normalsize: 10pt,
large: 14pt,
Large: 16pt,
LARGE: 20pt,
huge: 23pt,
Huge: 28pt,
)
// We prefer to use Times New Roman when ever it is possible.
#let font-family = ("Times New Roman", "Nimbus Roman", "TeX Gyre Termes")
#let font = (
Large: font-defaults.Large,
footnote: font-defaults.footnotesize,
large: font-defaults.large,
small: font-defaults.small,
normal: font-defaults.normalsize,
script: font-defaults.scriptsize,
)
#let make_figure_caption(it) = {
set align(center)
block({
set text(size: font.normal)
it.supplement
if it.numbering != none {
[ ]
it.counter.display(it.numbering)
}
it.separator
[ ]
it.body
})
}
#let make_figure(caption_above: false, it) = {
// set align(center + top)
// let body = block(breakable: false, width: 100%, {
let body = {
set text(size: font.normal)
if caption_above {
v(1em, weak: true) // Does not work at the block beginning.
it.caption
}
v(1em, weak: true)
it.body
v(8pt, weak: true) // Original 1em.
if not caption_above {
it.caption
v(1em, weak: true) // Does not work at the block ending.
}
}
if it.placement == none {
return body
} else {
return place(it.placement + center, body, float: true, clearance: 2.3em)
}
}
#let anonymous-author = (
name: "<NAME>)",
email: "<EMAIL>",
affl: ("anonymous-affl", ),
)
#let anonymous-affl = (
department: none,
institution: "Affilation",
location: "Address",
)
#let anonymous-notice = [
Submitted to 37th Conference on Neural Information Processing Systems
(NeurIPS 2023). Do not distribute.
]
#let arxiv-notice = [Preprint. Under review.]
#let public-notice = [
]
#let format-author-names(authors) = {
// Formats the author's names in a list with commas and a
// final "and".
let author_names = authors.map(author => author.name)
let author-string = if authors.len() == 2 {
author_names.join(" and ")
} else {
author_names.join(", ", last: ", and ")
}
return author_names
}
#let format-author-name(author, affl2idx, affilated: false) = {
// Sanitize author affilations.
let affl = author.at("affl")
if type(affl) == str {
affl = (affl,)
}
let indices = affl.map(it => str(affl2idx.at(it))).join(" ")
let result = strong(author.name)
if affilated {
result += super(typographic: false, indices)
}
return box(result)
}
#let format-afflilation(affl) = {
assert(affl.len() > 0, message: "Affilation must be non-empty.")
// Concatenate terms which representat affilation to a single text.
let affilation = ""
if type(affl) == array {
affilation = affl.join(", ")
} else if type(affl) == dictionary {
let terms = ()
if "department" in affl and affl.department != none {
terms.push(affl.department)
}
if "institution" in affl and affl.institution != none {
terms.push(affl.institution)
}
if "location" in affl and affl.location != none {
terms.push(affl.location)
}
if "country" in affl and affl.country != none {
terms.push(affl.country)
}
affilation = terms.filter(it => it.len() > 0).join(", ")
} else {
assert(false, message: "Unexpected execution branch.")
}
return affilation
}
#let make-single-author(author, affls, affl2idx) = {
// Sanitize author affilations.
let affl = author.at("affl")
if type(affl) == str {
affl = (affl,)
}
// Render author name.
let name = format-author-name(author, affl2idx)
// Render affilations.
let affilation = affl
.map(it => format-afflilation(affls.at(it)))
.map(it => box(it))
.join(" ")
let lines = (name, affilation)
if "email" in author {
let uri = "mailto:" + author.email
let text = raw(author.email)
lines.push(box(link(uri, text)))
}
// Combine all parts of author's info.
let body = lines.join([\ ])
return align(center, body)
}
#let make-two-authors(authors, affls, affl2idx) = {
let row = authors
.map(it => make-single-author(it, affls, affl2idx))
.map(it => box(it))
return align(center, grid(columns: (1fr, 1fr), gutter: 2em, ..row))
}
#let make-many-authors(authors, affls, affl2idx) = {
let format-affl(affls, key, index) = {
let affl = affls.at(key)
let affilation = format-afflilation(affl)
let entry = super(typographic: false, [#index]) + affilation
return box(entry)
}
// Concatenate all author names with affilation superscripts.
let names = authors
.map(it => format-author-name(it, affl2idx, affilated: true))
// Concatenate all affilations with superscripts.
let affilations = affl2idx
.pairs()
.map(it => format-affl(affls, ..it))
// Concatenate all emails to a single paragraph.
let emails = authors
.filter(it => "email" in it)
.map(it => box(link("mailto:" + it.email, raw(it.email))))
// Combine paragraph pieces to single array, then filter and join to
// paragraphs.
let paragraphs = (names, affilations, emails)
.filter(it => it.len() > 0)
.map(it => it.join(h(1em, weak: true)))
.join([#parbreak() ])
return align(center, {
pad(left: 1em, right: 1em, paragraphs)
})
}
#let make-authors(authors, affls) = {
// Prepare authors and footnote anchors.
let ordered-affls = authors.map(it => it.affl).flatten().dedup()
let affl2idx = ordered-affls.enumerate(start: 1).fold((:), (acc, it) => {
let (ix, affl) = it
acc.insert(affl, ix)
return acc
})
if authors.len() == 1 {
return make-single-author(authors.at(0), affls, affl2idx)
} else if authors.len() == 2 {
return make-two-authors(authors, affls, affl2idx)
} else {
return make-many-authors(authors, affls, affl2idx)
}
}
/**
* neurips2023
*
* Args:
* accepted: Valid values are `none`, `false`, and `true`. Missing value
* (`none`) is designed to prepare arxiv publication. Default is `false`.
*/
#let neurips(
title: [],
authors: (),
keywords: (),
date: auto,
abstract: none,
bibliography: none,
bibliography-opts: (:),
accepted: true,
body,
) = {
// Sanitize authors and affilations arguments.
if accepted != none and not accepted {
authors = ((anonymous-author,), (anonymous-affl: anonymous-affl))
}
let (authors, affls) = authors
// Configure document metadata.
set document(
title: title,
author: format-author-names(authors),
keywords: keywords,
date: date,
)
set page(
paper: "us-letter",
margin: (left: 1.5in, right: 1.5in,
top: 1.0in, bottom: 1in),
footer-descent: 25pt - font.normal,
footer: locate(loc => {
let i = counter(page).at(loc).first()
if i == 1 {
let notice = ""
if accepted == none {
notice = arxiv-notice
} else if accepted {
notice = public-notice
} else {
notice = anonymous-notice
}
return align(center, text(size: 9pt, notice))
} else {
return align(center, text(size: font.normal, [#i]))
}
}),
)
// In the original style, main body font is Times (Type-1) font but we use
// OpenType analogue.
set par(justify: true, leading: 0.55em)
set text(font: font-family, size: font.normal)
// Configure quotation (similar to LaTeX's `quoting` package).
show quote: set align(left)
show quote: set pad(x: 4em)
show quote: set block(spacing: 1em) // Original 11pt.
// Configure spacing code snippets as in the original LaTeX.
show raw.where(block: true): set block(spacing: 14pt) // TODO: May be 15pt?
// Configure bullet lists.
show list: set block(spacing: 15pt) // Original unknown.
set list(
indent: 30pt, // Original 3pc (=36pt) without bullet.
spacing: 8.5pt)
// Configure footnote.
set footnote.entry(
separator: line(length: 2in, stroke: 0.5pt),
clearance: 6.65pt,
indent: 12pt) // Original 11pt.
// Configure heading appearence and numbering.
set heading(numbering: "1.1")
show heading: it => {
// Create the heading numbering.
let number = if it.numbering != none {
counter(heading).display(it.numbering)
}
set align(left)
if it.level == 1 {
// TODO: font.large?
text(size: 12pt, weight: "bold", {
let ex = 7.95pt
v(2.7 * ex, weak: true)
[#number *#it.body*]
v(2 * ex, weak: true)
})
} else if it.level == 2 {
text(size: font.normal, weight: "bold", {
let ex = 6.62pt
v(2.70 * ex, weak: true)
[#number *#it.body*]
v(2.03 * ex, weak: true) // Original 1ex.
})
} else if it.level == 3 {
text(size: font.normal, weight: "bold", {
let ex = 6.62pt
v(2.6 * ex, weak: true)
[#number *#it.body*]
v(1.8 * ex, weak: true) // Original -1em.
})
}
}
// Configure images and tables appearence.
set figure.caption(separator: [:])
show figure: set block(breakable: false)
show figure.caption.where(kind: table): it => make_figure_caption(it)
show figure.caption.where(kind: image): it => make_figure_caption(it)
show figure.where(kind: image): it => make_figure(it)
show figure.where(kind: table): it => make_figure(it, caption_above: true)
// Math equation numbering and referencing.
set math.equation(numbering: "(1)")
show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
let numb = numbering(
"1",
..counter(eq).at(el.location())
)
let color = rgb(0%, 8%, 45%) // Originally `mydarkblue`. :D
let content = link(el.location(), text(fill: color, numb))
[(#content)]
} else {
return it
}
}
// Configure algorithm rendering.
counter(figure.where(kind: "algorithm")).update(0)
show figure.caption.where(kind: "algorithm"): it => {
strong[#it.supplement #it.counter.display(it.numbering)]
[ ]
it.body
}
show figure.where(kind: "algorithm"): it => {
place(top, float: true,
block(breakable: false, width: 100%, {
set block(spacing: 0em)
line(length: 100%, stroke: (thickness: 0.08em))
block(spacing: 0.4em, it.caption) // NOTE: No idea why we need it.
line(length: 100%, stroke: (thickness: 0.05em))
it.body
line(length: 100%, stroke: (thickness: 0.08em))
})
)
}
// Render title.
block(width: 5.5in, {
// We need to define line widths to reuse them in spacing.
let top-rule-width = 4pt
let bot-rule-width = 1pt
// Add some space based on line width.
v(0.1in + top-rule-width / 2)
line(length: 100%, stroke: top-rule-width + black)
align(center, text(size: 17pt, weight: "bold", [#title]))
v(-bot-rule-width)
line(length: 100%, stroke: bot-rule-width + black)
})
v(0.25in)
// Render authors.
block(width: 100%, {
set text(size: font.normal)
set par(leading: 4.5pt)
show par: set block(spacing: 1.0em) // Original 11pt.
make-authors(authors, affls)
v(0.3in - 0.1in)
})
// Vertical spacing between authors and abstract.
// Render abstract.
block(width: 100%, {
set text(size: 10pt)
set text(size: font.normal)
set par(leading: 0.43em) // Original 0.55em (or 0.45em?).
// NeurIPS instruction tels that font size of `Abstract` must equal to 12pt
// but there is not predefined font size.
align(center, text(size: 12pt)[*Abstract*])
v(0.215em) // Original 0.5ex.
pad(left: 0.5in, right: 0.5in, abstract)
v(0.43em) // Original 0.5ex.
})
v(0.43em / 2) // No idea.
pagebreak()
// Render main body
{
// Display body.
set text(size: font.normal)
set par(leading: 0.55em)
set par(leading: 0.43em)
show par: set block(spacing: 1.0em) // Original 11pt.
body
// Display the bibliography, if any is given.
if bibliography != none {
if "title" not in bibliography-opts {
bibliography-opts.title = "References"
}
if "style" not in bibliography-opts {
bibliography-opts.style = "ieee"
}
// NOTE It is allowed to reduce font to 9pt (small) but there is not
// small font of size 9pt in original sty.
show std-bibliography: set text(size: font.small)
set std-bibliography(..bibliography-opts)
bibliography
}
}
}
/**
* A routine for setting paragraph heading.
*/
#let paragraph(body) = {
parbreak()
[*#body*]
h(1em, weak: true)
}
/**
* A routine for rendering external links in monospace font.
*/
#let url(uri) = {
return link(uri, raw(uri))
} |
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/text/smartquotes_04.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 25-45 expected 2 quotes, found 4 quotes
// #set smartquote(quotes: (single: ("'",) * 4)) |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/commute/0.1.0/example.typ | typst | Apache License 2.0 | #import "@preview/commute:0.1.0": node, arr, commutative-diagram
A minimal diagram
#align(center, commutative-diagram(
node((0, 0), [$X$]),
node((0, 1), [$Y$]),
node((1, 0), [$X \/ "ker"(f)$]),
arr((0, 0), (0, 1), [$f$]),
arr((1, 0), (0, 1), [$tilde(f)$], label-pos: -1em, "dashed", "inj"),
arr((0, 0), (1, 0), [$pi$]),
))
A more complicated diagram, with various kinds of arrows
(plz don't report me to the math police, i know this diagram is wrong, it's just to show all the different arrows)
#align(center, commutative-diagram(
node((0, 0), [$pi_1(X sect Y)$]),
node((0, 1), [$pi_1(Y)$]),
node((1, 0), [$pi_1(X)$]),
node((1, 1), [$pi_1(Y) ast.op_(pi_1(X sect Y)) pi_1(X)$]),
arr((0, 0), (0, 1), [$i_1$], label-pos: -1em, "inj"),
arr((0, 0), (1, 0), [$i_2$], "inj"),
arr((1, 0), (2, 2), [$j_1$], curve: -15deg, "surj"),
arr((0, 1), (2, 2), [$j_2$], label-pos: -1em, curve: 20deg, "def"),
arr((1, 1), (2, 2), [$k$], label-pos: 0, "dashed", "bij"),
arr((1, 0), (1, 1), [], "dashed", "inj", "surj"),
arr((0, 1), (1, 1), [], "dashed", "inj"),
node((2, 2), [$pi_1(X union Y)$])
))
A diagram with `debug` enabled
#align(center, commutative-diagram(debug: true,
node((0, 0), [$A$]),
node((0, 1), [$B$]),
node((0, 2), [$C$]),
node((0, 3), [$D$]),
node((0, 4), [$E$]),
node((1, 0), [$A'$]),
node((1, 1), [$B'$]),
node((1, 2), [$C'$]),
node((1, 3), [$D'$]),
node((1, 4), [$E'$]),
arr((0, 0), (0, 1), [$a$]),
arr((0, 1), (0, 2), [$b$]),
arr((0, 2), (0, 3), [$c$]),
arr((0, 3), (0, 4), [$d$]),
arr((1, 0), (1, 1), [$a'$]),
arr((1, 1), (1, 2), [$b'$]),
arr((1, 2), (1, 3), [$c'$]),
arr((1, 3), (1, 4), [$d'$]),
arr((0, 0), (1, 0), [$alpha$]),
arr((0, 1), (1, 1), [$beta$]),
arr((0, 2), (1, 2), [$gamma$]),
arr((0, 3), (1, 3), [$delta$]),
arr((0, 4), (1, 4), [$epsilon$]),
))
|
https://github.com/Enter-tainer/typst-preview | https://raw.githubusercontent.com/Enter-tainer/typst-preview/main/docs/standalone.typ | typst | MIT License | #import "./book.typ": book-page
#import "./templates/gh-page.typ": page-width, is-dark-theme
#import "@preview/fontawesome:0.1.0": *
#import "@preview/colorful-boxes:1.1.0": *
#show: book-page.with(title: "Configuration")
#show link: underline
= Use Without VSCode
The `typst-preview` cli tool can be used to preview your documents without VSCode. It is quite similar to `typst watch` but with a few differences:
1. It will open a browser window. And it will automatically reload the page when you change the document.
2. It is faster than `typst watch` because it doesn't need to export the document to disk.
== Installation
Download `typst-preview` binary for your platform from #link("https://github.com/Enter-tainer/typst-preview/releases")[GitHub Release Page]. And put it in your `$PATH`.
== Typical Usage
Let's assume that you have a document `my-super-cool-doc.typ` in your current directory. You can use `typst-preview` to preview it.
Note that if you have extensions like dark-reader installed in your browser, you should *disable* them because the preview has a transparent background. If the background is set to black, you won't be able to see anything.
1. Use `typst-preview` to preview your document with partial rendering enabled. _*This is what you should do most of the time.*_
```bash
typst-preview --partial-rendering \
my-super-cool-doc.typ
```
2. Use `typst-preview` to do the same thing above but with `partital-rendering` disabled. Do this if you encounter any rendering issues.
```bash
typst-preview my-super-cool-doc.typ
```
3. Use `typst-preview` to preview your document with a custom host and port:
```bash
typst-preview \
--host 0.0.0.0:8090 my-super-cool-doc.typ
```
4. Use `typst-preview` to preview your document with a custom root directory. This is useful when you want to preview a document that is not in the current directory.
```bash
typst-preview --root \
/path/to/my-project \
/path/to/my-project/cool-doc.typ
```
5. Use `typst-preview` to preview your document with a custom font directory. This is useful when you want to use a custom font in your document.
```bash
typst-preview --font-path \
/path/to/my-fonts \
/path/to/my-super-cool-doc.typ
```
Or use the environment variable `TYPST_FONT_PATH` to specify the font directory:
```bash
export TYPST_FONT_PATH=/path/to/my-fonts
typst-preview /path/to/my-super-cool-doc.typ
```
6. Use `typst-preview` to preview your document but don't open the browser automatically:
```bash
typst-preview --no-open \
/path/to/my-super-cool-doc.typ
```
== CLI Options
```
Usage: typst-preview [OPTIONS] <INPUT>
Arguments:
<INPUT>
Options:
--font-path <DIR> Add additional directories to search for fonts
--root <DIR> Root directory for your project
--host <HOST> Host for the preview server [default: 127.0.0.1:23627]
--no-open Don't open the preview in the browser after compilation
--partial-rendering Only render visible part of the document. This can improve performance but still being experimental
-h, --help Print help
```
|
https://github.com/sa-concept-refactoring/doc | https://raw.githubusercontent.com/sa-concept-refactoring/doc/main/abstract-image.typ | typst | #set align(center)
#show raw: it => {
let backgroundColor = luma(0xF0)
if (it.block) {
block(
fill: backgroundColor,
inset: 8pt,
radius: 5pt,
it,
)
} else {
box(
fill: backgroundColor,
outset: 2pt,
radius: 2pt,
it,
)
}
}
== Inline Concept Requirement
#v(2mm)
#table(
columns: 3,
stroke: none,
[
*Before*
#v(-2mm)
```cpp
template <typename T>
void foo(T) requires std::integral<T>
```
],
[
#set align(start + horizon)
#set text(size: 2em)
#sym.arrow.r
],
[
*After*
#v(-2mm)
```cpp
template <std::integral T>
void foo()
```
],
)
#v(1cm)
== Abbreviate Function Template
#v(2mm)
#table(
columns: 3,
stroke: none,
[
*Before*
#v(-2mm)
```cpp
template <std::integral T>
void foo(T param)
```
],
[
#set align(start + horizon)
#set text(size: 2em)
#sym.arrow.r
],
[
*After*
#v(-2mm)
```cpp
void foo(std::integral auto param)
```
],
) |
|
https://github.com/0x1B05/nju_os | https://raw.githubusercontent.com/0x1B05/nju_os/main/book_notes/content/review.typ | typst | #import "../template.typ": *
= 简介
操作系统三座大山: 虚拟化,并发,持久化
总目标: easy to use
设计目标:高性能,低能耗,保护(隔离),可靠性(系统崩溃了,寄)
#tip("Tip")[
其他目标:节能,安全性,可移植性....
]
早期操作系统,就是一个库。
-> 有了保护
-> 多程序
-> 现代
= CPU 虚拟化
== 进程
问题:1个CPU如何制造出有许多CPU的假象?
答:多个程序之间来回切换。(time-sharing)
如何实现?
- machinery low lever 机制: time-sharing
- 高级策略:调度策略
进程的抽象: 进程是个状态机(内存,寄存器)
进程的一些api:
- Create(create a process)
- Destroy(destroy a process)
- Wait(wait for a process to stop running)
- Miscellaneous Control(suspend, resume…)
- Status(get some info about a process)
运行一个进程之前:
- 加载代码和静态数据到内存(进程的地址空间)
#tip("Tip")[
早期的操作系统,the loading process is done *eagerly*, 现在是lazily(paging and swapping)
]
- os给进程的栈和堆分配内存
- 初始化工作,例如IO相关
- 接着从程序的入口(跳到`main`)开始无情地执行指令
进程的状态: Running Ready Blocked
进程的数据结构(xv6-kernel):
#code(caption: [struct proc])[
```c
// Saved registers for kernel context switches.
struct context {
uint64 ra;
uint64 sp;
// callee-saved
uint64 s0;
uint64 s1;
uint64 s2;
uint64 s3;
uint64 s4;
uint64 s5;
uint64 s6;
uint64 s7;
uint64 s8;
uint64 s9;
uint64 s10;
uint64 s11;
};
enum procstate { UNUSED, USED, SLEEPING, RUNNABLE, RUNNING, ZOMBIE };
// Per-process state
struct proc {
struct spinlock lock;
// p->lock must be held when using these:
enum procstate state; // Process state
void *chan; // If non-zero, sleeping on chan
int killed; // If non-zero, have been killed
int xstate; // Exit status to be returned to parent's wait
int pid; // Process ID
// wait_lock must be held when using this:
struct proc *parent; // Parent process
// these are private to the process, so p->lock need not be held.
uint64 kstack; // Virtual address of kernel stack
uint64 sz; // Size of process memory (bytes)
pagetable_t pagetable; // User page table
struct trapframe *trapframe; // data page for trampoline.S
struct context context; // swtch() here to run process
struct file *ofile[NOFILE]; // Open files
struct inode *cwd; // Current directory
char name[16]; // Process name (debugging)
};
```
]
上下文切换:进程停止的时候,寄存器被存储在内存里,进程恢复运行的时候从内存恢复寄存器的值。
- 初始状态:进程被创建的时候。
- 最终状态:进程停止但尚未被清理的示(有时候叫僵尸状态zombie state)
- 最终状态一般被父母进程用来检测退出码(0表示成功,非0失败)
- 当进程运行结束的时候,进程一般会调用`wait()`系统调用来等待孩子进程的完成,并且通知OS可以清理相关的数据结构
数据结构:进程列表(Process list) 里面存储的是 *进程控制块(PCB)*
== 常见的Process API:
- `fork()`
- `wait()`
- `exec()`
- `kill()`
- <C-c> 发送`SIGINT`信号,终止进程
- <C-z> 发送`SIGSTP`信号,暂停进程(可以使用`fg`进行恢复)
- ...
== Mechanism: Limited Direct Execution
虚拟化两方面的挑战:
1. 性能: 如何实现虚拟化而不消耗太多系统性能。
2. 控制: 进程切换
=== 直接执行
#image("images/2023-12-12-19-59-56.png",width: 80%)
问题:
1. 保护(如果没有保护,那OS不就是一个library吗?)
2. 分时
=== 问题1:限制性操作
如果进程想要执行一些限制性操作,例如I/O操作或者获取更多系统资源?
简单的解决方案:不进行保护
引入user/kernel mode:
- user mode: 用户代码只能在user mode里面执行,例如在用户模式下,进程无法直接I/O操作,否则会异常然后OS直接杀死进程
- kernel mode:神!!!
当用户进程想要执行一些特权操作的时候就要使用syscall.
为了执行syscall, 必须限制性一条特殊的Trap指令:
- 进入kernel-mode(必须保存相应的寄存器), 然后执行syscall
- 返回用户进程(返回user-mode)
#tip("Tip")[
trap如何知道执行哪个系统调用呢?
1. 没法让用户进程直接指定指令地址,这样就失去了保护作用。(syscall编号)
2. 系统在启动的时候设置一个trap table,告诉硬件当特定的异常出现的时候应该执行哪些指令:
- hard-disk interrup出现
- 键盘中断出现
- 用户进程系统调用(把syscall number放在一个寄存器或者栈的指定位置,trap handler检查有效性然后执行)
- 。。。
]
#image("images/2023-12-12-20-37-13.png", width: 90%)
=== 问题2: 进程切换
如果一个进程在CPU上运行,那意味着OS不在运行,那操作系统能干啥?如何让OS重新获得CPU的控制权用来进程切换?
方案1: OS相信进程,进程自己会周期性地放弃CPU。什么样的进程呢?
- 会使用系统调用的进程。(`yield`syscall不做啥事儿,仅仅把控制权交还给os)
- 一些做了违法操作的进程(例如除0异常)
但是万一程序死循环了?只能重启了。
于是*计时器中断*
==== 上下文切换
OS重获控制权之后,继续当前运行的进程还是进行切换?(由scheduler进行决策)
上下文切换:
1. 把当前进程的的寄存器,pc,放到kernel stack里面(一个进程有一个kernel stack)
2. 把下面一个将要运行的进程的寄存器,pc,从kernel stack恢复(改变kernel stack指针)
#image("images/2023-12-12-20-37-13.png", width: 90%)
有两种上下文切换:
- 第一种是timer interrupt: 隐式地把当前进程信息进行硬件保存。(保存到当前进程的内核栈)
- 第二种是OS调度的切换: 显式地把当前进程信息进行软件保存。(保存到当前内存里面的进程数据结构里)
=== 并发问题?
一般来说再一个中断执行时需要关中断。(关中断时间太长实际上并不好)
#tip("Tip")[
上下文切换的执行时间? 可以使用`lmbench`
]
== 调度
调度指标: *性能*, *公平性*
== 内存虚拟化
早期的操作系统就是一个库,运行的进程直接放在物理内存里面。
#image("images/2023-12-12-20-46-40.png", width: 50%)
- 多道: 许多进程,os对这些进程进行切换(引入保护的问题)
- 分时: 多用户用一个机器,每个用户等待自己任务的响应
=== 地址空间
地址空间: 正在运行的程序 眼中的 操作系统的内存。
#image("images/2023-12-12-21-00-52.png", width: 70%)
#tip("Tip")[
- 隔离原则: 两个实体,一个寄了不会影响另一个。
- 内存隔离:进程寄了不会影响操作系统。
]
虚拟内存的设置目标:
1. 透明(程序不知道自己的内存是虚拟化的)
2. 时空效率
3. 保护
=== 地址转换
|
|
https://github.com/mintyfrankie/brilliant-CV | https://raw.githubusercontent.com/mintyfrankie/brilliant-CV/main/utils/lang.typ | typst | Apache License 2.0 | #let isNonLatin(lang) = {
let nonLatinLanguageCode = ("zh", "ja", "ko", "ru")
return nonLatinLanguageCode.contains(lang)
}
|
https://github.com/mem-courses/calculus | https://raw.githubusercontent.com/mem-courses/calculus/main/note-2/4.重积分.typ | typst | #import "../template.typ": *
#show: project.with(
course: "Calculus II",
course_fullname: "Calculus (A) II",
course_code: "821T0160",
semester: "Spring-Summer 2024",
title: "Note #4: 重积分",
authors: (
(
name: "memset0",
email: "<EMAIL>",
id: "3230104585",
),
),
date: "April 9, 2024",
)
#let iintd = iintb($D$)
#let iints = iintb($S$)
#let iintsg = iintb($sigma$)
#let iiintv = iiintb($V$)
#let iiintog = iiintb($Omega$)
= 二重积分
== 二重积分的定义
#definition(name: [二重积分])[
设二元函数 $z=f(x,y)$ 在平面有界闭区域 $sigma$ 上有界。用任意的曲线网将 $sigma$ 分割成 $n$ 个小闭区域:$Delta sigma_1, Delta sigma_2, dots.c, Delta sigma_n$。其中 $Delta sigma_i$ 的面积仍旧用 $Delta sigma_i$ 来表示,$Delta sigma_i$ 的直径用 $lambda_i$ 来表示,$i=1,2,dots.c,n$。$lambda=max{lambda_i | i=1,2,dots.c,n}$。$forall P_i (xi_i,eta_i) in Delta sigma_i$,若极限
$
display(sum_(i=1)^n f(xi_i,eta_i) Delta)
$
存在,且与 $sigma$ 的分割方法及 $P_i$ 的取法无关,则称 $f(x,y)$ 在 $sigma$ 上可积,并称此极限为函数 $z=f(x,y)$ 在区域 $sigma$ 上的#def[二重积分]。记作
$
iintsg f(x,y) dsg
$
其中,称 $sigma$ 为#def[积分区域],$f(x,y)$ 为#def[被积函数],$x,y$ 为#def[积分变量],$dsg$ 为#def[面积元素],$f(x,y) dsg$ 为#def[被积表达式]。
]
== 二重积分的可积条件
二重积分的可积性理论远比一元函数定积分复杂,故这里只给出二重积分可积的一个充分条件和一个必要条件。
#theorem[
设 $z=f(x,y)$ 是有界闭区域 $sigma$ 上的一个函数,则
(1) 若 $f(x,y)$ 在 $sigma$ 上连续,则 $f(x,y)$ 在 $sigma$ 上可积;
(2) 若 $f(x,y)$ 在 $sigma$ 上可积,则 $f(x,y)$ 在 $sigma$ 上有界。
]
== 二重积分的性质
下面总假定 $f(x,y)$,$g(x,y)$ 在有界闭区域 $sigma$ 上可积。
#theorem[
$iintsg dsg = sigma$
]
#theorem(name: [二重积分的线性性质])[
$
iintsg (f(x,y) + g(x,y)) dsg = iintsg f(x,y) dsg + iintsg g(x,y) dsg
$
$
iintsg k f(x,y) dsg = k iintsg f(x,y) dsg quad (k "为常数")
$
]
#theorem(name: [二重积分的区域可加性])[
设 $sigma=sigma_1 union sigma_2$ 且 $sigma_1,sigma_2$ 无公共内点,则
$
iintsg f(x,y) dsg = iintb(sigma_1) f(x,y) dsg + iintb(sigma_2) f(x,y) dsg
$
]
#theorem(name: [二重积分的保序性])[
若 $f(x,y) >= 0 space ((x,y) in sigma)$,则 $iintsg f(x,y) dsg >=0$。
]
#corollary[
若 $f(x,y) >= g(x,y) space ((x,y) in sigma)$,则 $iintsg f(x,y) dsg >= iintsg g(x,y) dsg$。
]
#theorem[
设 $f(x,y)$ 在有界闭区域 $sigma$ 上连续。若 $f(x,y) >= 0$ 且 $f(x,y) equiv.not 0$,$(x,y) in sigma$,则
$
iintsg f(x,y) dsg > 0
$
]
#theorem[
$
abs(iintsg f(x,y) dsg) <= iintsg abs(f(x,y)) dsg
$
]
#theorem(name: [估值定理])[
设 $f(x,y)$ 在有界闭区域 $sigma$ 上的最小值为 $m$,最大值为 $M$,则
$
m sigma <= iintsg f(x,y) dsg <= M sigma
$
]
#theorem(name: [中值定理])[
若 $f(x,y)$ 在 $sigma$ 上连续,则存在一点 $(xi,eta) in sigma$,满足
$
iintsg f(x,y) dsg = f(xi,eta) sigma
$
其中 $display(1/sigma iintsg f(x,y) dsg)$ 称为 $f(x,y)$ 在 $sigma$ 上的平均值。
]
== 二重积分的计算:累次积分
#definition[
平面点集
$
D = {(x,y) | a<=x<=b,space phi_1 (x) <= y <= phi_2 (x)}
$
称为 #def[$x$ 型区域];平面点集
$
D = {(x,y) | a<=y<=b,space psi_1 (y) <= x <= psi_2 (y)}
$
称为 #def[$y$ 型区域]。
]
#definition[
设 $f$ 为定义在 $x$ 型区域 $D$ 上的函数,若对 $[a,b]$ 上的每一个固定的 $x$,$f(x,y)$ 作为以 $y$ 为自变量的函数在区间 $[phi_1 (x),phi_2 (x)]$ 上可积,则得到如下用 #def[含参量 $x$ 积分]所表示的函数:
$
A(x) = int_(phi_1 (x))^(phi_2 (x)) f(x,y) dif y, quad x in [a,b]
$
]
#theorem[
对于 $x$ 型区域 $D$ 上的二重积分,可以将其化为先对 $y$ 积分再对 $x$ 积分的#def[累次积分]:
$
iintd f(x,y) dx dy = int_a^b dx int_(phi_1 (x))^(phi_2 (x)) f(x,y) dif y
$
类似地,对于 $y$ 型区域 $D$ 上的二重积分,可以将其化为先对 $x$ 积分再对 $y$ 积分的累次积分:
$
iintd f(x,y) dx dy = int_c^d dy int_(psi_1 (y))^(psi_2 (y)) f(x,y) dif x
$
]
#tip[
【空间立体体积的计算方法】
1. 确定底面 $z_下 = z_1 (x,y)$,顶面 $z_上 = z_2 (x,y)$。
2. 将立体向 $x O y$ 平面作投影,求出投影区域 $sigma_(x y)$:
- 题中不含 $z$ 的方程就是 $sigma_(x y)$ 的边界曲线方程。
- 若题中没有不含 $z$ 的方程,则联立 $display(cases(z=z_1 (x,y),z = z_2 (x,y)))$ 消去 $z$,记得 $sigma_(x y)$ 在平面直角坐标系中的边界曲线方程。
- 以上两种情况兼而有之。
3. 套公式 $V = display(iintb(sigma_(x y)) (z_1 - z_2) dif sigma)$。
]
#property[
设积分区域 $sigma$ 关于 $y$ 轴对称,则
(1) 若 $f(x,y)$ 关于 $x$ 是奇函数,即 $f(x,y) = -f(-x,y)$,则有 $display(iintb(sigma) f(x,y) dif sigma = 0)$。
(2) 若 $f(x,y)$ 关于 $x$ 是偶函数,即 $f(x,y) = f(-x,y)$,则有 $display(iintb(sigma) f(x,y) dif sigma = 2 iintb(sigma\,x>=0) f(x,y) dif sigma)$。
关于 $x$ 轴对称的情形也同理。
]
== 二重积分的计算:变量替换
这里先给出二重积分关于一般变量替换的定理。
#theorem[
设 $D' subset RR^2$ 是有界闭区域,该区域的边界 $diff D'$ 由有限条分段光滑曲线所组成,变换 $T(u,v) : display(cases(x = x(u, v), y = y(u,v)))$ 是 $D'$ 到有界闭区域 $D$ 上连续可导的一一映射,且满足 $display((diff (x,y))/(diff (u,v)) != 0)$。如果 $f$ 在有界闭区域 $D$ 上可积,则
$
iintd f(x,y) dx dy = iintb(D') f(x(u,v), y(u,v)) display(abs((diff (x,y))/(diff (u,v)))) dif u dif v
$
其中 $display((diff (x,y))/(diff (u,v)))$ 为雅可比行列式:
#set math.mat(delim: "|")
$
(diff (x,y)) / (diff (u,v))
= mat(
space display((diff x)/(diff u)),
space,
display((diff y)/(diff u)) space;
space display((diff x)/(diff v)),
space,
display((diff y)/(diff v)) space;
)
$
#set math.mat(delim: "(")
]
=== 极坐标换元
#note[
当被积函数或积分区域的边界曲线方程含有 $x^2+y^2$ 时,常采用极坐标计算二重积分。
]
#corollary[
作极坐标变换
$
x = r cos theta,quad y = r sin theta quad (0<=r<=+oo,space 0<=theta<=2 pi)
$
极坐标变换的雅可比行列式为 $display((diff (x,y))/(diff (r,theta)) = r)$,由上述定理可得
$
iintsg f(x,y) dif sigma = iintb(sigma') f(r cos theta, r sin theta)r dif r dif theta
$
更进一步地,设 $sigma$ 为 $phi_1 (theta) <= phi_2 (theta), space alpha<=theta<=beta$,则二重积分可写为
$
iintsg f(x,y) dsg
= int_alpha^beta dif theta int_(phi_1 (theta))^(phi_2 (theta)) f(r cos theta, r sin theta) dot r dif r
$
]
=== 广义极坐标换元
#corollary[
作广义极坐标变换
$
x = a r cos theta, quad y = b r sin theta quad (0<=r<=+theta, space 0<=theta<=2 pi)
$
可得
$
iintsg f(x,y) dif sigma = iintb(sigma') f(a r cos theta, b r sin theta) a b r dif r dif theta
$
]
= 三重积分
== 三重积分的定义
#definition[
设 $V$ 为空间有界闭区域,$f(x,y,z)$ 为 $V$ 上的有界函数,将 $V$ 任意划分成 $n$ 个小区域:$Delta V_1,Delta V_2,dots.c, Delta V_n$,记 $lambda = display(max_(1<=i<=n)) {Delta V_i "的直径"}$。并任取 $M_i (xi_i, eta_i, zeta_i) in Delta V_i$,若极限 $display(lim_(lambda -> 0) sum_(i=1)^n f(xi_i, eta_i, zeta_i) Delta V_i)$ 存在,则称此极限为函数 $f(x,y,z)$ 在闭区域 $V$ 上的#def[三重积分],记作 $iiintv f(x,y,z) dif V$,即
$
iiintv f(x,y,z) dif V = lim_(lambda->0) sum_(i=1)^n f(xi_i, eta_i, zeta_i) Delta V_i`
$
]
\
三重积分的可积条件与三重积分的性质可类比二重积分,这里略去。
== 三重积分的计算:累次积分
=== 投影法
#theorem[
记 $sigma_(x y)$ 是空间有界区域 $V$ 在 $x O y$ 平面的投影:
$
V = {(x,y,z) | z_1 (x,y) <= z <= z_2 (x,y),space (x,y) in sigma_(x y)}
$
即 $V$ 的底面为 $z= z_1 (x,y)$,顶面为 $z = z_2 (x,y)$,侧面是以 $sigma_(x y)$ 的边界曲线为准线,母线平行于 $z$ 轴的柱面。
如果对每一个固定的点 $(x,y) in sigma_(x y)$,$f(x,y,z)$ 是一个关于变量 $z$ 在区间 $[z_1 (x,y),z_2 (x,y)]$ 上的可积函数,则可以考虑如下积分
$
g(x,y)= int_(z_1 (x,y))^(z_2 (x,y)) f(x,y,z) dif z
$
进一步地,如果这一积分可积,则有
$
iiintv f(x,y,z) dx dy dz = iintb(sigma_(x y)) dx dy int_(z_1 (x,y))^(z_2 (x,y)) f(x,y,z) dif z
$
]
=== 截面法(平行截割法)
#theorem[
设 $V$ 在 $z$ 轴上的投影是一个区间 $[c_1,c_2]$,对每个 $z in [c_1,c_2]$,如果 $f(x,y,z)$ 是关于变量 $x,y$ 在 $z$ 截面 $J_z$ 上的可积函数,则可以考虑如下积分
$
iintb(J_z) f(x,y,z) dx dy
$
进一步地,如果这一积分可积,则有
$
iiintv f(x,y,z) dx dy dz = int_(c_1)^(c_2) dz iintb(J_z) f(x,y,z) dx dy
$
]
== 三重积分的计算:变量替换
三重积分的一般变量替换定理可类比二重积分。
=== 柱面坐标变换
#definition[
对于 $RR^3$ 中任意一点 $P(x,y,z)$,若将前两个分量 $(x,y)$ 在 $x O y$ 平面内用极坐标 $(r, theta)$ 表示,则 $P$ 可以表示为
$
display(cases(
x = r cos theta,
y = r sin theta,
z = z
))
$
称为点 $P$ 的#def[柱面坐标]。
]
#corollary[
三重积分的柱面坐标换元公式为
$
iiintv f(x,y,z) dx dy dz
= iiintv f(r cos theta, r sin theta, z) r dif r dif theta dif z
$
转化成累次积分公式即
$
iiintv f(x,y,z) dx dy dz
= iintb(sigma_(r theta)) r dif r dif theta int_(z_1 (r, theta))^(z_2 (r, theta)) f(
r cos theta, r sin theta, z
) dif z
$
]
=== 球面坐标变换
#definition[
注意到柱面坐标变换中,$z$ 轴和极轴 $r$ 总是正交的,如果对于 $z O r$ 平面引入极坐标 $(rho, phi)$,其中 $rho$ 表示点 $P$ 到原点的距离,而 $phi$ 表示 $z$ 轴到新的极径 $rho$ 的夹角,则 $P$ 可以表示为
$
display(cases(
x = rho sin phi cos theta,
y = rho sin phi sin theta,
z = rho cos phi
)) quad quad
(0 <= phi <= pi; space 0 <= theta <= 2pi)
$
称为点 $P$ 的#def[球面坐标]。
]
#theorem[
三重积分的球面坐标换元公式为
$
iiintv f(x,y,z) dx dy dz
= iiintv f(rho sin phi cos theta, rho sin phi sin theta, rho cos phi) rho^2 sin phi dif rho dif phi dif theta
$
转化成累次积分公式即
$
iiintv f(x,y,z) dx dy dz
= int_(theta_1)^(theta_2) dif theta
int_(phi_1)^(phi_2) dif phi
int_(rho_1 (theta, phi))^(rho_2 (theta, phi)) f(
rho sin phi cos theta, rho sin phi sin theta, rho cos phi
) rho^2 sin phi dif rho
$
]
|
|
https://github.com/Mouwrice/thesis-typst | https://raw.githubusercontent.com/Mouwrice/thesis-typst/main/main.typ | typst | #import "lib.typ": *
#show: template.with(
title: [Air Drumming: Applied on-device body pose estimation],
abstract: [
Body pose estimation is a new and exciting field in Computer Vision. It allows for the estimation of the position of key body parts in images or videos. In this paper, we explore the use of MediaPipe, a popular open-source library, for Body Pose Estimation, promising real-time on-device body pose estimation. We present a demo application that uses MediaPipe to estimate the body pose of a user air drumming. We evaluate the performance of the application and discuss the potential for future work in this area. The accuracy of the pose estimation is evaluated, and some issues are discussed. MediaPipe Pose is shown to achieve an average accuracy of 5-10 mm and an average of 30 fps. However, the MediaPipe estimation suffers from noise and jitter. We present a post-processing method that can reduce that noise and jitter. The method is general, and can be applied to any pose estimation model.
],
preface: [#include("preface.typ")],
authors: (
(
name: "<NAME>",
department: [Master of Science in Computer Science Engineering],
organization: [University of Ghent],
location: [Ghent, Belgium],
email: "<EMAIL>"
),
),
index-terms: ("Body Pose Estimation", "MediaPipe", "Computer Vision", "Motion Capture", "3D Pose Estimation", "Demo Application"),
bibliography: bibliography("bib.yml"),
)
#include "introduction.typ"
#include "sota.typ"
#include "mediapipe_pose.typ"
#include "measurements/measurements.typ"
#include "jitter_noise/jitter_noise.typ"
#include "drum_application.typ"
#include "future_work.typ"
#include "conclusion.typ"
|
|
https://github.com/crd2333/crd2333.github.io | https://raw.githubusercontent.com/crd2333/crd2333.github.io/main/src/docs/Languages/Markdown.md | markdown | ---
html:
embed_local_images: true # 设置为 true,那么所有的本地图片将会被嵌入为 base64 格式
embed_svg: true
offline: false
# toc: undefined # 默认是缺省的,目录会被启动,但是不会显示。可以设置为 true 或 false,来主动 显示 或 隐藏
# 导出设置
puppeteer:
landscape: false
format: "A4"
# timeout: 3000
markdown:
image_dir: ./assets
# path: output.md
ignore_from_front_matter: false
absolute_image_path: false
# 自动导出设置
# export_on_save:
# html: true
# markdown: true
# puppeteer: true # 保存文件时导出 PDF
# puppeteer: ["pdf", "png"] # 保存文件时导出 PDF 和 PNG
---
上面是 MPE 的导出设置,在渲染中是看不到的,只能看到这句话
***
<span style="font-size: 32px; font-weight: bold;">目录</span>
- 比较两种目录的差异,前者似乎是用 code chuck 实现(可自定义?)
<!-- @import "[TOC]" {cmd="toc" depthFrom=1 depthTo=6 orderedList=false ignoreLink=false} -->
<!-- code_chunk_output -->
- [1. markdown的数学公式](#1-markdown的数学公式)
- [1.1. 基本使用](#11-基本使用)
- [1.2. 进阶使用](#12-进阶使用)
- [2. Markdown 编辑器(VSCode)的技巧](#2-markdown-编辑器vscode的技巧)
- [2.1. Markdown 的快捷键](#21-markdown-的快捷键)
- [2.2. Markdown-index](#22-markdown-index)
- [paste image](#paste-image)
- [2.3. Markdown Preview Enhanced(MPE)](#23-markdown-preview-enhancedmpe)
- [3. Markdown Preview Enhanced(MPE) 的使用](#3-markdown-preview-enhancedmpe-的使用)
- [3.1. 导入](#31-导入)
- [3.2. 导出](#32-导出)
- [3.2.1. MPE 与 Pandoc 的使用](#321-mpe-与-pandoc-的使用)
- [配置文件](#配置文件)
- [3.3. 一些元素的测试](#33-一些元素的测试)
- [3.3.2. 图像测试](#332-图像测试)
- [3.3.3. code chunk](#333-code-chunk)
- [3.3.4. Admonition](#334-admonition)
- [3.3.5. 画图](#335-画图)
- [3.3.5.1. mermaid](#3351-mermaid)
- [3.3.5.2. graphviz](#3352-graphviz)
- [3.3.5.3. PlantUML](#3353-plantuml)
- [3.3.5.4. ditta](#3354-ditta)
- [3.3.6. 其他](#336-其他)
- [4. Markdown 本身的一些技巧](#4-markdown-本身的一些技巧)
- [4.1. Markdown 的空格](#41-markdown-的空格)
- [4.2. markdown 的图片插入](#42-markdown-的图片插入)
- [4.3. Markdown 反引号的使用](#43-markdown-反引号的使用)
- [4.4. markdown 页内跳转](#44-markdown-页内跳转)
- [4.5. markdown 左右分栏](#45-markdown-左右分栏)
<!-- /code_chunk_output -->
[toc]
***
# 1. markdown的数学公式
- 跟 LaTeX 有一定的相通之处(或者说本来就是脱胎于 LaTeX)
## 1.1. 基本使用
1. 上下标
`^` 表示上标,`_` 表示下标,如果上标或下标内容多于一个字符,则使用 `{}` 括起来。
例:$(x^2 + x^y )^{x^y}+ x_1^2= y_1 - y_2^{x_1-y_1^2}$
2. 分数
`\frac{分子}{分母}` 或 `分子\over分母`
例:$\frac{1-x}{y+1}$ 或 $x \over x+y$
3. 开方
`\sqrt[n]{a}` (n=2可省略)
例:$\sqrt[3]{4}$ 或 $\sqrt{9}$
4. 括号
- `()[]` 直接写就行,而 `{}` 需要用 `\{` 与 `\}` 转义
- 大 `()`,需要括号前加 `\left` 和 `\right`(成对出现);或者用 `\big`、`\Big`、`\bigg`、`\Bigg`(无需成对出现)
例:$x \in \{1,2,3\}$
例:$(\sqrt{1 \over 2})^2$与$\left(\sqrt{1 \over 2}\right)^2$与$\Bigg(\sqrt{1\over2}\Bigg)^2$
5. 分段函数
`\begin{cases}` 开始,`\end{cases}` 结束,中间情况用 `\\` 分隔
例:$y=\begin{cases} x+y=1\\ x-y = 0 \end{cases}$
6. 向量
向量用 `\vex{a}`,点乘用 `\cdot`,叉乘用 `\times`
例:$(\vec{a}\cdot\vec{a})\times\vec{b}$
7. 定积分
`\int`
例:$\int_0^1x^2dx$
8. 极限
`\lim_{n\rightnarrow+\infty}`
例:$\lim_{n\rightarrow+\infty}\frac{1}{n}$
9. 累加/累乘
`\sum_1^n`, `\prod_0^n`
例:$\sum_1^n$, $\prod_{i=0}^n$
10. 省略号
`\ldots` 底线对齐,`\cdots` 中线对齐
例:$\ldots$ 与 $\cdots$
## 1.2. 进阶使用
- 公式的对齐
- 类似 LaTeX,在 `$$ $$` 中使用 `\begin{align*}` 与 `\end{align*}`,中间用 `&` 来指定对齐位置
- 与 LaTeX 不一样的是,需要用 `$$$$` 包裹,而 LaTeX 直接 `\begin{align*}` 与 `\end{align*}` 就行
- 下大括号的使用
$$e^x\underbrace{=}_{\text{Taylor expansion}}1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\cdots$$
- 将文字置于函数底下
- 有时直接使用下标得到的只是位于右下角(对非内置函数如 $\max$, $\argmax$ 等)
$$p^*=\argmin_p \underset{p\sim posterior}{E}\{p\}$$
- 不过可以看到位置出了一点点的问题,暂且不管
***
# 2. Markdown 编辑器(VSCode)的技巧
- 采用 VSCode 作为 Markdown 编辑器
- 以 Markdown Preview Enhanced 作为核心
- Markdown All in One 其实可以卸了,因为 MPE 已经包含了大部分功能,还没卸的原因是捆绑的一些快捷键(现在我已经自己做到了)以及判断列表来调整缩进的功能
- 利用 Markdown-index 方便地为 Markdown 标题生成序号
- 利用 paste image 插件方便地将剪贴板中的图片粘贴到 Markdown 中
- 不用 Typora 的原因:不开源且收费,不够 fancy,且不符合我一切集成到 VSCode 的习惯
## 2.1. Markdown 的快捷键
- 转为标题:`shift+ctrl+]`
- 加粗:`ctrl+b`
- 倾斜:`ctrl+i`
- 删除线:`ctrl+shift+L`
- 数学公式:`ctrl+$` 或 `shift+$`,通过
## 2.2. Markdown-index
- 只是一个 VSCode 插件罢了,方便地为 VSCode 中的 Markdown 文件的目录生成序号
- 使用方法:在 Markdown 文件中,按下 `Ctrl+Shift+P`,输入 `markdown`,选择 `Markdown add index` 即可
- 还是比较方便的
- 兼容问题
1. 标题用 MPE 语法隐藏后,计数并没有隐藏
2. MPE 导出设置处的 `#` 顶格注释会被识别为标题,导致整个文档标题序号出错
## paste image
- 一个 VSCode 插件,方便地将剪贴板中的图片粘贴到 Markdown 中
- 可以自定义图片的存储路径、命名规则
- 按下 `ctrl+alt+v` 即可(多个 `alt` 是为了不和普通的文字粘贴冲突)
## 2.3. Markdown Preview Enhanced(MPE)
- VSCode 编辑 Markdown 的核心插件,单独开一个大标题来讲
***
# 3. Markdown Preview Enhanced(MPE) 的使用
- 可部分参考 [在 VSCode 下用 Markdown Preview Enhanced 愉快地写文档 - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/56699805)
## 3.1. 导入
- 参考[MPE官方介绍](https://shd101wyy.github.io/markdown-preview-enhanced/#/zh-cn/file-imports)
- `import`支持导入多种类型的文件,若和本教程一样导入的是markdown文件将会被分析处理然后被引用。支持导入特定行数,如`{line_begin=11}`表示从import指定文件的第11行开始导入,同理`{line_end=-4}`就表示导入到倒数第4行。
```markdown
@import '你的文件' {line_begin=11}
```
## 3.2. 导出
- [Markdown Preview Enhanced (MPE) 输出PDF文档分页及页眉页脚 - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/493494190?utm_id=0)
- [Markdown Preview Enhanced (MPE)踩坑记录_jiaojiaodubai的博客-CSDN博客](https://blog.csdn.net/qq_43803536/article/details/124774578)
- 导出为 PDF(prince)
- 需要安装 princexml 这个玩意儿
- 导出为 ebook
- 要导出电子书,需要事先安装好 `ebook-convert`。
### 3.2.1. MPE 与 Pandoc 的使用
- 下载 pandoc,直接 `choco install pandoc`,存储占用不大所以直接这样装在 C 盘了,会自动添加环境变量
- 然后是在 MPE 的使用。需要在文章开头写一些设置,比如:
```markdown
---
output:
pdf_document:
path: C:\Users\mofei\Desktop\test.pdf
toc: true
pandoc_args: ["--no-tex-ligatures"]
latex_engine: typst
---
```
- 也可以是格式化成别的文档形式比如 docx
- `latex_engine` 也可以用 pdflatex
- Pandoc 本身作为一个强大的文档转换工具自然不止能配合 MPE 使用,具体可以参考:
- [Pandoc 从入门到精通,你也可以学会这一个文本转换利器 - 少数派 (sspai.com)](https://sspai.com/post/77206)
- [Pandoc:一个超级强大的文档格式转换工具_pandoc是什么软件-CSDN博客](https://blog.csdn.net/horses/article/details/108536784)
## 配置文件
- CSS 样式表
- `ctrl+shift+p`,选择 `Markdown Preview Enhanced: 自定义样式(全局)`,就会打开一个 css 文件,里面的内容会全局生效
- 可以进行一些诸如字体等的设置
- 在扩展设置中可以将数学渲染引擎由默认的 KaTeX 改为 MathJax,前者虽然速度快但是少了好些功能,以及在我这的字体有些问题(等号渲染不全)
## 3.3. 一些元素的测试
### 3.3.1. Toc Ignore {ignore = true}
- 这个标题在 toc 中被隐藏了
- 但是,跟 Markdown-index 插件不兼容,导致虽然隐藏但序号加一
### 3.3.2. 图像测试
- 直接引入图像
- 语法是这样:"{width=50%}"
- 不再测试,痛点是粘贴的图片没有自动放到 assets 里
### 3.3.3. code chunk
```py {cmd=true}
print("Failed to run code")
```
- 估计是路径啊什么的原因,由于代码块需求不高且可被 Jupyter Notebook 替代,所以暂时不管了
```py {.line-numbers, highlight=[3-4]}
print("This is in code chunk")
print("There are line numbers in the left")
print("This line is highlighted")
print("This line is highlighted too")
```
### 3.3.4. Admonition
!!! note This is the admonition title
This is the admonition body
!!! info More icons
abstract, tip, success, question, failure, danger, bug, example, quote
### 3.3.5. 画图
- 这些画图语言的语法就不介绍了,不是很懂,需要的时候再查看,可以参考本文件夹下 `Markdown-Totorial` 仓库
#### 3.3.5.1. mermaid
- mermaid 是一个用于画流程图、时序图、甘特图等的工具
- 无需进行复杂的安装,直接就能使用
#### 3.3.5.2. graphviz
- 一个开源的图片渲染库。安装了这个库才能在 Windows 下实现把 PlantUML 脚本转换为图片。
- 在 MPE 里其本身也可以画图
#### 3.3.5.3. PlantUML
- PlantUML 是一个画图脚本语言,用它可以快速地画出:时序图、流程图、用例图、状态图、组件图
- 也就是说,跟 mermaid 有一定重叠
- 需要java支持,即要安装jdk
- 安装 graphviz
- 安装 plantuml 插件或这个软件
- 需要用到一个叫做 `plantuml.jar` 的文件,直接安装这个软件或者只安装插件都可以得到
- 需要注意的是这个路径得在 MPE 的设置里手动指定
#### 3.3.5.4. ditta
- 一个用字符描述图形的语言,而且是真正的『所见即所得』——你看到的字符怎么摆放,画出来的图形就是什么样的。
- ~~出了点问题,暂未解决~~ 是新版本改了接入的插件,旧ditaa不能用了。详情看他们更新记录。
- 将示例文档的 `{cmd=true run_on_save=true args=["-E"]}` 改成 `{kroki=true}` 就行了
### 3.3.6. 其他
- 可以使用 emoji
:smile:
- 高亮
A simple text with ==marked== word.
- 上下标
不只是数学模式,文本模式也可以使用^上^~下~标
***
# 4. Markdown 本身的一些技巧
## 4.1. Markdown 的空格
- 参考 [Markdown 语言中空格的几种表示方法_markdown 的空格-CSDN博客](https://blog.csdn.net/qq_34719188/article/details/84205243)
- 几种可能需要空格的情况:段首空格、数学公式
- 段首空格:由于本来是英文环境使用的,没有段首空格的需要,但是中文写手们需要啊
- 数学公式:数学公式内部的空格是无效的,会被忽略
- 下面按照那个博客介绍的方法来试试
1. 全角空格,切换到全角模式下(一般的中文输入法都是按 shift + space)输入两个空格就行了。这个相对来说稍微干净一点,而且宽度是整整两个汉字,很整齐
- 但是搜狗输入法的全角空格用起来很不爽,我给禁用了
- 但是实测,第一段由于前面没有换行(?)这样没有效果,得结合其他方法
- ~~非第一段倒是没关系,但是会有判定的问题~~ 啊不对,那是标点的问题
2. ` ` 表示半角空格(英文);` ` 表示全角空格(中文),这两个都是在非数学公式环境下使用的
3. `$~~~~$` 数学公式内部的空格,非常好用
4. 缩进的地方先用 有序 或 无序列表,再下一行使用 tab
5. 使用样式表
```
p{
text-indent: 2em; /*首行缩进*/
}
```
- 样式表指的是 CSS(Cascading Style Sheets,层叠样式表),不是很熟
## 4.2. markdown 的图片插入
- 带居中 caption 的图片,采用 css 样式
```html
<div align="center" style="color:grey"><img width=261em height=49em src="图片文件/QQ截图20230602095658.png"/>
<br>文字</div>
<div align="center" style="color:grey"><img src="图片文件/2.png" style="max-width: 50%"></div><br/> //由于形状不变变成按比例缩放了
```
- 文章 [关于 Markdown 的一些奇技淫巧 - 知乎 (zhihu.com)](https://zhuanlan.zhihu.com/p/28987530)
## 4.3. Markdown 反引号的使用
- 遇到了一个问题,如何对反引号使用反引号?如果反引号的内部需要反引号,该如何表示?
- 在 Obsidian 这样非纯正 markdown 环境不太清楚怎么搞,但是在 VSCode 中,需要这样:`` ` ``
```
`` ` ``
# 会显示一个反引号
# 注意空格,注意外围双反引号,如果还要嵌套,可以三反引号……
```
## 4.4. markdown 页内跳转
- 有两种方式,一是直接用目录,二是自定义锚,如下
1. 定义一个锚(id): `<span id="jump">跳转到的地方</span>`
2. 使用 markdown 语法:`[点击跳转](#jump)`
## 4.5. markdown 左右分栏
- 采用 html 实现(烂)
<html><table style="margin-left: auto; margin-right: auto;"><tr><td>
左侧内容
</td><td>
右侧内容
</td></tr></table></html> |
|
https://github.com/AntonioSilva03/CurriculumVitae | https://raw.githubusercontent.com/AntonioSilva03/CurriculumVitae/main/Curriculum em Português/lib.typ | typst | #import "@preview/fontawesome:0.2.1": *
#import "@preview/linguify:0.4.0": *
// const color
#let color-darknight = rgb("#131A28")
#let color-darkgray = rgb("#333333")
#let color-gray = rgb("#5d5d5d")
#let default-accent-color = rgb("#262F99")
// const icons
#let linkedin-icon = box(
fa-icon("linkedin", fill: color-darknight),
)
#let github-icon = box(
fa-icon("github", fill: color-darknight),
)
#let phone-icon = box(fa-icon("square-phone", fill: color-darknight))
#let email-icon = box(fa-icon("envelope", fill: color-darknight))
/// Helpers
// layout utility
#let __justify_align(left_body, right_body) = {
block[
#left_body
#box(width: 1fr)[
#align(right)[
#right_body
]
]
]
}
#let __justify_align_3(left_body, mid_body, right_body) = {
block[
#box(width: 1fr)[
#align(left)[
#left_body
]
]
#box(width: 1fr)[
#align(center)[
#mid_body
]
]
#box(width: 1fr)[
#align(right)[
#right_body
]
]
]
}
/// Show a link with an icon, specifically for Github projects
/// *Example*
/// #example(`resume.github-link("DeveloperPaul123/awesome-resume")`)
/// - github-path (string): The path to the Github project (e.g. "DeveloperPaul123/awesome-resume")
/// -> none
#let github-link(github-path) = {
set box(height: 11pt)
align(right + horizon)[
#fa-icon("github", fill: color-darkgray) #link(
"https://github.com/" + github-path,
github-path,
)
]
}
/// Right section for the justified headers
/// - body (content): The body of the right header
#let secondary-right-header(body) = {
set text(
size: 11pt,
weight: "medium",
)
body
}
/// Right section of a tertiaty headers.
/// - body (content): The body of the right header
#let tertiary-right-header(body) = {
set text(
weight: "light",
size: 9pt,
)
body
}
/// Justified header that takes a primary section and a secondary section. The primary section is on the left and the secondary section is on the right.
/// - primary (content): The primary section of the header
/// - secondary (content): The secondary section of the header
#let justified-header(primary, secondary) = {
set block(
above: 0.7em,
below: 0.7em,
)
pad[
#__justify_align[
== #primary
][
#secondary-right-header[#secondary]
]
]
}
/// Justified header that takes a primary section and a secondary section. The primary section is on the left and the secondary section is on the right. This is a smaller header compared to the `justified-header`.
/// - primary (content): The primary section of the header
/// - secondary (content): The secondary section of the header
#let secondary-justified-header(primary, secondary) = {
__justify_align[
=== #primary
][
#tertiary-right-header[#secondary]
]
}
/// --- End of Helpers
/// ---- Resume Template ----
/// Resume template that is inspired by the Awesome CV Latex template by posquit0. This template can loosely be considered a port of the original Latex template.
///
/// The original template: https://github.com/posquit0/Awesome-CV
///
/// - author (content): Structure that takes in all the author's information
/// - date (string): The date the resume was created
/// - accent-color (color): The accent color of the resume
/// - colored-headers (boolean): Whether the headers should be colored or not
/// - language (string): The language of the resume, defaults to "en". See lang.toml for available languages
/// - body (content): The body of the resume
/// -> none
#let resume(
author: (:),
date: datetime.today().display("[month repr:long] [day], [year]"),
accent-color: default-accent-color,
colored-headers: true,
language: "en",
body,
) = {
if type(accent-color) == "string" {
accent-color = rgb(accent-color)
}
let lang_data = toml("lang.toml")
set document(
author: author.firstname + " " + author.lastname,
title: "resume",
)
set text(
font: ("Source Sans Pro", "Source Sans 3"),
lang: language,
size: 11pt,
fill: color-darkgray,
fallback: true,
)
set page(
paper: "a4",
margin: (left: 15mm, right: 15mm, top: 10mm, bottom: 10mm),
footer: [
#set text(
fill: gray,
size: 8pt,
)
#__justify_align_3[
#smallcaps[#date]
][
#smallcaps[
#if language == "zh" or language == "ja" [
#author.firstname#author.lastname
] else [
#author.firstname#sym.space#author.lastname
]
#sym.dot.c
#linguify("resume", from: lang_data)
]
][
#counter(page).display()
]
],
footer-descent: 0pt,
)
// set paragraph spacing
show par: set block(
above: 0.75em,
below: 0.75em,
)
set par(justify: true)
set heading(
numbering: none,
outlined: false,
)
show heading.where(level: 1): it => [
#set block(
above: 1em,
below: 1em,
)
#set text(
size: 16pt,
weight: "regular",
)
#align(left)[
#let color = if colored-headers {
accent-color
} else {
color-darkgray
}
#text[#strong[#text(color)[#it.body.text]]]
#box(width: 1fr, line(length: 100%))
]
]
show heading.where(level: 2): it => {
set text(
color-darkgray,
size: 12pt,
style: "normal",
weight: "bold",
)
it.body
}
show heading.where(level: 3): it => {
set text(
size: 10pt,
weight: "regular",
)
smallcaps[#it.body]
}
let name = {
align(center)[
#pad(bottom: 5pt)[
#block[
#set text(
size: 32pt,
style: "normal",
font: ("Roboto"),
)
#if language == "zh" or language == "ja" [
#text(
accent-color,
weight: "thin",
)[#author.firstname]#text(weight: "bold")[#author.lastname]
] else [
#text(accent-color, weight: "thin")[#author.firstname]
#text(weight: "bold")[#author.lastname]
]
]
]
]
}
let positions = {
set text(
accent-color,
size: 9pt,
weight: "regular",
)
align(center)[
#smallcaps[
#author.positions.join(
text[#" "#sym.dot.c#" "],
)
]
]
}
let address = {
set text(
size: 9pt,
weight: "bold",
)
align(center)[
#if ("address" in author) [
#author.address
]
]
}
let contacts = {
set box(height: 9pt)
let separator = box(width: 5pt)
align(center)[
#set text(
size: 9pt,
weight: "regular",
style: "normal",
)
#block[
#align(horizon)[
#if ("phone" in author) [
#phone-icon
#box[#text(author.phone)]
#separator
]
#if ("email" in author) [
#email-icon
#box[#link("mailto:" + author.email)[#author.email]]
]
#if ("github" in author) [
#separator
#github-icon
#box[#link("https://github.com/" + author.github)[#author.github]]
]
#if ("linkedin" in author) [
#separator
#linkedin-icon
#box[
#link("https://www.linkedin.com/in/" + author.linkedin)[#author.firstname #author.lastname]
]
]
]
]
]
}
name
positions
address
contacts
body
}
/// The base item for resume entries.
/// This formats the item for the resume entries. Typically your body would be a bullet list of items. Could be your responsibilities at a company or your academic achievements in an educational background section.
/// - body (content): The body of the resume entry
#let resume-item(body) = {
set text(
size: 10pt,
style: "normal",
weight: "light",
fill: color-darknight,
)
set par(leading: 0.65em)
body
}
/// The base item for resume entries. This formats the item for the resume entries. Typically your body would be a bullet list of items. Could be your responsibilities at a company or your academic achievements in an educational background section.
/// - title (string): The title of the resume entry
/// - location (string): The location of the resume entry
/// - date (string): The date of the resume entry, this can be a range (e.g. "Jan 2020 - Dec 2020")
/// - description (content): The body of the resume entry
#let resume-entry(
title: none,
location: "",
date: "",
description: "",
accent-color: default-accent-color,
) = {
pad[
#justified-header(title, location)
#secondary-justified-header(description, date)
]
}
/// Show cumulative GPA.
/// *Example:*
/// #example(`resume.resume-gpa("3.5", "4.0")`)
#let resume-gpa(numerator, denominator) = {
set text(
size: 12pt,
style: "italic",
weight: "light",
)
text[Cumulative GPA: #box[#strong[#numerator] / #denominator]]
}
/// Show a certification in the resume.
/// *Example:*
/// #example(`resume.resume-certification("AWS Certified Solutions Architect - Associate", "Jan 2020")`)
/// - certification (content): The certification
/// - date (content): The date the certification was achieved
#let resume-certification(certification, date) = {
justified-header(certification, date)
}
/// Show a list of skills in the resume under a given category.
/// - category (string): The category of the skills
/// - items (list): The list of skills. This can be a list of strings but you can also emphasize certain skills by using the `strong` function.
#let resume-skill-item(category, items) = {
set block(below: 0.65em)
set pad(top: 2pt)
pad[
#grid(
columns: (20fr, 80fr),
gutter: 10pt,
align(right)[
#set text(hyphenate: false)
== #category
],
align(left)[
#set text(
size: 11pt,
style: "normal",
weight: "light",
)
#items.join(", ")
],
)
]
}
/// ---- End of Resume Template ----
/// ---- Coverletter ----
/// Cover letter template that is inspired by the Awesome CV Latex template by posquit0. This template can loosely be considered a port of the original Latex template.
/// This coverletter template is designed to be used with the resume template.
/// - author (content): Structure that takes in all the author's information
/// - profile-picture (image): The profile picture of the author. This will be cropped to a circle and should be square in nature.
/// - date (date): The date the cover letter was created
/// - accent-color (color): The accent color of the cover letter
/// - body (content): The body of the cover letter
#let coverletter(
author: (:),
profile-picture: image,
date: datetime.today().display("[month repr:long] [day], [year]"),
accent-color: default-accent-color,
language: "en",
body,
) = {
if type(accent-color) == "string" {
accent-color = rgb(accent-color)
}
// language data
let lang_data = toml("lang.toml")
set document(
author: author.firstname + " " + author.lastname,
title: "cover-letter",
)
set text(
font: ("Source Sans Pro", "Source Sans 3"),
lang: language,
size: 11pt,
fill: color-darkgray,
fallback: true,
)
set page(
paper: "a4",
margin: (left: 15mm, right: 15mm, top: 10mm, bottom: 10mm),
footer: [
#set text(
fill: gray,
size: 8pt,
)
#__justify_align_3[
#smallcaps[#date]
][
#smallcaps[
#if language == "zh" or language == "ja" [
#author.firstname#author.lastname
] else [
#author.firstname#sym.space#author.lastname
]
#sym.dot.c
#linguify("cover-letter", from: lang_data)
]
][
#counter(page).display()
]
],
footer-descent: 0pt,
)
// set paragraph spacing
show par: set block(
above: 0.75em,
below: 0.75em,
)
set par(justify: true)
set heading(
numbering: none,
outlined: false,
)
show heading: it => [
#set block(
above: 1em,
below: 1em,
)
#set text(
size: 16pt,
weight: "regular",
)
#align(left)[
#text[#strong[#text(accent-color)[#it.body.text]]]
#box(width: 1fr, line(length: 100%))
]
]
let name = {
align(right)[
#pad(bottom: 5pt)[
#block[
#set text(
size: 32pt,
style: "normal",
font: ("Roboto"),
)
#if language == "zh" or language == "ja" [
#text(
accent-color,
weight: "thin",
)[#author.firstname]#text(weight: "bold")[#author.lastname]
] else [
#text(accent-color, weight: "thin")[#author.firstname]
#text(weight: "bold")[#author.lastname]
]
]
]
]
}
let positions = {
set text(
accent-color,
size: 9pt,
weight: "regular",
)
align(right)[
#smallcaps[
#author.positions.join(
text[#" "#sym.dot.c#" "],
)
]
]
}
let address = {
set text(
size: 9pt,
weight: "bold",
fill: color-gray,
)
align(right)[
#if ("address" in author) [
#author.address
]
]
}
let contacts = {
set box(height: 9pt)
let separator = [#box(sym.bar.v)]
align(right)[
#set text(
size: 8pt,
weight: "light",
style: "normal",
)
#block[
#align(horizon)[
#stack(
dir: ltr,
spacing: 0.5em,
if ("phone" in author) [
#phone-icon
#box[#text(author.phone)]
#separator
],
if ("email" in author) [
#email-icon
#box[#link("mailto:" + author.email)[#author.email]]
],
if ("github" in author) [
#separator
#github-icon
#box[#link("https://github.com/" + author.github)[#author.github]]
],
if ("linkedin" in author) [
#separator
#linkedin-icon
#box[
#link("https://www.linkedin.com/in/" + author.linkedin)[#author.firstname #author.lastname]
]
],
)
]
]
]
}
let letter-heading = {
grid(
columns: (1fr, 2fr),
rows: (100pt),
align(left + horizon)[
#block(
clip: true,
stroke: 0pt,
radius: 2cm,
width: 4cm,
height: 4cm,
profile-picture,
)
],
[
#name
#positions
#address
#contacts
],
)
}
let letter-conclusion = {
align(bottom)[
#pad(bottom: 2em)[
#text(weight: "light")[#linguify(
"sincerely",
from: lang_data,
)#sym.comma] \
#text(weight: "bold")[#author.firstname #author.lastname] \ \
#text(weight: "light", style: "italic")[ #linguify(
"attached",
from: lang_data,
)#sym.colon #linguify("curriculum-vitae", from: lang_data)]
]
]
}
// actual content
letter-heading
body
linebreak()
letter-conclusion
}
/// Cover letter heading that takes in the information for the hiring company and formats it properly.
/// - entity-info (content): The information of the hiring entity including the company name, the target (who's attention to), street address, and city
/// - date (date): The date the letter was written (defaults to the current date)
#let hiring-entity-info(
entity-info: (:),
date: datetime.today().display("[month repr:long] [day], [year]"),
) = {
set par(leading: 1em)
pad(top: 1.5em, bottom: 1.5em)[
#__justify_align[
#text(weight: "bold", size: 12pt)[#entity-info.target]
][
#text(weight: "light", style: "italic", size: 9pt)[#date]
]
#pad(top: 0.65em, bottom: 0.65em)[
#text(weight: "regular", fill: color-gray, size: 9pt)[
#smallcaps[#entity-info.name] \
#entity-info.street-address \
#entity-info.city \
]
]
]
}
/// Letter heading for a given job position and addressee.
/// - job-position (string): The job position you are applying for
/// - addressee (string): The person you are addressing the letter to
/// - dear (string): optional field for redefining the "dear" variable
#let letter-heading(job-position: "", addressee: "", dear: "") = {
let lang_data = toml("lang.toml")
// TODO: Make this adaptable to content
underline(evade: false, stroke: 0.5pt, offset: 0.3em)[
#text(weight: "bold", size: 12pt)[Job Application for #job-position]
]
pad(top: 1em, bottom: 1em)[
#text(weight: "light", fill: color-gray)[
#if dear == "" [
#linguify("dear", from: lang_data)
] else [
#dear
]
#addressee,
]
]
}
/// Cover letter content paragraph. This is the main content of the cover letter.
/// - content (content): The content of the cover letter
#let coverletter-content(content) = {
pad(top: 1em, bottom: 1em)[
#set par(first-line-indent: 3em)
#set text(weight: "light")
#content
]
}
/// ---- End of Coverletter ----
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/cetz/0.0.1/lib.typ | typst | Apache License 2.0 | #import "canvas.typ": canvas
#import "draw.typ"
#import "coordinate.typ"
#import "vector.typ"
#import "matrix.typ"
// These are aliases to prevent name collisions
// You can use them for importing the module into the
// root namespace:
// #import "@.../cetz": canvas, cetz-draw
#let cetz-draw = draw
#let cetz-vector = vector
#let cetz-matrix = matrix
|
https://github.com/polarkac/MTG-Stories | https://raw.githubusercontent.com/polarkac/MTG-Stories/master/stories/034%20-%20Dominaria/002_Return%20to%20Dominaria%3A%20Episode%202.typ | typst | #import "@local/mtgstory:0.2.0": conf
#show: doc => conf(
"Return to Dominaria: Episode 2",
set_name: "Dominaria",
story_date: datetime(day: 22, month: 03, year: 2018),
author: "<NAME>",
doc
)
Liliana strode through the Morass under the hazy dawn light, the muddy grass dragging at her clothes. Ahead, a scatter of ravens took flight, bursting out of the shadows cloaking a dead tree. Furious, she shouted, "I know you're here! Face me, damn you!" She had been searching the marsh since dawn. It was full of foul distorted creatures created by the Cabal's spells, but each one who crossed her path learned who the real threat was.
The Raven Man had to be here, had to know how Belzenlok had managed to turn Josu into his lich. She had thought of nothing else last night, when the innkeeper had half-carried a semiconscious Gideon back to their room, and she had used the herbs she had collected to heal his wounds. She had meant to do this for Josu all those years ago, to make him whole, to save her brother's life. It was easy to see now that she had been single-minded and selfish about it, ignoring warnings, rushing as if minutes were meaningful, wanting only to succeed where others had failed and make herself the hero of her family. But it was a teenager's selfishness, a childish self-absorption. It didn't deserve this.
Josu didn't deserve this.
And while she had been working her healing on Gideon, she had been irrationally terrified it would happen again. That she would somehow kill or transform her only ally. But she had left him in the inn still recovering, whole and sleeping deeply.
She had to find the Raven Man. She had to find answers.
Above the trees ahead, ravens wheeled in the air, then dove to spiral into a dark whirlwind just above the ground. The rapid flap of their wings coalesced into a black mass, as if they had all joined together into one creature. Out of that mass stepped the Raven Man.
#figure(image("002_Return to Dominaria: Episode 2/01.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
He looked the same as the last time she had seen him, a tall pale figure dressed in black with hair white as bone and eyes of piercing gold. He had followed her across planes, making a pretense of wanting to help her, though she had no idea what his real motive was. She demanded, "Did you do this? Did you tell Belzenlok how my brother died? How did Belzenlok raise him again?"
"You already know the answers to these questions, Lili," he said, his calm infuriating.
"It's because of you." She stalked forward. There were ravens everywhere, perched on every rock or stump or rotted tree limb. They watched the confrontation silently, unmoving. She had never known what the Raven Man was, or why he was so determined to interfere in her life. He could be anything from a powerful Planeswalker to an elder dragon in human form. "You did this. Fix it. Lay Josu to rest."
"It can't be done." His golden eyes regarded her calmly, as if her pain was amusing. "If you miss your brother so much, you should have agreed to follow me."
Liliana's anger gathered in her chest, and at her side the Onakke spirits in the Chain Veil whispered. She rasped out, "For what purpose? What do you want of me?" He didn't answer, watching her thoughtfully while the damp wind stirred the birds' feathers. "Why stalk me from plane to plane? Why trick me into making my own brother undead when all I wanted was to help—" She felt her voice climb higher, as if it was about to break, and stopped. She took a breath. She wasn't vulnerable with emotion, she was raging with the desire to tear this creature apart, whatever he was. But she couldn't afford to show any sign that might be interpreted as weakness.
He said, "I think you know why."
The words fell into the silence of the marsh. Liliana didn't want to answer, couldn't answer. Did she know? She asked, "Were you trying to ignite my spark? Why did you want me to become a Planeswalker?"
The ravens around him took flight and Liliana lunged forward. "Oh no, don't you—" Before she could lift a hand the birds swirled into motion and he and every raven in sight abruptly vanished.
Liliana swore in thwarted fury. "Useless!"
She paced hard, sending snakes and the foul little creatures of the Morass fleeing in terror.
How could she help Josu? It wasn't just Belzenlok using her brother as a servant that rankled every bone in her body. It was her own healing work that went so terribly wrong all those years ago. The Raven Man had manipulated her, tricked her into performing the work, yes, but she was the one who had done it, the one who had turned Josu into a mindless undead remnant. And somehow it left his remains vulnerable to Belzenlok's magic, allowing Belzenlok to raise Josu from the grave once more, enslaving him, but with his wits and military knowledge intact.
#figure(image("002_Return to Dominaria: Episode 2/02.jpg", width: 100%), caption: [Art by Daarken], supplement: none, numbering: none)
#emph[I could use the Chain Veil] , she thought suddenly. Now that Josu was transformed into a lich, it would lay him to rest just as it would destroy a demon . . . She swore under her breath in realization. #emph[Oh, so that's it] .
That was Belzenlok's plan, his purpose in choosing Josu to lead his forces in Caligo. He knew if Liliana used the Chain Veil to unmake Josu, it would leave her so weak she wouldn't be able to use it to destroy Belzenlok.
Her lips curled in contempt. Belzenlok's overconfidence was just as misplaced as hers had been, that long-ago day when Josu had died. When she had killed him. She would use the Chain Veil to unmake her brother. #emph[I am <NAME>] , she thought. #emph[If there's a way to kill Belzenlok without the Chain Veil, I can find it] .
But first she had to get Josu back to <NAME>, back to the spot where he had been made undead in the first place. Only there would the spell of unmaking work; only there could she lay him to rest.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
The morning sun was breaking over the patched roofs of the town when she reached the inn again. Townspeople were out in the plaza, some keeping watch while others shoveled out the burned market stalls. As she passed they nodded to her respectfully, and a few of the younger ones waved. She stared, nonplussed, and strode past them into the inn.
She found Gideon awake and in the inn's garden court amid herb and vegetable beds. He was slowly moving through attack forms with a borrowed sword, clearly testing her work on his shoulder. She stopped in front of him, braced for a confrontation, her face set in a sneer, a cutting rejoinder ready.
Gideon sheathed the sword and faced her. He said mildly, "News?"
"What?" She frowned.
Gideon's brow quirked. "The innkeep said you'd gone out before dawn. I thought you were scouting out Belzenlok's forces."
She made an impatient gesture. "I was looking for information, yes, but—" She took a sharp breath. She had expected Gideon to be ready to abandon her cause because Nissa and Chandra had. Because of who she was. But he hadn't, and she was a fool not to ask for his help.
Walking back through the Morass, she had tried to think of a way to explain what she needed without telling him the truth, but every story she had come up with was more ridiculous than the last. She began reluctantly, "I have a problem . . . closer to home, shall we say. I told you I used to live here." It was unexpectedly hard to force the words out. "The lich leading the Cabal forces in this area is my brother, Josu."
She wasn't sure what reaction she had expected. But Gideon said nothing. His brow furrowed in consternation and he slowly took a seat on a bench, gesturing for her to go on. Liliana paced the uneven stone of the court and found herself explaining. "I made Josu undead, many years ago. It was an accident. I was young, foolish, inexperienced. I was trying to heal him and . . ." She made a sharp gesture. "It happened. The spells, the dark magic, was part of what ignited my spark, and I involuntarily planeswalked away. I haven't been back here since. Yesterday when I went to look for herbs, I found evidence of a powerful necromantic spell in the ruin of my family home. Belzenlok must have somehow been able to raise Josu again to use against me." She stopped and faced him. "I need to lay my brother to rest."
Again, she was expecting Gideon to leave. This was not what they had discussed and would not serve their goal of destroying <NAME>. In Gideon's place, Liliana would have already been gone. But he nodded, his expression thoughtful. "Yes, that's our next step, obviously."
"Obviously?" she said, startled.
"Belzenlok is using the Cabal to threaten all of Dominaria. If we can unmake Josu, not only will your brother be free, but the Cabal will lose his leadership in Caligo Morass. This will give the Benalish forces a chance to regroup and force Belzenlok and the Cabal off Aerona." Gideon glanced up at her and smiled grimly. "It's a good start."
Braced to argue, to make her case, she was left flailing by his agreement. She paced away, trying to get her thoughts together, and remembered she hadn't told him the worst part yet. "I'll need the Chain Veil to unmake Josu. After that, I won't have the strength to use it against Belzenlok."
Gideon considered that for a moment. "That can't be helped. We'll have to think of another way to destroy Belzenlok." He shrugged a little. "Nothing about this was ever going to be simple, or easy. We both knew that."
Liliana pressed her lips together. It was stupid to feel an annoying ripple of emotion. Gideon was being practical. She was just lucky that they temporarily shared the same goal. She said, "I'll need to get Josu back to Vess Manor to unmake him, but I'm not sure how. He's leading the Cabal forces, surrounded by them."
Gideon pushed to his feet. "For that, I think I know exactly what we need to do."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Gideon led the way into the marsh, using the directions he had gotten from the innkeeper and the other leaders of the town's defenses. As they followed the barely discernible path between stagnant pools and the heaped remains of rotting trees, he told Liliana, "Josu and the Cabal defeated a large Benalish force not far from here just a few days ago. Some of their wounded are still being sheltered in the town, and others have gone to ground in small groups all over this area. If we rally them and make Vess Manor our staging ground, Josu will have to come attack us there."
"Your optimism is boundless," Liliana said, a tinge of mockery in her voice.
"I can tell you're upset," he told her. "You're not putting much effort into your insults."
"I'm not upset!" Liliana snapped. "I'm . . . plotting. Why should these people listen to us?"
"Well, that's my job," Gideon said.
Ahead stood a perfectly round stone platform, surrounded by tall grass. Near it, three smooth columns, each a good sixty feet high, formed a half-circle. It was the remains of an ancient ruin, a place that had once been surrounded by heavy forest but was now exposed and partially sunken into the marshy ground. Dying vines clung to the upper portions, but like the other ancient structures Gideon had seen here, the stone was unstained and unweathered. Perched on the center column was the person Gideon had come to see.
It was an angel, with skin like burnished bronze and hair a dark cloud. Her wings were half-extended, the brilliant white feathers shading down to dark gray at the tips. She wore plate armor over chain mail and the sword that lay at her feet was nearly as tall as Gideon. He called up to her, "Will you speak with us? Gerrel, innkeeper of the town of Vess, sent us here to find you."
For a moment he thought she wouldn't answer. Then her wings extended fully and she rose, stepping off the column. She landed lightly, her knees flexing to take the weight. This close, he could see her white tabard was stained with blood and her armor bore the dents and scrapes of recent battle. Her face expressionless, she said, "Who are you?"
"I'm <NAME> and this is Liliana." They had decided not to tell anyone of Liliana's past association with Vess. Gideon already had enough to cope with. "We know you're Rael, Battle Angel and Protector of Caligo. You led the Benalish forces against the Cabal here."
Rael said flatly, "Then you know I failed."
"You lost a battle," Gideon told her. "It doesn't mean you failed."
Her brows lifted, a little life coming into her expression. It was irritation, but at least it was life. Her voice tinged with irony, she said, "Platitudes will not stop the Cabal."
"Yes, he's very annoying that way," Liliana said, folding her arms. "But we're here to offer you our help."
"You should have arrived earlier." Rael's grim gaze moved from Gideon to Liliana, evaluating them. "My forces are scattered, in hiding. If I engage the Cabal again, they'll be destroyed. Let them defend themselves and their own as best they can. We can't defeat the Cabal here in open battle."
"I understand, but it's not just strength of arms we're here to offer," Gideon said. "Liliana is a powerful mage, and she destroyed the undead knights who attacked Vess last night. With your help, we have a way to defeat the lich Josu who commands the grimnants here."
Rael's dark brows lowered. "You know the name of their commander?"
Gideon glanced at Liliana, whose expression gave nothing away. "Not only that, we have a way to lay him to rest."
Rael hesitated, and in her expression hope warred with resignation. Gideon watched hope win out. She took a deep breath, and said, "Tell me your plan."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
While Liliana prepared for her spell, Gideon spent the rest of their day with Rael, gathering the Benalish forces left in Caligo. When the next day dawned, they were at the high ground around Vess Manor with a small force of Benalish soldiers, knights, and aven scouts.
#figure(image("002_Return to Dominaria: Episode 2/03.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
The sky was heavy with clouds, threatening rain, as Gideon and Liliana met with Rael and her lieutenants in the overgrown remnants of the house's walled garden. Looking around at them all, Gideon knew he would need a good defensive strategy. Too many of the soldiers and knights were walking wounded, too many were disheartened by the deaths of their companions and the devastation the Cabal had caused in Caligo. He had no intention of letting them bear the brunt of the attack.
"Are there any other mages here?" Gideon had asked earlier.
"There's Corin." Rael had pointed to a small pale figure standing with the Benalish soldiers. "He's a Tolarian mage."
Corin seemed very young and dispirited, his robes dragging in the wet grass. He had some sort of crystal and metal artificer's gauntlet on one arm, but he didn't look formidable. "I see," Gideon said, and nodded politely, privately deciding to try to come up with a plan that didn't include mages.
It was true that laying Josu to rest would deprive Belzenlok of his general in this part of Benalia, but it was also a vital part of Gideon's plan to kill <NAME>. He couldn't let these weary people take the brunt of a battle to further his goals, even if those goals would ultimately benefit their plane.
Of course, Gideon was well aware that his defensive strategies largely consisted of throwing himself between whatever was attacking and his companions. It was still the best solution if he couldn't think of anything else.
"Why are we meeting here?" asked Thiago, a Benalish knight who was Rael's second in command. He glanced up at the lichen-covered stone wall looming over them. "This house is cursed. It can't be a good spot to stage a battle against the Cabal."
"The curse will end when I unmake the lich," Liliana told him. Her expression was cool and arch, as if nothing they discussed here affected her personally, but Gideon knew better. She had tried her best to keep her emotions in check when she told him about Josu, but he knew her just well enough to sense the real horror and dismay she felt. She might have used the moment to lie or try to manipulate him, but she hadn't. It had surprised him, and made him think they might actually have a chance to kill Belzenlok and then <NAME>. If they could really work together as allies, anything was possible. She added, "The spell has to be performed here."
The captain of the soldiers asked, "The lich was created by the curse of Vess?"
Gideon had no idea. He glanced at Liliana, who said, "It doesn't matter how it was created. This is where I'll destroy it."
An aven brought Rael a map, and she unrolled it on a stone table. It showed the Morass, the town, the river, and all the surrounding area. "The lich has a creature enslaved to him that he's used against us in Caligo. It's an undead remnant, a dread shade. There are also several skin witches in the lich's ranks."
Gideon nodded. "What are the powers of these dread shades and skin witches?"
"We're not entirely sure." Rael looked up at him, her mouth set in a grim line. "No one's ever survived to report back to us."
Liliana said, "Oh, skin witches are nothing too unusual. They wield death magic, but are mostly concerned with peeling the skin from their victims." Gideon raised his brows in inquiry. Liliana clarified, "They wear it."
Gideon sighed. "Of course they do."
"You've seen a skin witch?" Thiago asked, incredulous. Rael eyed Liliana dubiously.
"Several." Liliana adjusted one of her bracelets, apparently oblivious.
Gideon prompted, "And dread shades?"
Liliana said, "Now, those are more interesting. They can change size, so they're not only capable of becoming extremely large, they can also shrink down small enough to crawl inside a corpse and animate it." She waggled her fingers. "Rather like a puppet."
Gideon kept his expression neutral as the others stared at Liliana, baffled by how she had come by this information. She glanced around at them and said, her voice dry, "I know things."
After another thoughtful glance at Liliana, Rael continued, "The aven scouts have seen a dread shade coming from the riverside, here. It will be followed by grimnants and undead under their clerics' control. The lich will be somewhere nearby, waiting to move against us once the dread shade and the force with it attack." She straightened, shaking out her wings a little. "This means the skin witches probably won't take the field against us today. The lich has never before sent them into battle at the same time."
"Even one dread shade is bad enough," Thiago commented.
The captain said, "There's a first time for everything; we can't count on only facing one or the other."
Gideon didn't want the Benalish forces to face any of the lich's creatures. He asked Liliana, "Could you control a dread shade?"
Liliana frowned in thought. "Control, no. Not until Josu is . . . out of the way. What are you thinking?"
Instead Gideon turned to look for the young mage. He didn't want to put Corin in harm's way, but his part in this strategy should be safe enough. "Corin, with Liliana's help, could you create an illusion? Make a dread shade think I'm a skin witch?"
"Yes, I can do that!" Corin pushed forward between Thiago and the captain, apparently relieved to have some way to help. "I'm good with illusions."
Liliana's mouth quirked as she studied the map. "Oh, I see what you're thinking. That's a delightful idea."
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Rael and the others left to get into position, and Gideon asked Liliana, "Are you ready for this?"
Her expression was annoyed. "Of course I am. Now try to stay alive while I take care of Josu."
Gideon sighed, and as she slipped away around the house, he went to join Corin. They had managed some quick preparations, but most of the plan depended on Corin's spells.
As they went into the trees at the edge of the manor's grounds, Gideon slung the triple-bladed Cabal spear across his back. Rael had said it had a ritual purpose as well as being a weapon, which would lend more verisimilitude to his act. He hoped. If this didn't work, he would be facing a dread shade and the main Cabal force alone. That would be interesting.
As Corin cast the spell, Gideon felt the illusion settle over him like a wet blanket. He looked down at himself, but couldn't see any difference. "I can't see it."
"Because you're untouched by necromancy," Corin explained. "I've had to modify the illusion so a dread shade will be able to see it." He hesitated anxiously. "I hope it works."
"I hope it does too," Gideon agreed, and wished Liliana was a Tolarian mage instead of a necromancer. He sent Corin to join the soldiers and headed away.
As Gideon walked through the high grass, he felt it tug at him, as if he wore long skirts that dragged over it. An odd sensation, but it was proof Corin's spell was working to some extent.
Pushing through the mud and the dense foul growth of brush, he made his way toward the river. Once he emerged from a vine-tangled copse of dead trees, he saw the stretch of flat ground leading up to the sea of mud that had once been the river. Among the stands of rotted trees, dark shapes moved purposefully.
It was the Cabal force, a legion of the undead. Shambling corpses, the revenants of foot soldiers, carried looted weapons, and undead knights rode on creatures that had once been horses. Black-cloaked and black-armored grimnants and clerics strode among them. And leading the way . . .
#emph[So that's what a dread shade looks like] , Gideon thought. As if he didn't already have enough fodder for his nightmares.
It stood easily twice Gideon's height, a gray figure naked to the waist, its body like a muscular, desiccated corpse. Its chest had been ripped open collar to waist, revealing an empty cavity that glowed with spectral light, below a pointed face with a wide fanged jaw.
#figure(image("002_Return to Dominaria: Episode 2/04.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Gideon took a deep breath and started forward, lifting his hands.
The shade halted, its head twisting from side to side, as if trying to see him better. A grimnant moved forward and called out, "Witch, what are you doing here? Why do you disobey the orders of our master?"
#emph[Move fast and keep your big mouth shut] , Liliana had advised him. #emph[You'll have very little time before the illusion draws Josu's attention and he'll know immediately what it is.] Gideon strode forward, keeping his hands lifted, hoping his posture was witch-like enough.
Suddenly in front of him he saw the shapes of Drasus and Olexo, his friends, his Irregulars from the Foreigners' Quarter in Akros, and his heart froze in his chest. They were undead, their bodies mutilated, bloodless corpses, brought here somehow by Belzenlok.
Gideon almost fell back but steeled himself. #emph[No, it's not real] . A Cabal cleric somewhere in the approaching force must be casting dementia magic over a wide area. The images were just nightmares, drawn out of his unconscious mind. The grimnant near the shade yelled, "That's not—"
Gideon lunged forward and cast the spear straight at the gaping hole in the shade's chest. It hit dead center and the shade staggered and roared in rage. Gideon ran and the shade rushed after him.
Before he reached the trees, Gideon spared a glance upward to make sure the aven scout flying high overhead had seen him. The scout would signal Rael to send the Benalish force after the grimnants who had counted on the dread shade to lead the attack. #emph[The trick with shades like this] , Liliana had told him, #emph[is that they're always hungry and their brains are like porridge. Antagonize it enough, and it'll chase you no matter what its orders are.]
Gideon pelted downhill. He dodged through a sodden copse of trees and slid to an abrupt halt. Facing him was a tall hag-like figure draped in the shredded remnants of human skins, with two others not far behind her. Skin witches. So Josu had sent all his most formidable weapons after them.
Gideon's first thought was that he should dodge away and let the dread shade encounter the skin witches, thinking one of them had attacked it. Then he saw the faces of the skins tied around the closest witch's neck. Their eyes rolled and watered in pain and terror. Some foul magic kept her victims alive. So Gideon went with his second thought, and as she lifted her hands to cast a spell, he drew his sword and lunged.
The witch blew out a breath and a cloud of dark poisonous air flowed toward Gideon. Reacting instinctively, he used his shield spell, the eternal aegis, and the poisonous air flowed around it, harmless. The first stroke of his sword took her head off.
As the witch's surprised head bounced away through the grass and her body sunk to the ground, the dread shade burst out of the copse behind him. It leapt on the first skin witch it saw, snatching her off the ground and clasping her to the hole in its chest. The witch convulsed, her body jerking as it shrunk and crumpled; the dread shade was drinking the life force out of her.
The last witch screamed in fury and threw another toxic cloud at Gideon. He used his shield spell again and stabbed her through the stomach, ripping his sword downward to gut her as she flung more spells. As she fell to the ground, Gideon felt the illusion around him vanish.
He swung around to face the dread shade. #emph[I hope Corin's not dead] , he thought. The young mage must have been incapacitated for the illusion spell to break like that.
The dread shade stared at Gideon in incomprehension, then roared.
The plan hadn't worked quite as intended, but the point was to keep the shade confused and away from the Benalish force. There was no reason Gideon couldn't continue to do that. He roared back at the startled shade and charged.
#v(0.35em)
#line(length: 100%, stroke: rgb(90%, 90%, 90%))
#v(0.35em)
Liliana stood at the edge of the manor's grounds. She heard fighting in the distance, saw the aven flying over the Morass. Not far away, she could hear Gideon killing something loud and angry, but she could spare no attention for anything but Josu.
Then she felt something powerful approach. A cold wind rose over the marsh, stirring tall grass and rippling muddy pools, snapping the frail branches of dying trees. She traced its source, a concentrated center of necromantic power shot through with dementia magic. And a cold rage.
Liliana could sense pieces of her brother in that rage, fragments of memory and a familiar presence. She knew better than to expect to speak to the man who had been her brother. Whatever was left of the real Josu's personality was buried, locked away under layers of Belzenlok's death magic.
She turned her surge of emotion into a sharp blade of purpose; Josu's torment would end today and Belzenlok would lose his tool in Caligo.
She sent words into the wind: #emph[J<NAME>, I am here. You know me] .
Josu's attention snapped to her, pinpointing her location. Anger and disbelief flowed through their connection. His answer came to her: #emph[This is a trick] .
She let the wind hear her laughter. #emph[Surely you know your own sister] .
A roar of psychic rage reached her and she turned away, walking over the wet earth toward the manor.
She stopped just before the steps up to the main hall and looked back. Josu had moved out of the shadows of the trees.
As he strode forward, she could see nothing of his face. The magic that had transformed him from a mindless undead remnant into Belzenlok's lich general had covered his shape with dark metal armor. Sharp spikes stood up from his shoulders and back, and the heavy helm concealed his features. He stopped in the center of the grassy mound that had been the house's forecourt. #emph[So it is you, sister] .
She answered, #emph[I wish I could recognize you as easily, brother. Your master has changed you] .
#emph[It was you who changed me] . The rage colored his tone and perversely made him sound more like himself, though the Josu she remembered had never been truly angry with her. #emph[You did this to me] .
She was right: her corrupted healing spell had somehow allowed Belzenlok to raise him. #emph[You know I only wanted to help you. I was tricked, my magic—] She stopped herself. It was a trap, to talk to him in this form. They couldn't truly speak until she freed him from this curse. She took the first step up toward the main hall.
He surged after her and she ran up the steps, across the floor to the spot where Belzenlok had performed his spell. She turned and Josu was nearly on top of her, looming over her, his warhammer lifted. She gripped the Chain Veil.
The Onakke bound into the Chain Veil whispered in her mind as she drew on raw power. She was vaguely conscious of the undead all over the Morass dropping like stones as the Veil drew off the necromantic power that animated them. The lines on her body began to burn, but she could see Josu clearly now, a smaller figure buried in the encasing armor, the man he had been before her spells had destroyed his life, before Belzenlok had transformed him. His dark hair and pale skin, features so much like her own. #emph[That's impossible] , she realized. He was using dementia magic on her, clouding her vision. She had to act now.
The power of the Onakke in the Chain Veil flowed through her like a blast of fire.
It was gone in an instant, taking her strength with it. She stumbled, her body suddenly as weak as an unstrung puppet. She wanted to drop to the ground, but crumpled before her on the paving stones was the decomposing corpse of her brother. He looked up at her with empty eyes.
Wan gray daylight let her see the bones through the gaps in his desiccated skin. Dazed, she looked up, realizing the entire top half of the main hall was gone. Belzenlok's necromantic power had held it intact and the Chain Veil had blasted it all away, aging the house until it was a crumbled ruin. She was uncertain how much time had passed, but through the gaping holes in the front wall she could see Rael and her Benalish soldiers gathered on the forecourt, and Gideon cautiously climbing the steps.
She trembled with exhaustion and blood ran from the lines of her pact. She knew Josu's presence here was temporary, just the dissipating remnants of his soul and body. In a moment he would be gone, laid to rest. Not sure if he could hear her or not, she said, "Josu, it's all right. It's over. The curse of the House of Vess is ended."
But his bony jaw dropped open and he rasped, "It cannot end, Liliana. Not while you still live."
The raw hatred in his voice shocked her. "What do you mean?"
What was left of his lips formed a sneer. "You destroyed the House of Vess, Liliana"
She shook her head. He must be confused, his memory affected by Belzenlok's spells. "Josu, I wasn't here—"
"Of course you weren't." Josu's voice strengthened, even as his body failed. "What do you think happened after you left? They died. All of them. Father tried to lay me to rest. I killed him myself. Mother took our sisters away, searching for a cure for me. And searching for you. She thought you lived, thought you'd been stolen away. She followed a rumor of magic that could save me and the journey killed her. Others took up the burden, our sisters, our cousins, trying to stop me, to destroy me. All of them died." He was fading now, fragments of his body disappearing into windblown dust. "You killed me. You killed them. It is you, Liliana. It will always be you. #emph[You ] are the curse of the House of Vess."
And he was gone.
#figure(image("002_Return to Dominaria: Episode 2/05.jpg", width: 100%), caption: [Art by <NAME>], supplement: none, numbering: none)
Liliana staggered under the weight of his words. He had been undead all this time, all these years. Cold shock washed over her. It was horrifying. And worse still, her family, all dead trying to end the evil she had created. #emph[It was an accident] , she told herself. #emph[I was tricked] . But that didn't matter. The outcome had been the same as if she had deliberately set out to destroy her family.
Gideon came toward her. His expression was shocked, and he said, "Liliana, I'm sorry—"
#emph[He heard it, he heard all of it] , she thought, reeling. But she set her jaw and refused to be humiliated. As he reached for her arm to steady her, she shook her head and took a step back. She forced her spine to straighten. She wouldn't weaken. She had survived worse than this. And Belzenlok would pay for his part in it. Pay for her brother's suffering. Pay for the realization that she had caused her family's destruction.
Her voice hard with fury, she said, "If Belzenlok thinks this will stop me, he's a fool. I will pry open his Stronghold, slaughter his grimnants, and destroy his legacy. No matter what it takes. If I must be a curse, then let me be Belzenlok's!"
|
|
https://github.com/k-84mo10/typst_modification | https://raw.githubusercontent.com/k-84mo10/typst_modification/main/tests/typ/meta/bibliography-ordering.typ | typst | Apache License 2.0 | #set page(width: 300pt)
@mcintosh_anxiety, @psychology25
@netwok, @issue201, @arrgh, @quark, @distress,
@glacier-melt, @issue201, @tolkien54, @sharing, @restful
#bibliography("/files/works.bib")
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/visualize/image_00.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
// Test loading different image formats.
// Load an RGBA PNG image.
#image("/assets/files/rhino.png")
// Load an RGB JPEG image.
#set page(height: 60pt)
#image("/assets/files/tiger.jpg")
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/weave/0.2.0/README.md | markdown | Apache License 2.0 | # weave
A helper library for chaining lambda abstractions, imitating the `|>` or `.`
operator in some functional languages.
The function `compose` is the `pipe` function in the mathematical order.
Functions suffixed with underscore have their arguments flipped.
## Changelog
- 0.2.0 Redesigned interface to work with typst's `with` keyword.
- 0.1.0 Initial release
## Basic usage
It can help improve readability with nested applications to a content value, or
make the diff cleaner.
```typ
#compose_((
text.with(blue),
emph,
strong,
underline,
strike,
))[This is a very long content with a lot of words]
// Is equivalent to
#text(
blue,
emph(
strong(
underline(
strike[This is a very long content with a lot of words]
)
)
)
)
```
You can use it for show rules just like the example above.
```typ
#show link: compose_.with((
text.with(fill: blue),
emph,
underline,
))
// These two are equivalent
#show link: text.with(fill: blue)
#show link: emph
#show link: underline
```
This can also be useful when you need to destructure lists, as it allows creating binds that
are scoped by each lambda expression.
```typ
#let two_and_one = pipe(
(1, 2),
(
((a, b)) => (a, b, -1), // becomes a list of length three
((a, b, _)) => (b, a), // discard the third element and swap
),
)
```
|
https://github.com/jeffa5/typst-cambridge | https://raw.githubusercontent.com/jeffa5/typst-cambridge/main/thesis/manual-3.typ | typst | MIT License | #import "cambridge.typ": *
#show: chapter
= Work piece 2
#lorem(300)
== Some context
#lorem(800)
|
https://github.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53B-Notebook-Over-Under-2023-2024/master/entries/mid_season/cata_fix.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/templates/entries.typ": *
#import "/templates/headers.typ": *
#import "/templates/text.typ": *
#create_default_entry(
title: [Catapult Maintenance],
date: [November 17th, 2023],
witness: [Juan],
design: [Deb],
content: [
#box_header(
title: [Cata Fix],
color: red.lighten(60%)
) \
#entry_text()
We removed the catapult and fixed the gears by changing them with ones that had less slip. This was done to allow the catapult to go further down. Due to the ramps being bent when pushed against the hang-bar they were removed. Spacers were added in between c-channels to reinforce them.
#align(center)[
#image("/assets/cata.jpg", height: 85%)
]
]
) |
https://github.com/yingziyu-llt/blog | https://raw.githubusercontent.com/yingziyu-llt/blog/main/typst_document/linear_algebra/main.typ | typst | #import "template.typ": *
#show: template.with(
// 笔记标题
title: [线性代数],
// 在页眉展示的短标题(选填)
short-title: "线性代数学习笔记",
// 笔记描述(选填)
description: [
此笔记基于LADR(Linear Algebra Done Right) 5th edition \ 2024 Summer
],
// 笔记创建日期(选填)
date: datetime(year: 2024, month: 7, day: 2),
// 作者信息(除 name 外,其他参数选填)
authors: (
(
name: "yingziyu-llt",
github: "https://github.com/yingziyu-llt",
),
),
// 参考书目文件路径及引用样式
bibliography-file: "refs.bib",
bibstyle: "gb-7714-2015-numeric",
// 页面尺寸,同时会影响页边距。
paper-size: "a4",
// 中英文文本和代码的字体
fonts: (
(
en-font: "Linux Libertine",
zh-font: "Noto Sans CJK SC",
code-font: "DejaVu Sans Mono",
)
),
// 主题色
accent: orange,
// 封面背景图片(选填图片路径或 none)
cover-image: "./figures/cover-image.png",
// 正文背景颜色(选填 HEX 颜色或 none)
background-color: "#FAF9DE"
)
#include "content/chapter1.typ"
#include "content/chapter2.typ"
#include "content/chapter3.typ"
#include "content/chapter4.typ"
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/layout/place-float-auto_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
//
// // Error: 2-45 floating placement must be `auto`, `top`, or `bottom`
// #place(center + horizon, float: true)[Hello] |
https://github.com/denizenging/site | https://raw.githubusercontent.com/denizenging/site/master/page/links/index.tr.typ | typst | #import "@local/pub-page:0.0.0": *
#show: template(
title: "Bağlantılar",
menu: (4, "link"),
links: (
(
"ORCID iD",
"ORCID iD, araştırmacılar ve yayınları için eşsiz bir kimlik sağlar.",
"https://orcid.org/0009-0004-9445-8502",
"img/orcid.webp",
),
(
"GitHub",
"GitHub, yazılım projelerimin bulunduğu bir kod paylaşım ağıdır.",
"https://github.com/denizenging",
"img/github.webp",
),
(
"LinkedIn",
"LinkedIn, kariyer bağlantıları için profesyonel bir çevre sağlar.",
"https://linkedin.com/in/denizenging/",
"img/linkedin.webp",
),
(
"X/Twitter",
"X/Twitter, haber ve düşüncelerin paylaşıldığı sosyal bir platformdur.",
"https://x.com/denizenging",
"img/x.webp",
),
(
"YouTube",
"YouTube, tadına doyum olmayan çalma listelerimin bulunduğu bir platformdur.",
"https://www.youtube.com/@denizenging",
"img/youtube.webp",
),
(
"Instagram",
"Instagram, fotoğraf ve videolarımı paylaştığım bir sosyal medya platformudur.",
"https://instagram.com/denizenging/",
"img/instagram.webp",
),
(
"Goodreads",
"Goodreads, kitap takibi ve incelemeleri yapmak için kullanılan bir sosyal ağdır.",
"https://goodreads.com/denizenging/",
"img/goodreads.webp",
),
(
"Letterboxd",
"Letterboxd, film incelemeleri ve derecelendirmeleri için bir sosyal platformdur.",
"https://letterboxd.com/denizenging/",
"img/letterboxd.webp",
),
(
"Duolingo",
"Duolingo, etkileşimli derslerle bir çok dili öğrenebileceğiniz bir platformdur.",
"https://www.duolingo.com/profile/denizenging",
"img/duolingo.webp",
),
),
)
Kullandığım ağların ve platformların listesi. Bana buradan da ulaşabilirsiniz!
|
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/hydra/0.3.0/src/util/queryable-functions.typ | typst | Apache License 2.0 | /// A list of queryable element functions.
#let queryable-functions = (
bibliography,
cite,
figure,
footnote,
heading,
locate,
math.equation,
metadata,
ref,
)
|
https://github.com/mattyoung101/uqthesis_eecs_hons | https://raw.githubusercontent.com/mattyoung101/uqthesis_eecs_hons/master/pages/appendices/example.typ | typst | ISC License | // TODO auto increment "Appendix A, B, etc."
= Appendix A: Example appendix
#lorem(100)
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Hello, world!\n");
return 0;
}
```
#lorem(10)
|
https://github.com/bpkleer/typst-academicons | https://raw.githubusercontent.com/bpkleer/typst-academicons/main/README.md | markdown | MIT License | # typst-use-academicons
A Typst library for Academicons through the desktop fonts.
This is based on the code from `duskmoon314` and the package for [**typst-fontawesome**](https://github.com/duskmoon314/typst-fontawesome).
p.s. The library is based on the Academicons desktop fonts (v1.9.4)
## Usage
### Install the fonts
You can download the fonts from the [official website](https://jpswalsh.github.io/academicons/)
After downloading the zip file, you can install the fonts depending on your OS.
#### Typst web app
You can simply upload the `ttf` files to the web app and use them with this package.
#### Mac
You can double click the `ttf` files to install them.
#### Windows
You can right-click the `ttf` files and select `Install`.
### Import the library
#### Using the typst packages
You can install the library using the typst packages:
`#import "@preview/academicons:0.1.0": *`
#### Manually install
Copy all files start with `lib` to your project and import the library:
`#import "lib.typ": *`
There are three files:
- `lib.typ`: The main entrypoint of the library.
- `lib-impl.typ`: The implementation of `ai-icon`.
- `lib-gen.typ`: The generated icon map and functions.
I recommend renaming these files to avoid conflicts with other libraries.
### Use the icons
You can use the `ai-icon` function to create an icon with its name:
`#ai-icon("lattes")`
Or you can use the `ai-` prefix to create an icon with its name:
`#ai-lattes()` (This is equivalent to `#ai-icon().with("lattes")`)
#### Full list of icons
You can find all icons on the [official website](https://jpswalsh.github.io/academicons/)
#### Customization
The `ai-icon` function passes args to `text`, so you can customize the icon by passing parameters to it:
`#ai-icon("lattes", fill: blue)`
#### Stacking icons
The `ai-stack` function can be used to create stacked icons:
` #ai-stack(ai-icon-args: (fill: black), "doi", ("cv", (fill: blue, size: 20pt)))`
Declaration is `ai-stack(box-args: (:), grid-args: (:), ai-icon-args: (:), ..icons)`
- The order of the icons is from the bottom to the top.
- `ai-icon-args` is used to set the default args for all icons.
- You can also control the internal `box` and `grid` by passing the `box-args` and `grid-args` to the `ai-stack` function.
- Currently, four types of icons are supported. The first three types leverage the `ai-icon` function, and the last type is just a content you want to put in the stack.
- `str`, e.g., `"lattes"`
- `array`, e.g., `("lattes", (fill: white, size: 5.5pt))`
- `arguments`, e.g. `arguments("lattes", fill: white)`
- `content`, e.g. `ai-lattes(fill: white)`
## Example
See the [`use-academicons.typ`](https://typst.app/project/rsgOFC4YkwpN7OqtRyiXP3) file for a complete example.
## Contribution
Feel free to open an issue or a pull request if you find any problems or have any suggestions.
### R helper
The `helper.R` script is used to get unicodes for icons and generate typst code.
### Repo structure
- `helper.R`: The helper script to get unicodes and generate typst code.
- `lib.typ`: The main entrypoint of the library.
- `lib-impl.typ`: The implementation of `ai-icon`.
- `lib-gen.typ`: The generated functions of icons.
- `example.typ`: An example file to show how to use the library.
- `gallery.typ`: The generated gallery of icons. It is used in the example file.
## License
This library is licensed under the MIT license. Feel free to use it in your project.
|
https://github.com/TOD-theses/paper-T-RACE | https://raw.githubusercontent.com/TOD-theses/paper-T-RACE/main/appendix.typ | typst | #import "utils.typ": colls
= Overview of Generative AI Tools Used
I used #link("http://grammarly.com/")[Grammarly] to improve the readability of the text. The whole work was analyzed and I applied several small suggestions.
= Case studies
== Analysis of definition differences <app:analysis-of-definition-differences>
Here, we present one example for @sec:analysis-of-differences that is approximately TOD but not TOD.
For the following two transactions:
- $T_A$: `0xa723f53edcae821203572a773b8f1b5cf5c008a734794ee2acae771540363f11`
- $T_B$: `0x5aa39f4ff79f6653fdb0165a92fcb55e024ae8d5b8dba67c0b6e4c153ea4a8d4`
Both transactions changed a specific storage slot. Our tool outputs the following changes:
- $T_B$ (normal): `+0`
- $T_A$ (normal): `+0x1c7400000000000000000000000000000000000000000000000000000000`
- $T_B$ (reverse): `+0x1c7400000000000000000000000000000000000000000000000000000000`
- $T_A$ (reverse): `+0`
We see, that in both scenarios, the value increases by `0x1c7400000000000000000000000000000000000000000000000000000000`, therefore considering both transactions it is not TOD. However, if we only consider $T_B$, we would observe a TOD, as $T_B$ changes the storage slot differently in the scenarios (`+0` vs `+0x1c7400000000000000000000000000000000000000000000000000000000`).
In our manual analysis of all cases, this information is enough to say that the application of our definitions was correct, assuming that the state changes outputted by the tool are correct. To further understand, why such changes occur in practice, we analyzed this transaction pair in more detail.
Using Etherscan, we see that both transactions emit a `UsdPerTokenUpdated` event with the parameters `value: 0x429d069189e0000` and `timestamp: 0x663c689f`. Furthermore, it shows for the storage slot at transaction $T_A$:
- *Before*: `0x663c4c2b00000000000000000000000000000000000000000429d069189e0000`
- *After*: `0x663c689f00000000000000000000000000000000000000000429d069189e0000`
We observe, that the value after $T_A$ is composed of the timestamp and the value of the emitted event. As both transactions emitted the same event with this value and timestamp, it is likely, that both transactions set the value of this storage slot to `0x663c689f00000000000000000000000000000000000000000429d069189e0000`. For $T_A$, this led to a state change of this storage slot. As $T_B$ is executed after $T_A$, the storage slot was already at the target value and no change is recorded for $T_B$. In the reverse scenario, $T_B$ is executed first and therefore we observe a state change here. And similarly for $T_A$ we now record no state change.
The code that updates the storage slot is shown below, located at address `0x8c9b2efb7c64c394119270bfece7f54763b958ad`. In line 5 we see the assignment to the storage slot and in line 9 the logged event. Both transactions have the same values for `update.usdPerToken` and `block.timestamp`, therefore the value assigned to `s_usdPerToken[update.sourceToken]` is the same in both cases.
#[
#show raw.line: it => {
[#it.number #it]
}
```sol
contract PriceRegistry {
// ...
function updatePrices(/* ... */) {
// ...
s_usdPerToken[update.sourceToken] = Internal.TimestampedPackedUint224({
value: update.usdPerToken,
timestamp: uint32(block.timestamp)
});
emit UsdPerTokenUpdated(update.sourceToken, update.usdPerToken, block.timestamp);
}
}
```
]
== Analysis of TOD <app:analysis-TOD>
We analyze one of the cases where a TOD candidate $(T_A, T_B)$ is not TOD according to our definition, but is reported as an attack by @zhang_combatting_2023. The transaction $T_A$ is #link("https://etherscan.io/tx/0x5cf84067556e7db37fd0279ec3bfe227d71758786cb53f1cc24e20f8afd9f8d8")[0x5cf84067556e7db37fd0279ec3bfe227d71758786cb53f1cc24e20f8afd9f8d8] and $T_B$ is #link("https://etherscan.io/tx/0xd24cffe4cd2dd7c89cc7ec3d38f44f4563d184b5fa9a952b46358a8a8e8176cc")[0xd24cffe4cd2dd7c89cc7ec3d38f44f4563d184b5fa9a952b46358a8a8e8176cc].
To evaluate if this TOD candidate is TOD, we start by determining the collisions of $T_A$ and $T_B$. If the execution of $T_A$ influences $T_B$ or vice versa, it must be at a state key that one of them modifies and the other accesses or modifies as well. For this case study, we evaluate $(W_T_A sect R_T_B) union (W_T_A sect W_T_B) union (R_T_A sect W_T_B)$ to obtain the collisions rather than $colls(T_A, T_B)$, as we do not want to rely on the TOD approximation underlying the definition of $colls(T_A, T_B)$.
We use the `debug_traceTransaction` method to obtain the accessed state keys $R_T_A$ and $R_T_B$ (refer to the @sec:data-availability for the data). We then compare these state modifications $W_T_A$ and $W_T_B$ shown on Etherscan and only find a collision at the balance of the #link("https://etherscan.io/address/0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")[WETH] contract. Therefore, the only way $T_A$ may influence $T_B$, and vice versa, is by modifying and accessing the balance of the WETH contract.
In @tab:state_reading_instructions, we see the instructions that can access balances. The instructions `CALL`, `CALLCODE`, `CREATE`, `CREATE2` and `SELFDESTRUCT` access a balance by sending Ether from the caller to the recipient. These instructions can behave differently depending on whether enough Ether is available. This is not the case, because the transactions transfer less than 3 Ether from the WETH account to another account, but the WETH account had more than 6 million Ether at this time according to the `eth_getBalance` RPC method.
The remaining two instructions that can cause TOD when accessing balances are `BALANCE` and `SELFBALANCE`. We manually inspect the execution traces in the normal scenario to see if these instructions are used to access the balance of the WETH contract.
According to our normal scenario traces, $T_A$ has three executions of `SELFBALANCE` and $T_B$ has two executions of `SELFBALANCE`, however none of these are lookup the balance of the WETH contract. The traces also show no occurrence of the `BALANCE` instruction.
We further verify that our normal scenario traces execute the same instructions as on Etherscan. We compare the number of execution steps from our traces, which matches with those shown by Etherscan (15171 and 9164), thus we assume we execute the same instructions as on the blockchain.
In summary, we ruled out that any instruction accesses the balance of the WETH contract. As this is the only state key that one transaction writes and the other reads or writes, $T_A$ and $T_B$, these transactions cannot be TOD.
= Javascript tracer <app:javascript-tracer>
We use the following javascript tracer to extract `CALL` instructions and emitted token events. The `step` function is executed for each instruction. In case a `CALL` or `CALLCODE` instruction is found we append data to `this.calls` and for `LOG0`, `LOG1`, `LOG2`, `LOG3` or `LOG4` instruction is found we append it to `this.logs`.
To detect reverted calls, we check in the `exit` function if an error occurred. As an error reverts the current call context and all of its children, we store a mapping of each call context to its children in `children_of`. When reverting a call context, we can then recursively mark all child contexts as reverted.
The `result` function is called when the tracing has finished. We first check if the overall transaction is reverted. Then we return the calls and logs for which their call context has not been reverted.
```js
{
calls: [],
logs: [],
call_context_stack: [0],
call_context_counter: 0,
reverted_call_contexts: [],
children_of: {},
location: function(log) {
return {
'address': toHex(log.contract.getAddress()),
'pc': log.getPC(),
}
},
enter: function(callFrame) {
current_call_context = this.call_context_stack[this.call_context_stack.length - 1]
this.call_context_counter += 1
this.call_context_stack.push(this.call_context_counter)
if (!this.children_of[current_call_context]) {
this.children_of[current_call_context] = []
}
this.children_of[current_call_context].push(this.call_context_counter)
},
exit: function(frameResult) {
context_id = this.call_context_stack.pop(this.call_context_counter)
error = frameResult.getError()
if (error) {
this._revert(context_id)
}
},
_revert: function(id) {
// revert context and all of its sub contexts
this.reverted_call_contexts.push(id)
children = this.children_of[id] || []
for (child_id of children) {
this._revert(child_id)
}
},
step: function(log, db) {
opcode = log.op.toNumber()
if (opcode == 0xF1 || opcode == 0xF2) {
this.calls.push({
'op': opcode,
'sender': toHex(log.contract.getAddress()),
'to': toHex(toAddress(log.stack.peek(1).toString(16))),
'value': log.stack.peek(2).toString(16),
'location': this.location(log),
'call_context_id': this.call_context_stack[this.call_context_stack.length - 1],
})
}
else if (opcode >= 0xA0 && opcode <= 0xA4) {
offset = log.stack.peek(0).valueOf()
size = log.stack.peek(1).valueOf()
data = toHex(log.memory.slice(offset, offset + size))
topics_amount = opcode - 0xA0
topics = []
for (i = 0; i < topics_amount; i++) {
topics.push(log.stack.peek(2 + i).toString(16).padStart(64, "0"))
}
this.logs.push({
'topics': topics,
'data': data,
'address': toHex(log.contract.getAddress()),
'location': this.location(log),
'call_context_id': this.call_context_stack[this.call_context_stack.length - 1],
})
}
},
fault: function(log, db) {},
result: function(ctx, db) {
if (ctx.error) {
this._revert(0)
}
logs = this.logs.filter(log => !this.reverted_call_contexts.includes(log['call_context_id']))
calls = this.calls.filter(call => !this.reverted_call_contexts.includes(call['call_context_id']))
return {
"gas": ctx.gasUsed,
"calls": calls,
"logs": logs,
"reverted_call_contexts": this.reverted_call_contexts,
};
}
}
``` |
|
https://github.com/benjamineeckh/kul-typst-template | https://raw.githubusercontent.com/benjamineeckh/kul-typst-template/main/tests/test-work/test.typ | typst | MIT License | #let page-is-inserted(loc) = {
let pairs = state("chapter-markers").at(loc)
if pairs == none { return false }
// page is inserted if surrounded by end- and start-marker for any chapter
return pairs.any(((end-page, start-page)) => {
loc.page() > end-page and loc.page() < start-page
})
}
#set heading(numbering: "1.")
#let c-b() = context{
if page-is-inserted(here()){
rotate(45deg)[#text(size: 4em, fill:red)[inserted]]
}
}
#set page(paper: "a7", background: c-b(), numbering: "1")
#show heading.where(level: 1): it => [
#[]<chapter-end-marker> // marker positioned before the pagebreak
#pagebreak(to: "odd", weak: true)
#block[
#it
#v(6%)]<chapter-start-marker> // marker positioned after the pagebreak
]
#context {
let chapter-end-markers = query(<chapter-end-marker>)
let chapter-start-markers = query(<chapter-start-marker>)
let pairs = chapter-end-markers.enumerate().map(((index, chapter-end-marker)) => {
let chapter-start-marker = chapter-start-markers.at(index)
let end-page = chapter-end-marker.location().page()
let start-page = chapter-start-marker.location().page()
(end-page, start-page)
})
state("chapter-markers").update(pairs)
}
= Another header
asas
#context state("chapter-markers").display()
#set page(numbering: "i")
= asdjhasd
asdsd |
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/t4t/0.1.0/def.typ | typst | Apache License 2.0 | // Defaults
#let if-true( test, default, value ) = if test {
return default
} else {
return value
}
#let if-false( test, default, value ) = if not test {
return default
} else {
return value
}
#let if-none( default, value ) = if value == none {
return default
} else {
return value
}
#let if-auto( default, value ) = if value == auto {
return default
} else {
return value
}
#let if-any( ..compare, default, value ) = if value in compare.pos() {
return default
} else {
return value
}
#let if-not-any( ..compare, default, value ) = if value not in compare.pos() {
return default
} else {
return value
}
#let if-empty( default, value ) = if is-empty(value) {
return default
} else {
return value
}
|
https://github.com/nath-roset/suiviProjetHekzamGUI | https://raw.githubusercontent.com/nath-roset/suiviProjetHekzamGUI/master/typ%20sources/Rapport%20de%20Gestion.typ | typst | Apache License 2.0 | #import "template.typ": base
#show: doc => base(
// left_header:[],
right_header : [Equipe scan-GUI-Printemps-2024],
title: [Projet Hekzam-GUI - Printemps-2024],
subtitle: [Rapport de gestion],
version: [],
authors:(
(
name: "<NAME>",
affiliation:"Université Paul Sabatier",
email:"Licence Informatique",
),
(
name: "<NAME>",
affiliation:"Université Paul Sabatier",
email:"Licence Informatique",
),
(
name: "<NAME>",
affiliation:"Université Paul Sabatier",
email:"Licence Informatique",
),
(
name: "<NAME>",
affiliation:"Université Paul Sabatier",
email:"Licence Informatique",
)
),
doc
)
#outline(
title: none,
// target: heading.where(level: 2)
)
= Retours personnels
== <NAME>
Le projet se divisant en différentes phases, mes tâches ont évolué au fil de son avancement.
La première partie du projet consistait, pour ma part, à travailler sur la *réalisation des exigences fonctionnelles*, des cas de test et des plans de test en se basant sur le premier prototype moyenne fidélité, en duo avec Nathan.
La régularité des réunions de groupe et des rencontres avec notre responsable de projet nous a permis de rapidement identifier et éclaircir les différentes zones d’ombre du sujet.
Une fois le prototype validé, nous sommes passés à la seconde phase, la programmation.
J'ai travaillé avec Marco sur le tableau utilisé pour lister et rechercher des copies. Nous avons partagé les tâches entre nous deux : j'étais personnellement responsable de la barre de recherche.
Une des difficultés fut le choix entre utiliser un `QTableWidget` ou un `QStandardItemModel`, un `QSortFilterProxyModel` et une `QTableView` (c’est un affichage tableau suivant l’architecture Model/View en trois composants). Nous avons décidé de partir sur la `QTableWidget`, malgré son manque de flexibilité, pour sa lisibilité et facilité de compréhension.
Concernant la barre de recherche, elle permet de filtrer l'affichage, par exemple, par copie, page et de nombreux autres tags.
Nous pouvons séparer les différents types de recherche en trois parties : tout d'abord, la *recherche simple* : c'est la possibilité de rechercher un certain mot ou une certaine partie d'un mot dans tout le tableau. Deuxièmement, nous avons la *recherche de texte multiple* : elle permet à l'utilisateur de rechercher un groupe de mots. Pour être plus précis, mon algorithme de recherche compare chaque cellule avec le mot numéro 1 du groupe ou le numéro 2 ou le numéro 3, … Et enfin, nous avons la *recherche par tag *: elle permet de rechercher un mot ou un groupe de mots dans une certaine colonne.
Cette dernière a été la fonctionnalité la plus complexe à implémenter. Elle m'a obligé à revoir l'entièreté de mon code, car celui n'était pas assez modulaire. Après un court temps de recherches, je me suis rappelé une notion rapidement vue en cours de Structure Discrète 3 : les *expressions régulières*. En plus d'offrir des performances plus intéressantes que les comparaisons entre les chaînes de caractères, elles offrent une certaine modularité dans le format de recherche.
Après avoir mis en œuvre ces trois fonctionnalités, notre tuteur m'a parlé de ce que nous appelons la *recherche floue* (fuzzy search). C'est un algorithme qui implémente le concept de *distance de Levenshtein*. C'est la distance entre les lettres de deux mots différents. Si la recherche de l'utilisateur ne donne aucune réponse, l'algorithme suggère les mots les plus proches. J'ai décidé de montrer au maximum les trois premiers mots les plus proches.
J'ai également ajouté la possibilité d'effectuer une *recherche atomique*.
Cependant, due à l'implémentation tardive de ces 2 fonctionnalités, elles ne fonctionnent pas sur la recherche par tags.
En conclusion, ce projet m'a beaucoup apporté. D'un point de vue technique, cela m'a permis de développer des connaissances en C++ et de découvrir la programmation avec Qt. Sur le plan personnel et professionnel, ce projet m'a permis de mettre en pratique mes compétences de collaboration, au sein d'une équipe, acquises lors de ma licence.
== <NAME>
Lors de ce projet, j’eu trois tâches majeures à accomplir, devant implémenter et maintenir l’*interface générale* du programme, manipuler les *données de sauvegarde* et la *configuration utilisateur* et enfin créer une *CLI*. Je vais m’étendre sur chacun de ces points afin d’en relever les réussites et les échecs, pour finalement conclure sur ce projet.
Concernant la phase de développement de l’*interface*, il était nécessaire de la finir au plus vite afin que les autres membres de l’équipe puissent avancer, je m’y suis donc concentré sur l’espace d’une à deux journées pour créer quelque chose de cohérent et stable, mais d’incomplet. En effet, le *menu principal* et la structure de la *fenêtre d’évaluation* furent simples à implémenter, cependant la *fenêtre de création* prit plus de temps, ceci résultat d’un changement de widget pour la conception du formulaire. Par la suite, j’eu à maintenir cette structure en adéquation avec les changements de mon groupe et les demandes effectuées par le client, menant par exemple à l’inversion de l’ordre des `QSplitter` dans la fenêtre d’évaluation. En résumé, cette phase fut la moins périlleuse.
Ce ne fut pas le cas de la seconde phase de développement à laquelle j’ai fait face, celle-ci étant de créer et manipuler les *données de sauvegarde* et la *configuration utilisateur*. Concernant la *sauvegarde*, on s’est rapidement rendu compte en réunion qu’on serait dans l’incapacité de sauvegarder l’état actuel du tableau tant que celui-ci ne serait pas complet, il fut donc décidé de ne sauvegarder que l’état originel des données, ce que j’ai pû faire avec succès. Cependant, je pense que j’aurai pû faire mieux que cela, surtout dans la façon de sauvegarder un fichier où il aurait été plus logique de laisser à l’utilisateur nommer sa sauvegarde et choisir le répertoire où sauvegarder, plutôt que de juste demander un répertoire, ceci permettant d’avoir plusieurs sauvegardes en un emplacement. Pour la *configuration*, celle-ci aussi fut très dépendante de l’évolution des modules des autres, ceci menant à une conception de bas niveau, avec seulement la taille et position de la fenêtre retenues. Je suis un peu déçu de moi sur cette partie et je pense que si je n’avais pas été aussi encombré par les examens, j’aurai pû créer un système de configuration bien plus exhaustif que ce qui est aujourd’hui présent.
Enfin, il fut demandé d’intégrer une *CLI*, ce qui s’avérera être une tâche complexe, moi même travaillant sur *Windows*. En effet, mon Powershell ne voulait en aucun cas exécuter le programme et j’eu donc à programmer à l’aveugle, ceci quelques jours avant la dernière réunion. Heureusement, mon premier essai fut le bon, mais on m’a fait savoir que j’aurai pû utiliser un `QCommandLineParser` qui, après lecture de la documentation, serait en effet plus simple à implémenter et beaucoup plus efficace. J'aurais souhaité créer une CLI beaucoup plus extensive avant la fin du projet, mais ce ne fut malheureusement pas le cas.
En conclusion, ce projet m’a apporté de nouvelles compétences en programmation et en travail de groupe. J’ai découvert le langage *C++* ainsi que l’API *Qt* qui pourront m’être utiles dans le futur, étant donné que j’ai trouvé cela très intuitif et efficace. J’ai pû également découvrir de nouvelles fonctionnalités de *Git* et le langage *Typst* qui fut utile pour nos rapports. Travailler sur ce projet et avec ce groupe fut une bonne expérience, il n’y a pas eu de conflits interne et notre rythme de travail est toujours resté fluide, permettant ainsi au projet de ne pas stagner, même lors de périodes d’examens, d’autant plus qu’on était là pour aider les autres. En général, si on me proposait de travailler sur un projet similaire avec la même équipe, j’accepterais sans hésiter, et en évitant de refaire les mêmes erreurs du passé.
== <NAME>
Lors de la phase de prototypage, la tâche que je devais réaliser était *l’élaboration de la fenêtre d’évaluation*. La difficulté principale de cette tâche était d’obtenir un rendu qui correspondait aux attentes de notre encadrant. Grâce à ses retours sur les premières versions de la fenêtre j’ai pu finaliser le prototype avec succès.
Concernant la phase de développement, le défi principal était de proposer un code qui respecte les normes du langage *C++* tout en exploitant les fonctionnalités de la librairie *Qt*. Étant donné que je n’étais pas familier avec ces langages, j’ai dû suivit deux formations afin d'avoir une meilleure compréhension sur le sujet avant de pouvoir commencer à coder.
La première tâche qui m'a été assignée était d'*effectuer le tableau d'évaluation* visant à donner une vue détaillée de chaque donnée provenant d'un examen. La difficulté principale à laquelle j’ai dû faire face était de trouver les modèles de composants les plus adaptés afin d’optimiser l’ergonomie de l’interface utilisateur. J'ai dû tester plusieurs dispositions avant de trouver le tableau le plus optimal ce qui m'a aussi permis de prendre la librairie *Qt* en main ainsi que sa notion de *Qt Widgets*. \ Le tableau résultant de ces tests est un `QTableWidget` comportant 5 colonnes au moment de sa réalisation : *Nom*, *Syntaxe*, *Sémantique* et deux métriques arbitraires visant à démontrer la modularité du tableau.\ En parallèle, j'ai dû *créer un composant personnalisé* couplant un `QTableWidgetItem` et une `QProgressBar` afin de pouvoir afficher l'évolution de la syntaxe sous forme de barre de progression. Ceci m'a introduit à la notion de *double héritage* et aux potentielles difficultés d'une telle approche tel que le *problème du diamant*. Fort heureusement, je n'ai jamais eu à faire face à ce genre de problématiques lors de la phase de développement.
Après avoir réalisé le tableau, je me suis occupé de *programmer une interface de filtrage de colonnes*. Ceci m'a permis de me familiariser avec les `QLayouts` car il était important de disposer correctement tous les modules que j'avais effectué. Après avoir discuté avec le reste de mon groupe vis-à-vis de la structure à aborder, j'ai mis en place le système de filtrage qui est représenté par un `QButton` qui lorsqu'on clique dessus affiche un `QDockWidget` dans lequel il est possible de modifier des `QCheckBox` pour afficher où cacher une colonne spécifique du tableau.
Lors d'une réunion organisée avec notre encadrant, nous avons eu l'occasion de montrer l'avancée de notre travail et avec son approbation, nous sommes passés à la *phase de gestion de données*. En effet, bien que nous eussions tous les composants nécessaires permettant l'évaluation de copies d'examen, il était primordial d'implémenter une gestion de données efficace visant à *charger* les scans, *stocker* les informations d'examen, les *afficher* dans le tableau et la fenêtre d'évaluation et les *sauvegarder* à la fermeture du programme. La première chose que nous avons effectué à été de demander une série de cas de tests à notre encadrant afin que l'on puisse tester les différentes fonctionnalités de notre programme.
Après que Fabio ait mit en place un système de sélection de fichiers à l'aide de `QFileDialog,` je devais établir un système d'*association de scans avec leur fichier **JSON** correspondant* étant donné que la librairie responsable de cette tâche n'était pas encore implémentée. Cette tâche fût assez laborieuse car je devais *réaliser un système de structures de données* à là fois clair et performant. \ Mon premier prototype avait pour objectif de me familiariser avec la structure de donnée *std::map* en *C++*, j'avais simplement associé les fichiers *JSON* avec les fichiers de scan comportant le même identifiant dans leur nom de fichier. \ Après avoir établit les fondations, j'ai effectué un second prototype faisant usage du parser de *JSON* que Nathan avait programmé au préalable. Avec ce prototype, les *champs* présents dans les pages étaient stockés dans une structure de donnée avant de les associer à l'identifiant utilisé précédemment. Bien que ce système fût efficace pour l'affichage de champs individuels, il était trop fastidieux d'affilier ces champs à une *page* ou a une *copie* d'examen. Cette particularité n'était pas négligeable si nous voulions afficher plusieurs pages d'une même *copie*. \ Une réunion avec notre encadrant nous permit de réaliser que nous avions mal interprété les cas de tests ce qui nous à empêcher d'intégrer la notion de sujet à notre programme. J'ai donc totalement restructuré la manière dont je collectais les données de scan en intégrant un *système hiérarchique* de structures de données donnant des informations sur le *sujet*, la *copie*, les *pages* et les *champs* d'un examen. \ Avant d'ajouter ces données au tableau, il m'a fallu modifier les colonnes pour les faire correspondre à ce qui allait figurer dans le tableau.
Lors de la réunion qui a précédé la modification des structures de données, notre encadrant m'avait aussi fait part du fait qu'il désirait l'ajout d'une *vue groupée* du tableau afin d'apporter plus de clarté à l'utilisateur. J'ai donc *séparé le tableau principal en deux sous tableaux* contenant les mêmes données mais organisant les cellules d'une manière différente. \ J'ai ensuite pu finaliser la méthode permettant d'*afficher le contenu d'une cellule* dans la fenêtre de prévisualisation que j'avais commencé à développer en parallèle de tout cela. \ La difficulté de cette méthode était le fait de réfléchir avec Nathan à toutes les données dont il aurait besoin afin d'afficher précisément le contenu du tableau en fonction de la colonne dans laquelle étaient situées les cellules à afficher.
Finalement, nous avons mis en place une ultime réunion avec notre encadrant qui visait à présenter la version finale de notre interface graphique. Bien que nous n’ayons pas eu assez de temps pour implémenter certaines fonctionnalités qui étaient demandées tel que la *modification des valeurs des champs* directement depuis le tableau, notre encadrant avait l'air d'être satisfait du travail que nous lui avons fourni.
Dans l'ensemble, ce projet m'a permis d'acquérir beaucoup d'expérience en ce qui concerne mes compétences en matière de *développement*. Lorsque j'ai commencé à coder en *C++*, j'ai rencontré plusieurs difficultés car je manquais d'expérience dans ce langage, mais après m'être familiarisé avec la syntaxe, j'ai pris de plus en plus confiance en mes capacités au fur et à mesure que je travaillais sur ma section de l'interface utilisateur. Outre les compétences techniques que j'ai acquis, j'ai beaucoup progressé en matière de *résolution de problèmes*, de *communication* et de *gestion de projet* lorsque je collaborais avec d'autres développeurs. \ Je suis fier d'avoir contribué à un projet qui aura potentiellement un impact sur le domaine de l'éducation en abordant un problème commun rencontré par la plupart des enseignants et j'ai hâte d'assister à son évolution dans les années à venir.
== <NAME>
Durant ce semestre, j'ai implémenté les modules de visualisation des pages ainsi qu'un utilitaire de lecture de fichiers JSON. L'utilité première de la classe `ExamPreview` est de *visualiser* et d'*interagir* avec les pages des copies afin de montrer à l'utilisateur les éléments reconnus par le programme, d'apprécier la qualité de la reconnaissance automatique, et de modifier/calibrer l'interprétation du scan au besoin.\
L'*utilitaire de lecture de fichiers JSON* à été relativement facile à mettre en oeuvre par rapport au reste du projet. Les classes de bases implémentées par Qt ont amplement suffit à obtenir un utilitaire satisfaisant, nous permettant d'extraire les données pertinentes du fichier. Il sera de plus facile pour les développeurs suivants d'ajouter des champs à extraire, de séparer les différents types de champs en plusieurs liste, de modifier la taille des pages... Des messages d'erreurs ont également été ajoutés à chaque étape de la conversion du JSON pour faciliter le débogage.\
La partie *visualisation* de l'interface doit permettre de montrer à la fois la page sélectionnée en entier ainsi que des champs en particulier. Cela a été implémenté avec un `QDialog` et un `QStackedWidget` pour placer la preview dans la fenêtre. \
La fonctionnalité de preview a été implémentée en héritant des classes du framework `Graphics View`. J'ai donc séparé les composants de manière logique, où chaque élément est responsable d'une fonctionnalité du programme. \
`ExamPreview` est responsable des mises à l'échelle et des interactions non transformantes. \
`ExamScene` est un canevas dans lequel sont instanciés les items, tel que les pages, les champs et le masque de page qui sont donc tous des fils de la scène (la scène doit les instancier et les détruire). Le processus a nécessité de multiples remaniement à mesure que je me familiarisais des fonctionnalités de Qt.\
La *communication* entre la table et la preview a été gérée par Marco et moi-même, mais uniquement dans un sens : la Table n'est pas informé des changements ayant lieu dans la preview. \
Au final, ce projet m'a permit d'*apprendre à utiliser le langage C++* et de comprendre les bases de l'utilisation des librairies de Qt, en particulier les `QWidgets` et le module `QGraphicsView`. J'ai également pu approfondir mes connaissances en IHM, car la conception d'une interface en prenant en compte les considérations d'une personne extérieure est un exercice plus complexe que celui inclus dans le syllabus. J'ai rencontré quelques difficultés du fait de mon manque d'expérience avec Qt en essayant d'utiliser des classes non adaptées au besoin. De ce fait il m'a fallu remanier plusieures parties du programme afin d'obtenir un résultat agréable à utiliser pour l'utilisateur, et maintenable par l'équipe suivante. \
Cependant, malgré mes efforts, j'ai découvert une divergence entre la position supposée des `MarkerItems` et leur position réelle. Les Objets ont l'air bien positionnés sur la page mais sont en réalité tous situés à l'origine, avec une forme positionnée au bon endroit.
#pagebreak(weak: true)
= Échéancier final
#figure(
image(
"gantt final.png"
)
)
= Répartition des tâches en %
#let a = table.cell( // 25%
fill: blue.lighten(75%),
)[25%]
#let b = table.cell( // 50%
fill: blue.lighten(50%),
)[50%]
#let c = table.cell( // 20%
fill: blue.lighten(85%),
)[20%]
#let d = table.cell( // 40%
fill: blue.lighten(60%),
)[40%]
#let e = table.cell( // 33%
fill: blue.lighten(70%),
)[33%]
#let f = table.cell( // 100%
fill: blue.lighten(30%),
)[100%]
#table(
columns: (auto, auto, auto, auto, auto ,auto),
align: center,
table.header(
[*ID tâche*],[*Nom de la tâche*], [Nathan], [Fabio], [Marco], [Emilien],
),
[WP 0.1], [Capture du besoin] ,a ,a ,a ,a,
[WP 1], [Pilotage projet] ,a ,a ,a ,a,
[WP 2], [Prototypage] ,a ,a ,a ,a,
[WP 3.1], [Conception Fenêtre Principale] ,[] ,f ,[] ,[],
[WP 3.1.1], [Implémentation de la barre de menu] ,[] ,f ,[] ,[],
[WP 3.2], [Elaboration du tableau] ,[] ,[] ,f ,[],
[WP 3.2.2], [Filtrage du Tableau] ,[] ,[] ,[] ,f,
[WP 3.3], [Visualisation du scan] ,f ,[] ,[] ,[],
[WP 3.4], [Traitement des fichiers] ,e ,e ,e ,[],
[WP3.5], [Interaction tableau/visualisation] ,e ,[] ,e ,e,
[WP 3.6], [Interaction avec le scan] ,f ,[] ,[] ,[],
[WP 3.7], [Configuration de l'UI] ,c ,d ,c ,c,
[WP 3.8], [Test, déploiement, cross platform] ,a ,a ,a ,a,
[WP 3.9], [Prise en charge des options du CLI] ,[] ,f ,[] ,[],
)
#pagebreak(weak: true)
= Description et statut des tâches
#linebreak()
- [x] *Capture du Besoin*
- [x] *Pilotage de projet*
- *Prototypage*
- [x] Spécification des exigences
- [x] Création Prototype moyenne fidélité
- *Conception fenêtre principale*
- [x] Création du menu principal.
- [x] Création du menu de création.
- [x] Création du menu d'évaluation.
- *Implémentation de la barre menu.*
- [ ] Fonctionnalités fichier (ouvrir, sauvegarder, fermer).
- [ ] Fonctionnalités édition (undo, redo).
- [ ] Fonctionnalités d'aide (ouverture de la doc utilisateur).
- *Elaboration du tableau*
- [x] Création et remplissage du tableau
- [x] Implémentation d'une barre de progression sous forme de cellule
- [x] Gestion de l'affichage et du tri des colonnes
- *Filtrage du tableau*
- [x] Création du champ de recherche
- [x] Création de la fonction simple et multiples (fuzzy search...)
- [x] Création de la fonction de recherche par tags
- *Visualisation du scan*
- [x] Création des différentes scènes (grille et vue globale)
- [x] Affichage de la fenêtre de visualisation externe
- *Traitement des fichiers*
- [x] Ouverture via menu création.
- [x] Remplissage de la structure ScanInfo utilisée plus tard.
- [x] Lecture et interprétation des fichiers JSON
- *Interaction tableau/visualisation*
- [x] Définition d'une interface de communication entre les modules
- [x] Méthodes de correspondances entre cellules du tableau et fichiers
- *Interaction avec le scan*
- [x] Reglage des métriques de cadrage
- [x] Interactions aves les différents champs d'une page (modifier, déplacer, highlight)
- *Configuration de l'UI.*
- [ ] Options de configurations dans menu Affichage.
- [x] Sauvegarde de la configuration dans un fichier.
- *Test, déploiement, cross platform*
- [x] Tests non automatisés
- *Prise en charge des options du CLI *
- [x] Gestion des options (help, version...)
|
https://github.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024 | https://raw.githubusercontent.com/Area-53-Robotics/53E-Notebook-Over-Under-2023-2024/giga-notebook/entries/build-wedges/entry.typ | typst | Creative Commons Attribution Share Alike 4.0 International | #import "/packages.typ": notebookinator
#import notebookinator: *
#import themes.radial.components: *
#show: create-body-entry.with(
title: "Build: Pushing Robots",
type: "build",
date: datetime(year: 2023, month: 10, day: 6),
author: "<NAME>",
witness: "<NAME>",
)
#grid(
columns: (1fr, 1fr),
gutter: 20pt,
[
Today we built the wedges.
1. We cut 2 lengths of C-channel 5 holes long.
#admonition(
type: "note",
)[
2 of the 4 pieces of C-channel in the CAD are meant to be replaced with the
drivetrain.
]
2. We then cut a slit into 2 of the C-channels so that the high strength axles
could properly fold upwards.
3. We cut a high strength axle into 2 pieces, and drilled holes in the end of each
one.
4. We screwed 1 axle into each piece of C-channel.
5. We unmounted the omni-wheel on the front of the drivetrain in order to get
access to the C-channel on the side
6. We screwed the 2 pieces of C-channel to the drivetrain.
7. We remounted the omni-wheel to the drivetrain.
#admonition(
type: "warning",
)[
The wedges on one side couldn't be placed due to the tracking wheels. We had to
cut the back of the C-channel where the wedges were mounted down by one hole in
order to get them to fit.
]
],
[
#figure(image("./top.jpg"), caption: "Top view")
#figure(image("./side.jpg"), caption: "Side view")
],
)
#admonition(
type: "build",
)[
The wedges are complete! We can now test their effectiveness against other
robots.
]
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/universal-hit-thesis/0.2.0/harbin/bachelor/conf.typ | typst | Apache License 2.0 | #import "../../common/theme/type.typ": 字体, 字号
#import "components/typography.typ": main-format-heading, special-chapter-format-heading
#import "utils/numbering.typ": heading-numbering
#import "config/constants.typ": special-chapter-titles
#import "config/constants.typ": current-date
#import "utils/states.typ": thesis-info-state
#import "@preview/cuti:0.2.1": show-cn-fakebold
#import "@preview/i-figured:0.2.4": show-figure, reset-counters, show-equation
#let doc(content, thesis-info: (:)) = {
thesis-info = (
title-cn: "",
title-en: "",
author: "▢▢▢",
student-id: "▢▢▢▢▢▢▢▢▢▢",
supervisor: "▢▢▢ 教授",
profession: "▢▢▢ 专业",
collage: "▢▢▢ 学院",
institute: "哈尔滨工业大学",
year: current-date.year(),
month: current-date.month(),
day: current-date.day(),
) + thesis-info
set document(
title: thesis-info.at("title-cn"),
author: thesis-info.author,
)
thesis-info-state.update(current => {
current + thesis-info
})
set page(
paper: "a4",
margin: (top: 3.8cm, left: 3cm, right: 3cm, bottom: 3cm),
)
show: show-cn-fakebold
content
}
#let preface(content) = {
set page(header: {
[
#set align(center)
#set par(leading: 0em)
#text(font: 字体.宋体, size: 字号.小五, baseline: 6pt)[
哈尔滨工业大学本科毕业论文(设计)
]
#line(length: 100%, stroke: 2.2pt)
#v(2.2pt, weak: true)
#line(length: 100%, stroke: 0.6pt)
]
})
set page(numbering: "I")
set page(footer: context [
#align(center)[
#counter(page).display("- I -")
]
])
counter(page).update(1)
show heading: it => {
set par(first-line-indent: 0em)
if it.level == 1 {
align(center)[
#special-chapter-format-heading(it: it, font: 字体.黑体, size: 字号.小二)
]
} else {
it
}
}
set par(first-line-indent: 2em, leading: 1em, justify: true)
set text(font: 字体.宋体, size: 字号.小四)
content
}
#let main(
content,
extra-kinds: (),
extra-prefixes: (:),
) = {
set page(numbering: "1")
set page(footer: context [
#align(center)[
#counter(page).display("- 1 -")
]
])
counter(page).update(1)
set heading(numbering: heading-numbering)
show heading: it => {
set par(first-line-indent: 0em)
if it.level == 1 {
align(center)[
#main-format-heading(it: it, font: 字体.黑体, size: 字号.小二)
]
} else if it.level == 2 {
main-format-heading(it: it, font: 字体.黑体, size: 字号.小三)
} else if it.level >= 3 {
main-format-heading(it: it, font: 字体.黑体, size: 字号.小四)
}
}
show heading: reset-counters.with(extra-kinds: ("algorithm",) + extra-kinds)
show figure: show-figure.with(numbering: "1-1", extra-prefixes: ("algorithm": "algo:") + extra-prefixes)
show figure.where(kind: table): set figure.caption(position: top)
show figure.where(kind: raw): set figure.caption(position: top)
show figure.where(kind: "algorithm"): set figure.caption(position: top)
show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)
show raw.where(block: false): text.with(
font: 字体.代码,
size: 10.5pt,
)
show raw.where(block: true): block.with(
fill: luma(240),
inset: 8pt,
radius: 4pt,
width: 100%,
)
show raw.where(block: true): text.with(
font: 字体.代码,
size: 10.5pt,
)
show math.equation: show-equation.with(numbering: "(1-1)")
show ref: it => {
let eq = math.equation
let el = it.element
if el != none and el.func() == eq {
// Override equation references.
numbering(
el.numbering,
..counter(eq).at(el.location()),
)
} else {
// Other references as usual.
it
}
}
content
}
#let ending(content) = {
show heading: it => {
set par(first-line-indent: 0em)
if it.level == 1 {
align(center)[
#special-chapter-format-heading(it: it, font: 字体.黑体, size: 字号.小二)
]
} else {
it
}
}
set heading(numbering: none)
content
} |
https://github.com/EricWay1024/Homological-Algebra-Notes | https://raw.githubusercontent.com/EricWay1024/Homological-Algebra-Notes/master/ha/6-df.typ | typst | #import "../libs/template.typ": *
= Derived Functors
<derived-functor>
== Homological $delta$-functors
@weibel[Section 2.1]. The next two definitions are stated separately for clarity.
#definition[
Let $cA, cB$ be abelian categories. A *homological $delta$-functor* $T$ from $cA$ to $cB$
is a collection of additive functors ${T_n : cA -> cB}_(n >= 0)$ such that
#enum(block(width: 100%)[
(Existence of $delta$). For each #sest $ses(A, B, C)$ in $cA$, there exist morphisms
$delta_n : T_n (C) -> T_(n-1)(A) $
for $n >= 1$ such that $ ... -> T_(n+1)(C) ->^delta T_n (A) -> T_n (B) -> T_n (C) rgt(delta) T_(n-1)(A) -> ... \ -> T_1 (C) ->^delta T_0 (A) -> T_0 (B) -> T_0 (C) -> 0 $
is a #lest in $cB$. In particular, $T_0$ is right exact;
],
[
(Naturality of $delta$). For each morphism of #sess from $ses(A', B', C')$ to $ses(A, B, C)$, the $delta$'s above give a commutative diagram
// #align(center,image("../imgs/2023-11-24-19-38-59.png",width:30%)
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRABUB9MAAgAoAwgHIAlCAC+pdJlz5CKAIzkqtRizZc+YALQKR-AIKiJUkBmx4CRMgpX1mrRB278BYydItyiS29XvqTpo6eo<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$T_n (C')$]),
node((0, 1), [$T_(n-1) (A')$]),
node((1, 0), [$T_n (C)$]),
node((1, 1), [$T_(n-1) (A)$]),
arr((0, 0), (1, 0), []),
arr((0, 1), (1, 1), []),
arr((1, 0), (1, 1), [$delta$]),
arr((0, 0), (0, 1), [$delta$]),
))
])
]
#definition[
Let $cA, cB$ be abelian categories. A *cohomological $delta$-functor* $T$ from $cA$ to $cB$ is a collection of additive functors ${T^n : cA -> cB}_(n >= 0)$ such that
#enum(block(width: 100%)[
(Existence of $delta$). For each #sest $ses(A, B, C)$ in $cA$, there exist morphisms
$delta^n : T^n (C) -> T^(n+1)(A) $
for $n >= 0$ such that
$ 0 -> T^0 (A) -> T^0 (B) -> T^0 (C) ->^delta T^1 (A) -> ... \ -> T^(n-1)(C) ->^delta T^n (A) -> T^n (B) -> T^n (C) rgt(delta) T^(n+1)(A) -> ... $
is a long exact sequence in $cB$. In particular, $T^0$ is left exact;
],
[
(Naturality of $delta$). For each morphism of #sess from $ses(A', B', C')$ to $ses(A, B, C)$, the $delta$'s above give a commutative diagram
// #align(center,image("../imgs/2023-11-24-19-39-14.png",width:30%))
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRABUA9MAAgAoAwgHIAlCAC+pd<KEY>
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$T^n (C')$]),
node((0, 1), [$T^(n+1) (A')$]),
node((1, 0), [$T^n (C)$]),
node((1, 1), [$T^(n+1) (A)$]),
arr((0, 0), (1, 0), []),
arr((0, 1), (1, 1), []),
arr((1, 0), (1, 1), [$delta$]),
arr((0, 0), (0, 1), [$delta$]),
))
])
]
#example[
Homology gives a homological $delta$-functor
$
{H_n : Ch_(>= 0)(cA) -> cA}_(n >= 0),
$
where $Ch_(>=0) (cA)$ is the (full) subcategory of $Ch(cA)$ whose objects are chain complexes $C_cx$ such that $C_n = 0$ for all $n < 0$.
Similarly, cohomology gives a cohomological $delta$-functor $ {H^n : Ch^(>= 0) (cA) -> cA}_(n >= 0), $
where $Ch^(>= 0) (cA)$ is defined similarly.
]
#example[
If $p$ is an integer, the collection ${T_n : Ab -> Ab}_(n>=0)$ of functors defined by
$ T_n (A) = cases(
A over p A quad& n = 0,
zws_p A := brace.l a in A colon p a eq 0 brace.r quad& n = 1,
0 quad& n >= 2
) $
form a homological $delta$-functor (or a cohomological
$delta$-functor with $T^0 eq T_1$ and $T^1 eq T_0$).]
#proof[Apply the @snake[Snake Lemma] to the commutative diagram
// https://t.yw.je/#N4Igdg9gJgpgziAXAbVABwnAlgFyxMJZABgBpiBdUkANwEMAbAVxiRGJAF9T1Nd9CKAIzkqtRizYBBLjxAZseAkQBMo6vWatEIAEKzeigUQDM68VrYBhA-L5LByACznNknR26H+ylGSFibtrstgo+jiIBGhLBMl52Rr7IalEW7nqh9sYoZqlB1pmJji55MWyeYjBQAObwRKAAZgBOEAC2SCIgOBBIAGzRljpots1tSGpdPYgA7APpw-Gj7Yhmk0gAHHPBC3JLSGRriEKLLcud3eMnY4gTFytXy6t3Tg9IAKzUd72viP2H0z9Zod1j9NocAJycCicIA
#align(center, commutative-diagram(
node-padding: (50pt, 50pt),
node((0, 0), [$0$]),
node((0, 1), [$A$]),
node((0, 2), [$B$]),
node((0, 3), [$C$]),
node((0, 4), [$0$]),
node((1, 0), [$0$]),
node((1, 1), [$A$]),
node((1, 2), [$B$]),
node((1, 3), [$C$]),
node((1, 4), [$0$]),
arr((0, 1), (1, 1), [$p$]),
arr((0, 2), (1, 2), [$p$]),
arr((0, 3), (1, 3), [$p$]),
arr((0, 0), (0, 1), []),
arr((0, 1), (0, 2), []),
arr((0, 2), (0, 3), []),
arr((0, 3), (0, 4), []),
arr((1, 0), (1, 1), []),
arr((1, 1), (1, 2), []),
arr((1, 2), (1, 3), []),
arr((1, 3), (1, 4), []),
))
where $A ->^p A$ is the map of multiplication by $p$ and so on, so that we
// #align(center,image("../imgs/2023-11-06-21-52-48.png",width:50%))
get the exact
sequence
$ 0 arrow.r zws_p A arrow.r zws_p B arrow.r zws_p C arrow.r^delta A slash p A arrow.r B slash p B arrow.r C slash p C arrow.r 0. $
// For any integer $p$, define $T_(0)(A) = A over p A$ and $T_1(A) = p A = {a in A | p a = 0}$ and $T_n = 0$ for $n >= 2$ gives a homological $delta$-functor from $Ab -> Ab$, by the Snake Lemma,
// TODO
]
#let dftor = [$delta$-functor]
#definition[
A *morphism* $f: S->T$ of homological (resp. cohomological) $delta$-functors is a collection of natural transformations ${f_n : S_n -> T_n}_(n>=0)$ (resp. ${f^n : S^n -> T^n}_(n>=0)$) which commutes with $delta$. ]
#remark[
This definition is equivalent to saying that there is a commutative "ladder diagram" connecting
the long exact sequences for $S$ and $T$ associated to any short exact
sequence in $cA$.
]
#definition[
A homological $delta$-functor $T = {T_n}$ is *universal* if, given any other homological $delta$-functor $S = {S_n}$ and a natural transformation $f_0: S_0 -> T_0$, there exists a unique morphism $ f = {f_n : S_n -> T_n}_(n>=0) : S-> T $ extending $f_0$.
// A cohomological #dftor $T$ is *universal* if given $S$ and $f^0 : T^0 -> S^0$, there exists a unique extension $T->S$.
A *universal* cohomological $delta$-functor $T$ is similarly defined.
]
#example[
If $F : cA -> cB$ is an exact functor, then $T_0 = F$ and $T_n = 0$ for $n != 0$ defines a universal homological #dftor $T : cA -> cB$.
]
// How to construct a universal #dftor? In categories with enough projectives or injectives, derived functors work.
== Derived Functors
The main object of this section is to show that in an abelian category with enough projectives, left derived functors, defined as follows, are homological $delta$-functors.
#definition[
Let $cA$ and $cB$ be two abelian categories and
let $F : cA -> cB$ be a right exact functor. Assume that $cA$ has enough projectives. For any $A in cA$, pick a projective resolution $P_(cx) -> A$ by @enough-resolution. Then $L_i F$ given by $ L_i F(A) := H_i (F(P)) $ is called the *$i$-th left derived functor*.
]
<left-derived-functor>
#remark[ @rotman[p. 344].
To elaborate, given $F : cA -> cB$ and $A in cA$, to calculate $L_i F(A)$ we need the following steps:
+ #fw[Find a projective resolution of $A$ in $cA$:
$
... -> P_2 -> P_1 -> P_0 -> A -> 0;
$
]
+ Delete $A$ to form the *deleted projective resolution*, i.e., the chain complex $ ... -> P_2 -> P_1 -> P_0 -> 0, $ (which is not exact at $P_0$ unless $A = 0$);
+ Apply $F$ to form a chain complex in $cB$: $ ... -> F(P_2) -> F(P_1) -> F(P_0) -> 0; $
+ Calculate the $i$-th homology $H_i (F (P))$ of this chain complex.
// Now let $f: A -> B$ be a morphism in $cA$. To find $L_i F (f)$, we can find projective resolutions $P_cx -> A$ and $Q_cx -> B$, and by the @comparison[Comparison Theorem], there exists a chain map $f_cx : P_cx -> Q_cx$ lifting $f$. Then $L_i F (f) := H_i (F(f_cx))$, obtained in a similar fashion as above.
]
In fact, our definition of the "functor" $L_i F$ is still incomplete as we have not defined how it maps the morphisms in $cA$. However, we first need to show that for any object $A in cA$, our definition of $L_i F (A)$ is independent of the choice of projective resolution $P_cx -> A$. The following implies the case when $i = 0$.
#lemma[
$L_0 F(A) iso F(A)$.
]
#proof[ Consider the projective resolution of $A$:
$
... P_1 ->^(d_1) P_0 -> A -> 0
$
By definition, $L_0 F(A) = H_0(F(P)) iso Coker(F(d_1))$. Since $F$ is right exact, it preserves cokernels, so $Coker(F(d_1)) iso F(Coker(d_1)) = F(A)$.
]
// Notice that the previous lemma indicates that the choice of $P_cx$ does not affect $L_0 F $. This in fact holds in general for all $L_i F$, which indicates that $L_i F$ is well-defined.
#lemma[ Let $cA, cB, F, A$ be defined as in @left-derived-functor.
If $P_cx -> A$ and $Q_cx -> A$ are two projective resolutions, then there is a canonical isomorphism
$ H_i (F(P)) iso H_i (F(Q)) $
]
#proof[
By the @comparison[Comparison Theorem], there is a chain map $f: P_cx -> Q_cx$ lifting the identity $id_A : A->A$, which gives $f_ast : H_i F(P) -> H_i F(Q)$. Notice that any other lift $f' : P_cx -> Q_cx$ is chain homotopic to $f$ so $f_ast = f'_ast$,
so $f_ast$ is canonical.
We can also lift $id_A$ to a map $g: Q_cx -> P_cx$ and get $g_ast : H_i F(Q) -> H_i F(P)$.
Notice $g oo f : P_cx -> P_cx$ and $id_P : P_cx -> P_cx$ are both chain maps lifting $id_A$, and by the @comparison[Comparison Theorem] they are chain homotopic. Therefore
$ g_* oo f_* = (g oo f)_* = (id_P)_*.$
Similarly,
$ f_* oo g_* = (id_Q)_*,$
which gives an isomorphism $H_i (F(P)) iso H_i (F(Q)) $.
]
#corollary[
If $A$ is projective, then $L_i F (A) = 0$ for $i != 0$.
]
<projective-left-zero>
#proof[
Simply notice that $... -> 0 -> A -> A -> 0 $
is a projective resolution of $A$.
]
Now we complete the definition of $L_i F$ and prove that it is indeed a functor.
#lemma[
If $f : A' -> A$ a morphism in $cA$, then there is a natural map $ L_i F(f) : L_i F(A') -> L_i F(A) $
]
#proof[
Let $P'_cx -> A'$ and $P_cx -> A$ be projective resolutions. By the @comparison[Comparison Theorem], $f$ lifts to a chain map $tilde(f) : P'_cx -> P_cx$, which gives a map $tilde(f_ast) : H_i F(P') -> H_i F(P)$. As any other lift is chain homotopic to $tilde(f)$, the map $tilde(f_ast)$ is independent of the lift.
]
#proposition[
$L_i F : cA -> cB$ is an additive functor.
]
#proof[
Let $A in cA$ and $P_cx -> A$ be a projective resolution.
The chain map $id_P$ lifts $id_A$, so $L_i F(id_A) = id_(L_i F(A))$.
Given $A' rgt(f) A rgt(g) A''$ in $cA$ and projective resolutions $P'_cx -> A'$, $P_cx -> A$, and $P''_cx -> A''$, we obtain lifts $tilde(f) : P'_cx -> P_cx$ and $ tilde(g) : P_cx -> P''_cx$. Then the composition $tilde(g) oo tilde(f ) : P' -> P''$ is a lift of $g oo f$, so $g_ast oo f_ast = (g f)_ast : H_i F(P') -> H_i F(P'')$. Therefore, $L_i F$ is a functor.
If chain maps $tilde(f_1), tilde(f_2) : P'_cx -> P_cx$ lift $f_1, f_2 : A' -> A$, then the chain map $tilde(f_1) + tilde(f_2)$ lifts $f_1 + f_2$, so $f_(1 ast) + f_(2 ast) = (f_1 + f_2)_ast : H_i F(P') -> H_i F(P)$. Therefore, $L_i F$ is an additive functor.
]
#theorem[
Let $F : cA -> cB$ be a right exact functor, then
${L_i F}_(i >= 0)$ forms a universal homological #dftor.
]
// We never use the fact that it is universal. Check the book for proof.
#proof[
@weibel[Theorem 2.4.6 and Theorem 2.4.7].
First notice that $L_0 F = F$ is right exact.
Given a #sest $ ses(A', A, A'') $ and projective resolutions $P'_cx -> A'$ and $P''_cx -> A''$, by the @horseshoe[Horseshoe Lemma], there is a projective resolution $P_cx -> A$ such that $ses(P'_cx, P_cx, P''_cx)$ is a #sest of chain complexes and for each $n$, $ses(P'_n, P_n, P''_n)$ is split. Since $F$ is additive, by @additive-preserve-biproduct, $F$ preserves biproducts and thus preserves split exact sequences, so $
ses(F(P'_n), F(P_n), F(P''_n))
$
is split exact in $cB$. (Notice that $F$ is not necessarily an exact functor, so $ses(P'_n, P_n, P''_n)$ being split is crucial.) Hence
$
ses(F(P'_cx), F(P_cx), F(P''_cx))
$
is a #sest of chain complexes. Hence applying homology gives the connecting homomorphisms and a #lest
$
... -> L_(n+1) F(A'') ->^delta L_n F(A') -> L_n F(A) -> L_n F(A'') ->^delta L_(n-1) F(A') -> ...
$
by @connecting.
We omit the proofs that $delta$'s are natural and that ${L_i F}_(i >= 0)$ is universal.
]
#endlec(9)
#definition[
Let $cA$ and $cB$ be two abelian categories and
let $F : cA -> cB$ be a left exact functor. Assume that $cA$ has enough injectives and for any $A in cA$ we have an injective resolution $A -> I^cx$. Then the *$i$-th right derived functor* $R^i F$ is defined as
$ R^i F (A) := H^i (F (I^cx)) $
]
// If $F : cA -> cB$ is left exact, we can define the right derived functor $R^i F(A) = H^i F(I)$ for $A -> I^cx$.
#note[ $R^i F(A) = (L_i F^op)^op (A)$.]
#corollary[
Let $F: cA -> cB$ be a left exact functor, then ${R^i F}_(i >= 0)$ forms a universal cohomological $delta$-functor.
] |
|
https://github.com/augustebaum/petri | https://raw.githubusercontent.com/augustebaum/petri/main/tests/fletcher/two-concurrent-processes/test.typ | typst | MIT License | #import "/src/lib.typ": *
#set page(width: auto, height: auto, margin: 1cm)
#import "@preview/fletcher:0.4.2" as fletcher: edge
/// node distance=2cm,
/// on grid,
/// every transition/.style={fill=black,minimum width=.1cm, minimum height=0.9cm},
/// every place/.style={fill=red!25,draw=red!75},
/// every label/.style={black!75}]
///
/// % Places
/// \node[place,
/// label=left:$P_1$] (place1) {};
///
/// \node[place,
/// right=of place1,
/// tokens=1,
/// label=right:$P_2$] (place2) {};
///
/// \node[place,
/// right= 2.25cm of place2,
/// label=$P_3$] (place3) {};
///
/// \node[place,
/// right= 2.25cm of place3,
/// label=left:$P_4$] (place4) {};
///
/// \node[place,
/// right=of place4,
/// tokens=1,
/// label=right:$P_5$] (place5) {};
///
/// % Transitions
/// \node[transition,
/// above left=1.5cm and 1cm of place2,
/// label=$T_1$] (T1) {};
///
/// \node[transition,
/// below left=1.5cm and 1cm of place2,
/// label=below:$T_2$] (T2) {};
///
/// \node[transition,
/// above right=1.5cm and 1cm of place4,
/// label=$T_3$] (T3) {};
///
/// \node[transition,
/// below right=1.5cm and 1cm of place4,
/// label=below:$T_4$] (T4) {};
///
/// % connections
/// \draw (T1.east) edge[bend left,post] (place2)
/// (place2) edge[bend left,post] (T2.east)
/// (T2.west) edge[bend left,post] (place1.south)
/// (place1.north) edge[bend left,post] (T1.west);
///
/// \draw (T2.-70) edge[bend right,post] (place3)
/// (place3)edge[bend right,post] (T1.70);
///
/// \draw (T3.east) edge[bend left,pre] (place5)
/// (place5) edge[bend left,pre] (T4.east)
/// (T4.west) edge[bend left,pre] (place4.south)
/// (place4.north) edge[bend left,pre] (T3.west);
///
/// \draw (T4.250) edge[bend left,post] (place3)
/// (place3)edge[bend left,post] (T3.110) ;
#let p1 = (0,0)
#let p2 = (2,0)
#let p3 = (4,0)
#let p4 = (6,0)
#let p5 = (8,0)
#let t1 = (1,-1)
#let t2 = (1,1)
#let t3 = (7,-1)
#let t4 = (7,1)
#let bend-angle = 30deg
#let my-p = p.with(fill: red.lighten(25%), stroke: red)
#let my-t = t.with(fill: black)
#fletcher.diagram(
node-stroke: 1pt,
spacing: (3em, 4.5em),
// First process
my-p(p1, $P_1$, label-args: (anchor: "west")),
edge("-|>", bend: bend-angle),
my-t(t1, $T_1$),
edge("-|>", bend: bend-angle),
my-p(p2, $P_2$, tokens: 1, label-args: (anchor: "east")),
edge("-|>", bend: bend-angle),
my-t(t2, $T_2$, label-args: (anchor: "south")),
edge(t2, p1, "-|>", bend: bend-angle),
// Second process
my-p(p4, $P_4$, label-args: (anchor: "west")),
edge("-|>", bend: - bend-angle),
my-t(t4, $T_4$, label-args: (anchor: "south")),
edge("-|>", bend: - bend-angle),
my-p(p5, $P_5$, tokens: 1, label-args: (anchor: "east")),
edge("-|>", bend: - bend-angle),
my-t(t3, $T_3$),
edge(t3, p4, "-|>", bend: - bend-angle),
// Interaction
my-p(p3, $P_3$),
edge(p3, t1, "-|>", bend: - bend-angle),
edge(p3, t3, "-|>", bend: bend-angle),
edge(t2, p3, "-|>", bend: - bend-angle),
edge(t4, p3, "-|>", bend: bend-angle),
)
|
https://github.com/SergeyGorchakov/russian-phd-thesis-template-typst | https://raw.githubusercontent.com/SergeyGorchakov/russian-phd-thesis-template-typst/main/common/acronyms.typ | typst | MIT License | #let acronyms-entries = {(
(
key: "si",
short: "СИ",
long: "Система интернациональная",
),
(
key: "ацп",
short: "АЦП",
long: "Аналого-Цифровой Преобразователь",
),
)} |
https://github.com/ana-jiangR/Himcm-Typst-Template | https://raw.githubusercontent.com/ana-jiangR/Himcm-Typst-Template/main/README.md | markdown | MIT License | ## HIMCM Typst Template(Under Development)
⚠Warning: This project remains unfinished.
*HIMCM-Typst-Template* provides a template and toolset for HIMCM [High School Mathematical Contest in Modeling](https://www.contest.comap.com/highschool/contests/himcm/index.html) participants to create well-formatted competition papers using **Typst**.
## What is Typst?
https://typst.app/
## Get Started
## How to USE?
## License
This project is licensed under the **MIT** License - see the [LICENSE](LICENSE) file for details.
## TO DO
## Acknowledgments
- Typst - https://typst.app/
- Typst Official Templates - https://github.com/typst/templates/
- HUST Typst Template - https://github.com/werifu/HUST-typst-template
Happy HIMCM paper writing! |
https://github.com/pornmanut/resume | https://raw.githubusercontent.com/pornmanut/resume/main/resume.typ | typst |
#import "template.typ": *
#set page(
margin: (
left: 10mm,
right: 10mm,
top: 15mm,
bottom: 15mm
),
)
#set text(font: "Mulish")
#show: project.with(
theme: rgb("#4B2885"),
first_name: "Pornmanut",
last_name: "Hormsgasorn",
title: "Software Engineer",
profile_img: "assets/portrait/profile.png",
contact: (
contact(
text: "(+66)897049622",
type: "phone",
),
contact(
text: "Pornmanut",
link: "https://www.linkedin.com/in/pornmanut-hormgasorn-435b85192/",
type: "linkedin",
),
contact(
text: "pornmanut",
link: "https://github.com/pornmanut",
type: "github",
),
contact(
text: "<EMAIL>",
link: "mailto:<EMAIL>",
type: "email",
),
),
main: (
section(
content: (
"As a Software Engineer with over two years of experience, I have been directly involved in developing internal software to enhance quality and streamline the development process for internal users. I have experience in agile process, leading planning ceremony, developing and designing microservices applications. I have interests in software architecture, ETL processes, and developing applications with LLM."
)
),
section(
title: "Work Experience",
content: (
subSection(
title: "Software Engineer",
titleEnd: "Wisesight",
subTitle: "May 2022 - Present",
subTitleEnd: "Bangkok, Thailand",
content: list(
[Design and develop an application that aggregates data from various social media platforms, performs data processing and analysis, and integrates with Looker Studio for data visualization.],
[Develop an contractor managment system platform, allowing the research team to assign contractor to each task, contractor will labeling messages with configurable labels.],
[Develop an ETL application that routinely calculates well-known research metrics for the research team.],
[Design and develop internal micoservice bot that conditionally synchronize data from data warehouse to application.],
[Refactor and develop a new iteration of the web application that visualizes data from various social media platforms based on input keywords. Support both internal and external users, providing a visualization interface and an API.],
[Design, develop and maintain internal tools to assist the research team.],
[Collaborate with other teams to develop a boilerplate template in Golang.]
),
),
subSection(
title: "General Administration Officer",
titleEnd: "Phetchbun Internal Audit",
subTitle: "Sep 2021 - May 2022",
subTitleEnd: "Phetchabun, Thailand",
content: list(
[Design and develop a order-book feature for the 'ELECTRONIC SARABUN' website. This feature enables users to distribute order-book shares among departments within the organization. The feature],
[Design and develop a single page application for verifying the authenticity of lottery resellers using their personal identification.],
[Design and develop a new Phetchabun goverment website.],
),
),
),
),
),
bottom: (
section(
title: "Personal Project",
content: (
subSection(
title: "Task Manager Spring",
titleEnd: "github.com/pornmanut/task-manager-spring",
link: "https://d1taln2msl2iip.cloudfront.net/",
content: list(
[Task management website for tracking to-do list tasks. The application was built using Java, Spring Boot, and React. It was deployed on AWS using AWS Serverless Application Model (SAM), with Java Spring Boot running on AWS Lambda and React hosted on S3 via CloudFront. DynamoDB as the database. CI/CD were implemented using GitHub Actions.],
),
),
subSection(
title: "Resume Generator",
titleEnd: "github.com/pornmanut/resume",
link: "https://github.com//pornmanut/resume",
content: list(
[Developed a resume generator using the Typst language, with automated build and release processes implemented through GitHub Actions..],
),
),
),
),
),
sidebar: (
section(
title: "Skills",
content: (
subSection(
title: "Programing",
content: (
"Python",
"Golang",
"Typescript",
"Java"
).join(" • "),
),
subSection(
title: "Technologies",
content: list(
"AWS",
"Docker",
"SQL (PostgreSQL, MySQL)",
"NoSQL (MongoDB)",
"Git",
"GitHub Actions",
"AWS SAM",
"HTML / CSS",
"React",
"Spring Boot",
)
),
subSection(
title: "Interests",
content: list(
"Microservices",
"Software Architecture",
"Stable diffusion",
"LLM",
)
),
subSection(
title: "Language",
content: list(
"Thai (Native)",
"English (Intermediate)",
)
),
),
),
section(
title: "Education",
content: (
subSection(
title: "B.Eng. Computer Engineering",
titleEnd: "Kasetsart University",
subTitle: "Jun 2016 - May 2020",
subTitleEnd: "Bangkok, Thailand",
),
),
),
),
)
|
|
https://github.com/Myriad-Dreamin/typst.ts | https://raw.githubusercontent.com/Myriad-Dreamin/typst.ts/main/fuzzers/corpora/math/matrix-gaps_02.typ | typst | Apache License 2.0 |
#import "/contrib/templates/std-tests/preset.typ": *
#show: test-page
#set math.cases(gap: 1em)
$ x = cases(1, 2) $
|
https://github.com/typst/packages | https://raw.githubusercontent.com/typst/packages/main/packages/preview/unichar/0.1.0/ucd/block-1E7E0.typ | typst | Apache License 2.0 | #let data = (
("ETHIOPIC SYLLABLE HHYA", "Lo", 0),
("ETHIOPIC SYLLABLE HHYU", "Lo", 0),
("ETHIOPIC SYLLABLE HHYI", "Lo", 0),
("ETHIOPIC SYLLABLE HHYAA", "Lo", 0),
("ETHIOPIC SYLLABLE HHYEE", "Lo", 0),
("ETHIOPIC SYLLABLE HHYE", "Lo", 0),
("ETHIOPIC SYLLABLE HHYO", "Lo", 0),
(),
("ETHIOPIC SYLLABLE GURAGE HHWA", "Lo", 0),
("ETHIOPIC SYLLABLE HHWI", "Lo", 0),
("ETHIOPIC SYLLABLE HHWEE", "Lo", 0),
("ETHIOPIC SYLLABLE HHWE", "Lo", 0),
(),
("ETHIOPIC SYLLABLE GURAGE MWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE MWEE", "Lo", 0),
(),
("ETHIOPIC SYLLABLE GURAGE QWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE QWEE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE QWE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE BWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE BWEE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE KWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE KWEE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE KWE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE GWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE GWEE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE GWE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE FWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE FWEE", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE PWI", "Lo", 0),
("ETHIOPIC SYLLABLE GURAGE PWEE", "Lo", 0),
)
|
https://github.com/Dav1com/minerva-report-fcfm | https://raw.githubusercontent.com/Dav1com/minerva-report-fcfm/master/docs/preamble.typ | typst | MIT No Attribution | #import "../minerva-report-fcfm.typ" as minerva
#let main-file = read("../minerva-report-fcfm.typ")
#let lib-files = {
let names = ("departamentos", "footer", "front", "header", "rules", "states", "util")
let dict = (:)
for name in names {
dict.insert(name, read("../lib/" + name + ".typ"))
}
dict
}
|
https://github.com/Sematre/typst-letter-pro | https://raw.githubusercontent.com/Sematre/typst-letter-pro/main/template/src/main.typ | typst | MIT License | #import "@preview/letter-pro:2.1.0": letter-simple
#set text(lang: "de")
#show: letter-simple.with(
sender: (
name: "<NAME>",
address: "Deutschherrenufer 28, 60528 Frankfurt",
extra: [
Telefon: #link("tel:+4915228817386")[+49 152 28817386]\
E-Mail: #link("mailto:<EMAIL>")[<EMAIL>]\
],
),
annotations: [Einschreiben - Rückschein],
recipient: [
Finanzamt Frankfurt\
Einkommenssteuerstelle\
Gutleutstraße 5\
60329 Frankfurt
],
reference-signs: (
([Steuernummer], [333/24692/5775]),
),
date: "12. November 2014",
subject: "Einspruch gegen den ESt-Bescheid",
)
Sehr geehrte Damen und Herren,
die von mir bei den Werbekosten geltend gemachte Abschreibung für den im
vergangenen Jahr angeschafften Fotokopierer wurde von Ihnen nicht berücksichtigt.
Der Fotokopierer steht in meinem Büro und wird von mir ausschließlich zu beruflichen
Zwecken verwendet.
Ich lege deshalb Einspruch gegen den oben genannten Einkommensteuerbescheid ein
und bitte Sie, die Abschreibung anzuerkennen.
Anbei erhalten Sie eine Kopie der Rechnung des Gerätes.
Mit freundlichen Grüßen
#v(1cm)
<NAME>
#v(1fr)
*Anlagen:*
- Rechnung
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.