diff --git a/.all-contributorsrc b/.all-contributorsrc
deleted file mode 100644
index bc6a910..0000000
--- a/.all-contributorsrc
+++ /dev/null
@@ -1,45 +0,0 @@
-{
- "files": [
- "README.md"
- ],
- "imageSize": 100,
- "commit": false,
- "contributorsPerLine": 7,
- "projectName": "al-folio",
- "projectOwner": "alshedivat",
- "repoType": "github",
- "repoHost": "https://github.com",
- "badgeTemplate": "[core_contributors]: https://img.shields.io/badge/core_contributors-<%= contributors.length %>-orange.svg 'Number of core contributors'",
- "contributorTemplate": "\">\" width=\"<%= options.imageSize %>px;\" alt=\"\"/> <%= contributor.name %>",
- "skipCi": true,
- "contributors": [
- {
- "login": "alshedivat",
- "name": "Maruan",
- "avatar_url": "https://avatars.githubusercontent.com/u/2126561?v=4",
- "profile": "http://maruan.alshedivat.com",
- "contributions": [
- "design",
- "code"
- ]
- },
- {
- "login": "rohandebsarkar",
- "name": "Rohan Deb Sarkar",
- "avatar_url": "https://avatars.githubusercontent.com/u/50144004?v=4",
- "profile": "http://rohandebsarkar.github.io",
- "contributions": [
- "code"
- ]
- },
- {
- "login": "pourmand1376",
- "name": "Amir Pourmand",
- "avatar_url": "https://avatars.githubusercontent.com/u/32064808?v=4",
- "profile": "https://amirpourmand.ir",
- "contributions": [
- "code"
- ]
- }
- ]
-}
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
deleted file mode 100644
index c78502f..0000000
--- a/.github/FUNDING.yml
+++ /dev/null
@@ -1,12 +0,0 @@
-# These are supported funding model platforms
-
-github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
-patreon: # Replace with a single Patreon username
-open_collective: # Replace with a single Open Collective username
-ko_fi: alshedivat
-tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
-community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
-liberapay: # Replace with a single Liberapay username
-issuehunt: # Replace with a single IssueHunt username
-otechie: # Replace with a single Otechie username
-custom: # ['https://www.buymeacoffee.com/TkFxuKo']
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
deleted file mode 100644
index 511f585..0000000
--- a/.github/ISSUE_TEMPLATE/bug_report.md
+++ /dev/null
@@ -1,38 +0,0 @@
----
-name: Bug report
-about: Create a report to help us improve
-title: ''
-labels: bug
-assignees: ''
-
----
-
-**Acknowledge the following**
-- [ ] I carefully read and followed the [Getting Started](https://github.com/alshedivat/al-folio#getting-started) guide.
-- [ ] I read through [FAQ](https://github.com/alshedivat/al-folio#faq) and searched through the [past issues](https://github.com/alshedivat/al-folio/issues), none of which addressed my issue.
-- [ ] The issue I am raising is a potential bug in al-folio and not just a usage question. [For usage questions, please post in the [Discussions](https://github.com/alshedivat/al-folio/discussions) instead of raising an issue.]
-
-**Describe the bug**
-A clear and concise description of what the bug is.
-
-**To Reproduce**
-Steps to reproduce the behavior:
-1. Go to '...'
-2. Click on '....'
-3. Scroll down to '....'
-4. See error
-
-**Expected behavior**
-A clear and concise description of what you expected to happen.
-
-**Screenshots**
-If applicable, add screenshots to help explain your problem.
-
-**System (please complete the following information):**
- - OS: [e.g. iOS]
- - Browser (and its version) [e.g. chrome, safari]
- - Jekyll version [e.g. 3.8.7]
-- Ruby version [e.g. 2.6.5]
-
-**Additional context**
-Add any other context about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
deleted file mode 100644
index 11fc491..0000000
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ /dev/null
@@ -1,20 +0,0 @@
----
-name: Feature request
-about: Suggest an idea for this project
-title: ''
-labels: enhancement
-assignees: ''
-
----
-
-**Is your feature request related to a problem? Please describe.**
-A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
-
-**Describe the solution you'd like**
-A clear and concise description of what you want to happen.
-
-**Describe alternatives you've considered**
-A clear and concise description of any alternative solutions or features you've considered.
-
-**Additional context**
-Add any other context or screenshots about the feature request here.
diff --git a/.github/stale.yml b/.github/stale.yml
deleted file mode 100644
index 8ec2004..0000000
--- a/.github/stale.yml
+++ /dev/null
@@ -1,18 +0,0 @@
-# Number of days of inactivity before an issue becomes stale
-daysUntilStale: 60
-# Number of days of inactivity before a stale issue is closed
-daysUntilClose: 7
-# Issues with these labels will never be considered stale
-exemptLabels:
- - pinned
- - security
- - enhancement
-# Label to use when marking an issue as stale
-staleLabel: wontfix
-# Comment to post when marking an issue as stale. Set to `false` to disable
-markComment: >
- This issue has been automatically marked as stale because it has not had
- recent activity. It will be closed if no further activity occurs. Thank you
- for your contributions.
-# Comment to post when closing a stale issue. Set to `false` to disable
-closeComment: false
diff --git a/.github/workflows/deploy-image.yml b/.github/workflows/deploy-image.yml
deleted file mode 100644
index 93321b3..0000000
--- a/.github/workflows/deploy-image.yml
+++ /dev/null
@@ -1,32 +0,0 @@
-name: Docker Image CI
-
-on:
- push:
- branches: [ master ]
- pull_request:
- branches: [ master ]
-
-jobs:
-
- build:
-
- runs-on: ubuntu-latest
-
- steps:
- - name: Checkout
- uses: actions/checkout@v2
- - name: Buildx
- uses: docker/setup-buildx-action@v1
-
- - name: Login
- uses: docker/login-action@v1
- with:
- username: ${{ secrets.DOCKER_USERNAME }}
- password: ${{ secrets.DOCKER_PASSWORD }}
-
- - name: Build and push
- uses: docker/build-push-action@v2
- with:
- context: .
- push: true
- tags: amirpourmand/al-folio
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
deleted file mode 100644
index f6455fd..0000000
--- a/.github/workflows/deploy.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-name: deploy
-
-on:
- push:
- branches:
- - master
- - main
- pull_request:
- branches:
- - master
- - main
-
-jobs:
- deploy:
- runs-on: ubuntu-latest
- steps:
- - name: Checkout code
- uses: actions/checkout@v3
- - name: Setup Ruby
- uses: ruby/setup-ruby@v1
- with:
- ruby-version: '3.0.2'
- bundler-cache: true
- - name: Install deps
- run: |
- npm install -g mermaid.cli
- - name: Setup deploy options
- id: setup
- run: |
- git config --global user.name "GitHub Action"
- git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
- if [[ ${GITHUB_REF} = refs/pull/*/merge ]]; then # pull request
- echo "::set-output name=SRC_BRANCH::${GITHUB_HEAD_REF}"
- echo "::set-output name=NO_PUSH::--no-push"
- elif [[ ${GITHUB_REF} = refs/heads/* ]]; then # branch, e.g. master, source etc
- echo "::set-output name=SRC_BRANCH::${GITHUB_REF#refs/heads/}"
- fi
- echo "::set-output name=DEPLOY_BRANCH::gh-pages"
- - name: Deploy website
- run: yes | bash bin/deploy --verbose ${{ steps.setup.outputs.NO_PUSH }}
- --src ${{ steps.setup.outputs.SRC_BRANCH }}
- --deploy ${{ steps.setup.outputs.DEPLOY_BRANCH }}
diff --git a/.nojekyll b/.nojekyll
new file mode 100644
index 0000000..e69de29
diff --git a/404.html b/404.html
index 929fc57..1eb4d67 100644
--- a/404.html
+++ b/404.html
@@ -1,9 +1 @@
----
-layout: page
-permalink: /404.html
-title: "Page not found"
-description: "Looks like there has been a mistake. Nothing exists here."
-redirect: true
----
-
-
You will be redirected to the main page within 3 seconds. If not redirected, please click here.
+ Page not found | HKU NLP Group
Page not found
Looks like there has been a mistake. Nothing exists here.
You will be redirected to the main page within 3 seconds. If not redirected, please click here.
\ No newline at end of file
diff --git a/Gemfile b/Gemfile
deleted file mode 100644
index a8764ec..0000000
--- a/Gemfile
+++ /dev/null
@@ -1,25 +0,0 @@
-source 'https://rubygems.org'
-group :jekyll_plugins do
- gem 'jekyll'
- gem 'jekyll-archives'
- gem 'jekyll-diagrams'
- gem 'jekyll-email-protect'
- gem 'jekyll-feed'
- gem 'jekyll-imagemagick'
- gem 'jekyll-minifier'
- gem 'jekyll-paginate-v2'
- gem 'jekyll-scholar'
- gem 'jekyll-sitemap'
- gem 'jekyll-target-blank'
- gem 'jekyll-twitter-plugin'
- gem 'jekyll-redirect-from'
- gem 'jemoji'
- gem 'mini_racer'
- gem 'unicode_utils'
- gem 'webrick'
- gem 'jekyll-loading-lazy'
-end
-group :other_plugins do
- gem 'httparty'
- gem 'feedjira'
-end
diff --git a/_bibliography/papers.bib b/_bibliography/papers.bib
deleted file mode 100644
index 10db8b7..0000000
--- a/_bibliography/papers.bib
+++ /dev/null
@@ -1,580 +0,0 @@
----
----
-
-@article{Xie2023OpenAgentsAO,
- title = {OpenAgents: An Open Platform for Language Agents in the Wild},
- author = {Tianbao Xie and Fan Zhou and Zhoujun Cheng and Peng Shi and Luoxuan Weng and Yitao Liu and Toh Jing Hua and Junning Zhao and Qian Liu and Che Liu and Leo Z. Liu and Yiheng Xu and Hongjin Su and Dongchan Shin and Caiming Xiong and Tao Yu},
- journal = {Conference on Language Modeling (COLM)},
- year = {2024},
- arxiv = {2310.10634},
- code = {https://github.com/xlang-ai/OpenAgents},
- preview = {Xie2023OpenAgentsAO.png}
-}
-
-@article{Sun2023CorexPT,
- title = {Corex: Pushing the Boundaries of Complex Reasoning through Multi-Model Collaboration},
- author = {Qiushi Sun and Zhangyue Yin and Xiang Li and Zhiyong Wu and Xipeng Qiu and Lingpeng Kong},
- journal = {Conference on Language Modeling (COLM)},
- year = {2024},
- arxiv = {2310.00280},
- code = {https://github.com/QiushiSun/Corex},
- preview = {Sun2023CorexPT.png}
-}
-
-
-@article{Gao2024CoCA,
- title = {CoCA: Regaining Safety-awareness of Multimodal Large Language Models with Constitutional Calibration},
- author = {Jiahui Gao and Renjie Pi and Tianyang Han and Han Wu and Lanqing HONG and Lingpeng Kong and Xin Jiang and Zhenguo Li},
- journal = {Conference on Language Modeling (COLM)},
- year = {2024}
-}
-
-
-@article{Zhao2024EmpoweringLL,
- title = {Empowering Large Language Model Agents through Action Learning},
- author = {Haiteng Zhao and Chang Ma and Guoyin Wang and Jing Su and Lingpeng Kong and Jingjing Xu and Zhi-Hong Deng and Hongxia Yang},
- journal = {Conference on Language Modeling (COLM)},
- year = {2024},
- arxiv = {2402.15809},
- code = {https://github.com/zhao-ht/LearnAct},
- preview = {Zhao2024EmpoweringLL.png}
-}
-
-@article{zheng2023reparameterized,
- title = {A Reparameterized Discrete Diffusion Model for Text Generation},
- author = {Lin Zheng and Jianbo Yuan and Lei Yu and Lingpeng Kong},
- journal = {Conference on Language Modeling (COLM)},
- year = {2024},
- arxiv = {2302.04542},
- code = {https://github.com/HKUNLP/reparam-discrete-diffusion},
- preview = {zheng2023reparameterized.png}
-}
-
-
-@article{Zhao2023SEGOSS,
- title = {SEGO: Sequential Subgoal Optimization for Mathematical Problem-Solving},
- author = {Xueliang Zhao and Xinting Huang and Wei Bi and Lingpeng Kong},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2310.12960},
- code = {https://github.com/zhaoxlpku/SEGO},
- preview = {Zhao2023SEGOSS.png}
-}
-
-@article{Zhao2024BBABB,
- title = {BBA: Bi-Modal Behavioral Alignment for Reasoning with Large Vision-Language Models},
- author = {Xueliang Zhao and Xinting Huang and Tingchen Fu and Qintong Li and Shansan Gong and Lemao Liu and Wei Bi and Lingpeng Kong},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2024},
- arxiv = {2402.13577},
- preview = {Zhao2024BBABB.png}
-}
-
-@article{Li2024RedTV,
- title = {Red Teaming Visual Language Models},
- author = {Mukai Li and Lei Li and Yuwei Yin and Masood Ahmed and Zhenguang Liu and Qi Liu},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2024},
- arxiv = {2401.12915},
- code = {https://huggingface.co/datasets/MMInstruction/RedTeamingVLM},
- preview = {Li2024RedTV.png}
-}
-
-@article{Wang2023LargeLM,
- title = {Large Language Models are not Fair Evaluators},
- author = {Peiyi Wang and Lei Li and Liang Chen and Dawei Zhu and Binghuai Lin and Yunbo Cao and Qi Liu and Tianyu Liu and Zhifang Sui},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2305.17926},
- code = {https://github.com/i-Eval/FairEval},
- preview = {Wang2023LargeLM.png}
-}
-
-@article{Wang2023ACB,
- title = {A Challenging Benchmark for Low-Resource Learning},
- author = {Yudong Wang and Chang Ma and Qingxiu Dong and Lingpeng Kong and Jingjing Xu},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2024},
- arxiv = {2303.03840},
- code = {https://github.com/Qian2333/Hard-Bench},
- preview = {Wang2023ACB.png}
-}
-
-
-@article{Wang2024LoRAMD,
- title = {LoRA Meets Dropout under a Unified Framework},
- author = {Sheng Wang and Liheng Chen and Jiyue Jiang and Boyang Xue and Lingpeng Kong and Chuan Wu},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2024},
- arxiv = {2403.00812},
- preview = {Wang2024LoRAMD.png}
-}
-
-
-@article{Li2024GSMPlusAC,
- title = {GSM-Plus: A Comprehensive Benchmark for Evaluating the Robustness of LLMs as Mathematical Problem Solvers},
- author = {Qintong Li and Leyang Cui and Xueliang Zhao and Lingpeng Kong and Wei Bi},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2402.19255},
- code = {https://qtli.github.io/GSM-Plus/},
- preview = {Li2024GSMPlusAC.png}
-}
-
-@article{Wang2024PRoLoRAPR,
- title = {PRoLoRA: Partial Rotation Empowers More Parameter-Efficient LoRA},
- author = {Sheng Wang and Boyang Xue and Jiacheng Ye and Jiyue Jiang and Liheng Chen and Lingpeng Kong and Chuan Wu},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2402.16902},
- preview = {Wang2024PRoLoRAPR.png}
-}
-
-@article{An2023LEvalIS,
- title = {L-Eval: Instituting Standardized Evaluation for Long Context Language Models},
- author = {Chenxin An and Shansan Gong and Ming Zhong and Mukai Li and Jun Zhang and Lingpeng Kong and Xipeng Qiu},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2307.11088},
- code = {https://github.com/OpenLMLab/LEval},
- preview = {An2023LEvalIS.png}
-}
-
-@article{Li2024MultimodalAA,
- title = {Multimodal ArXiv: A Dataset for Improving Scientific Comprehension of Large Vision-Language Models},
- author = {Lei Li and Yuqi Wang and Runxin Xu and Peiyi Wang and Xiachong Feng and Lingpeng Kong and Qi Liu},
- journal = {In Proceedings of the
- Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2024},
- arxiv = {2403.00231},
- code = {https://mm-arxiv.github.io/},
- preview = {Li2024MultimodalAA.png}
-}
-
-@article{Zheng2023SelfInfillingCG,
- title = {Self-Infilling Code Generation},
- author = {Lin Zheng and Jianbo Yuan and Zhi Zhang and Hongxia Yang and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2024},
- arxiv = {2311.17972},
- code = {https://github.com/LZhengisme/self-infilling},
- preview = {Zheng2023SelfInfillingCG.png}
-}
-
-@article{An2024TrainingFreeLS,
- title = {Training-Free Long-Context Scaling of Large Language Models},
- author = {Chenxin An and Fei Huang and Jun Zhang and Shansan Gong and Xipeng Qiu and Chang Zhou and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2024},
- arxiv = {2402.17463},
- code = {https://github.com/HKUNLP/ChunkLlama},
- preview = {An2024TrainingFreeLS.png}
-}
-
-@article{Zhao2023DecomposingTE,
- title = {Decomposing the Enigma: Subgoal-based Demonstration Learning for Formal Theorem Proving},
- author = {Xueliang Zhao and Wenda Li and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2024},
- arxiv = {2305.16366},
- code = {https://github.com/HKUNLP/subgoal-theorem-prover},
- preview = {Zhao2023DecomposingTE.png}
-}
-
-@article{Xu2023LemurHN,
- title = {Lemur: Harmonizing Natural Language and Code for Language Agents},
- author = {Yiheng Xu and Hongjin Su and Chen Xing and Boyu Mi and Qian Liu and Weijia Shi and Binyuan Hui and Fan Zhou and Yitao Liu and Tianbao Xie and Zhoujun Cheng and Siheng Zhao and Lingpeng Kong and Bailin Wang and Caiming Xiong and Tao Yu},
- journal = {In International Conference on Learning Representations (ICLR)},
- year = {2024},
- arxiv = {2310.06830},
- code = {https://github.com/OpenLemur/Lemur},
- preview = {Xu2023LemurHN.png}
-}
-
-@article{Yang2023UniTabEAU,
- title = {UniTabE: A Universal Pretraining Protocol for Tabular Foundation Model in Data Science},
- author = {Yazheng Yang and Yuqi Wang and Guangyi Liu and Ledell Yu Wu and Qi Liu},
- journal = {In International Conference on Learning Representations (ICLR)},
- year = {2024},
- arxiv = {2307.09249},
- preview = {Yang2023UniTabEAU.png}
-}
-
-@article{Li2023CanLM,
- title = {Can Language Models Understand Physical Concepts?},
- author = {Lei Li and Jingjing Xu and Qingxiu Dong and Ce Zheng and Qi Liu and Lingpeng Kong and Xu Sun},
- journal = {In Proceedings of the Conference on Empirical Methods in Natural Language
- Processing (EMNLP)},
- year = {2023},
- arxiv = {2305.14057},
- code = {https://github.com/TobiasLee/VEC},
- preview = {Li2023CanLM.png}
-}
-
-@article{Pi2023DetGPTDW,
- title = {DetGPT: Detect What You Need via Reasoning},
- author = {Renjie Pi and Jiahui Gao and Shizhe Diao and Rui Pan and Hanze Dong and Jipeng Zhang and Lewei Yao and Jianhua Han and Hang Xu and Lingpeng Kong Tong Zhang},
- journal = {In Proceedings of the Conference on Empirical Methods in Natural Language
- Processing (EMNLP)},
- year = {2023},
- arxiv = {2305.14167},
- code = {https://detgpt.github.io/},
- preview = {Pi2023DetGPTDW.png}
-}
-
-@article{Ye2023GeneratingDF,
- title = {Generating Data for Symbolic Language with Large Language Models},
- author = {Jiacheng Ye and Chengzu Li and Lingpeng Kong and Tao Yu},
- journal = {In Proceedings of the Conference on Empirical Methods in Natural Language
- Processing (EMNLP)},
- year = {2023},
- arxiv = {2305.13917},
- code = {https://github.com/HKUNLP/SymGen},
- preview = {Ye2023GeneratingDF.png}
-}
-
-@article{Gong2023DiffuSeqv2BD,
- title = {DiffuSeq-v2: Bridging Discrete and Continuous Text Spaces for Accelerated Seq2Seq Diffusion Models},
- author = {Shansan Gong and Mukai Li and Jiangtao Feng and Zhiyong Wu and Lingpeng Kong},
- journal = {In Findings of the Conference on Empirical Methods in
- Natural Language Processing (EMNLP Findings)},
- year = {2023},
- arxiv = {2310.05793},
- code = {https://github.com/Shark-NLP/DiffuSeq},
- preview = {Gong2023DiffuSeqv2BD.png}
-}
-
-@article{Zhao2023GIMLETAU,
- title = {GIMLET: A Unified Graph-Text Model for Instruction-Based Molecule Zero-Shot Learning},
- author = {Haiteng Zhao and Shengchao Liu and Chang Ma and Hannan Xu and Jie Fu and Zhihong Deng and Lingpeng Kong and Qi Liu},
- journal = {In Advances in Neural Information Processing Systems (NeurIPS)},
- year = {2023},
- arxiv = {2306.13089},
- code = {https://github.com/zhao-ht/GIMLET},
- preview = {Zhao2023GIMLETAU.png}
-}
-
-@article{Dong2023StatisticalKA,
- title = {Statistical Knowledge Assessment for Large Language Models},
- author = {Qingxiu Dong and Jingjing Xu and Lingpeng Kong and Zhifang Sui and Lei Li},
- journal = {In Advances in Neural Information Processing Systems (NeurIPS)},
- year = {2023},
- arxiv = {2305.10519},
- code = {https://github.com/dqxiu/KAssess},
- preview = {Dong2023StatisticalKA.png}
-}
-
-@article{Wang2022EvaluatingSL,
- title = {Evaluating Self-Supervised Learning for Molecular Graph Embeddings},
- author = {Hanchen Wang and Jean Kaddour and Shengchao Liu and Jian Tang and Matt J. Kusner and Joan Lasenby and Qi Liu},
- journal = {In Advances in Neural Information Processing Systems (NeurIPS)},
- year = {2023},
- volume = {abs/2206.08005},
- url = {https://api.semanticscholar.org/CorpusID:249712002},
- preview = {Wang2022EvaluatingSL.png}
-}
-
-@article{Wu2022SelfAdaptiveIL,
- title = {Self-Adaptive In-Context Learning: An Information Compression Perspective for In-Context Example Selection and Ordering},
- author = {Zhiyong Wu and Yaoxiang Wang and Jiacheng Ye and Lingpeng Kong},
- journal = {In Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2023},
- arxiv = {2212.10375},
- code = {https://github.com/Shark-NLP/self-adaptive-ICL},
- preview = {Wu2022SelfAdaptiveIL.png}
-}
-
-@article{Li2022ExplanationRV,
- title = {Explanation Regeneration via Information Bottleneck},
- author = {Qintong Li and Zhiyong Wu and Lingpeng Kong and Wei Bi},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2023},
- arxiv = {2212.09603},
- code = {https://github.com/qtli/EIB},
- preview = {Li2022ExplanationRV.png}
-}
-
-@article{Jiang2023ACS,
- title = {A Cognitive Stimulation Dialogue System with Multi-source Knowledge Fusion for Elders with Cognitive Impairment},
- author = {Jiyue Jiang and Sheng Wang and Qintong Li and Lingpeng Kong and Chuan Wu},
- journal = {In Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2023},
- arxiv = {2305.08200},
- preview = {Jiang2023ACS.png}
-}
-
-@article{Zhao2023SORTIEDS,
- title = {SORTIE: Dependency-Aware Symbolic Reasoning for Logical Data-to-text Generation},
- author = {Xueliang Zhao and Tingchen Fu and Lemao Liu and Lingpeng Kong and Shuming Shi and Rui Yan},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2023},
- pdf = {https://aclanthology.org/2023.findings-acl.715.pdf},
- preview = {Zhao2023SORTIEDS.png}
-}
-
-@article{Su2022OneEA,
- title = {One Embedder, Any Task: Instruction-Finetuned Text Embeddings},
- author = {Hongjin Su and Weijia Shi and Jungo Kasai and Yizhong Wang and Yushi Hu and Mari Ostendorf and Wen-tau Yih and Noah A. Smith and Luke Zettlemoyer and Tao Yu},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2023},
- arxiv = {2212.09741},
- code = {https://instructor-embedding.github.io/},
- preview = {Su2022OneEA.png}
-}
-
-@article{Ye2023CompositionalEF,
- title = {Compositional Exemplars for In-context Learning},
- author = {Jiacheng Ye and Zhiyong Wu and Jiangtao Feng and Tao Yu and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2023},
- arxiv = {2302.05698},
- code = {https://github.com/HKUNLP/icl-ceil},
- preview = {Ye2023CompositionalEF.png}
-}
-
-@article{Zhang2022CABCA,
- title = {CAB: Comprehensive Attention Benchmarking on Long Sequence Modeling},
- author = {Jinchao Zhang and Shuyang Jiang and Jiangtao Feng and Lin Zheng and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2023},
- arxiv = {2210.07661},
- code = {https://github.com/Shark-NLP/CAB},
- preview = {Zhang2022CABCA.png}
-}
-
-@article{Lai2022DS1000AN,
- title = {DS-1000: A Natural and Reliable Benchmark for Data Science Code Generation},
- author = {Yuhang Lai and Chengxi Li and Yiming Wang and Tianyi Zhang and Ruiqi Zhong and Luke Zettlemoyer and Scott Yih and Daniel Fried and Si-yi Wang and Tao Yu},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2023},
- arxiv = {2211.11501},
- code = {https://github.com/xlang-ai/DS-1000},
- preview = {Lai2022DS1000AN.png}
-}
-
-@article{Zheng2023EfficientAV,
- title = {Efficient Attention via Control Variates},
- author = {Lin Zheng and Jianbo Yuan and Chong Wang and Lingpeng Kong},
- journal = {In International Conference on Learning Representations (ICLR)},
- year = {2023},
- arxiv = {2302.04542},
- code = {https://github.com/HKUNLP/efficient-attention},
- preview = {Zheng2023EfficientAV.png}
-}
-
-@article{gao2023selfguided,
- title = {Self-Guided Noise-Free Data Generation for Efficient Zero-Shot Learning},
- author = {Jiahui Gao and Renjie Pi and Lin Yong and Hang Xu and Jiacheng Ye and Zhiyong Wu and Weizhong Zhang and Xiaodan Liang and Zhenguo Li and Lingpeng Kong},
- journal = {International Conference on Learning Representations (ICLR)},
- location = {Kigali, Rwanda},
- year = {2023},
- arxiv = {2205.12679},
- code = {https://github.com/SumilerGAO/SunGen},
- preview = {gao2023selfguided.png}
-}
-
-@article{Qin2023ToeplitzNN,
- title = {Toeplitz Neural Network for Sequence Modeling},
- author = {Zhen Qin and Xiaodong Han and Weixuan Sun and Bowen He and Dong Li and Dongxu Li and Yuchao Dai and Lingpeng Kong and Yiran Zhong},
- journal = {International Conference on Learning Representations (ICLR)},
- year = {2023},
- arxiv = {2305.04749},
- code = {https://github.com/OpenNLPLab/Tnn},
- preview = {Qin2023ToeplitzNN.png}
-}
-
-@article{Gong2022DiffuSeqST,
- title = {DiffuSeq: Sequence to Sequence Text Generation with Diffusion Models},
- author = {Shansan Gong and Mukai Li and Jiangtao Feng and Zhiyong Wu and Lingpeng Kong},
- journal = {International Conference on Learning Representations (ICLR)},
- year = {2023},
- arxiv = {2210.08933},
- code = {https://github.com/Shark-NLP/DiffuSeq},
- preview = {Gong2022DiffuSeqST.png}
-}
-
-@article{cheng2023binding,
- title = {Binding Language Models in Symbolic Languages},
- author = {Cheng, Zhoujun and Xie, Tianbao and Shi, Peng and Li, Chengzu and Nadkarni, Rahul and Hu, Yushi and Xiong, Caiming and Radev, Dragomir and Ostendorf, Mari and Zettlemoyer, Luke and Smith, Noah A and Yu, Tao},
- journal = {International Conference on Learning Representations (ICLR)},
- location = {Berlin, Germany},
- year = {2023},
- arxiv = {2210.02875},
- code = {https://lm-code-binder.github.io/},
- poster = {https://lm-code-binder.github.io/},
- selected = {y},
- preview = {Gong2022DiffuSeqST.png}
-}
-
-@article{su2023selective,
- title = {Selective Annotation Makes Language Models Better Few-Shot Learners},
- author = {Su, Hongjin and Kasai, Jungo and Wu, Chen Henry and Shi, Weijia and Wang, Tianlu and Xin, Jiayi and Zhang, Rui and Ostendorf, Mari and Zettlemoyer, Luke and Smith, Noah A. and Yu, Tao},
- journal = {International Conference on Learning Representations (ICLR)},
- year = {2023},
- arxiv = {2209.01975},
- code = {https://github.com/HKUNLP/icl-selective-annotation},
- preview = {su2023selective.png}
-}
-
-@article{chen2023unsupervised,
- title = {Unsupervised Explanation Generation via Correct Instantiations},
- author = {Sijie Chen and Zhiyong Wu and Jiangjie Chen and Zhixing Li and Yang Liu and Lingpeng Kong},
- journal = {In Proceedings of AAAI Conference on Artificial Intelligence (AAAI)},
- location = {Washington, DC},
- year = {2023},
- arxiv = {2211.11160},
- code = {https://github.com/Shark-NLP/Neon},
- preview = {chen2023unsupervised.png}
-}
-
-@article{Wang2022AnES,
- title = {An Empirical Study of Retrieval-Enhanced Graph Neural Networks},
- author = {Dingmin Wang and Shengchao Liu and Hanchen Wang and Bernardo Cuenca Grau and Linfeng Song and Jian Tang and Song Le and Qi Li},
- journal = {European Conference on Artificial Intelligence (ECAI)},
- year = {2023},
- preview = {Wang2022AnES.png}
-}
-
-@article{ma2023retrieved,
- title = {Retrieved Sequence Augmentation for Protein Representation Learning},
- author = {Chang Ma and Haiteng Zhao and Lin Zheng and Jiayi Xin and Qintong Li and Lijun Wu and Zhihong Deng and Yang Lu and Qi Liu and Lingpeng Kong},
- journal = {arXiv preprint},
- year = {2023},
- arxiv = {2302.12563},
- code = {https://github.com/HKUNLP/RSA},
- preview = {ma2023retrieved.png}
-}
-
-
-
-
-%%%%%%%%%%%% 2022 %%%%%%%%%%%%
-
-
-@article{Ye2022ProGenPZ,
- title = {ProGen: Progressive Zero-shot Dataset Generation via In-context Feedback},
- author = {Jiacheng Ye and Jiahui Gao and Jiangtao Feng and Zhiyong Wu and Tao Yu and Lingpeng Kong},
- journal = {In Findings of the Conference on Empirical Methods in Natural Language Processing (EMNLP Findings)},
- year = {2022},
- arxiv = {2210.12329},
- code = {https://github.com/HKUNLP/ProGen},
- preview = {Ye2022ProGenPZ.png}
-}
-
-@article{liu2022augmenting,
- title = {Augmenting Multi-Turn Text-to-SQL Datasets with Self-Play},
- author = {Liu, Qi and Ye, Zihuiwen and Yu, Tao and Blunsom, Phil and Song, Linfeng},
- journal = {In Findings of the Conference on Empirical Methods in Natural Language Processing (EMNLP Findings)},
- year = {2022},
- arxiv = {2210.12096},
- code = {https://github.com/leuchine/self_play_picard},
- preview = {liu2022augmenting.png}
-}
-
-@article{ye2022zerogen,
- title = {ZeroGen: Efficient Zero-shot Learning via Dataset Generation},
- author = {Ye, Jiacheng and Gao, Jiahui and Li, Qintong and Xu, Hang and Feng, Jiangtao and Wu, Zhiyong and Yu, Tao and Kong, Lingpeng},
- journal = {In Proceedings of the Conference on Empirical Methods in Natural Language Processing (EMNLP)},
- year = {2022},
- arxiv = {2202.07922},
- code = {https://github.com/jiacheng-ye/ZeroGen},
- preview = {ye2022zerogen.png}
-}
-
-@article{xie2022unifiedskg,
- title = {UnifiedSKG: Unifying and Multi-Tasking Structured Knowledge Grounding with Text-to-Text Language Models},
- author = {Xie, Tianbao and Wu, Chen Henry and Shi, Peng and Zhong, Ruiqi and Scholak, Torsten and Yasunaga, Michihiro and Wu, Chien-Sheng and Zhong, Ming and Yin, Pengcheng and Wang, Sida and Zhong, Victor and Wang, Bailin and Li, Chengzu and Boyle, Connor and Ni, Ansong and Yao, Ziyu and Radev, Dragomir and Xiong, Caiming and Kong, Lingpeng and Zhang, Rui and Smith, Noah A. and Zettlemoyer, Luke and Yu, Tao},
- journal = {In Proceedings of the Conference on Empirical Methods in Natural Language Processing (EMNLP)},
- year = {2022},
- arxiv = {2201.05966},
- code = {https://github.com/hkunlp/unifiedskg},
- poster = {https://unifiedskg.com/},
- preview = {xie2022unifiedskg.png}
-}
-
-@article{An2022CoNTCN,
- title = {CoNT: Contrastive Neural Text Generation},
- author = {Chenxin An and Jiangtao Feng and Kai Lv and Lingpeng Kong and Xipeng Qiu and Xuanjing Huang},
- journal = {In Advances in Neural Information Processing Systems (NeurIPS)},
- year = {2022},
- arxiv = {2205.14690},
- code = {https://github.com/Shark-NLP/CoNT},
- preview = {An2022CoNTCN.png}
-}
-
-@article{zheng2022linear,
- title = {Linear Complexity Randomized Self-attention Mechanism},
- author = {Lin Zheng and Chong Wang and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2022},
- arxiv = {2204.04667},
- code = {https://github.com/HKUNLP/efficient-attention},
- preview = {zheng2022linear.png}
-}
-
-@article{zheng2022ripple,
- title = {Ripple Attention for Visual Perception with Sub-quadratic Complexity},
- author = {Lin Zheng and Huijie Pan and Lingpeng Kong},
- journal = {In Proceedings of the International Conference on Machine Learning (ICML)},
- year = {2022},
- arxiv = {2110.02453},
- preview = {zheng2022ripple.png}
-}
-
-@article{li2022event,
- title = {Event Transition Planning for Open-ended Text Generation},
- author = {Qintong Li and Piji Li and Wei Bi and Zhaochun Ren and Yuxuan Lai and Lingpeng Kong},
- journal = {In Findings of the Annual Meeting of the Association for Computational Linguistics (ACL Findings)},
- year = {2022},
- arxiv = {2204.09453},
- code = {https://github.com/qtli/EventPlanforTextGen},
- preview = {li2022event.png}
-}
-
-
-@article{wu2022lexical,
- title = {Lexical Knowledge Internalization for Neural Dialog Generation},
- author = {Zhiyong Wu and Wei Bi and Xiang Li and Lingpeng Kong and Ben Kao},
- journal = {In Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2022},
- arxiv = {2205.01941},
- code = {https://github.com/LividWo/KI},
- preview = {wu2022lexical.png}
-}
-
-@inproceedings{Prange2021LinguisticFG,
- title = {Linguistic Frameworks Go Toe-to-Toe at Neuro-Symbolic Language Modeling},
- author = {Jakob Prange and Nathan Schneider and Lingpeng Kong},
- booktitle = {North American Chapter of the Association for Computational Linguistics (NAACL)},
- year = {2022},
- arxiv = {2112.07874},
- preview = {wu2022lexical.png}
-}
-
-
-%%%%%%%%%%%% 2021 %%%%%%%%%%%%%%%%%%%
-
-@article{zheng2021cascaded,
- title = {Cascaded Head-colliding Attention},
- author = {Lin Zheng and Zhiyong Wu and Lingpeng Kong},
- journal = {In Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2021},
- arxiv = {2105.14850},
- code = {https://github.com/LZhengisme/CODA},
- preview = {zheng2021cascaded.png}
-}
-
-@article{wu2021good,
- title = {Good for Misconceived Reasons: An Empirical Revisiting on the Need for Visual Context in Multimodal Machine Translation},
- author = {Zhiyong Wu and Lingpeng Kong and Wei Bi and Xiang Li and Ben Kao},
- journal = {In Proceedings of the Annual Meeting of the Association for Computational Linguistics (ACL)},
- year = {2021},
- arxiv = {2105.14462},
- code = {https://github.com/LividWo/Revisit-MMT},
- preview = {wu2021good.png}
-}
diff --git a/_config.yml b/_config.yml
deleted file mode 100644
index 0a7d8d1..0000000
--- a/_config.yml
+++ /dev/null
@@ -1,329 +0,0 @@
-# -----------------------------------------------------------------------------
-# Site settings
-# -----------------------------------------------------------------------------
-
-title: blank # the website title (if blank, full name will be used instead)
-first_name: HKU NLP Group
-middle_name:
-last_name:
-email:
-description: > # the ">" symbol means to ignore newlines until "footer_text:"
- A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design.
-footer_text: >
- Powered by Jekyll with al-folio theme.
- Hosted by GitHub Pages.
-keywords: # jekyll, jekyll-theme, academic-website, portfolio-website # add your own keywords or leave empty
-
-
-lang: en # the language of your site (for example: en, fr, cn, ru, etc.)
-icon: icon.png # the emoji used as the favicon (alternatively, provide image name in /assets/img/)
-
-url: https://hkunlp.github.io # the base hostname & protocol for your site
-baseurl: # the subpath of your site, e.g. /blog/
-last_updated: false # set to true if you want to display last updated in the footer
-impressum_path: # set to path to include impressum link in the footer, use the same path as permalink in a page, helps to conform with EU GDPR
-
-# -----------------------------------------------------------------------------
-# RSS Feed
-# -----------------------------------------------------------------------------
-# will use title and url fields
-# Take a look to https://github.com/jekyll/jekyll-feed for more customization
-
-rss_icon: false
-
-# -----------------------------------------------------------------------------
-# Layout
-# -----------------------------------------------------------------------------
-
-navbar_fixed: true
-footer_fixed: true
-
-# Dimensions
-max_width: 800px
-
-# TODO: add layout settings (single page vs. multi-page)
-
-# -----------------------------------------------------------------------------
-# Open Graph & Schema.org
-# -----------------------------------------------------------------------------
-# Display links to the page with a preview object on social media.
-serve_og_meta: false # Include Open Graph meta tags in the HTML head
-serve_schema_org: false # Include Schema.org in the HTML head
-og_image: # The site-wide (default for all links) Open Graph preview image
-
-# -----------------------------------------------------------------------------
-# Social integration
-# -----------------------------------------------------------------------------
-
-github_username: HKUNLP # your GitHub user name
-gitlab_username: # your GitLab user name
-twitter_username: # your Twitter handle
-linkedin_username: # your LinkedIn user name
-scholar_userid: # your Google Scholar ID
-orcid_id: # your ORCID ID
-medium_username: # your Medium username
-quora_username: # your Quora username
-publons_id: # your ID on Publons
-research_gate_profile: # your profile on ResearchGate
-blogger_url: # your blogger URL
-work_url: # work page URL
-keybase_username: # your keybase user name
-wikidata_id: # your wikidata id
-dblp_url: # your DBLP profile url
-stackoverflow_id: #your stackoverflow id
-
-contact_note: >
- You can even add a little note about which of these is the best way to reach you.
-
-# -----------------------------------------------------------------------------
-# Analytics and search engine verification
-# -----------------------------------------------------------------------------
-
-google_analytics: # your google-analytics ID (format: UA-XXXXXXXXX)
-panelbear_analytics: # panelbear analytics site ID (format: XXXXXXXXX)
-
-google_site_verification: # your google-site-verification ID (Google Search Console)
-bing_site_verification: # out your bing-site-verification ID (Bing Webmaster)
-
-# -----------------------------------------------------------------------------
-# Blog
-# -----------------------------------------------------------------------------
-
-blog_name: Blog # blog_name will be displayed in your blog page
-blog_nav_title: Blog # your blog must have a title for it to be displayed in the nav bar
-blog_description: Posts on research projects @ HKU NLP Group
-permalink: /blog/:year/:title/
-
-# Pagination
-pagination:
- enabled: true
-
-# Comments
-disqus_shortname: al-folio # put your disqus shortname
-# https://help.disqus.com/en/articles/1717111-what-s-a-shortname
-
-# External sources.
-# If you have blog posts published on medium.com or other exteranl sources,
-# you can display them in your blog by adding a link to the RSS feed.
-# external_sources:
-# - name: medium.com
-# rss_url: https://medium.com/@al-folio/feed
-
-# -----------------------------------------------------------------------------
-# Collections
-# -----------------------------------------------------------------------------
-
-collections:
- news:
- defaults:
- layout: post
- output: true
- permalink: /news/:path/
- projects:
- output: true
- permalink: /projects/:path/
- people:
- output: true
- permalink: /people/:path/
-
-news_scrollable: true # adds a vertical scroll bar if there are more than 3 news items
-news_limit: 5 # leave blank to include all the news in the `_news` folder
-
-# -----------------------------------------------------------------------------
-# Jekyll settings
-# -----------------------------------------------------------------------------
-
-# Markdown and syntax highlight
-markdown: kramdown
-highlighter: rouge
-highlight_theme_light: github # https://github.com/jwarby/jekyll-pygments-themes
-highlight_theme_dark: native # https://github.com/jwarby/jekyll-pygments-themes
-kramdown:
- input: GFM
- syntax_highlighter_opts:
- css_class: 'highlight'
- span:
- line_numbers: false
- block:
- line_numbers: false
- start_line: 1
-
-# Includes & excludes
-include: ['_pages']
-exclude:
- - bin
- - Gemfile
- - Gemfile.lock
- - vendor
-keep_files:
- - CNAME
- - .nojekyll
- - .git
-
-# Plug-ins
-plugins:
- - jekyll-archives
- - jekyll-diagrams
- - jekyll-email-protect
- - jekyll-feed
- - jekyll-imagemagick
- - jekyll-minifier
- - jekyll-paginate-v2
- - jekyll/scholar
- - jekyll-sitemap
- - jekyll-target-blank
- - jekyll-twitter-plugin
- - jekyll-redirect-from
- - jemoji
- - jekyll-loading-lazy
-
-# Sitemap settings
-defaults:
- - scope:
- path: "assets/**/*.*"
- values:
- sitemap: false
-
-# -----------------------------------------------------------------------------
-# Jekyll Minifier
-# -----------------------------------------------------------------------------
-
-jekyll-minifier:
- exclude: ['robots.txt']
- uglifier_args:
- harmony: true
-
-# -----------------------------------------------------------------------------
-# Jekyll Archives
-# -----------------------------------------------------------------------------
-
-jekyll-archives:
- enabled: [year, tags, categories] # enables year, tag and category archives (remove if you need to disable one of them).
- layouts:
- year: archive-year
- tag: archive-tag
- category: archive-category
- permalinks:
- year: '/blog/:year/'
- tag: '/blog/tag/:name/'
- category: '/blog/category/:name/'
-
-display_tags: ['attention', 'transformers', 'generation', 'multi-modality', 'NLP'] # this tags will be dispalyed on the front page of your blog
-
-# -----------------------------------------------------------------------------
-# Jekyll Scholar
-# -----------------------------------------------------------------------------
-
-scholar:
-
- last_name: Einstein
- first_name: [Albert, A.]
-
- style: apa
- locale: en
-
- source: /_bibliography/
- bibliography: papers.bib
- bibliography_template: bib
- # Note: if you have latex math in your bibtex, the latex filter
- # preprocessing may conflict with MathJAX if the latter is enabled.
- # See https://github.com/alshedivat/al-folio/issues/357.
- bibtex_filters: [latex, smallcaps, superscript]
-
- replace_strings: true
- join_strings: true
-
- details_dir: bibliography
- details_layout: bibtex.html
- details_link: Details
-
- query: "@*"
-
-# Filter out certain bibtex entry keywords used internally from the bib output
-filtered_bibtex_keywords: [abbr, abstract, arxiv, bibtex_show, html, pdf, selected, supp, blog, code, poster, slides, website, preview]
-
-# Maximum number of authors to be shown, other authors will be visible on hover, leave blank to show all authors
-max_author_limit: 12
-
-# -----------------------------------------------------------------------------
-# Responsive WebP Images
-# -----------------------------------------------------------------------------
-
-imagemagick:
- enabled: true # enables responsive images for your site (recomended, see https://github.com/alshedivat/al-folio/issues/537)
- widths:
- - 480
- - 800
- - 1400
- input_directories:
- - assets/img/
- input_formats:
- - ".jpg"
- - ".jpeg"
- - ".png"
- - ".tiff"
- output_formats:
- webp: "-quality 75%"
-
-# -----------------------------------------------------------------------------
-# Jekyll Diagrams
-# -----------------------------------------------------------------------------
-
-jekyll-diagrams:
- # configuration, see https://github.com/zhustec/jekyll-diagrams.
- # feel free to comment out this section if not using jekyll diagrams.
-
-
-# -----------------------------------------------------------------------------
-# Optional Features
-# -----------------------------------------------------------------------------
-
-enable_google_analytics: false # enables google analytics
-enable_panelbear_analytics: false # enables panelbear analytics
-enable_google_verification: false # enables google site verification
-enable_bing_verification: false # enables bing site verification
-enable_masonry: true # enables automatic project cards arangement
-enable_math: true # enables math typesetting (uses MathJax)
-enable_tooltips: false # enables automatic tooltip links generated
- # for each section titles on pages and posts
-enable_darkmode: true # enables switching between light/dark modes
-enable_navbar_social: false # enables displaying social links in the
- # navbar on the about page
-enable_project_categories: true # enables categorization of projects into
- # multiple categories
-enable_people_categories: true # enables categorization of researchers into
- # multiple categories
-enable_medium_zoom: false # enables image zoom feature (as on medium.com)
-
-
-# -----------------------------------------------------------------------------
-# Library versions
-# -----------------------------------------------------------------------------
-
-academicons:
- version: "1.9.1"
- integrity: "sha256-i1+4qU2G2860dGGIOJscdC30s9beBXjFfzjWLjBRsBg="
-bootstrap:
- version: "4.6.1"
- integrity:
- css: "sha256-DF7Zhf293AJxJNTmh5zhoYYIMs2oXitRfBjY+9L//AY="
- js: "sha256-fgLAgv7fyCGopR/gBNq2iW3ZKIdqIcyshnUULC4vex8="
-fontawesome:
- version: "5.15.4"
- integrity: "sha256-mUZM63G8m73Mcidfrv5E+Y61y7a12O5mW4ezU3bxqW4="
-jquery:
- version: "3.6.0"
- integrity: "sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
-mathjax:
- version: "3.2.0"
-masonry:
- version: "4.2.2"
- integrity: "sha256-Nn1q/fx0H7SNLZMQ5Hw5JLaTRZp0yILA/FRexe19VdI="
-mdb:
- version: "4.20.0"
- integrity:
- css: "sha256-jpjYvU3G3N6nrrBwXJoVEYI/0zw8htfFnhT9ljN3JJw="
- js: "sha256-NdbiivsvWt7VYCt6hYNT3h/th9vSTL4EDWeGs5SN3DA="
-medium_zoom:
- version: "1.0.6"
- integrity: "sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM="
diff --git a/_data/coauthors.yml b/_data/coauthors.yml
deleted file mode 100644
index 8ed5212..0000000
--- a/_data/coauthors.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-"Adams":
- - firstname: ["Edwin", "E.", "E. P.", "Edwin Plimpton"]
- url: https://en.wikipedia.org/wiki/Edwin_Plimpton_Adams
-
-"Podolsky":
- - firstname: ["Boris", "B.", "B. Y.", "Boris Yakovlevich"]
- url: https://en.wikipedia.org/wiki/Boris_Podolsky
-
-"Rosen":
- - firstname: ["Nathan", "N."]
- url: https://en.wikipedia.org/wiki/Nathan_Rosen
-
-"Bach":
- - firstname: ["Johann Sebastian", "J. S."]
- url: https://en.wikipedia.org/wiki/Johann_Sebastian_Bach
-
- - firstname: ["Carl Philipp Emanuel", "C. P. E."]
- url: https://en.wikipedia.org/wiki/Carl_Philipp_Emanuel_Bach
-
-"Przibram":
- - firstname: ["Karl"]
- url: https://link.springer.com/article/10.1007/s00016-019-00242-z
-
-"Schrödinger":
- - firstname: ["Erwin"]
- url: https://en.wikipedia.org/wiki/Erwin_Schr%C3%B6dinger
-
-"Lorentz":
- - firstname: ["Hendrik Antoon"]
- url: https://en.wikipedia.org/wiki/Hendrik_Lorentz
-
-"Planck":
- - firstname: ["Max"]
- url: https://en.wikipedia.org/wiki/Max_Planck
diff --git a/_data/cv.yml b/_data/cv.yml
deleted file mode 100644
index 5b11572..0000000
--- a/_data/cv.yml
+++ /dev/null
@@ -1,97 +0,0 @@
-- title: General Information
- type: map
- contents:
- - name: Full Name
- value: Albert Einstein
- - name: Date of Birth
- value: 14th March 1879
- - name: Languages
- value: English, German
-
-- title: Education
- type: time_table
- contents:
- - title: PhD
- institution: University of Zurich, Zurich, Switzerland
- year: 1905
- description:
- - Description 1.
- - Description 2.
- - title: Description 3.
- contents:
- - Sub-description 1.
- - Sub-description 2.
- - title: Federal teaching diploma
- institution: Eidgenössische Technische Hochschule, Zurich, Switzerland
- year: 1900
- description:
- - Description 1.
- - Description 2.
-
-- title: Experience
- type: time_table
- contents:
- - title: Professor of Theoretical Physics
- institution: Institute for Advanced Study, Princeton University
- year: 1933 - 1955
- description:
- - Description 1.
- - Description 2.
- - title: Description 3.
- contents:
- - Sub-description 1.
- - Sub-description 2.
- - title: Visiting Professor
- institution: California Institute of Technology, Pasadena, California, US
- year: 1933
- description:
- - Description 1.
- - Description 2.
-
- - title: Director
- institution: Kaiser Wilhelm Institute for Physics, Berlin, Germany.
- year: 1917-1933
-
- - title: Professor of Theoretical Physics
- institution: Karl-Ferdinand University, Prague, Czechoslovakia
- year: 1911 - 1917
- description:
-
- - title: Associate Professor of Theoretical Physics
- institution: University of Zurich, Zurich, Switzerland
- year: 1909 - 1911
-
-- title: Open Source Projects
- type: time_table
- contents:
- - title: al-folio
- year: 2015-now
- description: A beautiful, simple, clean, and responsive Jekyll theme for academics.
-
-- title: Honors and Awards
- type: time_table
- contents:
- - year: 1921
- items:
- - Nobel Prize in Physics
- - Matteucci Medal
- - year: 2029
- items:
- - Max Planck Medal
-
-- title: Academic Interests
- type: nested_list
- contents:
- - title: Topic 1.
- items:
- - Description 1.
- - Description 2.
- - title: Topic 2.
- items:
- - Description 1.
- - Description 2.
-
-- title: Other Interests
- type: list
- contents:
- - Hobbies: Hobby 1, Hobby 2, etc.
diff --git a/_includes/cv/list.html b/_includes/cv/list.html
deleted file mode 100644
index 7562585..0000000
--- a/_includes/cv/list.html
+++ /dev/null
@@ -1,5 +0,0 @@
-
- {% for content in entry.contents %}
-
{{ content }}
- {% endfor %}
-
\ No newline at end of file
diff --git a/_includes/cv/map.html b/_includes/cv/map.html
deleted file mode 100644
index e0d1983..0000000
--- a/_includes/cv/map.html
+++ /dev/null
@@ -1,8 +0,0 @@
-
- {% for content in entry.contents %}
-
-
{{ content.name }}
-
{{ content.value }}
-
- {% endfor %}
-
\ No newline at end of file
diff --git a/_includes/cv/nested_list.html b/_includes/cv/nested_list.html
deleted file mode 100644
index 4778aca..0000000
--- a/_includes/cv/nested_list.html
+++ /dev/null
@@ -1,14 +0,0 @@
-
- {% for content in entry.contents %}
-
-
{{ content.title }}
- {% if content.items %}
-
- {% for subitem in content.items %}
-
{{ subitem }}
- {% endfor %}
-
- {% endif %}
-
- {% endfor %}
-
\ No newline at end of file
diff --git a/_includes/cv/time_table.html b/_includes/cv/time_table.html
deleted file mode 100644
index 123b9d0..0000000
--- a/_includes/cv/time_table.html
+++ /dev/null
@@ -1,59 +0,0 @@
-
- {% for content in entry.contents %}
-
-
- {% if content.year %}
-
-
- {{ content.year }}
-
-
- {% endif %}
-
- {% if content.title %}
-
{{content.title}}
- {% endif %}
- {% if content.institution %}
-
{{content.institution}}
- {% endif %}
- {% if content.description %}
-
- {% for item in content.description %}
-
- {% if item.contents %}
- {{ item.title }}
-
- {% for subitem in item.contents %}
-
{{ subitem }}
- {% endfor %}
-
- {% else %}
- {{ item }}
- {% endif %}
-
- {% endfor %}
-
- {% endif %}
- {% if content.items %}
-
- {% for item in content.items %}
-
- {% if item.contents %}
- {{ item.title }}
-
- {% for subitem in item.contents %}
-
{{ subitem }}
- {% endfor %}
-
- {% else %}
- {{ item }}
- {% endif %}
-
- {% endfor %}
-
- {% endif %}
-
-
-
- {% endfor %}
-
\ No newline at end of file
diff --git a/_includes/figure.html b/_includes/figure.html
deleted file mode 100644
index ffda4d1..0000000
--- a/_includes/figure.html
+++ /dev/null
@@ -1,26 +0,0 @@
-{%- assign img_path = include.path | remove: ".jpg" | remove: ".jpeg" | remove: ".png" | remove: ".tiff" -%}
-
-
\ No newline at end of file
diff --git a/_includes/footer.html b/_includes/footer.html
deleted file mode 100644
index 721d262..0000000
--- a/_includes/footer.html
+++ /dev/null
@@ -1,27 +0,0 @@
-{% if site.footer_fixed %}
-
-{%- else -%}
-
-{%- endif %}
\ No newline at end of file
diff --git a/_includes/head.html b/_includes/head.html
deleted file mode 100644
index 1661581..0000000
--- a/_includes/head.html
+++ /dev/null
@@ -1,31 +0,0 @@
-
- {% include metadata.html %}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- {% if site.icon.size < 3 %}
-
- {% elsif site.icon != blank %}
-
- {% endif %}
-
-
-
-
- {% if site.enable_darkmode %}
-
-
-
-
- {% endif %}
diff --git a/_includes/header.html b/_includes/header.html
deleted file mode 100644
index 092a046..0000000
--- a/_includes/header.html
+++ /dev/null
@@ -1,112 +0,0 @@
-
-
-
-
-
-
\ No newline at end of file
diff --git a/_includes/metadata.html b/_includes/metadata.html
deleted file mode 100644
index ce58cc3..0000000
--- a/_includes/metadata.html
+++ /dev/null
@@ -1,156 +0,0 @@
-{% if site.enable_google_verification or site.enable_bing_verification %}
-
- {% if site.enable_google_verification -%}
-
- {%- endif -%}
- {% if site.enable_bing_verification -%}
-
- {%- endif -%}
-{%- endif %}
-
-
-
-
-
-
- {%- if site.title == "blank" -%}
- {%- capture title -%}{{ site.first_name }} {{ site.middle_name }} {{ site.last_name }}{%- endcapture -%}
- {%- else -%}
- {%- capture title -%}{{ site.title }}{%- endcapture -%}
- {%- endif -%}
- {% if page.url == '/blog/index.html' %}
- {{ site.blog_nav_title }} | {{ title }}
- {%- elsif page.title != "blank" and page.url != "/" -%}
- {{ page.title }} | {{ title }}
- {%- else -%}
- {{ title }}
- {%- endif -%}
-
-
-
-{%- if page.keywords or site.keywords %}
-
-{%- endif %}
-
-{%- if site.serve_og_meta %}
-
-
-
-
-
-
-
- {% if page.og_image or site.og_image -%}
-
- {%- endif %}
-
-
-
-
-
-
- {% if page.og_image or site.og_image -%}
-
- {%- endif %}
- {% if site.twitter_username -%}
-
-
- {%- endif %}
-{%- endif %}
-
-{%- if site.serve_schema_org %}
-
-
- {%- comment -%} Social links generator for "sameAs schema" {%- endcomment %}
- {% assign sameaslinks = "" | split: "," %}
- {%- if site.orcid_id -%}
- {%- capture link -%}https://orcid.org/{{ site.orcid_id }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.scholar_userid -%}
- {%- capture link -%}https://scholar.google.com/citations?user={{ site.scholar_userid }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.publons_id -%}
- {%- capture link -%}https://publons.com/a/{{ site.publons_id }}/{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.research_gate_profile -%}
- {%- capture link -%}https://www.researchgate.net/profile/{{site.research_gate_profile}}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.github_username -%}
- {%- capture link -%}https://github.com/{{ site.github_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.linkedin_username -%}
- {%- capture link -%}https://www.linkedin.com/in/{{ site.linkedin_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.twitter_username -%}
- {%- capture link -%}https://twitter.com/{{ site.twitter_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.medium_username -%}
- {%- capture link -%}https://medium.com/@{{ site.medium_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.quora_username -%}
- {%- capture link -%}https://www.quora.com/profile/{{ site.quora_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.blogger_url -%}
- {%- capture link -%}{{ site.blogger_url }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.work_url -%}
- {%- capture link -%}{{ site.work_url }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.wikidata_id -%}
- {%- capture link -%}https://www.wikidata.org/wiki/{{ site.wikidata_id }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.strava_userid -%}
- {%- capture link -%}https://www.strava.com/athletes/{{ site.strava_userid }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.keybase_username -%}
- {%- capture link -%}https://keybase.io/{{ site.keybase_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.gitlab_username -%}
- {%- capture link -%}https://gitlab.com/{{ site.gitlab_username }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.dblp_url -%}
- {%- capture link -%}{{ site.dblp_url }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if site.stackoverflow_id -%}
- {%- capture link -%}https://stackoverflow.com/users/{{ site.stackoverflow_id }}{%- endcapture -%}
- {%- assign sameaslinks = sameaslinks | push: link -%}
- {%- endif -%}
- {%- if sameaslinks != blank -%}
- {%- assign sameaslinks = sameaslinks | split: "" -%}
- {%- endif -%}
-
-
-{%- endif %}
diff --git a/_includes/news.html b/_includes/news.html
deleted file mode 100644
index 307e532..0000000
--- a/_includes/news.html
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
- {%- for project in sorted_projects -%}
- {% include projects_horizontal.html %}
- {%- endfor %}
-
-
- {%- else -%}
-
- {%- for project in sorted_projects -%}
- {% include projects.html %}
- {%- endfor %}
-
- {%- endif -%}
-{%- endif -%}
-
diff --git a/_pages/_teaching.md b/_pages/_teaching.md
deleted file mode 100644
index 1a6c5be..0000000
--- a/_pages/_teaching.md
+++ /dev/null
@@ -1,12 +0,0 @@
----
-layout: page
-permalink: /teaching/
-title: teaching
-description: Materials for courses you taught. Replace this text with your description.
-nav: true
-nav_order: 4
----
-
-For now, this page is assumed to be a static description of your courses. You can convert it to a collection similar to `_projects/` so that you can have a dedicated page for each course.
-
-Organize your courses by years, topics, or universities, however you like!
diff --git a/_pages/about.md b/_pages/about.md
deleted file mode 100644
index 7ff6791..0000000
--- a/_pages/about.md
+++ /dev/null
@@ -1,33 +0,0 @@
----
-layout: about
-title: About
-permalink: /
-subtitle: Welcome to HKU NLP group! We are a group of researchers working on natural language processing in the Department of Computer Science at the University of Hong Kong.
-logo: group_name.png
-research: wordcloud.png
-
-profile:
- align: left #right
- image: group_photo_2022.jpeg
- image_cicular: false # crops the image to make it circular
- image_caption: Group members in Hong Kong as of September 12, 2022 @ Tai Long Wan
-
-
-
-
-news: true # includes a list of news items
-selected_papers: false # includes a list of papers marked as "selected={true}"
-social: true # includes social icons at the bottom of the page
-
----
-The current focus of the NLP group in HKU includes:
-• Pretraining algorithms, including novel objectives, neural network architectures and distillation methods;
-• Semantic parsing, natural language interfaces, human-computer interaction (HCI);
-• Dialog systems, long text generation and automatic evaluation;
-• Machine Translation, especially in the settings of simultaneous and multimodal MT.
-
-## Overview
-This blog post introduces a new perspective to understanding the **Random Feature Attention (RFA)** mechanism. We show that **1)** the conventional softmax attention can be equivalently rewritten as an **expectation over RFAs**, and that **2)** RFA is in fact a **self-normalized importance sampler** to estimate conventional softmax attention. This new perspective grounds the heuristic RFA approximation and also sheds light on how to generalize further and improve RFAs. More details can be found in our ICML paper .
-
-## Attention
-The attention mechanism has become a ubiquitous building block in modern deep learning models and brought great success across various domains, including natural language processing (NLP), computer vision (CV), bioinformatics, reinforcement learning, etc.
-Attention mechanisms take three different kinds of inputs: a set of $N$ query vectors $\mbQ \in \R^{N \times D}$, $M$ key vectors $\mbK \in \R^{M \times D}$ and value vectors $\mbV \in \R^{M \times D}$. In this work we focus on self-attention, where $M=N$ and all of queries, keys and values are obtained by projecting tokens of the same input sequence.
-
-For each query $\mbq_n$, conventional softmax attention computes the following quantity, We omit the commonly used scaling factor $1 / \sqrt{d}$ for simplicity as it can be merged into the computation of queries or keys.
-\begin{equation}
- \mathsf{SoftmaxAttn}\left(\mbq_{n},\mbK,\mbV\right)\coloneqq\sum_{m=1}^M\frac{\exp\left(\mbq_{n}^\top \mbk_{m} \right)}{\sum_{m'=1}^M \exp\left(\mbq_{n}^\top \mbk_{m'} \right)} \mbv_{m}^{\top}.
-\end{equation}
-Intuitively, softmax attention first compares the query against each key and then computes the average over value vectors weighted by the normalized query-key similarities. It is effective in capturing long-term dependencies across sequence elements and producing contextualized representations; however, it suffers from **quadratic** time and memory complexity due to the explicit computation of all $NM$ query-key pairs.
-
-
-## Random Feature Attention
-To reduce the computational complexity of softmax attention, researchers proposed to use **random features (RF)** to linearize softmax attention. In particular, they make use of the following identity to rewrite the **exponential kernel** as an expectation,
-\begin{equation}
- \exp(\mbx^\top \mby) = \mathbb{E}_{\omega \sim \mathcal{N}(\omega;0,\mathbf{I})}\left[\xi(\mbx,\omega)^\top\xi(\mby, \omega)\right], \label{eqn:identity}
-\end{equation}
-where $\xi(\cdot, \cdot): \R^D \times \R^D \rightarrow \R^l$, $l\geq 1$, is a non-linear **randomized mapping** projecting the input vector to a $l$-dimensional vector via a randomly drawn $\omega \sim \mathcal{N}(\omega;0,\mathbf{I})$. There are several parameterization choices of $\xi(\mbx,\omega)$ for the identity to hold; in this work we focus on the positive type $\xi(\mbx,\omega) = \exp{\left(\omega^\top \mbx - \frac{1}{2}\norm{\mbx}^2\right)}$ as proposed in . A classical choice of randomized mappings is to let $\xi(\mbx,\omega) = \exp{\left( \frac{1}{2}\norm{\mbx}^2\right)}\left[\sin{\left(\omega^\top \mbx\right)},\cos{\left(\omega^\top \mbx\right)}\right]^\top$ . Besides, there are other advanced randomized mappings enjoying more appealing properties; see for a more in-depth study.
-
-
-To estimate the expectation in \eqref{eqn:identity}, one can draw multiple Monte Carlo samples from $\mathcal{N}(\omega;0,\mathbf{I})$ such that $\exp(\mbx^{\top} \mby) \approx \frac{1}{S}\sum_{s=1}^S \xi(\mbx,\omega_s)^{\top}\xi(\mby, \omega_s)$. By substituting such approximation into the softmax attention, we obtain random feature attention (RFA) (also called Performer),
-$$
-\begin{align}
- \frac{\sum_{m=1}^M\exp\left(\mbq_{n}^\top \mbk_{m} \right)\mbv_{m}^{\top}}{\sum_{m'=1}^M \exp\left(\mbq_{n}^\top \mbk_{m'} \right)}
- &\approx
- \frac{\sum_{m=1}^M \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{m'=1}^M\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\xi(\mbk_{m'}, \omega_s)} \notag \\
- &=\frac{ \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)} \label{eqn:rfa}\\
- &\coloneqq \mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right) \notag.
-\end{align}
-$$
-Thanks to the linearized formulation, one can first pre-compute the corresponding key-value statistics $\sum_{m=1}^M\xi(\mbk_{m},\omega_s)\mbv_{m}^{\top}$ and $\sum_{m=1}^M\xi(\mbk_{m},\omega_s)$ once, and then reuse them for each query. Consequently, it achieves linear complexity in both time and memory with respect to the sequence length.
-
Why it is called random feature attention?
- This is due to the fact that the sample average can be written as $\mbphi(\mbx,\mbw)^\top \mbphi(\mby,\mbw)$, where $\mbphi(\mbx,\mbw) \coloneqq 1/\sqrt{S}[\xi(\mbx,\omega_1), \dots, \xi(\mbx, \omega_S)]^\top \in \R^{lS}$. The $\mbphi(\cdot,\cdot)$ can be considered as a feature map transforming the input vector to a new vector representation; as a result, $\mbphi(\cdot,\cdot)$ are conveniently referred to as random features.
-
-## The Biasedness of RFA
-RFA suffers from significant performance degradation across various tasks, as observed in many previous studies (e.g., see [here](#comp-tb)). Although computationally efficient, the reduced modeling capacity of RFA greatly limits its practical usage. Researchers try to improve the performance from different perspectives, such as
-- developing better random feature types ,
-- connecting it with fast weight programmers ,
-- incorporating relative information , and so on.
-
-In this work, we explore an orthogonal axis by re-examining the estimation bias of RFA. Our key observation is that RFA is a heuristic approximation to the **whole** softmax attention. Although the estimation of individual **exponential kernels** is unbiased, such estimation of a ratio of exponential kernels is not unbiased anymore. This is due to the non-linearity of ratios,
-
-Such bias not only incurs a potentially large approximation gap between RFA and softmax attention but also bottlenecks the effectiveness of unbiased kernel estimation.
-
-
-
- Our work aims to address the following research question:
- Given that we already know how to unbiasedly estimate exponential kernels, how do we construct an unbiased estimator for the whole softmax attention?
-
-
-
-## Randomized Attention: An Unbiased Estimator for Softmax Attention
-
-We answer this question in the affirmative and prove that softmax attention can be rewritten as an expectation of simple RFAs,
-$$
-\begin{equation}
-\mathsf{SoftmaxAttn}(\mbq_n, \mbK,\mbV) = \sum_{m} \frac{\exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m} \right)}{\sum_{m'} \exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m'} \right)} \mathbf{v}_{m}^{\top} = \mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right],\label{eqn:softmax_as_expectation}
-\end{equation}
-$$
-where
-$$
-\begin{align}
-p_n(\omega) &= \sum_{m=1}^M \frac{\exp\left( \mbq_n^\top\mbk_m \right)}{\sum_{m'=1}^M\exp\left( \mbq_n^\top\mbk_{m'} \right)} \mathcal{N}(\omega; \mbq_n + \mbk_m, \mathbf{I}), \label{eqn:ra-density} \\
-f_n(\omega) &= \frac{\xi(\mbq_n,\omega)^\top \sum_{m=1}^M \xi(\mbk_m, \omega) \mbv_{m}^{\top}}{\xi(\mbq_n,\omega)^\top \sum_{m'=1}^M \xi(\mbk_{m'}, \omega)} \label{eqn:ra-function}.
-\end{align}
-$$
-Intuitively,
-
-
$p_n(\omega)$ is a Gaussian mixture distribution whose component weights are exactly attention scores, while
-
$f_n(\omega)$ is an RFA, except that the linearized similarity between queries and keys is computed via individual randomized mappings (or equivalently, one-dimensional random features).
-
-
-
-Notably, our result can be viewed as a neat generalization of random feature approximation, which exhibits a high degree of symmetry:
-$$
-\begin{align}
- \exp(\mbq_n^\top \mbk_m)\mbv_m^\top &= \mathbb{E}_{q(\omega)}\left[\xi(\mbq_n,\omega)^\top\xi(\mbk_m, \omega)\mbv_m^\top\right] \notag \\
- \sum_{m} \frac{\exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m} \right)}{\sum_{m'} \exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m'} \right)} \mathbf{v}_{m}^{\top} &= \mathbb{E}_{p_n(\omega)}\left[\frac{\xi(\mbq_n,\omega)^\top \sum_{m=1}^M \xi(\mbk_m, \omega) \mbv_{m}^{\top}}{\xi(\mbq_n,\omega)^\top \sum_{m'=1}^M \xi(\mbk_{m'}, \omega)}\right].\notag
-\end{align}
-$$
-Another implication is that we can construct a Monte Carlo estimator to approximate softmax attention in an unbiased way. By drawing $\omega_n \sim p_n(\omega)$, we obtain
-$$
-\begin{align}
- \mathsf{SoftmaxAttn}(\mbq_n, \mbK,\mbV)
- &\approx \frac{\xi(\mbq_n,\omega_n)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_n) \mbv_{m}^{\top}}{ \xi(\mbq_n,\omega_n)^\top \sum_{m'=1}^M\xi(\mbk_{m'}, \omega_n)} \label{eqn:ra}\\
- &\coloneqq \mathsf{RA}\left(\mbq_{n},\mbK,\mbV\right) \notag
-\end{align}
-$$
-We name such estimator Randomized Attention (RA) since it computes similarity scores with individual randomized mappings (instead of concatenated features). To the best of our knowledge, this is the first result that generalizes the unbiased kernel estimation to unbiased attention estimation.
-
-
-
-
Remark:
- The proof of \eqref{eqn:softmax_as_expectation} is done by first reverse-engineering the formulation of RFA, equating it with self-normalized importance sampling (see below) and then completing the square of Gaussians to derive the density $p_n(\omega)$. The function $f_n(\omega)$ can be solved by substituting the density $p_n(\omega)$ into the equation. See the paper for a detailed proof.
-
-
-## RFA as a Self-normalized Importance Sampler
-The analysis above further reveals that RFA is a specific **self-normalized importance sampling** estimator to softmax attention.
-
-### Self-normalized Importance Sampling (SNIS)
-
-Importance sampling (IS) is a general approach to approximating expectation $\mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right]$ when it is difficult to directly draw samples from $p_n(\omega)$. In importance sampling, we use a proposal distribution $q(\omega)$ to draw samples and estimate the quantity as
-$$
-\mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right] = \mathbb{E}_{\omega \sim q(\omega)}\left[\frac{p_n(\omega)}{q(\omega)}f_n(\omega)\right] \approx \frac{1}{S} \sum_{s=1}^S \frac{p_n(\omega)}{q(\omega)} f_n(\omega_s),
-$$
-where $\omega_1, \dots, \omega_S \sim q(\omega)$. The self-normalized importance sampling (SNIS) is defined as
-$$
-\begin{equation}
- \mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right] \approx \frac{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}f(\omega_s)}{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}} = \sum_{s=1}^S\frac{\frac{p_n(\omega_s)}{q(\omega_s)}}{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}}f(\omega_s). \label{eqn:snis}
-\end{equation}
-$$
-The name self-normalized comes from the fact that the importance weights $p_n(\omega)/q(\omega)$ are explicitly normalized and sum to 1.
-
-
-
-
-
-### RFA as SNIS
-
Our key finding here is that the formulation of RFA can be exactly derived from SNIS. Supposing $p_n(\omega)$ and $f_n(\omega)$ are given in \eqref{eqn:ra-density} and \eqref{eqn:ra-function} respectively, and $q(\omega) = \mathcal{N}(\omega;0,\mathbf{I})$, we have
-$$
-\begin{align}
-\mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right)
-&= \frac{\sum_{s=1}^S\textcolor{strings}{\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}}{\sum_{s=1}^S \textcolor{keywords}{\xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)}} = \frac{ \sum_{s=1}^S\textcolor{strings}{\frac{p_n(\omega_s)}{q(\omega_s)} f(\omega_s)}}{ \sum_{s=1}^S\textcolor{keywords}{\frac{p_n(\omega_s)}{q(\omega_s)}}}. \label{eqn:rfa-as-snis}
-\end{align}
-$$
-This formulation provides a new understanding of RFA: it is just a specific instantiation of SNIS estimators for softmax attention, whose proposal distribution $q(\omega)$ is chosen to be standard Gaussian. This reveals one of the possible reasons why RFA does not work well in practice: The plain standard Gaussian proposal in RFA is far away from the true Gaussian mixture (as in RA), which might lead to a large approximation gap. More importantly, this view implies that we can generalize and extend RFA by using other proposal distributions or adopting other estimating schemes!
-
-## LARA: Generalizing Both RA and RFA
-So far, we have two types of estimators available for approximating softmax attention: unbiased RA and biased RFA. Besides the theoretical biasedness, how do they differ in terms of practical modeling behavior? We list a comprehensive comparison to better illustrate their main differences.
-
-- In terms of **expressiveness**:
- - ✔️ RA directly draws from the true distribution $p_n(\omega)$ \eqref{eqn:ra-density}. This makes the mechanism **adaptive** and **query-specific**, since the sampling distribution depends on the query vector. As a result, RA can **specialize** to each query and process the whole sequence at a finer-grained level.
- - ❌ RFA suffers from limited capacity, since there is a large discrepancy between the used proposal $q(\omega) = \mathcal{N}(\omega;0,\mathbf{I})$ and the true distribution $p_n(\omega)$; furthermore, $q(\omega)$ captures no contextual information, leading to low sample efficiency.
-- In terms of **efficiency**:
- - ❌ RA suffers from **quadratic** computational costs. Since the sampling distribution is distinct for each query, we have to draw at least $\mathcal{O}(N)$ samples for all queries; at the same time, we needs to sum over all $M$ key-value pairs at each sampled $\omega_n$ (see \eqref{eqn:ra}), which leads to $\mathcal{O}(NM)$ complexity overall, as is the case for softmax attention;
- - ✔️ RFA uses SNIS to avoid computing or sampling from $p_n(\omega)$, which require quadratic-time computation. Drawing from a simpler proposal distribution allows samples to be shared across queries and still resulting in a $\mathcal{O}(M)$ complexity.
-
-
- {% include figure.html path="assets/img/2022-07-12-lara-imgs/lara-as-combining-ra-and-rfa.png" class="img-fluid rounded z-depth-0" zoomable=true caption="A diagram of LARA that combines the strengths of both approaches." %}
-
-
-
-
-
-
-Motivated by the comparison, we propose LineAr-time Randomized Attention (LARA) that attempts to get the best of both worlds, combining both the efficiency of RFA and the expressiveness of RA.
-- On the one hand, LARA inherits the **SNIS** formulation as in RFA to achieve **linear complexity**;
-- On the other hand, its expressiveness is significantly improved towards RA via the following modifications:
- - The proposal distribution is data-dependent so that LARA can be **adaptive** with respect to the contextual information;
- - LARA adopts **multiple** proposal distributions, which can be combined in a **query-specific** manner.
-
-
-LARA takes the following form
-$$
-\begin{align}
-\mathsf{LARA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\sum_{c=1}^C\alpha_{nc}(\omega_c)\frac{p_n(\omega_c)}{q_c(\omega_c)} f_n(\omega_c)}{\sum_{c=1}^C\alpha_{nc}(\omega_c)\frac{p_n(\omega_c)}{q_c(\omega_c)}}.\label{eqn:lara}
-\end{align}
-$$
-Here,
-
-
$q_1(\omega), \dots, q_C(\omega)$ are $C$ different proposals that depend on different query and key information;
-
$\{\alpha_{nc}(\cdot)\}_{c=1}^C$ is a set of weights that controls the contribution of different proposals, which is exclusive to each query and satisfies $\sum_{c=1}^C \alpha_{nc}(\omega) = 1$;
-
as long as $C$ is smaller than $N$, the computational complexity of LARA is linear, that is, $\mathcal{O}(CN+CM)$.
-
-
-
-
Remark:
- We provide a detailed discussion about the parameterization of our proposal distributions in Appendix G.3 of our paper. To summarize, we find the key is to let different proposals depend on different sets of query information so that they could be as query-specific as possible. A good default is to divide the whole sequence into $C$ chunks, compute the mean of queries $\{\widetilde{\mbq}_c\}_{c=1}^C$ and keys $\{\widetilde{\mbk}_c\}_{c=1}^C$ within the same chunk, and set $q_c(\omega) = \mcN(\omega;\widetilde{\mbq}_c + \widetilde{\mbk}_c, \mathbf{I})$. We find this choice works well across various benchmarks.
-
-
-### A Unified View of LARA, RA, and RFA
-
LARA can be equivalently written in a similar way to RA and RFA. We spell it out here to see a systematic comparison among RA, LARA, and RFA:
-$$
-\begin{align}
-\mathsf{RA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\xi(\mbq_n,\omega_n)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_n) \mbv_{m}^{\top}}{ \xi(\mbq_n,\omega_n)^\top \sum_{m'=1}^M\xi(\mbk_{m'}, \omega_n)}, &&\textcolor{keywords}{\omega_n \sim p_n(\omega)}\notag\\
-\mathsf{LARA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\sum_{c=1}^C \textcolor{strings}{\alpha'_{nc}(\omega_c)} \xi(\mbq_n,\omega_c)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_c) \mbv_{m}^{\top}}{\sum_{c=1}^C \textcolor{strings}{\alpha'_{nc}(\omega_c)} \xi(\mbq_n,\omega_c)^\top \sum_{m=1}^M \xi(\mbk_{m}, \omega_c)}, &&\textcolor{keywords}{\omega_c \sim q_c(\omega)}\notag\\
-\mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{ \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)}, &&\textcolor{keywords}{\omega_1,\dots,\omega_S \sim \mcN(\omega;0, \mathbf{I})} \notag
-\end{align}
-$$
-where we denote $\alpha'_{nc}(\omega_c) \coloneqq \alpha_{nc}(\omega_c)\mcN(\omega_c;0, \mathbf{I})/q_c(\omega_c)$ to simplify the notation. Note that their major difference lies in the choice of sampling distributions.
-
-LARA is not designed to be a simple interpolation between RA and RFA; instead, it is a generalized estimation framework that includes both RA and RFA as its special cases. To see this,
-
-
LARA is equivalent to RA if $C = N$, $q_n(\omega) = p_n(\omega)$ and $\alpha_{nc}(\omega) = \delta_{nc}$ (that is, $\alpha_{nc}(\omega) = 1$ if $n = c$ and $0$ otherwise);
-
LARA is equivalent to RFA if $q_c(\omega) = \mcN(\omega;0,\mathbf{I})$ and $\alpha_{nc}(\cdot)$ is constant for all $c = 1,\dots,C$ and $n = 1,\dots,N$.
-
-With general proposals and weighting functions, LARA approximates softmax attention in a query-specific manner as in RA while achieving linear complexity as in RFA, effectively combining the advantages of both estimators. It is also easy to implement with a couple of lines of code.
-
-
-
-
-
-
-## Experimental Results
-
-To demonstrate the effectiveness of our approach, we first visualize the approximation error of LARA to the true softmax attention outputs. Our unbiased estimate, RA, achieves the lowest MSE among these three methods and gets very close to the true softmax attention; RFA (Performer) soon plateaus at large approximation error and does not improve even with more samples, possibly due to low sample efficiency. On the other hand, LARA exhibits much lower MSE than RFA and the approximation error continually decreases as the number of proposals increases.
-
-
- {% include figure.html path="assets/img/2022-07-12-lara-imgs/approx_error_deit_plot.png" class="img-fluid rounded z-depth-1" zoomable=true caption="Mean Squared Error (MSE) between the true softmax attention and different RF approximations under different numbers of
-samples (lower is better), which are evaluated on DeiT." %}
-
-
-
-We further verify the improved performance of LARA by conducting experiments across a wide range of data modalities, including images, videos, natural language texts, and a long-sequence benchmark. From the Table below, we observe that
-- RA performs competitively with conventional softmax attention, and
-- LARA greatly improves the performance of RFA and significantly reduces the performance gap between RFA and softmax attention.
-
-| Model | Complexity | Image Classification on ImageNet (🠅) | Video Recognition on SSv2 (🠅) | Machine Translation on WMT (🠅) | Long Range Arena suite (🠅) |
-|:---|:---:|:---:|:---:|:---:|:---:|
-| Softmax | $\mathcal{O}(N^2)$ | 79.9 | 66.5 | 27.5 | 59.08 |
-| RA | $\mathcal{O}(N^2)$ | 80.0 | 64.9 | 27.8 | 59.30 |
-| RFA | $\mathcal{O}(N)$ | 74.3 | 53.1 | 23.7 | 57.63 |
-| LARA | $\mathcal{O}(N)$ | **79.5** | **63.7** | **27.0** | **59.12** |
-
-LARA also enjoys much better scalability and could achieve SOTA results for image classification when applying it to advanced transformer architectures.
-
-
- {% include figure.html path="assets/img/2022-07-12-lara-imgs/imagenet-sota-lara.png" class="img-fluid rounded z-depth-1" zoomable=true caption="SOTA results on ImageNet-1k across various model architectures." %}
-
-
-
-
-Finally, we evaluate the empirical efficiency of different attention methods. We note that RA runs almost twice slower than softmax attention, while its linear variant LARA runs much faster and brings marginal computational overheads compared to RFA.
-
-
- {% include figure.html path="assets/img/2022-07-12-lara-imgs/mem-time-comparison.png" class="img-fluid rounded z-depth-1" zoomable=true caption="Empirical memory consumption (left) and running time (right) of different attention mechanisms under different sequence
-lengths. Metrics are measured relative to the true softmax attention." %}
-
-
-
-## Conclusion and Limitation
-In this work, we generalize the random feature attention (RFA) algorithm in two aspects:
-- On the one hand, we generalize the unbiased **kernel** estimation (RFA) to unbiased **attention** estimation (RA);
-- On the other hand, we uncover the self-normalized importance sampling nature of RFA and propose a general framework **LARA** that includes both RA and RFA as its special cases.
-
-LARA greatly improves the performance of RFA while also maintaining its efficiency of RFA. Our framework provides a novel perspective for understanding and improving RF-based attention approximation, which is also orthogonal to most previous work. At the same time, there are several limitations of our approach:
-- The choice of proposal distributions is sub-optimal. Although our modeling strategy enables a query-specific treatment as desired in RA, it needs to evaluate all the $C$ samples for each key-value pair, incurring a potential waste of computing. Future work might include more sophisticated implementations that use variable sample sets for different key-value pairs.
-- Currently, LARA is still a biased (but consistent) estimator for softmax attention. It would be interesting to adopt advanced sampling strategies (e.g., Markov chain Monte Carlo (MCMC), etc.) to derive lower-bias lower-variance estimators.
-- The proposal distribution should be carefully designed when dealing with auto-regressive modeling since it is non-trivial to apply the causal masking mechanism to LARA as in conventional softmax attention. Adapting the importance sampling formulation of LARA to support arbitrary auto-regressive modeling is also an interesting research direction.
-
-
-
diff --git a/_posts/_2015-03-15-formatting-and-links.md b/_posts/_2015-03-15-formatting-and-links.md
deleted file mode 100644
index 6a2d63e..0000000
--- a/_posts/_2015-03-15-formatting-and-links.md
+++ /dev/null
@@ -1,359 +0,0 @@
----
-layout: post
-title: a post with formatting and links
-date: 2015-03-15 16:40:16
-description: march & april, looking forward to summer
-tags: formatting links
-categories: sample-posts
-# redirect: /assets/pdf/example_pdf.pdf
----
-Jean shorts raw denim Vice normcore, art party High Life PBR skateboard stumptown vinyl kitsch. Four loko meh 8-bit, tousled banh mi tilde forage Schlitz dreamcatcher twee 3 wolf moon. Chambray asymmetrical paleo salvia, sartorial umami four loko master cleanse drinking vinegar brunch. Pinterest DIY authentic Schlitz, hoodie Intelligentsia butcher trust fund brunch shabby chic Kickstarter forage flexitarian. Direct trade cold-pressed meggings stumptown plaid, pop-up taxidermy. Hoodie XOXO fingerstache scenester Echo Park. Plaid ugh Wes Anderson, freegan pug selvage fanny pack leggings pickled food truck DIY irony Banksy.
-
-#### Hipster list
-
-
brunch
-
fixie
-
raybans
-
messenger bag
-
-
-Hoodie Thundercats retro, tote bag 8-bit Godard craft beer gastropub. Truffaut Tumblr taxidermy, raw denim Kickstarter sartorial dreamcatcher. Quinoa chambray slow-carb salvia readymade, bicycle rights 90's yr typewriter selfies letterpress cardigan vegan.
-
-
-
-Pug heirloom High Life vinyl swag, single-origin coffee four dollar toast taxidermy reprehenderit fap distillery master cleanse locavore. Est anim sapiente leggings Brooklyn ea. Thundercats locavore excepteur veniam eiusmod. Raw denim Truffaut Schlitz, migas sapiente Portland VHS twee Bushwick Marfa typewriter retro id keytar.
-
-
- We do not grow absolutely, chronologically. We grow sometimes in one dimension, and not in another, unevenly. We grow partially. We are relative. We are mature in one realm, childish in another.
- —Anais Nin
-
-
-Fap aliqua qui, scenester pug Echo Park polaroid irony shabby chic ex cardigan church-key Odd Future accusamus. Blog stumptown sartorial squid, gastropub duis aesthetic Truffaut vero. Pinterest tilde twee, odio mumblecore jean shorts lumbersexual.
-
-
-
-# Tweet
-An example of displaying a tweet:
-{% twitter https://twitter.com/rubygems/status/518821243320287232 %}
-
-# Timeline
-An example of pulling from a timeline:
-{% twitter https://twitter.com/jekyllrb maxwidth=500 limit=3 %}
-
-# Additional Details
-For more details on using the plugin visit: [jekyll-twitter-plugin](https://github.com/rob-murray/jekyll-twitter-plugin)
-
-
-This theme supports generating various diagrams from a text description using [jekyll-diagrams](https://github.com/zhustec/jekyll-diagrams){:target="\_blank"} plugin.
-Below, we generate a few examples of such diagrams using languages such as [mermaid](https://mermaid-js.github.io/mermaid/){:target="\_blank"}, [plantuml](https://plantuml.com/){:target="\_blank"}, [vega-lite](https://vega.github.io/vega-lite/){:target="\_blank"}, etc.
-
-**Note:** different diagram-generation packages require external dependencies to be installed on your machine.
-Also, be mindful of that because of diagram generation the fist time you build your Jekyll website after adding new diagrams will be SLOW.
-For any other details, please refer to [jekyll-diagrams](https://github.com/zhustec/jekyll-diagrams){:target="\_blank"} README.
-
-
-## Mermaid
-
-Install mermaid using `node.js` package manager `npm` by running the following command:
-```bash
-npm install -g mermaid.cli
-```
-
-The diagram below was generated by the following code:
-
-{% raw %}
-```
-{% mermaid %}
-sequenceDiagram
- participant John
- participant Alice
- Alice->>John: Hello John, how are you?
- John-->>Alice: Great!
-{% endmermaid %}
-```
-{% endraw %}
-
-{% mermaid %}
-sequenceDiagram
- participant John
- participant Alice
- Alice->>John: Hello John, how are you?
- John-->>Alice: Great!
-{% endmermaid %}
-
-
-
-A sample blog page that demonstrates the accessing of github meta data.
-
-## What does Github-MetaData do?
-* Propagates the site.github namespace with repository metadata
-* Setting site variables :
- * site.title
- * site.description
- * site.url
- * site.baseurl
-* Accessing the metadata - duh.
-* Generating edittable links.
-
-## Additional Reading
-* If you're recieving incorrect/missing data, you may need to perform a Github API authentication.
-* Go through this README for more details on the topic.
-* This page highlights all the feilds you can access with github-metadata.
-
-
-## Example MetaData
-* Host Name : {{ site.github.hostname }}
-* URL : {{ site.github.url }}
-* BaseURL : {{ site.github.baseurl }}
-* Archived : {{ site.github.archived}}
-* Contributors :
-{% for contributor in site.github.contributors %}
- * {{ contributor.login }}
-{% endfor %}
-
-
-This theme supports rendering beautiful math in inline and display modes using [MathJax 3](https://www.mathjax.org/) engine. You just need to surround your math expression with `$$`, like `$$ E = mc^2 $$`. If you leave it inside a paragraph, it will produce an inline expression, just like $$ E = mc^2 $$.
-
-To use display mode, again surround your expression with `$$` and place it as a separate paragraph. Here is an example:
-
-$$
-\sum_{k=1}^\infty |\langle x, e_k \rangle|^2 \leq \|x\|^2
-$$
-
-You can also use `\begin{equation}...\end{equation}` instead of `$$` for display mode math.
-MathJax will automatically number equations:
-
-\begin{equation}
-\label{eq:cauchy-schwarz}
-\left( \sum_{k=1}^n a_k b_k \right)^2 \leq \left( \sum_{k=1}^n a_k^2 \right) \left( \sum_{k=1}^n b_k^2 \right)
-\end{equation}
-
-and by adding `\label{...}` inside the equation environment, we can now refer to the equation using `\eqref`.
-
-Note that MathJax 3 is [a major re-write of MathJax](https://docs.mathjax.org/en/latest/upgrading/whats-new-3.0.html) that brought a significant improvement to the loading and rendering speed, which is now [on par with KaTeX](http://www.intmath.com/cg5/katex-mathjax-comparison.php).
-
-This is an example post with image galleries.
-
-
-
- {% include figure.html path="assets/img/9.jpg" class="img-fluid rounded z-depth-1" %}
-
-
- {% include figure.html path="assets/img/7.jpg" class="img-fluid rounded z-depth-1" %}
-
-
-
- A simple, elegant caption looks good between image rows, after each row, or doesn't have to be there at all.
-
-
-Images can be made zoomable.
-Simply add `data-zoomable` to `` tags that you want to make zoomable.
-
-
-
-This theme implements a built-in Jekyll feature, the use of Rouge, for syntax highlighting.
-It supports more than 100 languages.
-This example is in C++.
-All you have to do is wrap your code in a liquid tag:
-
-{% raw %}
-{% highlight c++ linenos %} code code code {% endhighlight %}
-{% endraw %}
-
-The keyword `linenos` triggers display of line numbers.
-Produces something like this:
-
-{% highlight c++ linenos %}
-
-int main(int argc, char const \*argv[])
-{
- string myString;
-
- cout << "input a string: ";
- getline(cin, myString);
- int length = myString.length();
-
- char charArray = new char * [length];
-
- charArray = myString;
- for(int i = 0; i < length; ++i){
- cout << charArray[i] << " ";
- }
-
- return 0;
-}
-
-{% endhighlight %}
-
-
-## Citations
-
-Citations are then used in the article body with the `` tag.
-The key attribute is a reference to the id provided in the bibliography.
-The key attribute can take multiple ids, separated by commas.
-
-The citation is presented inline like this: (a number that displays more information on hover).
-If you have an appendix, a bibliography is automatically created and populated in it.
-
-## Code Blocks
-
-Syntax highlighting is provided within `` tags.
-An example of inline code snippets: `let x = 10;`.
-For larger blocks of code, add a `block` attribute:
-
-
- var x = 25;
- function(x) {
- return x * x;
- }
-
-
-**Note:** `` blocks do not look well in the dark mode.
-You can always use the default code-highlight using the `highlight` liquid tag:
-
-{% highlight javascript %}
-var x = 25;
-function(x) {
- return x * x;
-}
-{% endhighlight %}
-
-***
-
-
-
-***
-
-## Other Typography?
-
-Emphasis, aka italics, with *asterisks* (`*asterisks*`) or _underscores_ (`_underscores_`).
-
-Strong emphasis, aka bold, with **asterisks** or __underscores__.
-
-Combined emphasis with **asterisks and _underscores_**.
-
-Strikethrough uses two tildes. ~~Scratch this.~~
-
-1. First ordered list item
-2. Another item
-⋅⋅* Unordered sub-list.
-1. Actual numbers don't matter, just that it's a number
-⋅⋅1. Ordered sub-list
-4. And another item.
-
-⋅⋅⋅You can have properly indented paragraphs within list items. Notice the blank line above, and the leading spaces (at least one, but we'll use three here to also align the raw Markdown).
-
-⋅⋅⋅To have a line break without a paragraph, you will need to use two trailing spaces.⋅⋅
-⋅⋅⋅Note that this line is separate, but within the same paragraph.⋅⋅
-⋅⋅⋅(This is contrary to the typical GFM line break behaviour, where trailing spaces are not required.)
-
-* Unordered list can use asterisks
-- Or minuses
-+ Or pluses
-
-[I'm an inline-style link](https://www.google.com)
-
-[I'm an inline-style link with title](https://www.google.com "Google's Homepage")
-
-[I'm a reference-style link][Arbitrary case-insensitive reference text]
-
-[I'm a relative reference to a repository file](../blob/master/LICENSE)
-
-[You can use numbers for reference-style link definitions][1]
-
-Or leave it empty and use the [link text itself].
-
-URLs and URLs in angle brackets will automatically get turned into links.
-http://www.example.com or and sometimes
-example.com (but not on Github, for example).
-
-Some text to show that the reference links can follow later.
-
-[arbitrary case-insensitive reference text]: https://www.mozilla.org
-[1]: http://slashdot.org
-[link text itself]: http://www.reddit.com
-
-Here's our logo (hover to see the title text):
-
-Inline-style:
-![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1")
-
-Reference-style:
-![alt text][logo]
-
-[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2"
-
-Inline `code` has `back-ticks around` it.
-
-```javascript
-var s = "JavaScript syntax highlighting";
-alert(s);
-```
-
-```python
-s = "Python syntax highlighting"
-print s
-```
\ No newline at end of file
diff --git a/_projects/1_project.md b/_projects/1_project.md
deleted file mode 100644
index 5a95b9a..0000000
--- a/_projects/1_project.md
+++ /dev/null
@@ -1,80 +0,0 @@
----
-layout: page
-title: project 1
-description: a project with a background image
-img: assets/img/12.jpg
-importance: 1
-category: work
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-```
-{% endraw %}
diff --git a/_projects/2_project.md b/_projects/2_project.md
deleted file mode 100644
index 4a26614..0000000
--- a/_projects/2_project.md
+++ /dev/null
@@ -1,80 +0,0 @@
----
-layout: page
-title: project 2
-description: a project with a background image
-img: assets/img/3.jpg
-importance: 2
-category: work
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-```
-{% endraw %}
diff --git a/_projects/3_project.md b/_projects/3_project.md
deleted file mode 100644
index 56968db..0000000
--- a/_projects/3_project.md
+++ /dev/null
@@ -1,81 +0,0 @@
----
-layout: page
-title: project 3
-description: a project that redirects to another website
-img: assets/img/7.jpg
-redirect: https://unsplash.com
-importance: 3
-category: work
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-```
-{% endraw %}
diff --git a/_projects/4_project.md b/_projects/4_project.md
deleted file mode 100644
index 96eeb0e..0000000
--- a/_projects/4_project.md
+++ /dev/null
@@ -1,80 +0,0 @@
----
-layout: page
-title: project 4
-description: another without an image
-img:
-importance: 3
-category: fun
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-```
-{% endraw %}
diff --git a/_projects/5_project.md b/_projects/5_project.md
deleted file mode 100644
index aa48810..0000000
--- a/_projects/5_project.md
+++ /dev/null
@@ -1,80 +0,0 @@
----
-layout: page
-title: project 5
-description: a project with a background image
-img: assets/img/1.jpg
-importance: 3
-category: fun
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-```
-{% endraw %}
diff --git a/_projects/6_project.md b/_projects/6_project.md
deleted file mode 100644
index 3d8d04d..0000000
--- a/_projects/6_project.md
+++ /dev/null
@@ -1,80 +0,0 @@
----
-layout: page
-title: project 6
-description: a project with no image
-img:
-importance: 4
-category: fun
----
-
-Every project has a beautiful feature showcase page.
-It's easy to include images in a flexible 3-column grid format.
-Make your photos 1/3, 2/3, or full width.
-
-To give your project a background in the portfolio page, just add the img tag to the front matter like so:
-
- ---
- layout: page
- title: project
- description: a project with a background image
- img: /assets/img/12.jpg
- ---
-
-
- Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
-
- This image can also have a caption. It's like magic.
-
-
-You can also put regular text between your rows of images.
-Say you wanted to write a little bit about your project before you posted the rest of the images.
-You describe how you toiled, sweated, *bled* for your project, and then... you reveal it's glory in the next row of images.
-
-
-
- You can also have artistically styled 2/3 + 1/3 images, like these.
-
-
-
-The code is simple.
-Just wrap your images with `
` and place them inside `
` (read more about the Bootstrap Grid system).
-To make images responsive, add `img-fluid` class to each; for rounded corners and shadows use `rounded` and `z-depth-1` classes.
-Here's the code for the last row of images above:
-
-{% raw %}
-```html
-
-
-`, false);
-
- class FootnoteList extends T$6(HTMLElement) {
-
- connectedCallback() {
- super.connectedCallback();
-
- this.list = this.root.querySelector('ol');
- // footnotes list is initially hidden
- this.root.style.display = 'none';
- // look through document and register existing footnotes
- // Store.subscribeTo('footnotes', (footnote) => {
- // this.renderFootnote(footnote);
- // });
- }
-
- // TODO: could optimize this to accept individual footnotes?
- set footnotes(footnotes) {
- this.list.innerHTML = '';
- if (footnotes.length) {
- // ensure footnote list is visible
- this.root.style.display = '';
-
- for (const footnote of footnotes) {
- // construct and append list item to show footnote
- const listItem = document.createElement('li');
- listItem.id = footnote.id + '-listing';
- listItem.innerHTML = footnote.innerHTML;
-
- const backlink = document.createElement('a');
- backlink.setAttribute('class', 'footnote-backlink');
- backlink.textContent = '[↩]';
- backlink.href = '#' + footnote.id;
-
- listItem.appendChild(backlink);
- this.list.appendChild(listItem);
- }
- } else {
- // ensure footnote list is invisible
- this.root.style.display = 'none';
- }
- }
-
- }
-
- // Copyright 2018 The Distill Template Authors
-
- const T$7 = Template('d-hover-box', `
-
-
-
-
-
-
-
-`);
-
- class HoverBox extends T$7(HTMLElement) {
-
- constructor() {
- super();
- }
-
- connectedCallback() {
-
- }
-
- listen(element) {
- // console.log(element)
- this.bindDivEvents(this);
- this.bindTriggerEvents(element);
- // this.style.display = "block";
- }
-
- bindDivEvents(element) {
- // For mice, same behavior as hovering on links
- element.addEventListener('mouseover', () => {
- if (!this.visible) this.showAtNode(element);
- this.stopTimeout();
- });
- element.addEventListener('mouseout', () => {
- this.extendTimeout(500);
- });
- // Don't trigger body touchstart event when touching within box
- element.addEventListener('touchstart', (event) => {
- event.stopPropagation();
- }, {passive: true});
- // Close box when touching outside box
- document.body.addEventListener('touchstart', () => {
- this.hide();
- }, {passive: true});
- }
-
- bindTriggerEvents(node) {
- node.addEventListener('mouseover', () => {
- if (!this.visible) {
- this.showAtNode(node);
- }
- this.stopTimeout();
- });
-
- node.addEventListener('mouseout', () => {
- this.extendTimeout(300);
- });
-
- node.addEventListener('touchstart', (event) => {
- if (this.visible) {
- this.hide();
- } else {
- this.showAtNode(node);
- }
- // Don't trigger body touchstart event when touching link
- event.stopPropagation();
- }, {passive: true});
- }
-
- show(position) {
- this.visible = true;
- this.style.display = 'block';
- // 10px extra offset from element
- this.style.top = Math.round(position[1] + 10) + 'px';
- }
-
- showAtNode(node) {
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop
- const bbox = node.getBoundingClientRect();
- this.show([node.offsetLeft + bbox.width, node.offsetTop + bbox.height]);
- }
-
- hide() {
- this.visible = false;
- this.style.display = 'none';
- this.stopTimeout();
- }
-
- stopTimeout() {
- if (this.timeout) {
- clearTimeout(this.timeout);
- }
- }
-
- extendTimeout(time) {
- this.stopTimeout();
- this.timeout = setTimeout(() => {
- this.hide();
- }, time);
- }
-
- }
-
- // Copyright 2018 The Distill Template Authors
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
-
- class Title extends HTMLElement {
- static get is() { return 'd-title'; }
- }
-
- // Copyright 2018 The Distill Template Authors
-
- const T$8 = Template('d-references', `
-
-`, false);
-
- class References extends T$8(HTMLElement) {
-
- }
-
- // Copyright 2018 The Distill Template Authors
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
-
- class TOC extends HTMLElement {
-
- static get is() { return 'd-toc'; }
-
- connectedCallback() {
- if (!this.getAttribute('prerendered')) {
- window.onload = () => {
- const article = document.querySelector('d-article');
- const headings = article.querySelectorAll('h2, h3');
- renderTOC(this, headings);
- };
- }
- }
-
- }
-
- function renderTOC(element, headings) {
-
- let ToC =`
-
-
-
Table of contents
-
`;
-
- for (const el of headings) {
- // should element be included in TOC?
- const isInTitle = el.parentElement.tagName == 'D-TITLE';
- const isException = el.getAttribute('no-toc');
- if (isInTitle || isException) continue;
- // create TOC entry
- const title = el.textContent;
- const link = '#' + el.getAttribute('id');
-
- let newLine = '
-`;
-
- // Copyright 2018 The Distill Template Authors
-
- const T$b = Template('distill-header', headerTemplate, false);
-
- class DistillHeader extends T$b(HTMLElement) {
-
- }
-
- // Copyright 2018 The Distill Template Authors
-
- const styles$2 = `
-
-`;
-
- function appendixTemplate(frontMatter) {
- let html = styles$2;
-
- if (typeof frontMatter.githubUrl !== 'undefined') {
- html += `
-
Updates and Corrections
-
`;
- if (frontMatter.githubCompareUpdatesUrl) {
- html += `View all changes to this article since it was first published.`;
- }
- html += `
- If you see mistakes or want to suggest changes, please create an issue on GitHub.
Diagrams and text are licensed under Creative Commons Attribution CC-BY 4.0 with the source available on GitHub, unless noted otherwise. The figures that have been reused from other sources don’t fall under this license and can be recognized by a note in their caption: “Figure from …”.
- `;
- }
-
- if (typeof frontMatter.publishedDate !== 'undefined') {
- html += `
-
Citation
-
For attribution in academic contexts, please cite this work as
',n.githubCompareUpdatesUrl&&(t+=`View all changes to this article since it was first published.`),t+=`\n If you see mistakes or want to suggest changes, please create an issue on GitHub.
Diagrams and text are licensed under Creative Commons Attribution CC-BY 4.0 with the source available on GitHub, unless noted otherwise. The figures that have been reused from other sources don\u2019t fall under this license and can be recognized by a note in their caption: \u201cFigure from \u2026\u201d.
`)}}
+// Copyright 2018 The Distill Template Authors
+const co="\nd-citation-list {\n contain: style;\n}\n\nd-citation-list .references {\n grid-column: text;\n}\n\nd-citation-list .references .title {\n font-weight: 500;\n}\n";class ho extends HTMLElement{static get is(){return"d-citation-list"}connectedCallback(){this.hasAttribute("distill-prerendered")||(this.style.display="none")}set citations(n){x(this,n)}}var po=m(function(n){var t=function(n){function t(n,t,e,i,r){this.type=n,this.content=t,this.alias=e,this.length=0|(i||"").length,this.greedy=!!r}function e(n,i,a,s,l,u,d){for(var h in a)if(a.hasOwnProperty(h)&&a[h]){var p=a[h];p=Array.isArray(p)?p:[p];for(var f=0;fn.length)return;if(!(M instanceof t)){var T=1;if(y&&k!=i.tail.prev){if(g.lastIndex=S,!(N=g.exec(n)))break;var _=N.index+(b&&N[1]?N[1].length:0),C=N.index+N[0].length,A=S;for(A+=k.value.length;_>=A;)A+=(k=k.next).value.length;if(S=A-=k.value.length,k.value instanceof t)continue;for(var E=k;E!==i.tail&&(A1&&e(n,i,a,k.prev,S,!0,h+","+f),u)break}else if(u)break}}}}}function i(){var n={value:null,prev:null,next:null},t={value:null,prev:n,next:null};n.next=t,this.head=n,this.tail=t,this.length=0}function r(n,t,e){var i=t.next,r={value:e,prev:t,next:i};return t.next=r,i.prev=r,n.length++,r}function o(n,t,e){for(var i=t.next,r=0;r"+i.content+""+i.tag+">"},!n.document)return n.addEventListener?(c.disableWorkerMessageHandler||n.addEventListener("message",function(t){var e=JSON.parse(t.data),i=e.language,r=e.code,o=e.immediateClose;n.postMessage(c.highlight(r,c.languages[i],i)),o&&n.close()},!1),c):c;var d=c.util.currentScript();if(d&&(c.filename=d.src,d.hasAttribute("data-manual")&&(c.manual=!0)),!c.manual){var h=document.readyState;"loading"===h||"interactive"===h&&d&&d.defer?document.addEventListener("DOMContentLoaded",s):window.requestAnimationFrame?window.requestAnimationFrame(s):window.setTimeout(s,16)}return c}("undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{});n.exports&&(n.exports=t),void 0!==ro&&(ro.Prism=t),t.languages.markup={comment://,prolog:/<\?[\s\S]+?\?>/,doctype:{pattern:/"'[\]]|"[^"]*"|'[^']*')+(?:\[(?:(?!)*\]\s*)?>/i,greedy:!0},cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<%]+(?:\s(?:\s*[^\s>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+(?=[\s>]))|(?=[\s/>])))+)?\s*\/?>/i,greedy:!0,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+)/i,inside:{punctuation:[/^=/,{pattern:/^(\s*)["']|["']$/,lookbehind:!0}]}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/?[\da-z]{1,8};/i},t.languages.markup.tag.inside["attr-value"].inside.entity=t.languages.markup.entity,t.hooks.add("wrap",function(n){"entity"===n.type&&(n.attributes.title=n.content.replace(/&/,"&"))}),Object.defineProperty(t.languages.markup.tag,"addInlined",{value:function(n,e){var i={};i["language-"+e]={pattern:/(^$)/i,lookbehind:!0,inside:t.languages[e]},i.cdata=/^$/i;var r={"included-cdata":{pattern://i,inside:i}};r["language-"+e]={pattern:/[\s\S]+/,inside:t.languages[e]};var o={};o[n]={pattern:RegExp(/(<__[\s\S]*?>)(?:\s*|[\s\S])*?(?=<\/__>)/.source.replace(/__/g,function(){return n}),"i"),lookbehind:!0,greedy:!0,inside:r},t.languages.insertBefore("markup","cdata",o)}}),t.languages.xml=t.languages.extend("markup",{}),t.languages.html=t.languages.markup,t.languages.mathml=t.languages.markup,t.languages.svg=t.languages.markup,function(n){var t=/("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/;n.languages.css={comment:/\/\*[\s\S]*?\*\//,atrule:{pattern:/@[\w-]+[\s\S]*?(?:;|(?=\s*\{))/,inside:{rule:/^@[\w-]+/,"selector-function-argument":{pattern:/(\bselector\s*\((?!\s*\))\s*)(?:[^()]|\((?:[^()]|\([^()]*\))*\))+?(?=\s*\))/,lookbehind:!0,alias:"selector"}}},url:{pattern:RegExp("url\\((?:"+t.source+"|[^\n\r()]*)\\)","i"),greedy:!0,inside:{"function":/^url/i,punctuation:/^\(|\)$/}},selector:RegExp("[^{}\\s](?:[^{};\"']|"+t.source+")*?(?=\\s*\\{)"),string:{pattern:t,greedy:!0},property:/[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i,important:/!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:,]/},n.languages.css.atrule.inside.rest=n.languages.css;var e=n.languages.markup;e&&(e.tag.addInlined("style","css"),n.languages.insertBefore("inside","attr-value",{"style-attr":{pattern:/\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i,inside:{"attr-name":{pattern:/^\s*style/i,inside:e.tag.inside},punctuation:/^\s*=\s*['"]|['"]\s*$/,"attr-value":{pattern:/.+/i,inside:n.languages.css}},alias:"language-css"}},e.tag))}(t),t.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,boolean:/\b(?:true|false)\b/,"function":/\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},t.languages.javascript=t.languages.extend("clike",{"class-name":[t.languages.clike["class-name"],{pattern:/(^|[^$\w\xA0-\uFFFF])[_$A-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\.(?:prototype|constructor))/,lookbehind:!0}],keyword:[{pattern:/((?:^|})\s*)(?:catch|finally)\b/,lookbehind:!0},{pattern:/(^|[^.]|\.\.\.\s*)\b(?:as|async(?=\s*(?:function\b|\(|[$\w\xA0-\uFFFF]|$))|await|break|case|class|const|continue|debugger|default|delete|do|else|enum|export|extends|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)\b/,lookbehind:!0}],number:/\b(?:(?:0[xX](?:[\dA-Fa-f](?:_[\dA-Fa-f])?)+|0[bB](?:[01](?:_[01])?)+|0[oO](?:[0-7](?:_[0-7])?)+)n?|(?:\d(?:_\d)?)+n|NaN|Infinity)\b|(?:\b(?:\d(?:_\d)?)+\.?(?:\d(?:_\d)?)*|\B\.(?:\d(?:_\d)?)+)(?:[Ee][+-]?(?:\d(?:_\d)?)+)?/,"function":/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*(?:\.\s*(?:apply|bind|call)\s*)?\()/,operator:/--|\+\+|\*\*=?|=>|&&|\|\||[!=]==|<<=?|>>>?=?|[-+*/%&|^!=<>]=?|\.{3}|\?[.?]?|[~:]/}),t.languages.javascript["class-name"][0].pattern=/(\b(?:class|interface|extends|implements|instanceof|new)\s+)[\w.\\]+/,t.languages.insertBefore("javascript","keyword",{regex:{pattern:/((?:^|[^$\w\xA0-\uFFFF."'\])\s])\s*)\/(?:\[(?:[^\]\\\r\n]|\\.)*]|\\.|[^/\\\[\r\n])+\/[gimyus]{0,6}(?=(?:\s|\/\*[\s\S]*?\*\/)*(?:$|[\r\n,.;:})\]]|\/\/))/,lookbehind:!0,greedy:!0},"function-variable":{pattern:/#?[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*[=:]\s*(?:async\s*)?(?:\bfunction\b|(?:\((?:[^()]|\([^()]*\))*\)|[_$a-zA-Z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/,alias:"function"},parameter:[{pattern:/(function(?:\s+[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)?\s*\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\))/,lookbehind:!0,inside:t.languages.javascript},{pattern:/[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=>)/i,inside:t.languages.javascript},{pattern:/(\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*=>)/,lookbehind:!0,inside:t.languages.javascript},{pattern:/((?:\b|\s|^)(?!(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|undefined|var|void|while|with|yield)(?![$\w\xA0-\uFFFF]))(?:[_$A-Za-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*\s*)\(\s*)(?!\s)(?:[^()]|\([^()]*\))+?(?=\s*\)\s*\{)/,lookbehind:!0,inside:t.languages.javascript}],constant:/\b[A-Z](?:[A-Z_]|\dx?)*\b/}),t.languages.insertBefore("javascript","string",{"template-string":{pattern:/`(?:\\[\s\S]|\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}|(?!\${)[^\\`])*`/,greedy:!0,inside:{"template-punctuation":{pattern:/^`|`$/,alias:"string"},interpolation:{pattern:/((?:^|[^\\])(?:\\{2})*)\${(?:[^{}]|{(?:[^{}]|{[^}]*})*})+}/,lookbehind:!0,inside:{"interpolation-punctuation":{pattern:/^\${|}$/,alias:"punctuation"},rest:t.languages.javascript}},string:/[\s\S]+/}}}),t.languages.markup&&t.languages.markup.tag.addInlined("script","javascript"),t.languages.js=t.languages.javascript,"undefined"!=typeof self&&self.Prism&&self.document&&document.querySelector&&(self.Prism.fileHighlight=function(n){n=n||document;var e={js:"javascript",py:"python",rb:"ruby",ps1:"powershell",psm1:"powershell",sh:"bash",bat:"batch",h:"c",tex:"latex"};Array.prototype.slice.call(n.querySelectorAll("pre[data-src]")).forEach(function(n){if(!n.hasAttribute("data-src-loaded")){for(var i,r=n.getAttribute("data-src"),o=n,a=/\blang(?:uage)?-([\w-]+)\b/i;o&&!a.test(o.className);)o=o.parentNode;if(o&&(i=(n.className.match(a)||[,""])[1]),!i){var s=(r.match(/\.(\w+)$/)||[,""])[1];i=e[s]||s}var l=document.createElement("code");l.className="language-"+i,n.textContent="",l.textContent="Loading\u2026",n.appendChild(l);var u=new XMLHttpRequest;u.open("GET",r,!0),u.onreadystatechange=function(){4==u.readyState&&(u.status<400&&u.responseText?(l.textContent=u.responseText,t.highlightElement(l),n.setAttribute("data-src-loaded","")):u.status>=400?l.textContent="\u2716 Error "+u.status+" while fetching file: "+u.statusText:l.textContent="\u2716 Error: File does not exist or is empty")},u.send(null)}})},document.addEventListener("DOMContentLoaded",function(){self.Prism.fileHighlight()}))});Prism.languages.python={comment:{pattern:/(^|[^\\])#.*/,lookbehind:!0},"string-interpolation":{pattern:/(?:f|rf|fr)(?:("""|''')[\s\S]+?\1|("|')(?:\\.|(?!\2)[^\\\r\n])*\2)/i,greedy:!0,inside:{interpolation:{pattern:/((?:^|[^{])(?:{{)*){(?!{)(?:[^{}]|{(?!{)(?:[^{}]|{(?!{)(?:[^{}])+})+})+}/,lookbehind:!0,inside:{"format-spec":{pattern:/(:)[^:(){}]+(?=}$)/,lookbehind:!0},"conversion-option":{pattern:/![sra](?=[:}]$)/,alias:"punctuation"},rest:null}},string:/[\s\S]+/}},"triple-quoted-string":{pattern:/(?:[rub]|rb|br)?("""|''')[\s\S]+?\1/i,greedy:!0,alias:"string"},string:{pattern:/(?:[rub]|rb|br)?("|')(?:\\.|(?!\1)[^\\\r\n])*\1/i,greedy:!0},"function":{pattern:/((?:^|\s)def[ \t]+)[a-zA-Z_]\w*(?=\s*\()/g,lookbehind:!0},"class-name":{pattern:/(\bclass\s+)\w+/i,lookbehind:!0},decorator:{pattern:/(^\s*)@\w+(?:\.\w+)*/im,lookbehind:!0,alias:["annotation","punctuation"],inside:{punctuation:/\./}},keyword:/\b(?:and|as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|nonlocal|not|or|pass|print|raise|return|try|while|with|yield)\b/,builtin:/\b(?:__import__|abs|all|any|apply|ascii|basestring|bin|bool|buffer|bytearray|bytes|callable|chr|classmethod|cmp|coerce|compile|complex|delattr|dict|dir|divmod|enumerate|eval|execfile|file|filter|float|format|frozenset|getattr|globals|hasattr|hash|help|hex|id|input|int|intern|isinstance|issubclass|iter|len|list|locals|long|map|max|memoryview|min|next|object|oct|open|ord|pow|property|range|raw_input|reduce|reload|repr|reversed|round|set|setattr|slice|sorted|staticmethod|str|sum|super|tuple|type|unichr|unicode|vars|xrange|zip)\b/,boolean:/\b(?:True|False|None)\b/,number:/(?:\b(?=\d)|\B(?=\.))(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,punctuation:/[{}[\];(),.:]/},Prism.languages.python["string-interpolation"].inside.interpolation.inside.rest=Prism.languages.python,Prism.languages.py=Prism.languages.python,Prism.languages.clike={comment:[{pattern:/(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/,lookbehind:!0},{pattern:/(^|[^\\:])\/\/.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,greedy:!0},"class-name":{pattern:/(\b(?:class|interface|extends|implements|trait|instanceof|new)\s+|\bcatch\s+\()[\w.\\]+/i,lookbehind:!0,inside:{punctuation:/[.\\]/}},keyword:/\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,boolean:/\b(?:true|false)\b/,"function":/\w+(?=\()/,number:/\b0x[\da-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:e[+-]?\d+)?/i,operator:/[<>]=?|[!=]=?=?|--?|\+\+?|&&?|\|\|?|[?*/~^%]/,punctuation:/[{}[\];(),.:]/},Prism.languages.lua={comment:/^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,string:{pattern:/(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[\s\S]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,greedy:!0},number:/\b0x[a-f\d]+\.?[a-f\d]*(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|\.?\d*(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,keyword:/\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,"function":/(?!\d)\w+(?=\s*(?:[({]))/,operator:[/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,{pattern:/(^|[^.])\.\.(?!\.)/,lookbehind:!0}],punctuation:/[\[\](){},;]|\.+|:+/},function(n){var t="\\b(?:BASH|BASHOPTS|BASH_ALIASES|BASH_ARGC|BASH_ARGV|BASH_CMDS|BASH_COMPLETION_COMPAT_DIR|BASH_LINENO|BASH_REMATCH|BASH_SOURCE|BASH_VERSINFO|BASH_VERSION|COLORTERM|COLUMNS|COMP_WORDBREAKS|DBUS_SESSION_BUS_ADDRESS|DEFAULTS_PATH|DESKTOP_SESSION|DIRSTACK|DISPLAY|EUID|GDMSESSION|GDM_LANG|GNOME_KEYRING_CONTROL|GNOME_KEYRING_PID|GPG_AGENT_INFO|GROUPS|HISTCONTROL|HISTFILE|HISTFILESIZE|HISTSIZE|HOME|HOSTNAME|HOSTTYPE|IFS|INSTANCE|JOB|LANG|LANGUAGE|LC_ADDRESS|LC_ALL|LC_IDENTIFICATION|LC_MEASUREMENT|LC_MONETARY|LC_NAME|LC_NUMERIC|LC_PAPER|LC_TELEPHONE|LC_TIME|LESSCLOSE|LESSOPEN|LINES|LOGNAME|LS_COLORS|MACHTYPE|MAILCHECK|MANDATORY_PATH|NO_AT_BRIDGE|OLDPWD|OPTERR|OPTIND|ORBIT_SOCKETDIR|OSTYPE|PAPERSIZE|PATH|PIPESTATUS|PPID|PS1|PS2|PS3|PS4|PWD|RANDOM|REPLY|SECONDS|SELINUX_INIT|SESSION|SESSIONTYPE|SESSION_MANAGER|SHELL|SHELLOPTS|SHLVL|SSH_AUTH_SOCK|TERM|UID|UPSTART_EVENTS|UPSTART_INSTANCE|UPSTART_JOB|UPSTART_SESSION|USER|WINDOWID|XAUTHORITY|XDG_CONFIG_DIRS|XDG_CURRENT_DESKTOP|XDG_DATA_DIRS|XDG_GREETER_DATA_DIR|XDG_MENU_PREFIX|XDG_RUNTIME_DIR|XDG_SEAT|XDG_SEAT_PATH|XDG_SESSION_DESKTOP|XDG_SESSION_ID|XDG_SESSION_PATH|XDG_SESSION_TYPE|XDG_VTNR|XMODIFIERS)\\b",e={environment:{pattern:RegExp("\\$"+t),alias:"constant"},variable:[{pattern:/\$?\(\([\s\S]+?\)\)/,greedy:!0,inside:{variable:[{pattern:/(^\$\(\([\s\S]+)\)\)/,lookbehind:!0},/^\$\(\(/],number:/\b0x[\dA-Fa-f]+\b|(?:\b\d+\.?\d*|\B\.\d+)(?:[Ee]-?\d+)?/,operator:/--?|-=|\+\+?|\+=|!=?|~|\*\*?|\*=|\/=?|%=?|<<=?|>>=?|<=?|>=?|==?|&&?|&=|\^=?|\|\|?|\|=|\?|:/,punctuation:/\(\(?|\)\)?|,|;/}},{pattern:/\$\((?:\([^)]+\)|[^()])+\)|`[^`]+`/,greedy:!0,inside:{variable:/^\$\(|^`|\)$|`$/}},{pattern:/\$\{[^}]+\}/,greedy:!0,inside:{operator:/:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,punctuation:/[\[\]]/,environment:{pattern:RegExp("(\\{)"+t),lookbehind:!0,alias:"constant"}}},/\$(?:\w+|[#?*!@$])/],entity:/\\(?:[abceEfnrtv\\"]|O?[0-7]{1,3}|x[0-9a-fA-F]{1,2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})/};n.languages.bash={shebang:{pattern:/^#!\s*\/.*/,alias:"important"},comment:{pattern:/(^|[^"{\\$])#.*/,lookbehind:!0},"function-name":[{pattern:/(\bfunction\s+)\w+(?=(?:\s*\(?:\s*\))?\s*\{)/,lookbehind:!0,alias:"function"},{pattern:/\b\w+(?=\s*\(\s*\)\s*\{)/,alias:"function"}],"for-or-select":{pattern:/(\b(?:for|select)\s+)\w+(?=\s+in\s)/,alias:"variable",lookbehind:!0},"assign-left":{pattern:/(^|[\s;|&]|[<>]\()\w+(?=\+?=)/,inside:{environment:{pattern:RegExp("(^|[\\s;|&]|[<>]\\()"+t),lookbehind:!0,alias:"constant"}},alias:"variable",lookbehind:!0},string:[{pattern:/((?:^|[^<])<<-?\s*)(\w+?)\s*(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\2/,lookbehind:!0,greedy:!0,inside:e},{pattern:/((?:^|[^<])<<-?\s*)(["'])(\w+)\2\s*(?:\r?\n|\r)[\s\S]*?(?:\r?\n|\r)\3/,lookbehind:!0,greedy:!0},{pattern:/(^|[^\\](?:\\\\)*)(["'])(?:\\[\s\S]|\$\([^)]+\)|`[^`]+`|(?!\2)[^\\])*\2/,lookbehind:!0,greedy:!0,inside:e}],environment:{pattern:RegExp("\\$?"+t),alias:"constant"},variable:e.variable,"function":{pattern:/(^|[\s;|&]|[<>]\()(?:add|apropos|apt|aptitude|apt-cache|apt-get|aspell|automysqlbackup|awk|basename|bash|bc|bconsole|bg|bzip2|cal|cat|cfdisk|chgrp|chkconfig|chmod|chown|chroot|cksum|clear|cmp|column|comm|cp|cron|crontab|csplit|curl|cut|date|dc|dd|ddrescue|debootstrap|df|diff|diff3|dig|dir|dircolors|dirname|dirs|dmesg|du|egrep|eject|env|ethtool|expand|expect|expr|fdformat|fdisk|fg|fgrep|file|find|fmt|fold|format|free|fsck|ftp|fuser|gawk|git|gparted|grep|groupadd|groupdel|groupmod|groups|grub-mkconfig|gzip|halt|head|hg|history|host|hostname|htop|iconv|id|ifconfig|ifdown|ifup|import|install|ip|jobs|join|kill|killall|less|link|ln|locate|logname|logrotate|look|lpc|lpr|lprint|lprintd|lprintq|lprm|ls|lsof|lynx|make|man|mc|mdadm|mkconfig|mkdir|mke2fs|mkfifo|mkfs|mkisofs|mknod|mkswap|mmv|more|most|mount|mtools|mtr|mutt|mv|nano|nc|netstat|nice|nl|nohup|notify-send|npm|nslookup|op|open|parted|passwd|paste|pathchk|ping|pkill|pnpm|popd|pr|printcap|printenv|ps|pushd|pv|quota|quotacheck|quotactl|ram|rar|rcp|reboot|remsync|rename|renice|rev|rm|rmdir|rpm|rsync|scp|screen|sdiff|sed|sendmail|seq|service|sftp|sh|shellcheck|shuf|shutdown|sleep|slocate|sort|split|ssh|stat|strace|su|sudo|sum|suspend|swapon|sync|tac|tail|tar|tee|time|timeout|top|touch|tr|traceroute|tsort|tty|umount|uname|unexpand|uniq|units|unrar|unshar|unzip|update-grub|uptime|useradd|userdel|usermod|users|uudecode|uuencode|v|vdir|vi|vim|virsh|vmstat|wait|watch|wc|wget|whereis|which|who|whoami|write|xargs|xdg-open|yarn|yes|zenity|zip|zsh|zypper)(?=$|[)\s;|&])/,lookbehind:!0},keyword:{pattern:/(^|[\s;|&]|[<>]\()(?:if|then|else|elif|fi|for|while|in|case|esac|function|select|do|done|until)(?=$|[)\s;|&])/,lookbehind:!0},builtin:{pattern:/(^|[\s;|&]|[<>]\()(?:\.|:|break|cd|continue|eval|exec|exit|export|getopts|hash|pwd|readonly|return|shift|test|times|trap|umask|unset|alias|bind|builtin|caller|command|declare|echo|enable|help|let|local|logout|mapfile|printf|read|readarray|source|type|typeset|ulimit|unalias|set|shopt)(?=$|[)\s;|&])/,lookbehind:!0,alias:"class-name"},boolean:{pattern:/(^|[\s;|&]|[<>]\()(?:true|false)(?=$|[)\s;|&])/,lookbehind:!0},"file-descriptor":{pattern:/\B&\d\b/,alias:"important"},operator:{pattern:/\d?<>|>\||\+=|==?|!=?|=~|<<[<-]?|[&\d]?>>|\d?[<>]&?|&[>&]?|\|[&|]?|<=?|>=?/,inside:{"file-descriptor":{pattern:/^\d/,alias:"important"}}},punctuation:/\$?\(\(?|\)\)?|\.\.|[{}[\];\\]/,number:{pattern:/(^|\s)(?:[1-9]\d*|0)(?:[.,]\d+)?\b/,lookbehind:!0}};for(var i=["comment","function-name","for-or-select","assign-left","string","environment","function","keyword","builtin","boolean","file-descriptor","operator","punctuation","number"],r=e.variable[1].inside,o=0;o(?:>=?|=)?|<(?:<=?|=|-)?|:=|\.\.\./,number:/(?:\b0x[a-f\d]+|(?:\b\d+\.?\d*|\B\.\d+)(?:e[-+]?\d+)?)i?/i,string:{pattern:/(["'`])(?:\\[\s\S]|(?!\1)[^\\])*\1/,greedy:!0}}),delete Prism.languages.go["class-name"],function(n){function t(n,t){return n=n.replace(//g,function(){return e}),t&&(n=n+"|"+n.replace(/_/g,"\\*")),RegExp(/((?:^|[^\\])(?:\\{2})*)/.source+"(?:"+n+")")}var e=/(?:\\.|[^\\\n\r]|(?:\n|\r\n?)(?!\n|\r\n?))/.source,i=/(?:\\.|``.+?``|`[^`\r\n]+`|[^\\|\r\n`])+/.source,r=/\|?__(?:\|__)+\|?(?:(?:\n|\r\n?)|$)/.source.replace(/__/g,function(){return i}),o=/\|?[ \t]*:?-{3,}:?[ \t]*(?:\|[ \t]*:?-{3,}:?[ \t]*)+\|?(?:\n|\r\n?)/.source;n.languages.markdown=n.languages.extend("markup",{}),n.languages.insertBefore("markdown","prolog",{blockquote:{pattern:/^>(?:[\t ]*>)*/m,alias:"punctuation"},table:{pattern:RegExp("^"+r+o+"(?:"+r+")*","m"),inside:{"table-data-rows":{pattern:RegExp("^("+r+o+")(?:"+r+")*$"),lookbehind:!0,inside:{"table-data":{pattern:RegExp(i),inside:n.languages.markdown},punctuation:/\|/}},"table-line":{pattern:RegExp("^("+r+")"+o+"$"),lookbehind:!0,inside:{punctuation:/\||:?-{3,}:?/}},"table-header-row":{pattern:RegExp("^"+r+"$"),inside:{"table-header":{pattern:RegExp(i),alias:"important",inside:n.languages.markdown},punctuation:/\|/}}}},code:[{pattern:/((?:^|\n)[ \t]*\n|(?:^|\r\n?)[ \t]*\r\n?)(?: {4}|\t).+(?:(?:\n|\r\n?)(?: {4}|\t).+)*/,lookbehind:!0,alias:"keyword"},{pattern:/``.+?``|`[^`\r\n]+`/,alias:"keyword"},{pattern:/^```[\s\S]*?^```$/m,greedy:!0,inside:{"code-block":{pattern:/^(```.*(?:\n|\r\n?))[\s\S]+?(?=(?:\n|\r\n?)^```$)/m,lookbehind:!0},"code-language":{pattern:/^(```).+/,lookbehind:!0},punctuation:/```/}}],title:[{pattern:/\S.*(?:\n|\r\n?)(?:==+|--+)(?=[ \t]*$)/m,alias:"important",inside:{punctuation:/==+$|--+$/}},{pattern:/(^\s*)#+.+/m,lookbehind:!0,alias:"important",inside:{punctuation:/^#+|#+$/}}],hr:{pattern:/(^\s*)([*-])(?:[\t ]*\2){2,}(?=\s*$)/m,lookbehind:!0,alias:"punctuation"},list:{pattern:/(^\s*)(?:[*+-]|\d+\.)(?=[\t ].)/m,lookbehind:!0,alias:"punctuation"},"url-reference":{pattern:/!?\[[^\]]+\]:[\t ]+(?:\S+|<(?:\\.|[^>\\])+>)(?:[\t ]+(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\)))?/,inside:{variable:{pattern:/^(!?\[)[^\]]+/,lookbehind:!0},string:/(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\((?:\\.|[^)\\])*\))$/,punctuation:/^[\[\]!:]|[<>]/},alias:"url"},bold:{pattern:t(/__(?:(?!_)|_(?:(?!_))+_)+__/.source,!0),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^..)[\s\S]+(?=..$)/,lookbehind:!0,inside:{}},punctuation:/\*\*|__/}},italic:{pattern:t(/_(?:(?!_)|__(?:(?!_))+__)+_/.source,!0),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^.)[\s\S]+(?=.$)/,lookbehind:!0,inside:{}},punctuation:/[*_]/}},strike:{pattern:t(/(~~?)(?:(?!~))+?\2/.source,!1),lookbehind:!0,greedy:!0,inside:{content:{pattern:/(^~~?)[\s\S]+(?=\1$)/,lookbehind:!0,inside:{}},punctuation:/~~?/}},url:{pattern:t(/!?\[(?:(?!\]))+\](?:\([^\s)]+(?:[\t ]+"(?:\\.|[^"\\])*")?\)| ?\[(?:(?!\]))+\])/.source,!1),lookbehind:!0,greedy:!0,inside:{variable:{pattern:/(\[)[^\]]+(?=\]$)/,lookbehind:!0},content:{pattern:/(^!?\[)[^\]]+(?=\])/,lookbehind:!0,inside:{}},string:{pattern:/"(?:\\.|[^"\\])*"(?=\)$)/}}}}),["url","bold","italic","strike"].forEach(function(t){["url","bold","italic","strike"].forEach(function(e){t!==e&&(n.languages.markdown[t].inside.content.inside[e]=n.languages.markdown[e])})}),n.hooks.add("after-tokenize",function(n){function t(n){if(n&&"string"!=typeof n)for(var e=0,i=n.length;e]?|<(?:<=?|[=:])?|>(?:=|>>?=?)?|==?=?|[~\u2260\u2264\u2265]/,punctuation:/[{}[\];(),.:]/,constant:/\b(?:(?:NaN|Inf)(?:16|32|64)?)\b/};
+// Copyright 2018 The Distill Template Authors
+const fo=Or("d-code",`\n\n\n\n\n`);class go extends(Dr(fo(HTMLElement))){renderContent(){if(this.languageName=this.getAttribute("language"),!this.languageName)return void console.warn('You need to provide a language attribute to your block to let us know how to highlight your code; e.g.:\n zeros = np.zeros(shape).');const n=po.languages[this.languageName];if(n==undefined)return void console.warn(`Distill does not yet support highlighting your code block in "${this.languageName}'.`);let t=this.textContent;const e=this.shadowRoot.querySelector("#code-container");if(this.hasAttribute("block")){const n=(t=t.replace(/\n/,"")).match(/\s*/);if(t=(t=t.replace(new RegExp("\n"+n,"g"),"\n")).trim(),e.parentNode instanceof ShadowRoot){const n=document.createElement("pre");this.shadowRoot.removeChild(e),n.appendChild(e),this.shadowRoot.appendChild(n)}}e.className=`language-${this.languageName}`,e.innerHTML=po.highlight(t,n)}}
+// Copyright 2018 The Distill Template Authors
+const mo=Or("d-footnote",'\n\n\n\n
\n \n
\n\n\n\n \n\n\n');class bo extends(mo(HTMLElement)){constructor(){super();const n={childList:!0,characterData:!0,subtree:!0};new MutationObserver(this.notify).observe(this,n)}notify(){const n=new CustomEvent("onFootnoteChanged",{detail:this,bubbles:!0});document.dispatchEvent(n)}connectedCallback(){this.hoverBox=this.root.querySelector("d-hover-box"),window.customElements.whenDefined("d-hover-box").then(()=>{this.hoverBox.listen(this)}),bo.currentFootnoteId+=1;const n=bo.currentFootnoteId.toString();this.root.host.id="d-footnote-"+n;const t="dt-fn-hover-box-"+n;this.hoverBox.id=t;const e=this.root.querySelector("#fn-");e.setAttribute("id","fn-"+n),e.setAttribute("data-hover-ref",t),e.textContent=n}}bo.currentFootnoteId=0;
+// Copyright 2018 The Distill Template Authors
+const yo=Or("d-footnote-list","\n\n\n
Footnotes
\n\n",!1);class vo extends(yo(HTMLElement)){connectedCallback(){super.connectedCallback(),this.list=this.root.querySelector("ol"),this.root.style.display="none"}set footnotes(n){if(this.list.innerHTML="",n.length){this.root.style.display="";for(const t of n){const n=document.createElement("li");n.id=t.id+"-listing",n.innerHTML=t.innerHTML;const e=document.createElement("a");e.setAttribute("class","footnote-backlink"),e.textContent="[\u21a9]",e.href="#"+t.id,n.appendChild(e),this.list.appendChild(n)}}else this.root.style.display="none"}}
+// Copyright 2018 The Distill Template Authors
+const wo=Or("d-hover-box",'\n\n\n
\n
\n \n
\n
\n');class xo extends(wo(HTMLElement)){constructor(){super()}connectedCallback(){}listen(n){this.bindDivEvents(this),this.bindTriggerEvents(n)}bindDivEvents(n){n.addEventListener("mouseover",()=>{this.visible||this.showAtNode(n),this.stopTimeout()}),n.addEventListener("mouseout",()=>{this.extendTimeout(500)}),n.addEventListener("touchstart",n=>{n.stopPropagation()},{passive:!0}),document.body.addEventListener("touchstart",()=>{this.hide()},{passive:!0})}bindTriggerEvents(n){n.addEventListener("mouseover",()=>{this.visible||this.showAtNode(n),this.stopTimeout()}),n.addEventListener("mouseout",()=>{this.extendTimeout(300)}),n.addEventListener("touchstart",t=>{this.visible?this.hide():this.showAtNode(n),t.stopPropagation()},{passive:!0})}show(n){this.visible=!0,this.style.display="block",this.style.top=Math.round(n[1]+10)+"px"}showAtNode(n){const t=n.getBoundingClientRect();this.show([n.offsetLeft+t.width,n.offsetTop+t.height])}hide(){this.visible=!1,this.style.display="none",this.stopTimeout()}stopTimeout(){this.timeout&&clearTimeout(this.timeout)}extendTimeout(n){this.stopTimeout(),this.timeout=setTimeout(()=>{this.hide()},n)}}
+// Copyright 2018 The Distill Template Authors
+class ko extends HTMLElement{static get is(){return"d-title"}}
+// Copyright 2018 The Distill Template Authors
+const So=Or("d-references","\n\n",!1);class Mo extends(So(HTMLElement)){}
+// Copyright 2018 The Distill Template Authors
+class To extends HTMLElement{static get is(){return"d-toc"}connectedCallback(){this.getAttribute("prerendered")||(window.onload=(()=>{k(this,document.querySelector("d-article").querySelectorAll("h2, h3"))}))}}class _o extends HTMLElement{static get is(){return"d-figure"}static get readyQueue(){return _o._readyQueue||(_o._readyQueue=[]),_o._readyQueue}static addToReadyQueue(n){-1===_o.readyQueue.indexOf(n)&&(_o.readyQueue.push(n),_o.runReadyQueue())}static runReadyQueue(){const n=_o.readyQueue.sort((n,t)=>n._seenOnScreen-t._seenOnScreen).filter(n=>!n._ready).pop();n&&(n.ready(),requestAnimationFrame(_o.runReadyQueue))}constructor(){super(),this._ready=!1,this._onscreen=!1,this._offscreen=!0}connectedCallback(){this.loadsWhileScrolling=this.hasAttribute("loadsWhileScrolling"),_o.marginObserver.observe(this),_o.directObserver.observe(this)}disconnectedCallback(){_o.marginObserver.unobserve(this),_o.directObserver.unobserve(this)}static get marginObserver(){if(!_o._marginObserver){const n=window.innerHeight,t=Math.floor(2*n),e={rootMargin:t+"px 0px "+t+"px 0px",threshold:.01},i=_o.didObserveMarginIntersection,r=new IntersectionObserver(i,e);_o._marginObserver=r}return _o._marginObserver}static didObserveMarginIntersection(n){for(const t of n){const n=t.target;t.isIntersecting&&!n._ready&&_o.addToReadyQueue(n)}}static get directObserver(){return _o._directObserver||(_o._directObserver=new IntersectionObserver(_o.didObserveDirectIntersection,{rootMargin:"0px",threshold:[0,1]})),_o._directObserver}static didObserveDirectIntersection(n){for(const t of n){const n=t.target;t.isIntersecting?(n._seenOnScreen=new Date,n._offscreen&&n.onscreen()):n._onscreen&&n.offscreen()}}addEventListener(n,t){super.addEventListener(n,t),"ready"===n&&-1!==_o.readyQueue.indexOf(this)&&(this._ready=!1,_o.runReadyQueue()),"onscreen"===n&&this.onscreen()}ready(){this._ready=!0,_o.marginObserver.unobserve(this);const n=new CustomEvent("ready");this.dispatchEvent(n)}onscreen(){this._onscreen=!0,this._offscreen=!1;const n=new CustomEvent("onscreen");this.dispatchEvent(n)}offscreen(){this._onscreen=!1,this._offscreen=!0;const n=new CustomEvent("offscreen");this.dispatchEvent(n)}}if("undefined"!=typeof window){let n;_o.isScrolling=!1;const t=()=>{_o.isScrolling=!0,clearTimeout(n),n=setTimeout(()=>{_o.isScrolling=!1,_o.runReadyQueue()},500)};window.addEventListener("scroll",t,!0)}
+// Copyright 2018 The Distill Template Authors
+const Co="distill.pub",Ao=Or("d-interstitial",'\n\n\n
\n
\n
This article is in review.
\n
Do not share this URL or the contents of this article. Thank you!
\n \n
Enter the password we shared with you as part of the review process to view the article.
\n
\n
\n');class Eo extends(Ao(HTMLElement)){connectedCallback(){if(this.shouldRemoveSelf())this.parentElement.removeChild(this);else{this.root.querySelector("#interstitial-password-input").oninput=(n=>this.passwordChanged(n))}}passwordChanged(n){n.target.value===this.password&&(console.log("Correct password entered."),this.parentElement.removeChild(this),"undefined"!=typeof Storage&&(console.log("Saved that correct password was entered."),localStorage.setItem(this.localStorageIdentifier(),"true")))}shouldRemoveSelf(){return window&&window.location.hostname===Co?(console.warn("Interstitial found on production, hiding it."),!0):"undefined"!=typeof Storage&&"true"===localStorage.getItem(this.localStorageIdentifier())&&(console.log("Loaded that correct password was entered before; skipping interstitial."),!0)}localStorageIdentifier(){const n="interstitial-password-correct";return"distill-drafts"+(window?window.location.pathname:"-")+n}}var No=M(S).right,Lo=Math.sqrt(50),Do=Math.sqrt(10),Oo=Math.sqrt(2),Io=.7,Fo=1/Io,Ro="\\s*([+-]?\\d+)\\s*",Uo="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",$o="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Po=/^#([0-9a-f]{3,8})$/,Ho=new RegExp("^rgb\\("+[Ro,Ro,Ro]+"\\)$"),zo=new RegExp("^rgb\\("+[$o,$o,$o]+"\\)$"),qo=new RegExp("^rgba\\("+[Ro,Ro,Ro,Uo]+"\\)$"),jo=new RegExp("^rgba\\("+[$o,$o,$o,Uo]+"\\)$"),Bo=new RegExp("^hsl\\("+[Uo,$o,$o]+"\\)$"),Yo=new RegExp("^hsla\\("+[Uo,$o,$o,Uo]+"\\)$"),Wo={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};L(O,U,{copy:function(n){return Object.assign(new this.constructor,this,n)},displayable:function(){return this.rgb().displayable()},hex:I,formatHex:I,formatHsl:F,formatRgb:R,toString:R}),L(q,z,D(O,{brighter:function(n){return n=null==n?Fo:Math.pow(Fo,n),new q(this.r*n,this.g*n,this.b*n,this.opacity)},darker:function(n){return n=null==n?Io:Math.pow(Io,n),new q(this.r*n,this.g*n,this.b*n,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:j,formatHex:j,formatRgb:B,toString:B})),L(K,V,D(O,{brighter:function(n){return n=null==n?Fo:Math.pow(Fo,n),new K(this.h,this.s,this.l*n,this.opacity)},darker:function(n){return n=null==n?Io:Math.pow(Io,n),new K(this.h,this.s,this.l*n,this.opacity)},rgb:function(){var n=this.h%360+360*(this.h<0),t=isNaN(n)||isNaN(this.s)?0:this.s,e=this.l,i=e+(e<.5?e:1-e)*t,r=2*e-i;return new q(X(n>=240?n-240:n+120,r,i),X(n,r,i),X(n<120?n+240:n-120,r,i),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var n=this.opacity;return(1===(n=isNaN(n)?1:Math.max(0,Math.min(1,n)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===n?")":", "+n+")")}}));var Go=Math.PI/180,Vo=180/Math.PI,Ko=18,Xo=.96422,Zo=1,Qo=.82521,Jo=4/29,na=6/29,ta=3*na*na,ea=na*na*na;L(J,Q,D(O,{brighter:function(n){return new J(this.l+Ko*(null==n?1:n),this.a,this.b,this.opacity)},darker:function(n){return new J(this.l-Ko*(null==n?1:n),this.a,this.b,this.opacity)},rgb:function(){var n=(this.l+16)/116,t=isNaN(this.a)?n:n+this.a/500,e=isNaN(this.b)?n:n-this.b/200;return new q(en(3.1338561*(t=Xo*tn(t))-1.6168667*(n=Zo*tn(n))-.4906146*(e=Qo*tn(e))),en(-.9787684*t+1.9161415*n+.033454*e),en(.0719453*t-.2289914*n+1.4052427*e),this.opacity)}})),L(sn,an,D(O,{brighter:function(n){return new sn(this.h,this.c,this.l+Ko*(null==n?1:n),this.opacity)},darker:function(n){return new sn(this.h,this.c,this.l-Ko*(null==n?1:n),this.opacity)},rgb:function(){return ln(this).rgb()}}));var ia=-.14861,ra=1.78277,oa=-.29227,aa=-.90649,sa=1.97294,la=sa*aa,ua=sa*ra,ca=ra*oa-aa*ia;L(dn,cn,D(O,{brighter:function(n){return n=null==n?Fo:Math.pow(Fo,n),new dn(this.h,this.s,this.l*n,this.opacity)},darker:function(n){return n=null==n?Io:Math.pow(Io,n),new dn(this.h,this.s,this.l*n,this.opacity)},rgb:function(){var n=isNaN(this.h)?0:(this.h+120)*Go,t=+this.l,e=isNaN(this.s)?0:this.s*t*(1-t),i=Math.cos(n),r=Math.sin(n);return new q(255*(t+e*(ia*i+ra*r)),255*(t+e*(oa*i+aa*r)),255*(t+e*(sa*i)),this.opacity)}}));var da,ha=function gs(n){function t(n,t){var i=e((n=z(n)).r,(t=z(t)).r),r=e(n.g,t.g),o=e(n.b,t.b),a=mn(n.opacity,t.opacity);return function(t){return n.r=i(t),n.g=r(t),n.b=o(t),n.opacity=a(t),n+""}}var e=gn(n);return t.gamma=gs,t}(1),pa=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,fa=new RegExp(pa.source,"g"),ga=[0,1],ma=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;qn.prototype=jn.prototype,jn.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===undefined?"":Math.max(1,0|this.width))+(this.comma?",":"")+(this.precision===undefined?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var ba,ya,va,wa={"%":function(n,t){return(100*n).toFixed(t)},b:function(n){return Math.round(n).toString(2)},c:function(n){return n+""},d:function(n){return Math.round(n).toString(10)},e:function(n,t){return n.toExponential(t)},f:function(n,t){return n.toFixed(t)},g:function(n,t){return n.toPrecision(t)},o:function(n){return Math.round(n).toString(8)},p:function(n,t){return Wn(100*n,t)},r:Wn,s:Yn,X:function(n){return Math.round(n).toString(16).toUpperCase()},x:function(n){return Math.round(n).toString(16)}},xa=Array.prototype.map,ka=["y","z","a","f","p","n","\xb5","m","","k","M","G","T","P","E","Z","Y"];Kn({decimal:".",thousands:",",grouping:[3],currency:["$",""],minus:"-"});var Sa=new Date,Ma=new Date,Ta=et(function(){},function(n,t){n.setTime(+n+t)},function(n,t){return t-n});Ta.every=function(n){return n=Math.floor(n),isFinite(n)&&n>0?n>1?et(function(t){t.setTime(Math.floor(t/n)*n)},function(t,e){t.setTime(+t+e*n)},function(t,e){return(e-t)/n}):Ta:null};var _a=1e3,Ca=6e4,Aa=36e5,Ea=864e5,Na=6048e5,La=(et(function(n){n.setTime(n-n.getMilliseconds())},function(n,t){n.setTime(+n+t*_a)},function(n,t){return(t-n)/_a},function(n){return n.getUTCSeconds()}),et(function(n){n.setTime(n-n.getMilliseconds()-n.getSeconds()*_a)},function(n,t){n.setTime(+n+t*Ca)},function(n,t){return(t-n)/Ca},function(n){return n.getMinutes()}),et(function(n){n.setTime(n-n.getMilliseconds()-n.getSeconds()*_a-n.getMinutes()*Ca)},function(n,t){n.setTime(+n+t*Aa)},function(n,t){return(t-n)/Aa},function(n){return n.getHours()}),et(function(n){n.setHours(0,0,0,0)},function(n,t){n.setDate(n.getDate()+t)},function(n,t){return(t-n-(t.getTimezoneOffset()-n.getTimezoneOffset())*Ca)/Ea},function(n){return n.getDate()-1})),Da=it(0),Oa=it(1),Ia=(it(2),it(3),it(4)),Fa=(it(5),it(6),et(function(n){n.setDate(1),n.setHours(0,0,0,0)},function(n,t){n.setMonth(n.getMonth()+t)},function(n,t){return t.getMonth()-n.getMonth()+12*(t.getFullYear()-n.getFullYear())},function(n){return n.getMonth()}),et(function(n){n.setMonth(0,1),n.setHours(0,0,0,0)},function(n,t){n.setFullYear(n.getFullYear()+t)},function(n,t){return t.getFullYear()-n.getFullYear()},function(n){return n.getFullYear()}));Fa.every=function(n){return isFinite(n=Math.floor(n))&&n>0?et(function(t){t.setFullYear(Math.floor(t.getFullYear()/n)*n),t.setMonth(0,1),t.setHours(0,0,0,0)},function(t,e){t.setFullYear(t.getFullYear()+e*n)}):null};et(function(n){n.setUTCSeconds(0,0)},function(n,t){n.setTime(+n+t*Ca)},function(n,t){return(t-n)/Ca},function(n){return n.getUTCMinutes()}),et(function(n){n.setUTCMinutes(0,0,0)},function(n,t){n.setTime(+n+t*Aa)},function(n,t){return(t-n)/Aa},function(n){return n.getUTCHours()});var Ra=et(function(n){n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCDate(n.getUTCDate()+t)},function(n,t){return(t-n)/Ea},function(n){return n.getUTCDate()-1}),Ua=rt(0),$a=rt(1),Pa=(rt(2),rt(3),rt(4)),Ha=(rt(5),rt(6),et(function(n){n.setUTCDate(1),n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCMonth(n.getUTCMonth()+t)},function(n,t){return t.getUTCMonth()-n.getUTCMonth()+12*(t.getUTCFullYear()-n.getUTCFullYear())},function(n){return n.getUTCMonth()}),et(function(n){n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)},function(n,t){n.setUTCFullYear(n.getUTCFullYear()+t)},function(n,t){return t.getUTCFullYear()-n.getUTCFullYear()},function(n){return n.getUTCFullYear()}));Ha.every=function(n){return isFinite(n=Math.floor(n))&&n>0?et(function(t){t.setUTCFullYear(Math.floor(t.getUTCFullYear()/n)*n),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},function(t,e){t.setUTCFullYear(t.getUTCFullYear()+e*n)}):null};var za,qa,ja,Ba={"-":"",_:" ",0:"0"},Ya=/^\s*\d+/,Wa=/^%/,Ga=/[\\^$*+?|[\]().{}]/g;me({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var Va="%Y-%m-%dT%H:%M:%S.%LZ",Ka=(Date.prototype.toISOString||qa(Va),+new Date("2000-01-01T00:00:00.000Z")||ja(Va),{value:function(){}});we.prototype=ve.prototype={constructor:we,on:function(n,t){var e,i=this._,r=xe(n+"",i),o=-1,a=r.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw new Error("invalid callback: "+t);for(;++o0)for(var e,i,r=new Array(e),o=0;o=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(n){return this._names.indexOf(n)>=0}};var Ja={},ns=null;"undefined"!=typeof document&&("onmouseenter"in document.documentElement||(Ja={mouseenter:"mouseover",mouseleave:"mouseout"}));var ts=[null];or.prototype=ar.prototype={constructor:or,select:Ne,selectAll:Oe,filter:Fe,data:qe,enter:Ue,exit:je,join:Be,merge:Ye,order:We,sort:Ge,call:Ke,nodes:Xe,node:Ze,size:Qe,empty:Je,each:ni,attr:si,style:hi,property:bi,classed:_i,text:Ni,html:Ii,raise:Ri,lower:$i,append:Pi,insert:zi,remove:ji,clone:Wi,datum:Gi,on:Ji,dispatch:rr},br.prototype.on=function(){var n=this._.on.apply(this._,arguments);return n===this._?this:n};const es=Or("d-slider","\n\n\n
-`;
- }
-
- // Copyright 2018 The Distill Template Authors
-
- function Byline(dom, data) {
- const byline = dom.querySelector('d-byline');
- if (byline) {
- byline.innerHTML = bylineTemplate(data);
- }
- }
-
- // Copyright 2018 The Distill Template Authors
- //
- // Licensed under the Apache License, Version 2.0 (the "License");
- // you may not use this file except in compliance with the License.
- // You may obtain a copy of the License at
- //
- // http://www.apache.org/licenses/LICENSE-2.0
- //
- // Unless required by applicable law or agreed to in writing, software
- // distributed under the License is distributed on an "AS IS" BASIS,
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- // See the License for the specific language governing permissions and
- // limitations under the License.
-
- // no appendix -> add appendix
- // title in front, no h1 -> add it
- // no title in front, h1 -> read and put into frontMatter
- // footnote -> footnote list
- // break up bib
- // if citation, no bib-list -> add citation-list
-
- // if authors, no byline -> add byline
-
- function OptionalComponents(dom, data) {
- const body = dom.body;
- const article = body.querySelector('d-article');
-
- // If we don't have an article tag, something weird is going on—giving up.
- if (!article) {
- console.warn('No d-article tag found; skipping adding optional components!');
- return;
- }
-
- let byline = dom.querySelector('d-byline');
- if (!byline) {
- if (data.authors) {
- byline = dom.createElement('d-byline');
- body.insertBefore(byline, article);
- } else {
- console.warn('No authors found in front matter; please add them before submission!');
- }
- }
-
- let title = dom.querySelector('d-title');
- if (!title) {
- title = dom.createElement('d-title');
- body.insertBefore(title, byline);
- }
-
- let h1 = title.querySelector('h1');
- if (!h1) {
- h1 = dom.createElement('h1');
- h1.textContent = data.title;
- title.insertBefore(h1, title.firstChild);
- }
-
- const hasPassword = typeof data.password !== 'undefined';
- let interstitial = body.querySelector('d-interstitial');
- if (hasPassword && !interstitial) {
- const inBrowser = typeof window !== 'undefined';
- const onLocalhost = inBrowser && window.location.hostname.includes('localhost');
- if (!inBrowser || !onLocalhost) {
- interstitial = dom.createElement('d-interstitial');
- interstitial.password = data.password;
- body.insertBefore(interstitial, body.firstChild);
- }
- } else if (!hasPassword && interstitial) {
- interstitial.parentElement.removeChild(this);
- }
-
- let appendix = dom.querySelector('d-appendix');
- if (!appendix) {
- appendix = dom.createElement('d-appendix');
- dom.body.appendChild(appendix);
- }
-
- let footnoteList = dom.querySelector('d-footnote-list');
- if (!footnoteList) {
- footnoteList = dom.createElement('d-footnote-list');
- appendix.appendChild(footnoteList);
- }
-
- let citationList = dom.querySelector('d-citation-list');
- if (!citationList) {
- citationList = dom.createElement('d-citation-list');
- appendix.appendChild(citationList);
- }
-
- }
-
- var katex$1 = createCommonjsModule(function (module, exports) {
- (function(f){{module.exports=f();}})(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o= 0; --i) {
- tok = expansion[i];
- if (tok.text === "#") {
- if (i === 0) {
- throw new _ParseError2.default("Incomplete placeholder at end of macro body", tok);
- }
- tok = expansion[--i]; // next token on stack
- if (tok.text === "#") {
- // ## → #
- expansion.splice(i + 1, 1); // drop first #
- } else if (/^[1-9]$/.test(tok.text)) {
- // expansion.splice(i, 2, arg[0], arg[1], …)
- // to replace placeholder with the indicated argument.
- // TODO: use spread once we move to ES2015
- expansion.splice.apply(expansion, [i, 2].concat(args[tok.text - 1]));
- } else {
- throw new _ParseError2.default("Not a valid argument number", tok);
- }
- }
- }
- }
- this.stack = this.stack.concat(expansion);
- }
- }
- }, {
- key: "get",
- value: function get(ignoreSpace) {
- this.discardedWhiteSpace = [];
- var token = this.nextToken();
- if (ignoreSpace) {
- while (token.text === " ") {
- this.discardedWhiteSpace.push(token);
- token = this.nextToken();
- }
- }
- return token;
- }
-
- /**
- * Undo the effect of the preceding call to the get method.
- * A call to this method MUST be immediately preceded and immediately followed
- * by a call to get. Only used during mode switching, i.e. after one token
- * was got in the old mode but should get got again in a new mode
- * with possibly different whitespace handling.
- */
-
- }, {
- key: "unget",
- value: function unget(token) {
- this.stack.push(token);
- while (this.discardedWhiteSpace.length !== 0) {
- this.stack.push(this.discardedWhiteSpace.pop());
- }
- }
- }]);
- return MacroExpander;
- }();
-
- module.exports = MacroExpander;
-
- },{"./Lexer":26,"./ParseError":29,"./macros":44,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5,"object-assign":25}],28:[function(require,module,exports){
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- var _createClass2 = require("babel-runtime/helpers/createClass");
-
- var _createClass3 = _interopRequireDefault(_createClass2);
-
- var _fontMetrics2 = require("./fontMetrics");
-
- var _fontMetrics3 = _interopRequireDefault(_fontMetrics2);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- var BASESIZE = 6; /**
- * This file contains information about the options that the Parser carries
- * around with it while parsing. Data is held in an `Options` object, and when
- * recursing, a new `Options` object can be created with the `.with*` and
- * `.reset` functions.
- */
-
- var sizeStyleMap = [
- // Each element contains [textsize, scriptsize, scriptscriptsize].
- // The size mappings are taken from TeX with \normalsize=10pt.
- [1, 1, 1], // size1: [5, 5, 5] \tiny
- [2, 1, 1], // size2: [6, 5, 5]
- [3, 1, 1], // size3: [7, 5, 5] \scriptsize
- [4, 2, 1], // size4: [8, 6, 5] \footnotesize
- [5, 2, 1], // size5: [9, 6, 5] \small
- [6, 3, 1], // size6: [10, 7, 5] \normalsize
- [7, 4, 2], // size7: [12, 8, 6] \large
- [8, 6, 3], // size8: [14.4, 10, 7] \Large
- [9, 7, 6], // size9: [17.28, 12, 10] \LARGE
- [10, 8, 7], // size10: [20.74, 14.4, 12] \huge
- [11, 10, 9]];
-
- var sizeMultipliers = [
- // fontMetrics.js:getFontMetrics also uses size indexes, so if
- // you change size indexes, change that function.
- 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.2, 1.44, 1.728, 2.074, 2.488];
-
- var sizeAtStyle = function sizeAtStyle(size, style) {
- return style.size < 2 ? size : sizeStyleMap[size - 1][style.size - 1];
- };
-
- /**
- * This is the main options class. It contains the current style, size, color,
- * and font.
- *
- * Options objects should not be modified. To create a new Options with
- * different properties, call a `.having*` method.
- */
-
- var Options = function () {
- function Options(data) {
- (0, _classCallCheck3.default)(this, Options);
-
- this.style = data.style;
- this.color = data.color;
- this.size = data.size || BASESIZE;
- this.textSize = data.textSize || this.size;
- this.phantom = data.phantom;
- this.font = data.font;
- this.sizeMultiplier = sizeMultipliers[this.size - 1];
- this._fontMetrics = null;
- }
-
- /**
- * Returns a new options object with the same properties as "this". Properties
- * from "extension" will be copied to the new options object.
- */
-
-
- (0, _createClass3.default)(Options, [{
- key: "extend",
- value: function extend(extension) {
- var data = {
- style: this.style,
- size: this.size,
- textSize: this.textSize,
- color: this.color,
- phantom: this.phantom,
- font: this.font
- };
-
- for (var key in extension) {
- if (extension.hasOwnProperty(key)) {
- data[key] = extension[key];
- }
- }
-
- return new Options(data);
- }
-
- /**
- * Return an options object with the given style. If `this.style === style`,
- * returns `this`.
- */
-
- }, {
- key: "havingStyle",
- value: function havingStyle(style) {
- if (this.style === style) {
- return this;
- } else {
- return this.extend({
- style: style,
- size: sizeAtStyle(this.textSize, style)
- });
- }
- }
-
- /**
- * Return an options object with a cramped version of the current style. If
- * the current style is cramped, returns `this`.
- */
-
- }, {
- key: "havingCrampedStyle",
- value: function havingCrampedStyle() {
- return this.havingStyle(this.style.cramp());
- }
-
- /**
- * Return an options object with the given size and in at least `\textstyle`.
- * Returns `this` if appropriate.
- */
-
- }, {
- key: "havingSize",
- value: function havingSize(size) {
- if (this.size === size && this.textSize === size) {
- return this;
- } else {
- return this.extend({
- style: this.style.text(),
- size: size,
- textSize: size
- });
- }
- }
-
- /**
- * Like `this.havingSize(BASESIZE).havingStyle(style)`. If `style` is omitted,
- * changes to at least `\textstyle`.
- */
-
- }, {
- key: "havingBaseStyle",
- value: function havingBaseStyle(style) {
- style = style || this.style.text();
- var wantSize = sizeAtStyle(BASESIZE, style);
- if (this.size === wantSize && this.textSize === BASESIZE && this.style === style) {
- return this;
- } else {
- return this.extend({
- style: style,
- size: wantSize,
- baseSize: BASESIZE
- });
- }
- }
-
- /**
- * Create a new options object with the given color.
- */
-
- }, {
- key: "withColor",
- value: function withColor(color) {
- return this.extend({
- color: color
- });
- }
-
- /**
- * Create a new options object with "phantom" set to true.
- */
-
- }, {
- key: "withPhantom",
- value: function withPhantom() {
- return this.extend({
- phantom: true
- });
- }
-
- /**
- * Create a new options objects with the give font.
- */
-
- }, {
- key: "withFont",
- value: function withFont(font) {
- return this.extend({
- font: font || this.font
- });
- }
-
- /**
- * Return the CSS sizing classes required to switch from enclosing options
- * `oldOptions` to `this`. Returns an array of classes.
- */
-
- }, {
- key: "sizingClasses",
- value: function sizingClasses(oldOptions) {
- if (oldOptions.size !== this.size) {
- return ["sizing", "reset-size" + oldOptions.size, "size" + this.size];
- } else {
- return [];
- }
- }
-
- /**
- * Return the CSS sizing classes required to switch to the base size. Like
- * `this.havingSize(BASESIZE).sizingClasses(this)`.
- */
-
- }, {
- key: "baseSizingClasses",
- value: function baseSizingClasses() {
- if (this.size !== BASESIZE) {
- return ["sizing", "reset-size" + this.size, "size" + BASESIZE];
- } else {
- return [];
- }
- }
-
- /**
- * Return the font metrics for this size.
- */
-
- }, {
- key: "fontMetrics",
- value: function fontMetrics() {
- if (!this._fontMetrics) {
- this._fontMetrics = _fontMetrics3.default.getFontMetrics(this.size);
- }
- return this._fontMetrics;
- }
-
- /**
- * A map of color names to CSS colors.
- * TODO(emily): Remove this when we have real macros
- */
-
- }, {
- key: "getColor",
-
-
- /**
- * Gets the CSS color of the current options object, accounting for the
- * `colorMap`.
- */
- value: function getColor() {
- if (this.phantom) {
- return "transparent";
- } else {
- return Options.colorMap[this.color] || this.color;
- }
- }
- }]);
- return Options;
- }();
-
- /**
- * The base size index.
- */
-
-
- Options.colorMap = {
- "katex-blue": "#6495ed",
- "katex-orange": "#ffa500",
- "katex-pink": "#ff00af",
- "katex-red": "#df0030",
- "katex-green": "#28ae7b",
- "katex-gray": "gray",
- "katex-purple": "#9d38bd",
- "katex-blueA": "#ccfaff",
- "katex-blueB": "#80f6ff",
- "katex-blueC": "#63d9ea",
- "katex-blueD": "#11accd",
- "katex-blueE": "#0c7f99",
- "katex-tealA": "#94fff5",
- "katex-tealB": "#26edd5",
- "katex-tealC": "#01d1c1",
- "katex-tealD": "#01a995",
- "katex-tealE": "#208170",
- "katex-greenA": "#b6ffb0",
- "katex-greenB": "#8af281",
- "katex-greenC": "#74cf70",
- "katex-greenD": "#1fab54",
- "katex-greenE": "#0d923f",
- "katex-goldA": "#ffd0a9",
- "katex-goldB": "#ffbb71",
- "katex-goldC": "#ff9c39",
- "katex-goldD": "#e07d10",
- "katex-goldE": "#a75a05",
- "katex-redA": "#fca9a9",
- "katex-redB": "#ff8482",
- "katex-redC": "#f9685d",
- "katex-redD": "#e84d39",
- "katex-redE": "#bc2612",
- "katex-maroonA": "#ffbde0",
- "katex-maroonB": "#ff92c6",
- "katex-maroonC": "#ed5fa6",
- "katex-maroonD": "#ca337c",
- "katex-maroonE": "#9e034e",
- "katex-purpleA": "#ddd7ff",
- "katex-purpleB": "#c6b9fc",
- "katex-purpleC": "#aa87ff",
- "katex-purpleD": "#7854ab",
- "katex-purpleE": "#543b78",
- "katex-mintA": "#f5f9e8",
- "katex-mintB": "#edf2df",
- "katex-mintC": "#e0e5cc",
- "katex-grayA": "#f6f7f7",
- "katex-grayB": "#f0f1f2",
- "katex-grayC": "#e3e5e6",
- "katex-grayD": "#d6d8da",
- "katex-grayE": "#babec2",
- "katex-grayF": "#888d93",
- "katex-grayG": "#626569",
- "katex-grayH": "#3b3e40",
- "katex-grayI": "#21242c",
- "katex-kaBlue": "#314453",
- "katex-kaGreen": "#71B307"
- };
- Options.BASESIZE = BASESIZE;
-
- module.exports = Options;
-
- },{"./fontMetrics":41,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],29:[function(require,module,exports){
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * This is the ParseError class, which is the main error thrown by KaTeX
- * functions when something has gone wrong. This is used to distinguish internal
- * errors from errors in the expression that the user provided.
- *
- * If possible, a caller should provide a Token or ParseNode with information
- * about where in the source string the problem occurred.
- *
- * @param {string} message The error message
- * @param {(Token|ParseNode)=} token An object providing position information
- */
- var ParseError = function ParseError(message, token) {
- (0, _classCallCheck3.default)(this, ParseError);
-
- var error = "KaTeX parse error: " + message;
- var start = void 0;
- var end = void 0;
-
- if (token && token.lexer && token.start <= token.end) {
- // If we have the input and a position, make the error a bit fancier
-
- // Get the input
- var input = token.lexer.input;
-
- // Prepend some information
- start = token.start;
- end = token.end;
- if (start === input.length) {
- error += " at end of input: ";
- } else {
- error += " at position " + (start + 1) + ": ";
- }
-
- // Underline token in question using combining underscores
- var underlined = input.slice(start, end).replace(/[^]/g, "$&\u0332");
-
- // Extract some context from the input and add it to the error
- var left = void 0;
- if (start > 15) {
- left = "…" + input.slice(start - 15, start);
- } else {
- left = input.slice(0, start);
- }
- var right = void 0;
- if (end + 15 < input.length) {
- right = input.slice(end, end + 15) + "…";
- } else {
- right = input.slice(end);
- }
- error += left + underlined + right;
- }
-
- // Some hackery to make ParseError a prototype of Error
- // See http://stackoverflow.com/a/8460753
- var self = new Error(error);
- self.name = "ParseError";
- self.__proto__ = ParseError.prototype;
-
- self.position = start;
- return self;
- };
-
- // More hackery
-
-
- ParseError.prototype.__proto__ = Error.prototype;
-
- module.exports = ParseError;
-
- },{"babel-runtime/helpers/classCallCheck":4}],30:[function(require,module,exports){
-
- Object.defineProperty(exports, "__esModule", {
- value: true
- });
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * The resulting parse tree nodes of the parse tree.
- *
- * It is possible to provide position information, so that a ParseNode can
- * fulfil a role similar to a Token in error reporting.
- * For details on the corresponding properties see Token constructor.
- * Providing such information can lead to better error reporting.
- *
- * @param {string} type type of node, like e.g. "ordgroup"
- * @param {?object} value type-specific representation of the node
- * @param {string} mode parse mode in action for this node,
- * "math" or "text"
- * @param {Token=} firstToken first token of the input for this node,
- * will omit position information if unset
- * @param {Token=} lastToken last token of the input for this node,
- * will default to firstToken if unset
- */
- var ParseNode = function ParseNode(type, value, mode, firstToken, lastToken) {
- (0, _classCallCheck3.default)(this, ParseNode);
-
- this.type = type;
- this.value = value;
- this.mode = mode;
- if (firstToken && (!lastToken || lastToken.lexer === firstToken.lexer)) {
- this.lexer = firstToken.lexer;
- this.start = firstToken.start;
- this.end = (lastToken || firstToken).end;
- }
- };
-
- exports.default = ParseNode;
-
- },{"babel-runtime/helpers/classCallCheck":4}],31:[function(require,module,exports){
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- var _createClass2 = require("babel-runtime/helpers/createClass");
-
- var _createClass3 = _interopRequireDefault(_createClass2);
-
- var _functions = require("./functions");
-
- var _functions2 = _interopRequireDefault(_functions);
-
- var _environments = require("./environments");
-
- var _environments2 = _interopRequireDefault(_environments);
-
- var _MacroExpander = require("./MacroExpander");
-
- var _MacroExpander2 = _interopRequireDefault(_MacroExpander);
-
- var _symbols = require("./symbols");
-
- var _symbols2 = _interopRequireDefault(_symbols);
-
- var _utils = require("./utils");
-
- var _utils2 = _interopRequireDefault(_utils);
-
- var _units = require("./units");
-
- var _units2 = _interopRequireDefault(_units);
-
- var _unicodeRegexes = require("./unicodeRegexes");
-
- var _ParseNode = require("./ParseNode");
-
- var _ParseNode2 = _interopRequireDefault(_ParseNode);
-
- var _ParseError = require("./ParseError");
-
- var _ParseError2 = _interopRequireDefault(_ParseError);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * This file contains the parser used to parse out a TeX expression from the
- * input. Since TeX isn't context-free, standard parsers don't work particularly
- * well.
- *
- * The strategy of this parser is as such:
- *
- * The main functions (the `.parse...` ones) take a position in the current
- * parse string to parse tokens from. The lexer (found in Lexer.js, stored at
- * this.lexer) also supports pulling out tokens at arbitrary places. When
- * individual tokens are needed at a position, the lexer is called to pull out a
- * token, which is then used.
- *
- * The parser has a property called "mode" indicating the mode that
- * the parser is currently in. Currently it has to be one of "math" or
- * "text", which denotes whether the current environment is a math-y
- * one or a text-y one (e.g. inside \text). Currently, this serves to
- * limit the functions which can be used in text mode.
- *
- * The main functions then return an object which contains the useful data that
- * was parsed at its given point, and a new position at the end of the parsed
- * data. The main functions can call each other and continue the parsing by
- * using the returned position as a new starting point.
- *
- * There are also extra `.handle...` functions, which pull out some reused
- * functionality into self-contained functions.
- *
- * The earlier functions return ParseNodes.
- * The later functions (which are called deeper in the parse) sometimes return
- * ParseFuncOrArgument, which contain a ParseNode as well as some data about
- * whether the parsed object is a function which is missing some arguments, or a
- * standalone object which can be used as an argument to another function.
- */
-
- /**
- * An initial function (without its arguments), or an argument to a function.
- * The `result` argument should be a ParseNode.
- */
- function ParseFuncOrArgument(result, isFunction, token) {
- this.result = result;
- // Is this a function (i.e. is it something defined in functions.js)?
- this.isFunction = isFunction;
- this.token = token;
- } /* eslint no-constant-condition:0 */
-
- var Parser = function () {
- function Parser(input, settings) {
- (0, _classCallCheck3.default)(this, Parser);
-
- // Create a new macro expander (gullet) and (indirectly via that) also a
- // new lexer (mouth) for this parser (stomach, in the language of TeX)
- this.gullet = new _MacroExpander2.default(input, settings.macros);
- // Use old \color behavior (same as LaTeX's \textcolor) if requested.
- // We do this after the macros object has been copied by MacroExpander.
- if (settings.colorIsTextColor) {
- this.gullet.macros["\\color"] = "\\textcolor";
- }
- // Store the settings for use in parsing
- this.settings = settings;
- // Count leftright depth (for \middle errors)
- this.leftrightDepth = 0;
- }
-
- /**
- * Checks a result to make sure it has the right type, and throws an
- * appropriate error otherwise.
- *
- * @param {boolean=} consume whether to consume the expected token,
- * defaults to true
- */
-
-
- (0, _createClass3.default)(Parser, [{
- key: "expect",
- value: function expect(text, consume) {
- if (this.nextToken.text !== text) {
- throw new _ParseError2.default("Expected '" + text + "', got '" + this.nextToken.text + "'", this.nextToken);
- }
- if (consume !== false) {
- this.consume();
- }
- }
-
- /**
- * Considers the current look ahead token as consumed,
- * and fetches the one after that as the new look ahead.
- */
-
- }, {
- key: "consume",
- value: function consume() {
- this.nextToken = this.gullet.get(this.mode === "math");
- }
- }, {
- key: "switchMode",
- value: function switchMode(newMode) {
- this.gullet.unget(this.nextToken);
- this.mode = newMode;
- this.consume();
- }
-
- /**
- * Main parsing function, which parses an entire input.
- *
- * @return {?Array.}
- */
-
- }, {
- key: "parse",
- value: function parse() {
- // Try to parse the input
- this.mode = "math";
- this.consume();
- var parse = this.parseInput();
- return parse;
- }
-
- /**
- * Parses an entire input tree.
- */
-
- }, {
- key: "parseInput",
- value: function parseInput() {
- // Parse an expression
- var expression = this.parseExpression(false);
- // If we succeeded, make sure there's an EOF at the end
- this.expect("EOF", false);
- return expression;
- }
- }, {
- key: "parseExpression",
-
-
- /**
- * Parses an "expression", which is a list of atoms.
- *
- * @param {boolean} breakOnInfix Should the parsing stop when we hit infix
- * nodes? This happens when functions have higher precendence
- * than infix nodes in implicit parses.
- *
- * @param {?string} breakOnTokenText The text of the token that the expression
- * should end with, or `null` if something else should end the
- * expression.
- *
- * @return {ParseNode}
- */
- value: function parseExpression(breakOnInfix, breakOnTokenText) {
- var body = [];
- // Keep adding atoms to the body until we can't parse any more atoms (either
- // we reached the end, a }, or a \right)
- while (true) {
- var lex = this.nextToken;
- if (Parser.endOfExpression.indexOf(lex.text) !== -1) {
- break;
- }
- if (breakOnTokenText && lex.text === breakOnTokenText) {
- break;
- }
- if (breakOnInfix && _functions2.default[lex.text] && _functions2.default[lex.text].infix) {
- break;
- }
- var atom = this.parseAtom();
- if (!atom) {
- if (!this.settings.throwOnError && lex.text[0] === "\\") {
- var errorNode = this.handleUnsupportedCmd();
- body.push(errorNode);
- continue;
- }
-
- break;
- }
- body.push(atom);
- }
- return this.handleInfixNodes(body);
- }
-
- /**
- * Rewrites infix operators such as \over with corresponding commands such
- * as \frac.
- *
- * There can only be one infix operator per group. If there's more than one
- * then the expression is ambiguous. This can be resolved by adding {}.
- *
- * @returns {Array}
- */
-
- }, {
- key: "handleInfixNodes",
- value: function handleInfixNodes(body) {
- var overIndex = -1;
- var funcName = void 0;
-
- for (var i = 0; i < body.length; i++) {
- var node = body[i];
- if (node.type === "infix") {
- if (overIndex !== -1) {
- throw new _ParseError2.default("only one infix operator per group", node.value.token);
- }
- overIndex = i;
- funcName = node.value.replaceWith;
- }
- }
-
- if (overIndex !== -1) {
- var numerNode = void 0;
- var denomNode = void 0;
-
- var numerBody = body.slice(0, overIndex);
- var denomBody = body.slice(overIndex + 1);
-
- if (numerBody.length === 1 && numerBody[0].type === "ordgroup") {
- numerNode = numerBody[0];
- } else {
- numerNode = new _ParseNode2.default("ordgroup", numerBody, this.mode);
- }
-
- if (denomBody.length === 1 && denomBody[0].type === "ordgroup") {
- denomNode = denomBody[0];
- } else {
- denomNode = new _ParseNode2.default("ordgroup", denomBody, this.mode);
- }
-
- var value = this.callFunction(funcName, [numerNode, denomNode], null);
- return [new _ParseNode2.default(value.type, value, this.mode)];
- } else {
- return body;
- }
- }
-
- // The greediness of a superscript or subscript
-
- }, {
- key: "handleSupSubscript",
-
-
- /**
- * Handle a subscript or superscript with nice errors.
- */
- value: function handleSupSubscript(name) {
- var symbolToken = this.nextToken;
- var symbol = symbolToken.text;
- this.consume();
- var group = this.parseGroup();
-
- if (!group) {
- if (!this.settings.throwOnError && this.nextToken.text[0] === "\\") {
- return this.handleUnsupportedCmd();
- } else {
- throw new _ParseError2.default("Expected group after '" + symbol + "'", symbolToken);
- }
- } else if (group.isFunction) {
- // ^ and _ have a greediness, so handle interactions with functions'
- // greediness
- var funcGreediness = _functions2.default[group.result].greediness;
- if (funcGreediness > Parser.SUPSUB_GREEDINESS) {
- return this.parseFunction(group);
- } else {
- throw new _ParseError2.default("Got function '" + group.result + "' with no arguments " + "as " + name, symbolToken);
- }
- } else {
- return group.result;
- }
- }
-
- /**
- * Converts the textual input of an unsupported command into a text node
- * contained within a color node whose color is determined by errorColor
- */
-
- }, {
- key: "handleUnsupportedCmd",
- value: function handleUnsupportedCmd() {
- var text = this.nextToken.text;
- var textordArray = [];
-
- for (var i = 0; i < text.length; i++) {
- textordArray.push(new _ParseNode2.default("textord", text[i], "text"));
- }
-
- var textNode = new _ParseNode2.default("text", {
- body: textordArray,
- type: "text"
- }, this.mode);
-
- var colorNode = new _ParseNode2.default("color", {
- color: this.settings.errorColor,
- value: [textNode],
- type: "color"
- }, this.mode);
-
- this.consume();
- return colorNode;
- }
-
- /**
- * Parses a group with optional super/subscripts.
- *
- * @return {?ParseNode}
- */
-
- }, {
- key: "parseAtom",
- value: function parseAtom() {
- // The body of an atom is an implicit group, so that things like
- // \left(x\right)^2 work correctly.
- var base = this.parseImplicitGroup();
-
- // In text mode, we don't have superscripts or subscripts
- if (this.mode === "text") {
- return base;
- }
-
- // Note that base may be empty (i.e. null) at this point.
-
- var superscript = void 0;
- var subscript = void 0;
- while (true) {
- // Lex the first token
- var lex = this.nextToken;
-
- if (lex.text === "\\limits" || lex.text === "\\nolimits") {
- // We got a limit control
- if (!base || base.type !== "op") {
- throw new _ParseError2.default("Limit controls must follow a math operator", lex);
- } else {
- var limits = lex.text === "\\limits";
- base.value.limits = limits;
- base.value.alwaysHandleSupSub = true;
- }
- this.consume();
- } else if (lex.text === "^") {
- // We got a superscript start
- if (superscript) {
- throw new _ParseError2.default("Double superscript", lex);
- }
- superscript = this.handleSupSubscript("superscript");
- } else if (lex.text === "_") {
- // We got a subscript start
- if (subscript) {
- throw new _ParseError2.default("Double subscript", lex);
- }
- subscript = this.handleSupSubscript("subscript");
- } else if (lex.text === "'") {
- // We got a prime
- if (superscript) {
- throw new _ParseError2.default("Double superscript", lex);
- }
- var prime = new _ParseNode2.default("textord", "\\prime", this.mode);
-
- // Many primes can be grouped together, so we handle this here
- var primes = [prime];
- this.consume();
- // Keep lexing tokens until we get something that's not a prime
- while (this.nextToken.text === "'") {
- // For each one, add another prime to the list
- primes.push(prime);
- this.consume();
- }
- // If there's a superscript following the primes, combine that
- // superscript in with the primes.
- if (this.nextToken.text === "^") {
- primes.push(this.handleSupSubscript("superscript"));
- }
- // Put everything into an ordgroup as the superscript
- superscript = new _ParseNode2.default("ordgroup", primes, this.mode);
- } else {
- // If it wasn't ^, _, or ', stop parsing super/subscripts
- break;
- }
- }
-
- if (superscript || subscript) {
- // If we got either a superscript or subscript, create a supsub
- return new _ParseNode2.default("supsub", {
- base: base,
- sup: superscript,
- sub: subscript
- }, this.mode);
- } else {
- // Otherwise return the original body
- return base;
- }
- }
-
- // A list of the size-changing functions, for use in parseImplicitGroup
-
-
- // A list of the style-changing functions, for use in parseImplicitGroup
-
-
- // Old font functions
-
- }, {
- key: "parseImplicitGroup",
-
-
- /**
- * Parses an implicit group, which is a group that starts at the end of a
- * specified, and ends right before a higher explicit group ends, or at EOL. It
- * is used for functions that appear to affect the current style, like \Large or
- * \textrm, where instead of keeping a style we just pretend that there is an
- * implicit grouping after it until the end of the group. E.g.
- * small text {\Large large text} small text again
- * It is also used for \left and \right to get the correct grouping.
- *
- * @return {?ParseNode}
- */
- value: function parseImplicitGroup() {
- var start = this.parseSymbol();
-
- if (start == null) {
- // If we didn't get anything we handle, fall back to parseFunction
- return this.parseFunction();
- }
-
- var func = start.result;
-
- if (func === "\\left") {
- // If we see a left:
- // Parse the entire left function (including the delimiter)
- var left = this.parseFunction(start);
- // Parse out the implicit body
- ++this.leftrightDepth;
- var body = this.parseExpression(false);
- --this.leftrightDepth;
- // Check the next token
- this.expect("\\right", false);
- var right = this.parseFunction();
- return new _ParseNode2.default("leftright", {
- body: body,
- left: left.value.value,
- right: right.value.value
- }, this.mode);
- } else if (func === "\\begin") {
- // begin...end is similar to left...right
- var begin = this.parseFunction(start);
- var envName = begin.value.name;
- if (!_environments2.default.hasOwnProperty(envName)) {
- throw new _ParseError2.default("No such environment: " + envName, begin.value.nameGroup);
- }
- // Build the environment object. Arguments and other information will
- // be made available to the begin and end methods using properties.
- var env = _environments2.default[envName];
- var args = this.parseArguments("\\begin{" + envName + "}", env);
- var context = {
- mode: this.mode,
- envName: envName,
- parser: this,
- positions: args.pop()
- };
- var result = env.handler(context, args);
- this.expect("\\end", false);
- var endNameToken = this.nextToken;
- var end = this.parseFunction();
- if (end.value.name !== envName) {
- throw new _ParseError2.default("Mismatch: \\begin{" + envName + "} matched " + "by \\end{" + end.value.name + "}", endNameToken);
- }
- result.position = end.position;
- return result;
- } else if (_utils2.default.contains(Parser.sizeFuncs, func)) {
- // If we see a sizing function, parse out the implicit body
- this.consumeSpaces();
- var _body = this.parseExpression(false);
- return new _ParseNode2.default("sizing", {
- // Figure out what size to use based on the list of functions above
- size: _utils2.default.indexOf(Parser.sizeFuncs, func) + 1,
- value: _body
- }, this.mode);
- } else if (_utils2.default.contains(Parser.styleFuncs, func)) {
- // If we see a styling function, parse out the implicit body
- this.consumeSpaces();
- var _body2 = this.parseExpression(true);
- return new _ParseNode2.default("styling", {
- // Figure out what style to use by pulling out the style from
- // the function name
- style: func.slice(1, func.length - 5),
- value: _body2
- }, this.mode);
- } else if (func in Parser.oldFontFuncs) {
- var style = Parser.oldFontFuncs[func];
- // If we see an old font function, parse out the implicit body
- this.consumeSpaces();
- var _body3 = this.parseExpression(true);
- if (style.slice(0, 4) === 'text') {
- return new _ParseNode2.default("text", {
- style: style,
- body: new _ParseNode2.default("ordgroup", _body3, this.mode)
- }, this.mode);
- } else {
- return new _ParseNode2.default("font", {
- font: style,
- body: new _ParseNode2.default("ordgroup", _body3, this.mode)
- }, this.mode);
- }
- } else if (func === "\\color") {
- // If we see a styling function, parse out the implicit body
- var color = this.parseColorGroup(false);
- if (!color) {
- throw new _ParseError2.default("\\color not followed by color");
- }
- var _body4 = this.parseExpression(true);
- return new _ParseNode2.default("color", {
- type: "color",
- color: color.result.value,
- value: _body4
- }, this.mode);
- } else if (func === "$") {
- if (this.mode === "math") {
- throw new _ParseError2.default("$ within math mode");
- }
- this.consume();
- var outerMode = this.mode;
- this.switchMode("math");
- var _body5 = this.parseExpression(false, "$");
- this.expect("$", true);
- this.switchMode(outerMode);
- return new _ParseNode2.default("styling", {
- style: "text",
- value: _body5
- }, "math");
- } else {
- // Defer to parseFunction if it's not a function we handle
- return this.parseFunction(start);
- }
- }
-
- /**
- * Parses an entire function, including its base and all of its arguments.
- * The base might either have been parsed already, in which case
- * it is provided as an argument, or it's the next group in the input.
- *
- * @param {ParseFuncOrArgument=} baseGroup optional as described above
- * @return {?ParseNode}
- */
-
- }, {
- key: "parseFunction",
- value: function parseFunction(baseGroup) {
- if (!baseGroup) {
- baseGroup = this.parseGroup();
- }
-
- if (baseGroup) {
- if (baseGroup.isFunction) {
- var func = baseGroup.result;
- var funcData = _functions2.default[func];
- if (this.mode === "text" && !funcData.allowedInText) {
- throw new _ParseError2.default("Can't use function '" + func + "' in text mode", baseGroup.token);
- } else if (this.mode === "math" && funcData.allowedInMath === false) {
- throw new _ParseError2.default("Can't use function '" + func + "' in math mode", baseGroup.token);
- }
-
- var args = this.parseArguments(func, funcData);
- var token = baseGroup.token;
- var result = this.callFunction(func, args, args.pop(), token);
- return new _ParseNode2.default(result.type, result, this.mode);
- } else {
- return baseGroup.result;
- }
- } else {
- return null;
- }
- }
-
- /**
- * Call a function handler with a suitable context and arguments.
- */
-
- }, {
- key: "callFunction",
- value: function callFunction(name, args, positions, token) {
- var context = {
- funcName: name,
- parser: this,
- positions: positions,
- token: token
- };
- return _functions2.default[name].handler(context, args);
- }
-
- /**
- * Parses the arguments of a function or environment
- *
- * @param {string} func "\name" or "\begin{name}"
- * @param {{numArgs:number,numOptionalArgs:number|undefined}} funcData
- * @return the array of arguments, with the list of positions as last element
- */
-
- }, {
- key: "parseArguments",
- value: function parseArguments(func, funcData) {
- var totalArgs = funcData.numArgs + funcData.numOptionalArgs;
- if (totalArgs === 0) {
- return [[this.pos]];
- }
-
- var baseGreediness = funcData.greediness;
- var positions = [this.pos];
- var args = [];
-
- for (var i = 0; i < totalArgs; i++) {
- var nextToken = this.nextToken;
- var argType = funcData.argTypes && funcData.argTypes[i];
- var arg = void 0;
- if (i < funcData.numOptionalArgs) {
- if (argType) {
- arg = this.parseGroupOfType(argType, true);
- } else {
- arg = this.parseGroup(true);
- }
- if (!arg) {
- args.push(null);
- positions.push(this.pos);
- continue;
- }
- } else {
- if (argType) {
- arg = this.parseGroupOfType(argType);
- } else {
- arg = this.parseGroup();
- }
- if (!arg) {
- if (!this.settings.throwOnError && this.nextToken.text[0] === "\\") {
- arg = new ParseFuncOrArgument(this.handleUnsupportedCmd(this.nextToken.text), false);
- } else {
- throw new _ParseError2.default("Expected group after '" + func + "'", nextToken);
- }
- }
- }
- var argNode = void 0;
- if (arg.isFunction) {
- var argGreediness = _functions2.default[arg.result].greediness;
- if (argGreediness > baseGreediness) {
- argNode = this.parseFunction(arg);
- } else {
- throw new _ParseError2.default("Got function '" + arg.result + "' as " + "argument to '" + func + "'", nextToken);
- }
- } else {
- argNode = arg.result;
- }
- args.push(argNode);
- positions.push(this.pos);
- }
-
- args.push(positions);
-
- return args;
- }
-
- /**
- * Parses a group when the mode is changing.
- *
- * @return {?ParseFuncOrArgument}
- */
-
- }, {
- key: "parseGroupOfType",
- value: function parseGroupOfType(innerMode, optional) {
- var outerMode = this.mode;
- // Handle `original` argTypes
- if (innerMode === "original") {
- innerMode = outerMode;
- }
-
- if (innerMode === "color") {
- return this.parseColorGroup(optional);
- }
- if (innerMode === "size") {
- return this.parseSizeGroup(optional);
- }
-
- this.switchMode(innerMode);
- if (innerMode === "text") {
- // text mode is special because it should ignore the whitespace before
- // it
- this.consumeSpaces();
- }
- // By the time we get here, innerMode is one of "text" or "math".
- // We switch the mode of the parser, recurse, then restore the old mode.
- var res = this.parseGroup(optional);
- this.switchMode(outerMode);
- return res;
- }
- }, {
- key: "consumeSpaces",
- value: function consumeSpaces() {
- while (this.nextToken.text === " ") {
- this.consume();
- }
- }
-
- /**
- * Parses a group, essentially returning the string formed by the
- * brace-enclosed tokens plus some position information.
- *
- * @param {string} modeName Used to describe the mode in error messages
- * @param {boolean=} optional Whether the group is optional or required
- */
-
- }, {
- key: "parseStringGroup",
- value: function parseStringGroup(modeName, optional) {
- if (optional && this.nextToken.text !== "[") {
- return null;
- }
- var outerMode = this.mode;
- this.mode = "text";
- this.expect(optional ? "[" : "{");
- var str = "";
- var firstToken = this.nextToken;
- var lastToken = firstToken;
- while (this.nextToken.text !== (optional ? "]" : "}")) {
- if (this.nextToken.text === "EOF") {
- throw new _ParseError2.default("Unexpected end of input in " + modeName, firstToken.range(this.nextToken, str));
- }
- lastToken = this.nextToken;
- str += lastToken.text;
- this.consume();
- }
- this.mode = outerMode;
- this.expect(optional ? "]" : "}");
- return firstToken.range(lastToken, str);
- }
-
- /**
- * Parses a regex-delimited group: the largest sequence of tokens
- * whose concatenated strings match `regex`. Returns the string
- * formed by the tokens plus some position information.
- *
- * @param {RegExp} regex
- * @param {string} modeName Used to describe the mode in error messages
- */
-
- }, {
- key: "parseRegexGroup",
- value: function parseRegexGroup(regex, modeName) {
- var outerMode = this.mode;
- this.mode = "text";
- var firstToken = this.nextToken;
- var lastToken = firstToken;
- var str = "";
- while (this.nextToken.text !== "EOF" && regex.test(str + this.nextToken.text)) {
- lastToken = this.nextToken;
- str += lastToken.text;
- this.consume();
- }
- if (str === "") {
- throw new _ParseError2.default("Invalid " + modeName + ": '" + firstToken.text + "'", firstToken);
- }
- this.mode = outerMode;
- return firstToken.range(lastToken, str);
- }
-
- /**
- * Parses a color description.
- */
-
- }, {
- key: "parseColorGroup",
- value: function parseColorGroup(optional) {
- var res = this.parseStringGroup("color", optional);
- if (!res) {
- return null;
- }
- var match = /^(#[a-z0-9]+|[a-z]+)$/i.exec(res.text);
- if (!match) {
- throw new _ParseError2.default("Invalid color: '" + res.text + "'", res);
- }
- return new ParseFuncOrArgument(new _ParseNode2.default("color", match[0], this.mode), false);
- }
-
- /**
- * Parses a size specification, consisting of magnitude and unit.
- */
-
- }, {
- key: "parseSizeGroup",
- value: function parseSizeGroup(optional) {
- var res = void 0;
- if (!optional && this.nextToken.text !== "{") {
- res = this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/, "size");
- } else {
- res = this.parseStringGroup("size", optional);
- }
- if (!res) {
- return null;
- }
- var match = /([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(res.text);
- if (!match) {
- throw new _ParseError2.default("Invalid size: '" + res.text + "'", res);
- }
- var data = {
- number: +(match[1] + match[2]), // sign + magnitude, cast to number
- unit: match[3]
- };
- if (!_units2.default.validUnit(data)) {
- throw new _ParseError2.default("Invalid unit: '" + data.unit + "'", res);
- }
- return new ParseFuncOrArgument(new _ParseNode2.default("size", data, this.mode), false);
- }
-
- /**
- * If the argument is false or absent, this parses an ordinary group,
- * which is either a single nucleus (like "x") or an expression
- * in braces (like "{x+y}").
- * If the argument is true, it parses either a bracket-delimited expression
- * (like "[x+y]") or returns null to indicate the absence of a
- * bracket-enclosed group.
- *
- * @param {boolean=} optional Whether the group is optional or required
- * @return {?ParseFuncOrArgument}
- */
-
- }, {
- key: "parseGroup",
- value: function parseGroup(optional) {
- var firstToken = this.nextToken;
- // Try to parse an open brace
- if (this.nextToken.text === (optional ? "[" : "{")) {
- // If we get a brace, parse an expression
- this.consume();
- var expression = this.parseExpression(false, optional ? "]" : null);
- var lastToken = this.nextToken;
- // Make sure we get a close brace
- this.expect(optional ? "]" : "}");
- if (this.mode === "text") {
- this.formLigatures(expression);
- }
- return new ParseFuncOrArgument(new _ParseNode2.default("ordgroup", expression, this.mode, firstToken, lastToken), false);
- } else {
- // Otherwise, just return a nucleus, or nothing for an optional group
- return optional ? null : this.parseSymbol();
- }
- }
-
- /**
- * Form ligature-like combinations of characters for text mode.
- * This includes inputs like "--", "---", "``" and "''".
- * The result will simply replace multiple textord nodes with a single
- * character in each value by a single textord node having multiple
- * characters in its value. The representation is still ASCII source.
- *
- * @param {Array.} group the nodes of this group,
- * list will be moified in place
- */
-
- }, {
- key: "formLigatures",
- value: function formLigatures(group) {
- var n = group.length - 1;
- for (var i = 0; i < n; ++i) {
- var a = group[i];
- var v = a.value;
- if (v === "-" && group[i + 1].value === "-") {
- if (i + 1 < n && group[i + 2].value === "-") {
- group.splice(i, 3, new _ParseNode2.default("textord", "---", "text", a, group[i + 2]));
- n -= 2;
- } else {
- group.splice(i, 2, new _ParseNode2.default("textord", "--", "text", a, group[i + 1]));
- n -= 1;
- }
- }
- if ((v === "'" || v === "`") && group[i + 1].value === v) {
- group.splice(i, 2, new _ParseNode2.default("textord", v + v, "text", a, group[i + 1]));
- n -= 1;
- }
- }
- }
-
- /**
- * Parse a single symbol out of the string. Here, we handle both the functions
- * we have defined, as well as the single character symbols
- *
- * @return {?ParseFuncOrArgument}
- */
-
- }, {
- key: "parseSymbol",
- value: function parseSymbol() {
- var nucleus = this.nextToken;
-
- if (_functions2.default[nucleus.text]) {
- this.consume();
- // If there exists a function with this name, we return the function and
- // say that it is a function.
- return new ParseFuncOrArgument(nucleus.text, true, nucleus);
- } else if (_symbols2.default[this.mode][nucleus.text]) {
- this.consume();
- // Otherwise if this is a no-argument function, find the type it
- // corresponds to in the symbols map
- return new ParseFuncOrArgument(new _ParseNode2.default(_symbols2.default[this.mode][nucleus.text].group, nucleus.text, this.mode, nucleus), false, nucleus);
- } else if (this.mode === "text" && _unicodeRegexes.cjkRegex.test(nucleus.text)) {
- this.consume();
- return new ParseFuncOrArgument(new _ParseNode2.default("textord", nucleus.text, this.mode, nucleus), false, nucleus);
- } else if (nucleus.text === "$") {
- return new ParseFuncOrArgument(nucleus.text, false, nucleus);
- } else {
- return null;
- }
- }
- }]);
- return Parser;
- }();
-
- Parser.endOfExpression = ["}", "\\end", "\\right", "&", "\\\\", "\\cr"];
- Parser.SUPSUB_GREEDINESS = 1;
- Parser.sizeFuncs = ["\\tiny", "\\sixptsize", "\\scriptsize", "\\footnotesize", "\\small", "\\normalsize", "\\large", "\\Large", "\\LARGE", "\\huge", "\\Huge"];
- Parser.styleFuncs = ["\\displaystyle", "\\textstyle", "\\scriptstyle", "\\scriptscriptstyle"];
- Parser.oldFontFuncs = {
- "\\rm": "mathrm",
- "\\sf": "mathsf",
- "\\tt": "mathtt",
- "\\bf": "mathbf",
- "\\it": "mathit"
- };
-
-
- Parser.prototype.ParseNode = _ParseNode2.default;
-
- module.exports = Parser;
-
- },{"./MacroExpander":27,"./ParseError":29,"./ParseNode":30,"./environments":40,"./functions":43,"./symbols":48,"./unicodeRegexes":49,"./units":50,"./utils":51,"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],32:[function(require,module,exports){
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- var _utils = require("./utils");
-
- var _utils2 = _interopRequireDefault(_utils);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * The main Settings object
- *
- * The current options stored are:
- * - displayMode: Whether the expression should be typeset as inline math
- * (false, the default), meaning that the math starts in
- * \textstyle and is placed in an inline-block); or as display
- * math (true), meaning that the math starts in \displaystyle
- * and is placed in a block with vertical margin.
- */
- var Settings = function Settings(options) {
- (0, _classCallCheck3.default)(this, Settings);
-
- // allow null options
- options = options || {};
- this.displayMode = _utils2.default.deflt(options.displayMode, false);
- this.throwOnError = _utils2.default.deflt(options.throwOnError, true);
- this.errorColor = _utils2.default.deflt(options.errorColor, "#cc0000");
- this.macros = options.macros || {};
- this.colorIsTextColor = _utils2.default.deflt(options.colorIsTextColor, false);
- }; /**
- * This is a module for storing settings passed into KaTeX. It correctly handles
- * default settings.
- */
-
- module.exports = Settings;
-
- },{"./utils":51,"babel-runtime/helpers/classCallCheck":4}],33:[function(require,module,exports){
-
- var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck");
-
- var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
-
- var _createClass2 = require("babel-runtime/helpers/createClass");
-
- var _createClass3 = _interopRequireDefault(_createClass2);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * This file contains information and classes for the various kinds of styles
- * used in TeX. It provides a generic `Style` class, which holds information
- * about a specific style. It then provides instances of all the different kinds
- * of styles possible, and provides functions to move between them and get
- * information about them.
- */
-
- /**
- * The main style class. Contains a unique id for the style, a size (which is
- * the same for cramped and uncramped version of a style), and a cramped flag.
- */
- var Style = function () {
- function Style(id, size, cramped) {
- (0, _classCallCheck3.default)(this, Style);
-
- this.id = id;
- this.size = size;
- this.cramped = cramped;
- }
-
- /**
- * Get the style of a superscript given a base in the current style.
- */
-
-
- (0, _createClass3.default)(Style, [{
- key: "sup",
- value: function sup() {
- return styles[_sup[this.id]];
- }
-
- /**
- * Get the style of a subscript given a base in the current style.
- */
-
- }, {
- key: "sub",
- value: function sub() {
- return styles[_sub[this.id]];
- }
-
- /**
- * Get the style of a fraction numerator given the fraction in the current
- * style.
- */
-
- }, {
- key: "fracNum",
- value: function fracNum() {
- return styles[_fracNum[this.id]];
- }
-
- /**
- * Get the style of a fraction denominator given the fraction in the current
- * style.
- */
-
- }, {
- key: "fracDen",
- value: function fracDen() {
- return styles[_fracDen[this.id]];
- }
-
- /**
- * Get the cramped version of a style (in particular, cramping a cramped style
- * doesn't change the style).
- */
-
- }, {
- key: "cramp",
- value: function cramp() {
- return styles[_cramp[this.id]];
- }
-
- /**
- * Get a text or display version of this style.
- */
-
- }, {
- key: "text",
- value: function text() {
- return styles[_text[this.id]];
- }
-
- /**
- * Return if this style is tightly spaced (scriptstyle/scriptscriptstyle)
- */
-
- }, {
- key: "isTight",
- value: function isTight() {
- return this.size >= 2;
- }
- }]);
- return Style;
- }();
-
- // IDs of the different styles
-
-
- var D = 0;
- var Dc = 1;
- var T = 2;
- var Tc = 3;
- var S = 4;
- var Sc = 5;
- var SS = 6;
- var SSc = 7;
-
- // Instances of the different styles
- var styles = [new Style(D, 0, false), new Style(Dc, 0, true), new Style(T, 1, false), new Style(Tc, 1, true), new Style(S, 2, false), new Style(Sc, 2, true), new Style(SS, 3, false), new Style(SSc, 3, true)];
-
- // Lookup tables for switching from one style to another
- var _sup = [S, Sc, S, Sc, SS, SSc, SS, SSc];
- var _sub = [Sc, Sc, Sc, Sc, SSc, SSc, SSc, SSc];
- var _fracNum = [T, Tc, S, Sc, SS, SSc, SS, SSc];
- var _fracDen = [Tc, Tc, Sc, Sc, SSc, SSc, SSc, SSc];
- var _cramp = [Dc, Dc, Tc, Tc, Sc, Sc, SSc, SSc];
- var _text = [D, Dc, T, Tc, T, Tc, T, Tc];
-
- // We only export some of the styles. Also, we don't export the `Style` class so
- // no more styles can be generated.
- module.exports = {
- DISPLAY: styles[D],
- TEXT: styles[T],
- SCRIPT: styles[S],
- SCRIPTSCRIPT: styles[SS]
- };
-
- },{"babel-runtime/helpers/classCallCheck":4,"babel-runtime/helpers/createClass":5}],34:[function(require,module,exports){
-
- var _domTree = require("./domTree");
-
- var _domTree2 = _interopRequireDefault(_domTree);
-
- var _fontMetrics = require("./fontMetrics");
-
- var _fontMetrics2 = _interopRequireDefault(_fontMetrics);
-
- var _symbols = require("./symbols");
-
- var _symbols2 = _interopRequireDefault(_symbols);
-
- var _utils = require("./utils");
-
- var _utils2 = _interopRequireDefault(_utils);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- // The following have to be loaded from Main-Italic font, using class mainit
- /* eslint no-console:0 */
- /**
- * This module contains general functions that can be used for building
- * different kinds of domTree nodes in a consistent manner.
- */
-
- var mainitLetters = ["\\imath", // dotless i
- "\\jmath", // dotless j
- "\\pounds"];
-
- /**
- * Looks up the given symbol in fontMetrics, after applying any symbol
- * replacements defined in symbol.js
- */
- var lookupSymbol = function lookupSymbol(value, fontFamily, mode) {
- // Replace the value with its replaced value from symbol.js
- if (_symbols2.default[mode][value] && _symbols2.default[mode][value].replace) {
- value = _symbols2.default[mode][value].replace;
- }
- return {
- value: value,
- metrics: _fontMetrics2.default.getCharacterMetrics(value, fontFamily)
- };
- };
-
- /**
- * Makes a symbolNode after translation via the list of symbols in symbols.js.
- * Correctly pulls out metrics for the character, and optionally takes a list of
- * classes to be attached to the node.
- *
- * TODO: make argument order closer to makeSpan
- * TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
- * should if present come first in `classes`.
- */
- var makeSymbol = function makeSymbol(value, fontFamily, mode, options, classes) {
- var lookup = lookupSymbol(value, fontFamily, mode);
- var metrics = lookup.metrics;
- value = lookup.value;
-
- var symbolNode = void 0;
- if (metrics) {
- var italic = metrics.italic;
- if (mode === "text") {
- italic = 0;
- }
- symbolNode = new _domTree2.default.symbolNode(value, metrics.height, metrics.depth, italic, metrics.skew, classes);
- } else {
- // TODO(emily): Figure out a good way to only print this in development
- typeof console !== "undefined" && console.warn("No character metrics for '" + value + "' in style '" + fontFamily + "'");
- symbolNode = new _domTree2.default.symbolNode(value, 0, 0, 0, 0, classes);
- }
-
- if (options) {
- symbolNode.maxFontSize = options.sizeMultiplier;
- if (options.style.isTight()) {
- symbolNode.classes.push("mtight");
- }
- if (options.getColor()) {
- symbolNode.style.color = options.getColor();
- }
- }
-
- return symbolNode;
- };
-
- /**
- * Makes a symbol in Main-Regular or AMS-Regular.
- * Used for rel, bin, open, close, inner, and punct.
- */
- var mathsym = function mathsym(value, mode, options, classes) {
- // Decide what font to render the symbol in by its entry in the symbols
- // table.
- // Have a special case for when the value = \ because the \ is used as a
- // textord in unsupported command errors but cannot be parsed as a regular
- // text ordinal and is therefore not present as a symbol in the symbols
- // table for text
- if (value === "\\" || _symbols2.default[mode][value].font === "main") {
- return makeSymbol(value, "Main-Regular", mode, options, classes);
- } else {
- return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
- }
- };
-
- /**
- * Makes a symbol in the default font for mathords and textords.
- */
- var mathDefault = function mathDefault(value, mode, options, classes, type) {
- if (type === "mathord") {
- var fontLookup = mathit(value);
- return makeSymbol(value, fontLookup.fontName, mode, options, classes.concat([fontLookup.fontClass]));
- } else if (type === "textord") {
- var font = _symbols2.default[mode][value] && _symbols2.default[mode][value].font;
- if (font === "ams") {
- return makeSymbol(value, "AMS-Regular", mode, options, classes.concat(["amsrm"]));
- } else {
- // if (font === "main") {
- return makeSymbol(value, "Main-Regular", mode, options, classes.concat(["mathrm"]));
- }
- } else {
- throw new Error("unexpected type: " + type + " in mathDefault");
- }
- };
-
- /**
- * Determines which of the two font names (Main-Italic and Math-Italic) and
- * corresponding style tags (mainit or mathit) to use for font "mathit",
- * depending on the symbol. Use this function instead of fontMap for font
- * "mathit".
- */
- var mathit = function mathit(value, mode, options, classes) {
- if (/[0-9]/.test(value.charAt(0)) ||
- // glyphs for \imath and \jmath do not exist in Math-Italic so we
- // need to use Main-Italic instead
- _utils2.default.contains(mainitLetters, value)) {
- return {
- fontName: "Main-Italic",
- fontClass: "mainit"
- };
- } else {
- return {
- fontName: "Math-Italic",
- fontClass: "mathit"
- };
- }
- };
-
- /**
- * Makes either a mathord or textord in the correct font and color.
- */
- var makeOrd = function makeOrd(group, options, type) {
- var mode = group.mode;
- var value = group.value;
-
- var classes = ["mord"];
-
- var font = options.font;
- if (font) {
- var fontLookup = void 0;
- if (font === "mathit" || _utils2.default.contains(mainitLetters, value)) {
- fontLookup = mathit(value);
- } else {
- fontLookup = fontMap[font];
- }
- if (lookupSymbol(value, fontLookup.fontName, mode).metrics) {
- return makeSymbol(value, fontLookup.fontName, mode, options, classes.concat([fontLookup.fontClass || font]));
- } else {
- return mathDefault(value, mode, options, classes, type);
- }
- } else {
- return mathDefault(value, mode, options, classes, type);
- }
- };
-
- /**
- * Calculate the height, depth, and maxFontSize of an element based on its
- * children.
- */
- var sizeElementFromChildren = function sizeElementFromChildren(elem) {
- var height = 0;
- var depth = 0;
- var maxFontSize = 0;
-
- if (elem.children) {
- for (var i = 0; i < elem.children.length; i++) {
- if (elem.children[i].height > height) {
- height = elem.children[i].height;
- }
- if (elem.children[i].depth > depth) {
- depth = elem.children[i].depth;
- }
- if (elem.children[i].maxFontSize > maxFontSize) {
- maxFontSize = elem.children[i].maxFontSize;
- }
- }
- }
-
- elem.height = height;
- elem.depth = depth;
- elem.maxFontSize = maxFontSize;
- };
-
- /**
- * Makes a span with the given list of classes, list of children, and options.
- *
- * TODO: Ensure that `options` is always provided (currently some call sites
- * don't pass it).
- * TODO: add a separate argument for math class (e.g. `mop`, `mbin`), which
- * should if present come first in `classes`.
- */
- var makeSpan = function makeSpan(classes, children, options) {
- var span = new _domTree2.default.span(classes, children, options);
-
- sizeElementFromChildren(span);
-
- return span;
- };
-
- /**
- * Prepends the given children to the given span, updating height, depth, and
- * maxFontSize.
- */
- var prependChildren = function prependChildren(span, children) {
- span.children = children.concat(span.children);
-
- sizeElementFromChildren(span);
- };
-
- /**
- * Makes a document fragment with the given list of children.
- */
- var makeFragment = function makeFragment(children) {
- var fragment = new _domTree2.default.documentFragment(children);
-
- sizeElementFromChildren(fragment);
-
- return fragment;
- };
-
- /**
- * Makes a vertical list by stacking elements and kerns on top of each other.
- * Allows for many different ways of specifying the positioning method.
- *
- * Arguments:
- * - children: A list of child or kern nodes to be stacked on top of each other
- * (i.e. the first element will be at the bottom, and the last at
- * the top). Element nodes are specified as
- * {type: "elem", elem: node}
- * while kern nodes are specified as
- * {type: "kern", size: size}
- * - positionType: The method by which the vlist should be positioned. Valid
- * values are:
- * - "individualShift": The children list only contains elem
- * nodes, and each node contains an extra
- * "shift" value of how much it should be
- * shifted (note that shifting is always
- * moving downwards). positionData is
- * ignored.
- * - "top": The positionData specifies the topmost point of
- * the vlist (note this is expected to be a height,
- * so positive values move up)
- * - "bottom": The positionData specifies the bottommost point
- * of the vlist (note this is expected to be a
- * depth, so positive values move down
- * - "shift": The vlist will be positioned such that its
- * baseline is positionData away from the baseline
- * of the first child. Positive values move
- * downwards.
- * - "firstBaseline": The vlist will be positioned such that
- * its baseline is aligned with the
- * baseline of the first child.
- * positionData is ignored. (this is
- * equivalent to "shift" with
- * positionData=0)
- * - positionData: Data used in different ways depending on positionType
- * - options: An Options object
- *
- */
- var makeVList = function makeVList(children, positionType, positionData, options) {
- var depth = void 0;
- var currPos = void 0;
- var i = void 0;
- if (positionType === "individualShift") {
- var oldChildren = children;
- children = [oldChildren[0]];
-
- // Add in kerns to the list of children to get each element to be
- // shifted to the correct specified shift
- depth = -oldChildren[0].shift - oldChildren[0].elem.depth;
- currPos = depth;
- for (i = 1; i < oldChildren.length; i++) {
- var diff = -oldChildren[i].shift - currPos - oldChildren[i].elem.depth;
- var size = diff - (oldChildren[i - 1].elem.height + oldChildren[i - 1].elem.depth);
-
- currPos = currPos + diff;
-
- children.push({ type: "kern", size: size });
- children.push(oldChildren[i]);
- }
- } else if (positionType === "top") {
- // We always start at the bottom, so calculate the bottom by adding up
- // all the sizes
- var bottom = positionData;
- for (i = 0; i < children.length; i++) {
- if (children[i].type === "kern") {
- bottom -= children[i].size;
- } else {
- bottom -= children[i].elem.height + children[i].elem.depth;
- }
- }
- depth = bottom;
- } else if (positionType === "bottom") {
- depth = -positionData;
- } else if (positionType === "shift") {
- depth = -children[0].elem.depth - positionData;
- } else if (positionType === "firstBaseline") {
- depth = -children[0].elem.depth;
- } else {
- depth = 0;
- }
-
- // Create a strut that is taller than any list item. The strut is added to
- // each item, where it will determine the item's baseline. Since it has
- // `overflow:hidden`, the strut's top edge will sit on the item's line box's
- // top edge and the strut's bottom edge will sit on the item's baseline,
- // with no additional line-height spacing. This allows the item baseline to
- // be positioned precisely without worrying about font ascent and
- // line-height.
- var pstrutSize = 0;
- for (i = 0; i < children.length; i++) {
- if (children[i].type === "elem") {
- var child = children[i].elem;
- pstrutSize = Math.max(pstrutSize, child.maxFontSize, child.height);
- }
- }
- pstrutSize += 2;
- var pstrut = makeSpan(["pstrut"], []);
- pstrut.style.height = pstrutSize + "em";
-
- // Create a new list of actual children at the correct offsets
- var realChildren = [];
- var minPos = depth;
- var maxPos = depth;
- currPos = depth;
- for (i = 0; i < children.length; i++) {
- if (children[i].type === "kern") {
- currPos += children[i].size;
- } else {
- var _child = children[i].elem;
-
- var childWrap = makeSpan([], [pstrut, _child]);
- childWrap.style.top = -pstrutSize - currPos - _child.depth + "em";
- if (children[i].marginLeft) {
- childWrap.style.marginLeft = children[i].marginLeft;
- }
- if (children[i].marginRight) {
- childWrap.style.marginRight = children[i].marginRight;
- }
-
- realChildren.push(childWrap);
- currPos += _child.height + _child.depth;
- }
- minPos = Math.min(minPos, currPos);
- maxPos = Math.max(maxPos, currPos);
- }
-
- // The vlist contents go in a table-cell with `vertical-align:bottom`.
- // This cell's bottom edge will determine the containing table's baseline
- // without overly expanding the containing line-box.
- var vlist = makeSpan(["vlist"], realChildren);
- vlist.style.height = maxPos + "em";
-
- // A second row is used if necessary to represent the vlist's depth.
- var rows = void 0;
- if (minPos < 0) {
- var depthStrut = makeSpan(["vlist"], []);
- depthStrut.style.height = -minPos + "em";
-
- // Safari wants the first row to have inline content; otherwise it
- // puts the bottom of the *second* row on the baseline.
- var topStrut = makeSpan(["vlist-s"], [new _domTree2.default.symbolNode("\u200B")]);
-
- rows = [makeSpan(["vlist-r"], [vlist, topStrut]), makeSpan(["vlist-r"], [depthStrut])];
- } else {
- rows = [makeSpan(["vlist-r"], [vlist])];
- }
-
- var vtable = makeSpan(["vlist-t"], rows);
- if (rows.length === 2) {
- vtable.classes.push("vlist-t2");
- }
- vtable.height = maxPos;
- vtable.depth = -minPos;
- return vtable;
- };
-
- // A map of spacing functions to their attributes, like size and corresponding
- // CSS class
- var spacingFunctions = {
- "\\qquad": {
- size: "2em",
- className: "qquad"
- },
- "\\quad": {
- size: "1em",
- className: "quad"
- },
- "\\enspace": {
- size: "0.5em",
- className: "enspace"
- },
- "\\;": {
- size: "0.277778em",
- className: "thickspace"
- },
- "\\:": {
- size: "0.22222em",
- className: "mediumspace"
- },
- "\\,": {
- size: "0.16667em",
- className: "thinspace"
- },
- "\\!": {
- size: "-0.16667em",
- className: "negativethinspace"
- }
- };
-
- /**
- * Maps TeX font commands to objects containing:
- * - variant: string used for "mathvariant" attribute in buildMathML.js
- * - fontName: the "style" parameter to fontMetrics.getCharacterMetrics
- */
- // A map between tex font commands an MathML mathvariant attribute values
- var fontMap = {
- // styles
- "mathbf": {
- variant: "bold",
- fontName: "Main-Bold"
- },
- "mathrm": {
- variant: "normal",
- fontName: "Main-Regular"
- },
- "textit": {
- variant: "italic",
- fontName: "Main-Italic"
- },
-
- // "mathit" is missing because it requires the use of two fonts: Main-Italic
- // and Math-Italic. This is handled by a special case in makeOrd which ends
- // up calling mathit.
-
- // families
- "mathbb": {
- variant: "double-struck",
- fontName: "AMS-Regular"
- },
- "mathcal": {
- variant: "script",
- fontName: "Caligraphic-Regular"
- },
- "mathfrak": {
- variant: "fraktur",
- fontName: "Fraktur-Regular"
- },
- "mathscr": {
- variant: "script",
- fontName: "Script-Regular"
- },
- "mathsf": {
- variant: "sans-serif",
- fontName: "SansSerif-Regular"
- },
- "mathtt": {
- variant: "monospace",
- fontName: "Typewriter-Regular"
- }
- };
-
- module.exports = {
- fontMap: fontMap,
- makeSymbol: makeSymbol,
- mathsym: mathsym,
- makeSpan: makeSpan,
- makeFragment: makeFragment,
- makeVList: makeVList,
- makeOrd: makeOrd,
- prependChildren: prependChildren,
- spacingFunctions: spacingFunctions
- };
-
- },{"./domTree":39,"./fontMetrics":41,"./symbols":48,"./utils":51}],35:[function(require,module,exports){
-
- var _stringify = require("babel-runtime/core-js/json/stringify");
-
- var _stringify2 = _interopRequireDefault(_stringify);
-
- var _ParseError = require("./ParseError");
-
- var _ParseError2 = _interopRequireDefault(_ParseError);
-
- var _Style = require("./Style");
-
- var _Style2 = _interopRequireDefault(_Style);
-
- var _buildCommon = require("./buildCommon");
-
- var _buildCommon2 = _interopRequireDefault(_buildCommon);
-
- var _delimiter = require("./delimiter");
-
- var _delimiter2 = _interopRequireDefault(_delimiter);
-
- var _domTree = require("./domTree");
-
- var _domTree2 = _interopRequireDefault(_domTree);
-
- var _units = require("./units");
-
- var _units2 = _interopRequireDefault(_units);
-
- var _utils = require("./utils");
-
- var _utils2 = _interopRequireDefault(_utils);
-
- var _stretchy = require("./stretchy");
-
- var _stretchy2 = _interopRequireDefault(_stretchy);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /* eslint no-console:0 */
- /**
- * This file does the main work of building a domTree structure from a parse
- * tree. The entry point is the `buildHTML` function, which takes a parse tree.
- * Then, the buildExpression, buildGroup, and various groupTypes functions are
- * called, to produce a final HTML tree.
- */
-
- var isSpace = function isSpace(node) {
- return node instanceof _domTree2.default.span && node.classes[0] === "mspace";
- };
-
- // Binary atoms (first class `mbin`) change into ordinary atoms (`mord`)
- // depending on their surroundings. See TeXbook pg. 442-446, Rules 5 and 6,
- // and the text before Rule 19.
- var isBin = function isBin(node) {
- return node && node.classes[0] === "mbin";
- };
-
- var isBinLeftCanceller = function isBinLeftCanceller(node, isRealGroup) {
- // TODO: This code assumes that a node's math class is the first element
- // of its `classes` array. A later cleanup should ensure this, for
- // instance by changing the signature of `makeSpan`.
- if (node) {
- return _utils2.default.contains(["mbin", "mopen", "mrel", "mop", "mpunct"], node.classes[0]);
- } else {
- return isRealGroup;
- }
- };
-
- var isBinRightCanceller = function isBinRightCanceller(node, isRealGroup) {
- if (node) {
- return _utils2.default.contains(["mrel", "mclose", "mpunct"], node.classes[0]);
- } else {
- return isRealGroup;
- }
- };
-
- /**
- * Splice out any spaces from `children` starting at position `i`, and return
- * the spliced-out array. Returns null if `children[i]` does not exist or is not
- * a space.
- */
- var spliceSpaces = function spliceSpaces(children, i) {
- var j = i;
- while (j < children.length && isSpace(children[j])) {
- j++;
- }
- if (j === i) {
- return null;
- } else {
- return children.splice(i, j - i);
- }
- };
-
- /**
- * Take a list of nodes, build them in order, and return a list of the built
- * nodes. documentFragments are flattened into their contents, so the
- * returned list contains no fragments. `isRealGroup` is true if `expression`
- * is a real group (no atoms will be added on either side), as opposed to
- * a partial group (e.g. one created by \color).
- */
- var buildExpression = function buildExpression(expression, options, isRealGroup) {
- // Parse expressions into `groups`.
- var groups = [];
- for (var i = 0; i < expression.length; i++) {
- var group = expression[i];
- var output = buildGroup(group, options);
- if (output instanceof _domTree2.default.documentFragment) {
- Array.prototype.push.apply(groups, output.children);
- } else {
- groups.push(output);
- }
- }
- // At this point `groups` consists entirely of `symbolNode`s and `span`s.
-
- // Explicit spaces (e.g., \;, \,) should be ignored with respect to atom
- // spacing (e.g., "add thick space between mord and mrel"). Since CSS
- // adjacency rules implement atom spacing, spaces should be invisible to
- // CSS. So we splice them out of `groups` and into the atoms themselves.
- for (var _i = 0; _i < groups.length; _i++) {
- var spaces = spliceSpaces(groups, _i);
- if (spaces) {
- // Splicing of spaces may have removed all remaining groups.
- if (_i < groups.length) {
- // If there is a following group, move space within it.
- if (groups[_i] instanceof _domTree2.default.symbolNode) {
- groups[_i] = (0, _buildCommon.makeSpan)([].concat(groups[_i].classes), [groups[_i]]);
- }
- _buildCommon2.default.prependChildren(groups[_i], spaces);
- } else {
- // Otherwise, put any spaces back at the end of the groups.
- Array.prototype.push.apply(groups, spaces);
- break;
- }
- }
- }
-
- // Binary operators change to ordinary symbols in some contexts.
- for (var _i2 = 0; _i2 < groups.length; _i2++) {
- if (isBin(groups[_i2]) && (isBinLeftCanceller(groups[_i2 - 1], isRealGroup) || isBinRightCanceller(groups[_i2 + 1], isRealGroup))) {
- groups[_i2].classes[0] = "mord";
- }
- }
-
- // Process \\not commands within the group.
- // TODO(kevinb): Handle multiple \\not commands in a row.
- // TODO(kevinb): Handle \\not{abc} correctly. The \\not should appear over
- // the 'a' instead of the 'c'.
- for (var _i3 = 0; _i3 < groups.length; _i3++) {
- if (groups[_i3].value === "\u0338" && _i3 + 1 < groups.length) {
- var children = groups.slice(_i3, _i3 + 2);
-
- children[0].classes = ["mainrm"];
- // \u0338 is a combining glyph so we could reorder the children so
- // that it comes after the other glyph. This works correctly on
- // most browsers except for Safari. Instead we absolutely position
- // the glyph and set its right side to match that of the other
- // glyph which is visually equivalent.
- children[0].style.position = "absolute";
- children[0].style.right = "0";
-
- // Copy the classes from the second glyph to the new container.
- // This is so it behaves the same as though there was no \\not.
- var classes = groups[_i3 + 1].classes;
- var container = (0, _buildCommon.makeSpan)(classes, children);
-
- // LaTeX adds a space between ords separated by a \\not.
- if (classes.indexOf("mord") !== -1) {
- // \glue(\thickmuskip) 2.77771 plus 2.77771
- container.style.paddingLeft = "0.277771em";
- }
-
- // Ensure that the \u0338 is positioned relative to the container.
- container.style.position = "relative";
- groups.splice(_i3, 2, container);
- }
- }
-
- return groups;
- };
-
- // Return math atom class (mclass) of a domTree.
- var getTypeOfDomTree = function getTypeOfDomTree(node) {
- if (node instanceof _domTree2.default.documentFragment) {
- if (node.children.length) {
- return getTypeOfDomTree(node.children[node.children.length - 1]);
- }
- } else {
- if (_utils2.default.contains(["mord", "mop", "mbin", "mrel", "mopen", "mclose", "mpunct", "minner"], node.classes[0])) {
- return node.classes[0];
- }
- }
- return null;
- };
-
- /**
- * Sometimes, groups perform special rules when they have superscripts or
- * subscripts attached to them. This function lets the `supsub` group know that
- * its inner element should handle the superscripts and subscripts instead of
- * handling them itself.
- */
- var shouldHandleSupSub = function shouldHandleSupSub(group, options) {
- if (!group.value.base) {
- return false;
- } else {
- var base = group.value.base;
- if (base.type === "op") {
- // Operators handle supsubs differently when they have limits
- // (e.g. `\displaystyle\sum_2^3`)
- return base.value.limits && (options.style.size === _Style2.default.DISPLAY.size || base.value.alwaysHandleSupSub);
- } else if (base.type === "accent") {
- return isCharacterBox(base.value.base);
- } else if (base.type === "horizBrace") {
- var isSup = group.value.sub ? false : true;
- return isSup === base.value.isOver;
- } else {
- return null;
- }
- }
- };
-
- /**
- * Sometimes we want to pull out the innermost element of a group. In most
- * cases, this will just be the group itself, but when ordgroups and colors have
- * a single element, we want to pull that out.
- */
- var getBaseElem = function getBaseElem(group) {
- if (!group) {
- return false;
- } else if (group.type === "ordgroup") {
- if (group.value.length === 1) {
- return getBaseElem(group.value[0]);
- } else {
- return group;
- }
- } else if (group.type === "color") {
- if (group.value.value.length === 1) {
- return getBaseElem(group.value.value[0]);
- } else {
- return group;
- }
- } else if (group.type === "font") {
- return getBaseElem(group.value.body);
- } else {
- return group;
- }
- };
-
- /**
- * TeXbook algorithms often reference "character boxes", which are simply groups
- * with a single character in them. To decide if something is a character box,
- * we find its innermost group, and see if it is a single character.
- */
- var isCharacterBox = function isCharacterBox(group) {
- var baseElem = getBaseElem(group);
-
- // These are all they types of groups which hold single characters
- return baseElem.type === "mathord" || baseElem.type === "textord" || baseElem.type === "bin" || baseElem.type === "rel" || baseElem.type === "inner" || baseElem.type === "open" || baseElem.type === "close" || baseElem.type === "punct";
- };
-
- var makeNullDelimiter = function makeNullDelimiter(options, classes) {
- var moreClasses = ["nulldelimiter"].concat(options.baseSizingClasses());
- return (0, _buildCommon.makeSpan)(classes.concat(moreClasses));
- };
-
- /**
- * This is a map of group types to the function used to handle that type.
- * Simpler types come at the beginning, while complicated types come afterwards.
- */
- var groupTypes = {};
-
- groupTypes.mathord = function (group, options) {
- return _buildCommon2.default.makeOrd(group, options, "mathord");
- };
-
- groupTypes.textord = function (group, options) {
- return _buildCommon2.default.makeOrd(group, options, "textord");
- };
-
- groupTypes.bin = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["mbin"]);
- };
-
- groupTypes.rel = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["mrel"]);
- };
-
- groupTypes.open = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["mopen"]);
- };
-
- groupTypes.close = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["mclose"]);
- };
-
- groupTypes.inner = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["minner"]);
- };
-
- groupTypes.punct = function (group, options) {
- return _buildCommon2.default.mathsym(group.value, group.mode, options, ["mpunct"]);
- };
-
- groupTypes.ordgroup = function (group, options) {
- return (0, _buildCommon.makeSpan)(["mord"], buildExpression(group.value, options, true), options);
- };
-
- groupTypes.text = function (group, options) {
- var newOptions = options.withFont(group.value.style);
- var inner = buildExpression(group.value.body, newOptions, true);
- for (var i = 0; i < inner.length - 1; i++) {
- if (inner[i].tryCombine(inner[i + 1])) {
- inner.splice(i + 1, 1);
- i--;
- }
- }
- return (0, _buildCommon.makeSpan)(["mord", "text"], inner, newOptions);
- };
-
- groupTypes.color = function (group, options) {
- var elements = buildExpression(group.value.value, options.withColor(group.value.color), false);
-
- // \color isn't supposed to affect the type of the elements it contains.
- // To accomplish this, we wrap the results in a fragment, so the inner
- // elements will be able to directly interact with their neighbors. For
- // example, `\color{red}{2 +} 3` has the same spacing as `2 + 3`
- return new _buildCommon2.default.makeFragment(elements);
- };
-
- groupTypes.supsub = function (group, options) {
- // Superscript and subscripts are handled in the TeXbook on page
- // 445-446, rules 18(a-f).
-
- // Here is where we defer to the inner group if it should handle
- // superscripts and subscripts itself.
- if (shouldHandleSupSub(group, options)) {
- return groupTypes[group.value.base.type](group, options);
- }
-
- var base = buildGroup(group.value.base, options);
- var supm = void 0;
- var subm = void 0;
-
- var metrics = options.fontMetrics();
- var newOptions = void 0;
-
- // Rule 18a
- var supShift = 0;
- var subShift = 0;
-
- if (group.value.sup) {
- newOptions = options.havingStyle(options.style.sup());
- supm = buildGroup(group.value.sup, newOptions, options);
- if (!isCharacterBox(group.value.base)) {
- supShift = base.height - newOptions.fontMetrics().supDrop * newOptions.sizeMultiplier / options.sizeMultiplier;
- }
- }
-
- if (group.value.sub) {
- newOptions = options.havingStyle(options.style.sub());
- subm = buildGroup(group.value.sub, newOptions, options);
- if (!isCharacterBox(group.value.base)) {
- subShift = base.depth + newOptions.fontMetrics().subDrop * newOptions.sizeMultiplier / options.sizeMultiplier;
- }
- }
-
- // Rule 18c
- var minSupShift = void 0;
- if (options.style === _Style2.default.DISPLAY) {
- minSupShift = metrics.sup1;
- } else if (options.style.cramped) {
- minSupShift = metrics.sup3;
- } else {
- minSupShift = metrics.sup2;
- }
-
- // scriptspace is a font-size-independent size, so scale it
- // appropriately
- var multiplier = options.sizeMultiplier;
- var scriptspace = 0.5 / metrics.ptPerEm / multiplier + "em";
-
- var supsub = void 0;
- if (!group.value.sup) {
- // Rule 18b
- subShift = Math.max(subShift, metrics.sub1, subm.height - 0.8 * metrics.xHeight);
-
- var vlistElem = [{ type: "elem", elem: subm, marginRight: scriptspace }];
- // Subscripts shouldn't be shifted by the base's italic correction.
- // Account for that by shifting the subscript back the appropriate
- // amount. Note we only do this when the base is a single symbol.
- if (base instanceof _domTree2.default.symbolNode) {
- vlistElem[0].marginLeft = -base.italic + "em";
- }
-
- supsub = _buildCommon2.default.makeVList(vlistElem, "shift", subShift, options);
- } else if (!group.value.sub) {
- // Rule 18c, d
- supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
-
- supsub = _buildCommon2.default.makeVList([{ type: "elem", elem: supm, marginRight: scriptspace }], "shift", -supShift, options);
- } else {
- supShift = Math.max(supShift, minSupShift, supm.depth + 0.25 * metrics.xHeight);
- subShift = Math.max(subShift, metrics.sub2);
-
- var ruleWidth = metrics.defaultRuleThickness;
-
- // Rule 18e
- if (supShift - supm.depth - (subm.height - subShift) < 4 * ruleWidth) {
- subShift = 4 * ruleWidth - (supShift - supm.depth) + subm.height;
- var psi = 0.8 * metrics.xHeight - (supShift - supm.depth);
- if (psi > 0) {
- supShift += psi;
- subShift -= psi;
- }
- }
-
- var _vlistElem = [{ type: "elem", elem: subm, shift: subShift, marginRight: scriptspace }, { type: "elem", elem: supm, shift: -supShift, marginRight: scriptspace }];
- // See comment above about subscripts not being shifted
- if (base instanceof _domTree2.default.symbolNode) {
- _vlistElem[0].marginLeft = -base.italic + "em";
- }
-
- supsub = _buildCommon2.default.makeVList(_vlistElem, "individualShift", null, options);
- }
-
- // We ensure to wrap the supsub vlist in a span.msupsub to reset text-align
- var mclass = getTypeOfDomTree(base) || "mord";
- return (0, _buildCommon.makeSpan)([mclass], [base, (0, _buildCommon.makeSpan)(["msupsub"], [supsub])], options);
- };
-
- groupTypes.genfrac = function (group, options) {
- // Fractions are handled in the TeXbook on pages 444-445, rules 15(a-e).
- // Figure out what style this fraction should be in based on the
- // function used
- var style = options.style;
- if (group.value.size === "display") {
- style = _Style2.default.DISPLAY;
- } else if (group.value.size === "text") {
- style = _Style2.default.TEXT;
- }
-
- var nstyle = style.fracNum();
- var dstyle = style.fracDen();
- var newOptions = void 0;
-
- newOptions = options.havingStyle(nstyle);
- var numerm = buildGroup(group.value.numer, newOptions, options);
-
- newOptions = options.havingStyle(dstyle);
- var denomm = buildGroup(group.value.denom, newOptions, options);
-
- var rule = void 0;
- var ruleWidth = void 0;
- var ruleSpacing = void 0;
- if (group.value.hasBarLine) {
- rule = makeLineSpan("frac-line", options);
- ruleWidth = rule.height;
- ruleSpacing = rule.height;
- } else {
- rule = null;
- ruleWidth = 0;
- ruleSpacing = options.fontMetrics().defaultRuleThickness;
- }
-
- // Rule 15b
- var numShift = void 0;
- var clearance = void 0;
- var denomShift = void 0;
- if (style.size === _Style2.default.DISPLAY.size) {
- numShift = options.fontMetrics().num1;
- if (ruleWidth > 0) {
- clearance = 3 * ruleSpacing;
- } else {
- clearance = 7 * ruleSpacing;
- }
- denomShift = options.fontMetrics().denom1;
- } else {
- if (ruleWidth > 0) {
- numShift = options.fontMetrics().num2;
- clearance = ruleSpacing;
- } else {
- numShift = options.fontMetrics().num3;
- clearance = 3 * ruleSpacing;
- }
- denomShift = options.fontMetrics().denom2;
- }
-
- var frac = void 0;
- if (ruleWidth === 0) {
- // Rule 15c
- var candidateClearance = numShift - numerm.depth - (denomm.height - denomShift);
- if (candidateClearance < clearance) {
- numShift += 0.5 * (clearance - candidateClearance);
- denomShift += 0.5 * (clearance - candidateClearance);
- }
-
- frac = _buildCommon2.default.makeVList([{ type: "elem", elem: denomm, shift: denomShift }, { type: "elem", elem: numerm, shift: -numShift }], "individualShift", null, options);
- } else {
- // Rule 15d
- var axisHeight = options.fontMetrics().axisHeight;
-
- if (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth) < clearance) {
- numShift += clearance - (numShift - numerm.depth - (axisHeight + 0.5 * ruleWidth));
- }
-
- if (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift) < clearance) {
- denomShift += clearance - (axisHeight - 0.5 * ruleWidth - (denomm.height - denomShift));
- }
-
- var midShift = -(axisHeight - 0.5 * ruleWidth);
-
- frac = _buildCommon2.default.makeVList([{ type: "elem", elem: denomm, shift: denomShift }, { type: "elem", elem: rule, shift: midShift }, { type: "elem", elem: numerm, shift: -numShift }], "individualShift", null, options);
- }
-
- // Since we manually change the style sometimes (with \dfrac or \tfrac),
- // account for the possible size change here.
- newOptions = options.havingStyle(style);
- frac.height *= newOptions.sizeMultiplier / options.sizeMultiplier;
- frac.depth *= newOptions.sizeMultiplier / options.sizeMultiplier;
-
- // Rule 15e
- var delimSize = void 0;
- if (style.size === _Style2.default.DISPLAY.size) {
- delimSize = options.fontMetrics().delim1;
- } else {
- delimSize = options.fontMetrics().delim2;
- }
-
- var leftDelim = void 0;
- var rightDelim = void 0;
- if (group.value.leftDelim == null) {
- leftDelim = makeNullDelimiter(options, ["mopen"]);
- } else {
- leftDelim = _delimiter2.default.customSizedDelim(group.value.leftDelim, delimSize, true, options.havingStyle(style), group.mode, ["mopen"]);
- }
- if (group.value.rightDelim == null) {
- rightDelim = makeNullDelimiter(options, ["mclose"]);
- } else {
- rightDelim = _delimiter2.default.customSizedDelim(group.value.rightDelim, delimSize, true, options.havingStyle(style), group.mode, ["mclose"]);
- }
-
- return (0, _buildCommon.makeSpan)(["mord"].concat(newOptions.sizingClasses(options)), [leftDelim, (0, _buildCommon.makeSpan)(["mfrac"], [frac]), rightDelim], options);
- };
-
- groupTypes.array = function (group, options) {
- var r = void 0;
- var c = void 0;
- var nr = group.value.body.length;
- var nc = 0;
- var body = new Array(nr);
-
- // Horizontal spacing
- var pt = 1 / options.fontMetrics().ptPerEm;
- var arraycolsep = 5 * pt; // \arraycolsep in article.cls
-
- // Vertical spacing
- var baselineskip = 12 * pt; // see size10.clo
- // Default \jot from ltmath.dtx
- // TODO(edemaine): allow overriding \jot via \setlength (#687)
- var jot = 3 * pt;
- // Default \arraystretch from lttab.dtx
- // TODO(gagern): may get redefined once we have user-defined macros
- var arraystretch = _utils2.default.deflt(group.value.arraystretch, 1);
- var arrayskip = arraystretch * baselineskip;
- var arstrutHeight = 0.7 * arrayskip; // \strutbox in ltfsstrc.dtx and
- var arstrutDepth = 0.3 * arrayskip; // \@arstrutbox in lttab.dtx
-
- var totalHeight = 0;
- for (r = 0; r < group.value.body.length; ++r) {
- var inrow = group.value.body[r];
- var height = arstrutHeight; // \@array adds an \@arstrut
- var depth = arstrutDepth; // to each tow (via the template)
-
- if (nc < inrow.length) {
- nc = inrow.length;
- }
-
- var outrow = new Array(inrow.length);
- for (c = 0; c < inrow.length; ++c) {
- var elt = buildGroup(inrow[c], options);
- if (depth < elt.depth) {
- depth = elt.depth;
- }
- if (height < elt.height) {
- height = elt.height;
- }
- outrow[c] = elt;
- }
-
- var gap = 0;
- if (group.value.rowGaps[r]) {
- gap = _units2.default.calculateSize(group.value.rowGaps[r].value, options);
- if (gap > 0) {
- // \@argarraycr
- gap += arstrutDepth;
- if (depth < gap) {
- depth = gap; // \@xargarraycr
- }
- gap = 0;
- }
- }
- // In AMS multiline environments such as aligned and gathered, rows
- // correspond to lines that have additional \jot added to the
- // \baselineskip via \openup.
- if (group.value.addJot) {
- depth += jot;
- }
-
- outrow.height = height;
- outrow.depth = depth;
- totalHeight += height;
- outrow.pos = totalHeight;
- totalHeight += depth + gap; // \@yargarraycr
- body[r] = outrow;
- }
-
- var offset = totalHeight / 2 + options.fontMetrics().axisHeight;
- var colDescriptions = group.value.cols || [];
- var cols = [];
- var colSep = void 0;
- var colDescrNum = void 0;
- for (c = 0, colDescrNum = 0;
- // Continue while either there are more columns or more column
- // descriptions, so trailing separators don't get lost.
- c < nc || colDescrNum < colDescriptions.length; ++c, ++colDescrNum) {
-
- var colDescr = colDescriptions[colDescrNum] || {};
-
- var firstSeparator = true;
- while (colDescr.type === "separator") {
- // If there is more than one separator in a row, add a space
- // between them.
- if (!firstSeparator) {
- colSep = (0, _buildCommon.makeSpan)(["arraycolsep"], []);
- colSep.style.width = options.fontMetrics().doubleRuleSep + "em";
- cols.push(colSep);
- }
-
- if (colDescr.separator === "|") {
- var separator = (0, _buildCommon.makeSpan)(["vertical-separator"], []);
- separator.style.height = totalHeight + "em";
- separator.style.verticalAlign = -(totalHeight - offset) + "em";
-
- cols.push(separator);
- } else {
- throw new _ParseError2.default("Invalid separator type: " + colDescr.separator);
- }
-
- colDescrNum++;
- colDescr = colDescriptions[colDescrNum] || {};
- firstSeparator = false;
- }
-
- if (c >= nc) {
- continue;
- }
-
- var sepwidth = void 0;
- if (c > 0 || group.value.hskipBeforeAndAfter) {
- sepwidth = _utils2.default.deflt(colDescr.pregap, arraycolsep);
- if (sepwidth !== 0) {
- colSep = (0, _buildCommon.makeSpan)(["arraycolsep"], []);
- colSep.style.width = sepwidth + "em";
- cols.push(colSep);
- }
- }
-
- var col = [];
- for (r = 0; r < nr; ++r) {
- var row = body[r];
- var elem = row[c];
- if (!elem) {
- continue;
- }
- var shift = row.pos - offset;
- elem.depth = row.depth;
- elem.height = row.height;
- col.push({ type: "elem", elem: elem, shift: shift });
- }
-
- col = _buildCommon2.default.makeVList(col, "individualShift", null, options);
- col = (0, _buildCommon.makeSpan)(["col-align-" + (colDescr.align || "c")], [col]);
- cols.push(col);
-
- if (c < nc - 1 || group.value.hskipBeforeAndAfter) {
- sepwidth = _utils2.default.deflt(colDescr.postgap, arraycolsep);
- if (sepwidth !== 0) {
- colSep = (0, _buildCommon.makeSpan)(["arraycolsep"], []);
- colSep.style.width = sepwidth + "em";
- cols.push(colSep);
- }
- }
- }
- body = (0, _buildCommon.makeSpan)(["mtable"], cols);
- return (0, _buildCommon.makeSpan)(["mord"], [body], options);
- };
-
- groupTypes.spacing = function (group, options) {
- if (group.value === "\\ " || group.value === "\\space" || group.value === " " || group.value === "~") {
- // Spaces are generated by adding an actual space. Each of these
- // things has an entry in the symbols table, so these will be turned
- // into appropriate outputs.
- if (group.mode === "text") {
- return _buildCommon2.default.makeOrd(group, options, "textord");
- } else {
- return (0, _buildCommon.makeSpan)(["mspace"], [_buildCommon2.default.mathsym(group.value, group.mode, options)], options);
- }
- } else {
- // Other kinds of spaces are of arbitrary width. We use CSS to
- // generate these.
- return (0, _buildCommon.makeSpan)(["mspace", _buildCommon2.default.spacingFunctions[group.value].className], [], options);
- }
- };
-
- groupTypes.llap = function (group, options) {
- var inner = (0, _buildCommon.makeSpan)(["inner"], [buildGroup(group.value.body, options)]);
- var fix = (0, _buildCommon.makeSpan)(["fix"], []);
- return (0, _buildCommon.makeSpan)(["mord", "llap"], [inner, fix], options);
- };
-
- groupTypes.rlap = function (group, options) {
- var inner = (0, _buildCommon.makeSpan)(["inner"], [buildGroup(group.value.body, options)]);
- var fix = (0, _buildCommon.makeSpan)(["fix"], []);
- return (0, _buildCommon.makeSpan)(["mord", "rlap"], [inner, fix], options);
- };
-
- groupTypes.op = function (group, options) {
- // Operators are handled in the TeXbook pg. 443-444, rule 13(a).
- var supGroup = void 0;
- var subGroup = void 0;
- var hasLimits = false;
- if (group.type === "supsub") {
- // If we have limits, supsub will pass us its group to handle. Pull
- // out the superscript and subscript and set the group to the op in
- // its base.
- supGroup = group.value.sup;
- subGroup = group.value.sub;
- group = group.value.base;
- hasLimits = true;
- }
-
- var style = options.style;
-
- // Most operators have a large successor symbol, but these don't.
- var noSuccessor = ["\\smallint"];
-
- var large = false;
- if (style.size === _Style2.default.DISPLAY.size && group.value.symbol && !_utils2.default.contains(noSuccessor, group.value.body)) {
-
- // Most symbol operators get larger in displaystyle (rule 13)
- large = true;
- }
-
- var base = void 0;
- if (group.value.symbol) {
- // If this is a symbol, create the symbol.
- var fontName = large ? "Size2-Regular" : "Size1-Regular";
- base = _buildCommon2.default.makeSymbol(group.value.body, fontName, "math", options, ["mop", "op-symbol", large ? "large-op" : "small-op"]);
- } else if (group.value.value) {
- // If this is a list, compose that list.
- var inner = buildExpression(group.value.value, options, true);
- if (inner.length === 1 && inner[0] instanceof _domTree2.default.symbolNode) {
- base = inner[0];
- base.classes[0] = "mop"; // replace old mclass
- } else {
- base = (0, _buildCommon.makeSpan)(["mop"], inner, options);
- }
- } else {
- // Otherwise, this is a text operator. Build the text from the
- // operator's name.
- // TODO(emily): Add a space in the middle of some of these
- // operators, like \limsup
- var output = [];
- for (var i = 1; i < group.value.body.length; i++) {
- output.push(_buildCommon2.default.mathsym(group.value.body[i], group.mode));
- }
- base = (0, _buildCommon.makeSpan)(["mop"], output, options);
- }
-
- // If content of op is a single symbol, shift it vertically.
- var baseShift = 0;
- var slant = 0;
- if (base instanceof _domTree2.default.symbolNode) {
- // Shift the symbol so its center lies on the axis (rule 13). It
- // appears that our fonts have the centers of the symbols already
- // almost on the axis, so these numbers are very small. Note we
- // don't actually apply this here, but instead it is used either in
- // the vlist creation or separately when there are no limits.
- baseShift = (base.height - base.depth) / 2 - options.fontMetrics().axisHeight;
-
- // The slant of the symbol is just its italic correction.
- slant = base.italic;
- }
-
- if (hasLimits) {
- // IE 8 clips \int if it is in a display: inline-block. We wrap it
- // in a new span so it is an inline, and works.
- base = (0, _buildCommon.makeSpan)([], [base]);
-
- var supm = void 0;
- var supKern = void 0;
- var subm = void 0;
- var subKern = void 0;
- var newOptions = void 0;
- // We manually have to handle the superscripts and subscripts. This,
- // aside from the kern calculations, is copied from supsub.
- if (supGroup) {
- newOptions = options.havingStyle(style.sup());
- supm = buildGroup(supGroup, newOptions, options);
-
- supKern = Math.max(options.fontMetrics().bigOpSpacing1, options.fontMetrics().bigOpSpacing3 - supm.depth);
- }
-
- if (subGroup) {
- newOptions = options.havingStyle(style.sub());
- subm = buildGroup(subGroup, newOptions, options);
-
- subKern = Math.max(options.fontMetrics().bigOpSpacing2, options.fontMetrics().bigOpSpacing4 - subm.height);
- }
-
- // Build the final group as a vlist of the possible subscript, base,
- // and possible superscript.
- var finalGroup = void 0;
- var top = void 0;
- var bottom = void 0;
- if (!supGroup) {
- top = base.height - baseShift;
-
- // Shift the limits by the slant of the symbol. Note
- // that we are supposed to shift the limits by 1/2 of the slant,
- // but since we are centering the limits adding a full slant of
- // margin will shift by 1/2 that.
- finalGroup = _buildCommon2.default.makeVList([{ type: "kern", size: options.fontMetrics().bigOpSpacing5 }, { type: "elem", elem: subm, marginLeft: -slant + "em" }, { type: "kern", size: subKern }, { type: "elem", elem: base }], "top", top, options);
- } else if (!subGroup) {
- bottom = base.depth + baseShift;
-
- finalGroup = _buildCommon2.default.makeVList([{ type: "elem", elem: base }, { type: "kern", size: supKern }, { type: "elem", elem: supm, marginLeft: slant + "em" }, { type: "kern", size: options.fontMetrics().bigOpSpacing5 }], "bottom", bottom, options);
- } else if (!supGroup && !subGroup) {
- // This case probably shouldn't occur (this would mean the
- // supsub was sending us a group with no superscript or
- // subscript) but be safe.
- return base;
- } else {
- bottom = options.fontMetrics().bigOpSpacing5 + subm.height + subm.depth + subKern + base.depth + baseShift;
-
- finalGroup = _buildCommon2.default.makeVList([{ type: "kern", size: options.fontMetrics().bigOpSpacing5 }, { type: "elem", elem: subm, marginLeft: -slant + "em" }, { type: "kern", size: subKern }, { type: "elem", elem: base }, { type: "kern", size: supKern }, { type: "elem", elem: supm, marginLeft: slant + "em" }, { type: "kern", size: options.fontMetrics().bigOpSpacing5 }], "bottom", bottom, options);
- }
-
- return (0, _buildCommon.makeSpan)(["mop", "op-limits"], [finalGroup], options);
- } else {
- if (baseShift) {
- base.style.position = "relative";
- base.style.top = baseShift + "em";
- }
-
- return base;
- }
- };
-
- groupTypes.mod = function (group, options) {
- var inner = [];
-
- if (group.value.modType === "bmod") {
- // “\nonscript\mskip-\medmuskip\mkern5mu”
- if (!options.style.isTight()) {
- inner.push((0, _buildCommon.makeSpan)(["mspace", "negativemediumspace"], [], options));
- }
- inner.push((0, _buildCommon.makeSpan)(["mspace", "thickspace"], [], options));
- } else if (options.style.size === _Style2.default.DISPLAY.size) {
- inner.push((0, _buildCommon.makeSpan)(["mspace", "quad"], [], options));
- } else if (group.value.modType === "mod") {
- inner.push((0, _buildCommon.makeSpan)(["mspace", "twelvemuspace"], [], options));
- } else {
- inner.push((0, _buildCommon.makeSpan)(["mspace", "eightmuspace"], [], options));
- }
-
- if (group.value.modType === "pod" || group.value.modType === "pmod") {
- inner.push(_buildCommon2.default.mathsym("(", group.mode));
- }
-
- if (group.value.modType !== "pod") {
- var modInner = [_buildCommon2.default.mathsym("m", group.mode), _buildCommon2.default.mathsym("o", group.mode), _buildCommon2.default.mathsym("d", group.mode)];
- if (group.value.modType === "bmod") {
- inner.push((0, _buildCommon.makeSpan)(["mbin"], modInner, options));
- // “\mkern5mu\nonscript\mskip-\medmuskip”
- inner.push((0, _buildCommon.makeSpan)(["mspace", "thickspace"], [], options));
- if (!options.style.isTight()) {
- inner.push((0, _buildCommon.makeSpan)(["mspace", "negativemediumspace"], [], options));
- }
- } else {
- Array.prototype.push.apply(inner, modInner);
- inner.push((0, _buildCommon.makeSpan)(["mspace", "sixmuspace"], [], options));
- }
- }
-
- if (group.value.value) {
- Array.prototype.push.apply(inner, buildExpression(group.value.value, options, false));
- }
-
- if (group.value.modType === "pod" || group.value.modType === "pmod") {
- inner.push(_buildCommon2.default.mathsym(")", group.mode));
- }
-
- return _buildCommon2.default.makeFragment(inner);
- };
-
- groupTypes.katex = function (group, options) {
- // The KaTeX logo. The offsets for the K and a were chosen to look
- // good, but the offsets for the T, E, and X were taken from the
- // definition of \TeX in TeX (see TeXbook pg. 356)
- var k = (0, _buildCommon.makeSpan)(["k"], [_buildCommon2.default.mathsym("K", group.mode)], options);
- var a = (0, _buildCommon.makeSpan)(["a"], [_buildCommon2.default.mathsym("A", group.mode)], options);
-
- a.height = (a.height + 0.2) * 0.75;
- a.depth = (a.height - 0.2) * 0.75;
-
- var t = (0, _buildCommon.makeSpan)(["t"], [_buildCommon2.default.mathsym("T", group.mode)], options);
- var e = (0, _buildCommon.makeSpan)(["e"], [_buildCommon2.default.mathsym("E", group.mode)], options);
-
- e.height = e.height - 0.2155;
- e.depth = e.depth + 0.2155;
-
- var x = (0, _buildCommon.makeSpan)(["x"], [_buildCommon2.default.mathsym("X", group.mode)], options);
-
- return (0, _buildCommon.makeSpan)(["mord", "katex-logo"], [k, a, t, e, x], options);
- };
-
- var makeLineSpan = function makeLineSpan(className, options, thickness) {
- var line = (0, _buildCommon.makeSpan)([className], [], options);
- line.height = thickness || options.fontMetrics().defaultRuleThickness;
- line.style.borderBottomWidth = line.height + "em";
- line.maxFontSize = 1.0;
- return line;
- };
-
- groupTypes.overline = function (group, options) {
- // Overlines are handled in the TeXbook pg 443, Rule 9.
-
- // Build the inner group in the cramped style.
- var innerGroup = buildGroup(group.value.body, options.havingCrampedStyle());
-
- // Create the line above the body
- var line = makeLineSpan("overline-line", options);
-
- // Generate the vlist, with the appropriate kerns
- var vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: innerGroup }, { type: "kern", size: 3 * line.height }, { type: "elem", elem: line }, { type: "kern", size: line.height }], "firstBaseline", null, options);
-
- return (0, _buildCommon.makeSpan)(["mord", "overline"], [vlist], options);
- };
-
- groupTypes.underline = function (group, options) {
- // Underlines are handled in the TeXbook pg 443, Rule 10.
- // Build the inner group.
- var innerGroup = buildGroup(group.value.body, options);
-
- // Create the line above the body
- var line = makeLineSpan("underline-line", options);
-
- // Generate the vlist, with the appropriate kerns
- var vlist = _buildCommon2.default.makeVList([{ type: "kern", size: line.height }, { type: "elem", elem: line }, { type: "kern", size: 3 * line.height }, { type: "elem", elem: innerGroup }], "top", innerGroup.height, options);
-
- return (0, _buildCommon.makeSpan)(["mord", "underline"], [vlist], options);
- };
-
- groupTypes.sqrt = function (group, options) {
- // Square roots are handled in the TeXbook pg. 443, Rule 11.
-
- // First, we do the same steps as in overline to build the inner group
- // and line
- var inner = buildGroup(group.value.body, options.havingCrampedStyle());
-
- // Some groups can return document fragments. Handle those by wrapping
- // them in a span.
- if (inner instanceof _domTree2.default.documentFragment) {
- inner = (0, _buildCommon.makeSpan)([], [inner], options);
- }
-
- // Calculate the minimum size for the \surd delimiter
- var metrics = options.fontMetrics();
- var theta = metrics.defaultRuleThickness;
-
- var phi = theta;
- if (options.style.id < _Style2.default.TEXT.id) {
- phi = options.fontMetrics().xHeight;
- }
-
- // Calculate the clearance between the body and line
- var lineClearance = theta + phi / 4;
-
- var minDelimiterHeight = (inner.height + inner.depth + lineClearance + theta) * options.sizeMultiplier;
-
- // Create a sqrt SVG of the required minimum size
- var img = _delimiter2.default.customSizedDelim("\\surd", minDelimiterHeight, false, options, group.mode);
-
- // Calculate the actual line width.
- // This actually should depend on the chosen font -- e.g. \boldmath
- // should use the thicker surd symbols from e.g. KaTeX_Main-Bold, and
- // have thicker rules.
- var ruleWidth = options.fontMetrics().sqrtRuleThickness * img.sizeMultiplier;
-
- var delimDepth = img.height - ruleWidth;
-
- // Adjust the clearance based on the delimiter size
- if (delimDepth > inner.height + inner.depth + lineClearance) {
- lineClearance = (lineClearance + delimDepth - inner.height - inner.depth) / 2;
- }
-
- // Shift the sqrt image
- var imgShift = img.height - inner.height - lineClearance - ruleWidth;
-
- // We add a special case here, because even when `inner` is empty, we
- // still get a line. So, we use a simple heuristic to decide if we
- // should omit the body entirely. (note this doesn't work for something
- // like `\sqrt{\rlap{x}}`, but if someone is doing that they deserve for
- // it not to work.
- var body = void 0;
- if (inner.height === 0 && inner.depth === 0) {
- body = (0, _buildCommon.makeSpan)();
- } else {
- inner.style.paddingLeft = img.surdWidth + "em";
-
- // Overlay the image and the argument.
- body = _buildCommon2.default.makeVList([{ type: "elem", elem: inner }, { type: "kern", size: -(inner.height + imgShift) }, { type: "elem", elem: img }, { type: "kern", size: ruleWidth }], "firstBaseline", null, options);
- body.children[0].children[0].classes.push("svg-align");
- }
-
- if (!group.value.index) {
- return (0, _buildCommon.makeSpan)(["mord", "sqrt"], [body], options);
- } else {
- // Handle the optional root index
-
- // The index is always in scriptscript style
- var newOptions = options.havingStyle(_Style2.default.SCRIPTSCRIPT);
- var rootm = buildGroup(group.value.index, newOptions, options);
-
- // The amount the index is shifted by. This is taken from the TeX
- // source, in the definition of `\r@@t`.
- var toShift = 0.6 * (body.height - body.depth);
-
- // Build a VList with the superscript shifted up correctly
- var rootVList = _buildCommon2.default.makeVList([{ type: "elem", elem: rootm }], "shift", -toShift, options);
- // Add a class surrounding it so we can add on the appropriate
- // kerning
- var rootVListWrap = (0, _buildCommon.makeSpan)(["root"], [rootVList]);
-
- return (0, _buildCommon.makeSpan)(["mord", "sqrt"], [rootVListWrap, body], options);
- }
- };
-
- function sizingGroup(value, options, baseOptions) {
- var inner = buildExpression(value, options, false);
- var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
-
- // Add size-resetting classes to the inner list and set maxFontSize
- // manually. Handle nested size changes.
- for (var i = 0; i < inner.length; i++) {
- var pos = _utils2.default.indexOf(inner[i].classes, "sizing");
- if (pos < 0) {
- Array.prototype.push.apply(inner[i].classes, options.sizingClasses(baseOptions));
- } else if (inner[i].classes[pos + 1] === "reset-size" + options.size) {
- // This is a nested size change: e.g., inner[i] is the "b" in
- // `\Huge a \small b`. Override the old size (the `reset-` class)
- // but not the new size.
- inner[i].classes[pos + 1] = "reset-size" + baseOptions.size;
- }
-
- inner[i].height *= multiplier;
- inner[i].depth *= multiplier;
- }
-
- return _buildCommon2.default.makeFragment(inner);
- }
-
- groupTypes.sizing = function (group, options) {
- // Handle sizing operators like \Huge. Real TeX doesn't actually allow
- // these functions inside of math expressions, so we do some special
- // handling.
- var newOptions = options.havingSize(group.value.size);
- return sizingGroup(group.value.value, newOptions, options);
- };
-
- groupTypes.styling = function (group, options) {
- // Style changes are handled in the TeXbook on pg. 442, Rule 3.
-
- // Figure out what style we're changing to.
- var styleMap = {
- "display": _Style2.default.DISPLAY,
- "text": _Style2.default.TEXT,
- "script": _Style2.default.SCRIPT,
- "scriptscript": _Style2.default.SCRIPTSCRIPT
- };
-
- var newStyle = styleMap[group.value.style];
- var newOptions = options.havingStyle(newStyle);
- return sizingGroup(group.value.value, newOptions, options);
- };
-
- groupTypes.font = function (group, options) {
- var font = group.value.font;
- return buildGroup(group.value.body, options.withFont(font));
- };
-
- groupTypes.delimsizing = function (group, options) {
- var delim = group.value.value;
-
- if (delim === ".") {
- // Empty delimiters still count as elements, even though they don't
- // show anything.
- return (0, _buildCommon.makeSpan)([group.value.mclass]);
- }
-
- // Use delimiter.sizedDelim to generate the delimiter.
- return _delimiter2.default.sizedDelim(delim, group.value.size, options, group.mode, [group.value.mclass]);
- };
-
- groupTypes.leftright = function (group, options) {
- // Build the inner expression
- var inner = buildExpression(group.value.body, options, true);
-
- var innerHeight = 0;
- var innerDepth = 0;
- var hadMiddle = false;
-
- // Calculate its height and depth
- for (var i = 0; i < inner.length; i++) {
- if (inner[i].isMiddle) {
- hadMiddle = true;
- } else {
- innerHeight = Math.max(inner[i].height, innerHeight);
- innerDepth = Math.max(inner[i].depth, innerDepth);
- }
- }
-
- // The size of delimiters is the same, regardless of what style we are
- // in. Thus, to correctly calculate the size of delimiter we need around
- // a group, we scale down the inner size based on the size.
- innerHeight *= options.sizeMultiplier;
- innerDepth *= options.sizeMultiplier;
-
- var leftDelim = void 0;
- if (group.value.left === ".") {
- // Empty delimiters in \left and \right make null delimiter spaces.
- leftDelim = makeNullDelimiter(options, ["mopen"]);
- } else {
- // Otherwise, use leftRightDelim to generate the correct sized
- // delimiter.
- leftDelim = _delimiter2.default.leftRightDelim(group.value.left, innerHeight, innerDepth, options, group.mode, ["mopen"]);
- }
- // Add it to the beginning of the expression
- inner.unshift(leftDelim);
-
- // Handle middle delimiters
- if (hadMiddle) {
- for (var _i4 = 1; _i4 < inner.length; _i4++) {
- var middleDelim = inner[_i4];
- if (middleDelim.isMiddle) {
- // Apply the options that were active when \middle was called
- inner[_i4] = _delimiter2.default.leftRightDelim(middleDelim.isMiddle.value, innerHeight, innerDepth, middleDelim.isMiddle.options, group.mode, []);
- // Add back spaces shifted into the delimiter
- var spaces = spliceSpaces(middleDelim.children, 0);
- if (spaces) {
- _buildCommon2.default.prependChildren(inner[_i4], spaces);
- }
- }
- }
- }
-
- var rightDelim = void 0;
- // Same for the right delimiter
- if (group.value.right === ".") {
- rightDelim = makeNullDelimiter(options, ["mclose"]);
- } else {
- rightDelim = _delimiter2.default.leftRightDelim(group.value.right, innerHeight, innerDepth, options, group.mode, ["mclose"]);
- }
- // Add it to the end of the expression.
- inner.push(rightDelim);
-
- return (0, _buildCommon.makeSpan)(["minner"], inner, options);
- };
-
- groupTypes.middle = function (group, options) {
- var middleDelim = void 0;
- if (group.value.value === ".") {
- middleDelim = makeNullDelimiter(options, []);
- } else {
- middleDelim = _delimiter2.default.sizedDelim(group.value.value, 1, options, group.mode, []);
- middleDelim.isMiddle = { value: group.value.value, options: options };
- }
- return middleDelim;
- };
-
- groupTypes.rule = function (group, options) {
- // Make an empty span for the rule
- var rule = (0, _buildCommon.makeSpan)(["mord", "rule"], [], options);
-
- // Calculate the shift, width, and height of the rule, and account for units
- var shift = 0;
- if (group.value.shift) {
- shift = _units2.default.calculateSize(group.value.shift, options);
- }
-
- var width = _units2.default.calculateSize(group.value.width, options);
- var height = _units2.default.calculateSize(group.value.height, options);
-
- // Style the rule to the right size
- rule.style.borderRightWidth = width + "em";
- rule.style.borderTopWidth = height + "em";
- rule.style.bottom = shift + "em";
-
- // Record the height and width
- rule.width = width;
- rule.height = height + shift;
- rule.depth = -shift;
- // Font size is the number large enough that the browser will
- // reserve at least `absHeight` space above the baseline.
- // The 1.125 factor was empirically determined
- rule.maxFontSize = height * 1.125 * options.sizeMultiplier;
-
- return rule;
- };
-
- groupTypes.kern = function (group, options) {
- // Make an empty span for the rule
- var rule = (0, _buildCommon.makeSpan)(["mord", "rule"], [], options);
-
- if (group.value.dimension) {
- var dimension = _units2.default.calculateSize(group.value.dimension, options);
- rule.style.marginLeft = dimension + "em";
- }
-
- return rule;
- };
-
- groupTypes.accent = function (group, options) {
- // Accents are handled in the TeXbook pg. 443, rule 12.
- var base = group.value.base;
-
- var supsubGroup = void 0;
- if (group.type === "supsub") {
- // If our base is a character box, and we have superscripts and
- // subscripts, the supsub will defer to us. In particular, we want
- // to attach the superscripts and subscripts to the inner body (so
- // that the position of the superscripts and subscripts won't be
- // affected by the height of the accent). We accomplish this by
- // sticking the base of the accent into the base of the supsub, and
- // rendering that, while keeping track of where the accent is.
-
- // The supsub group is the group that was passed in
- var supsub = group;
- // The real accent group is the base of the supsub group
- group = supsub.value.base;
- // The character box is the base of the accent group
- base = group.value.base;
- // Stick the character box into the base of the supsub group
- supsub.value.base = base;
-
- // Rerender the supsub group with its new base, and store that
- // result.
- supsubGroup = buildGroup(supsub, options);
- }
-
- // Build the base group
- var body = buildGroup(base, options.havingCrampedStyle());
-
- // Does the accent need to shift for the skew of a character?
- var mustShift = group.value.isShifty && isCharacterBox(base);
-
- // Calculate the skew of the accent. This is based on the line "If the
- // nucleus is not a single character, let s = 0; otherwise set s to the
- // kern amount for the nucleus followed by the \skewchar of its font."
- // Note that our skew metrics are just the kern between each character
- // and the skewchar.
- var skew = 0;
- if (mustShift) {
- // If the base is a character box, then we want the skew of the
- // innermost character. To do that, we find the innermost character:
- var baseChar = getBaseElem(base);
- // Then, we render its group to get the symbol inside it
- var baseGroup = buildGroup(baseChar, options.havingCrampedStyle());
- // Finally, we pull the skew off of the symbol.
- skew = baseGroup.skew;
- // Note that we now throw away baseGroup, because the layers we
- // removed with getBaseElem might contain things like \color which
- // we can't get rid of.
- // TODO(emily): Find a better way to get the skew
- }
-
- // calculate the amount of space between the body and the accent
- var clearance = Math.min(body.height, options.fontMetrics().xHeight);
-
- // Build the accent
- var accentBody = void 0;
- if (!group.value.isStretchy) {
- var accent = _buildCommon2.default.makeSymbol(group.value.label, "Main-Regular", group.mode, options);
- // Remove the italic correction of the accent, because it only serves to
- // shift the accent over to a place we don't want.
- accent.italic = 0;
-
- // The \vec character that the fonts use is a combining character, and
- // thus shows up much too far to the left. To account for this, we add a
- // specific class which shifts the accent over to where we want it.
- // TODO(emily): Fix this in a better way, like by changing the font
- // Similarly, text accent \H is a combining character and
- // requires a different adjustment.
- var accentClass = null;
- if (group.value.label === "\\vec") {
- accentClass = "accent-vec";
- } else if (group.value.label === '\\H') {
- accentClass = "accent-hungarian";
- }
-
- accentBody = (0, _buildCommon.makeSpan)([], [accent]);
- accentBody = (0, _buildCommon.makeSpan)(["accent-body", accentClass], [accentBody]);
-
- // Shift the accent over by the skew. Note we shift by twice the skew
- // because we are centering the accent, so by adding 2*skew to the left,
- // we shift it to the right by 1*skew.
- accentBody.style.marginLeft = 2 * skew + "em";
-
- accentBody = _buildCommon2.default.makeVList([{ type: "elem", elem: body }, { type: "kern", size: -clearance }, { type: "elem", elem: accentBody }], "firstBaseline", null, options);
- } else {
- accentBody = _stretchy2.default.svgSpan(group, options);
-
- accentBody = _buildCommon2.default.makeVList([{ type: "elem", elem: body }, { type: "elem", elem: accentBody }], "firstBaseline", null, options);
-
- var styleSpan = accentBody.children[0].children[0].children[1];
- styleSpan.classes.push("svg-align"); // text-align: left;
- if (skew > 0) {
- // Shorten the accent and nudge it to the right.
- styleSpan.style.width = "calc(100% - " + 2 * skew + "em)";
- styleSpan.style.marginLeft = 2 * skew + "em";
- }
- }
-
- var accentWrap = (0, _buildCommon.makeSpan)(["mord", "accent"], [accentBody], options);
-
- if (supsubGroup) {
- // Here, we replace the "base" child of the supsub with our newly
- // generated accent.
- supsubGroup.children[0] = accentWrap;
-
- // Since we don't rerun the height calculation after replacing the
- // accent, we manually recalculate height.
- supsubGroup.height = Math.max(accentWrap.height, supsubGroup.height);
-
- // Accents should always be ords, even when their innards are not.
- supsubGroup.classes[0] = "mord";
-
- return supsubGroup;
- } else {
- return accentWrap;
- }
- };
-
- groupTypes.horizBrace = function (group, options) {
- var style = options.style;
-
- var hasSupSub = group.type === "supsub";
- var supSubGroup = void 0;
- var newOptions = void 0;
- if (hasSupSub) {
- // Ref: LaTeX source2e: }}}}\limits}
- // i.e. LaTeX treats the brace similar to an op and passes it
- // with \limits, so we need to assign supsub style.
- if (group.value.sup) {
- newOptions = options.havingStyle(style.sup());
- supSubGroup = buildGroup(group.value.sup, newOptions, options);
- } else {
- newOptions = options.havingStyle(style.sub());
- supSubGroup = buildGroup(group.value.sub, newOptions, options);
- }
- group = group.value.base;
- }
-
- // Build the base group
- var body = buildGroup(group.value.base, options.havingBaseStyle(_Style2.default.DISPLAY));
-
- // Create the stretchy element
- var braceBody = _stretchy2.default.svgSpan(group, options);
-
- // Generate the vlist, with the appropriate kerns ┏━━━━━━━━┓
- // This first vlist contains the subject matter and the brace: equation
- var vlist = void 0;
- if (group.value.isOver) {
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: body }, { type: "kern", size: 0.1 }, { type: "elem", elem: braceBody }], "firstBaseline", null, options);
- vlist.children[0].children[0].children[1].classes.push("svg-align");
- } else {
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: braceBody }, { type: "kern", size: 0.1 }, { type: "elem", elem: body }], "bottom", body.depth + 0.1 + braceBody.height, options);
- vlist.children[0].children[0].children[0].classes.push("svg-align");
- }
-
- if (hasSupSub) {
- // In order to write the supsub, wrap the first vlist in another vlist:
- // They can't all go in the same vlist, because the note might be wider
- // than the equation. We want the equation to control the brace width.
-
- // note long note long note
- // ┏━━━━━━━━┓ or ┏━━━┓ not ┏━━━━━━━━━┓
- // equation eqn eqn
-
- var vSpan = (0, _buildCommon.makeSpan)(["mord", group.value.isOver ? "mover" : "munder"], [vlist], options);
-
- if (group.value.isOver) {
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: vSpan }, { type: "kern", size: 0.2 }, { type: "elem", elem: supSubGroup }], "firstBaseline", null, options);
- } else {
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: supSubGroup }, { type: "kern", size: 0.2 }, { type: "elem", elem: vSpan }], "bottom", vSpan.depth + 0.2 + supSubGroup.height, options);
- }
- }
-
- return (0, _buildCommon.makeSpan)(["mord", group.value.isOver ? "mover" : "munder"], [vlist], options);
- };
-
- groupTypes.accentUnder = function (group, options) {
- // Treat under accents much like underlines.
- var innerGroup = buildGroup(group.value.body, options);
-
- var accentBody = _stretchy2.default.svgSpan(group, options);
- var kern = /tilde/.test(group.value.label) ? 0.12 : 0;
-
- // Generate the vlist, with the appropriate kerns
- var vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: accentBody }, { type: "kern", size: kern }, { type: "elem", elem: innerGroup }], "bottom", accentBody.height + kern, options);
-
- vlist.children[0].children[0].children[0].classes.push("svg-align");
-
- return (0, _buildCommon.makeSpan)(["mord", "accentunder"], [vlist], options);
- };
-
- groupTypes.enclose = function (group, options) {
- // \cancel, \bcancel, \xcancel, \sout, \fbox
- var inner = buildGroup(group.value.body, options);
-
- var label = group.value.label.substr(1);
- var scale = options.sizeMultiplier;
- var img = void 0;
- var pad = 0;
- var imgShift = 0;
-
- if (label === "sout") {
- img = (0, _buildCommon.makeSpan)(["stretchy", "sout"]);
- img.height = options.fontMetrics().defaultRuleThickness / scale;
- imgShift = -0.5 * options.fontMetrics().xHeight;
- } else {
- // Add horizontal padding
- inner.classes.push(label === "fbox" ? "boxpad" : "cancel-pad");
-
- // Add vertical padding
- var isCharBox = isCharacterBox(group.value.body);
- // ref: LaTeX source2e: \fboxsep = 3pt; \fboxrule = .4pt
- // ref: cancel package: \advance\totalheight2\p@ % "+2"
- pad = label === "fbox" ? 0.34 : isCharBox ? 0.2 : 0;
- imgShift = inner.depth + pad;
-
- img = _stretchy2.default.encloseSpan(inner, label, pad, options);
- }
-
- var vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: inner, shift: 0 }, { type: "elem", elem: img, shift: imgShift }], "individualShift", null, options);
-
- if (label !== "fbox") {
- vlist.children[0].children[0].children[1].classes.push("svg-align");
- }
-
- if (/cancel/.test(label)) {
- // cancel does not create horiz space for its line extension.
- // That is, not when adjacent to a mord.
- return (0, _buildCommon.makeSpan)(["mord", "cancel-lap"], [vlist], options);
- } else {
- return (0, _buildCommon.makeSpan)(["mord"], [vlist], options);
- }
- };
-
- groupTypes.xArrow = function (group, options) {
- var style = options.style;
-
- // Build the argument groups in the appropriate style.
- // Ref: amsmath.dtx: \hbox{$\scriptstyle\mkern#3mu{#6}\mkern#4mu$}%
-
- var newOptions = options.havingStyle(style.sup());
- var upperGroup = buildGroup(group.value.body, newOptions, options);
- upperGroup.classes.push("x-arrow-pad");
-
- var lowerGroup = void 0;
- if (group.value.below) {
- // Build the lower group
- newOptions = options.havingStyle(style.sub());
- lowerGroup = buildGroup(group.value.below, newOptions, options);
- lowerGroup.classes.push("x-arrow-pad");
- }
-
- var arrowBody = _stretchy2.default.svgSpan(group, options);
-
- var arrowShift = -options.fontMetrics().axisHeight + arrowBody.depth;
- var upperShift = -options.fontMetrics().axisHeight - arrowBody.height - 0.111; // 2 mu. Ref: amsmath.dtx: #7\if0#2\else\mkern#2mu\fi
-
- // Generate the vlist
- var vlist = void 0;
- if (group.value.below) {
- var lowerShift = -options.fontMetrics().axisHeight + lowerGroup.height + arrowBody.height + 0.111;
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: upperGroup, shift: upperShift }, { type: "elem", elem: arrowBody, shift: arrowShift }, { type: "elem", elem: lowerGroup, shift: lowerShift }], "individualShift", null, options);
- } else {
- vlist = _buildCommon2.default.makeVList([{ type: "elem", elem: upperGroup, shift: upperShift }, { type: "elem", elem: arrowBody, shift: arrowShift }], "individualShift", null, options);
- }
-
- vlist.children[0].children[0].children[1].classes.push("svg-align");
-
- return (0, _buildCommon.makeSpan)(["mrel", "x-arrow"], [vlist], options);
- };
-
- groupTypes.phantom = function (group, options) {
- var elements = buildExpression(group.value.value, options.withPhantom(), false);
-
- // \phantom isn't supposed to affect the elements it contains.
- // See "color" for more details.
- return new _buildCommon2.default.makeFragment(elements);
- };
-
- groupTypes.mclass = function (group, options) {
- var elements = buildExpression(group.value.value, options, true);
-
- return (0, _buildCommon.makeSpan)([group.value.mclass], elements, options);
- };
-
- /**
- * buildGroup is the function that takes a group and calls the correct groupType
- * function for it. It also handles the interaction of size and style changes
- * between parents and children.
- */
- var buildGroup = function buildGroup(group, options, baseOptions) {
- if (!group) {
- return (0, _buildCommon.makeSpan)();
- }
-
- if (groupTypes[group.type]) {
- // Call the groupTypes function
- var groupNode = groupTypes[group.type](group, options);
-
- // If the size changed between the parent and the current group, account
- // for that size difference.
- if (baseOptions && options.size !== baseOptions.size) {
- groupNode = (0, _buildCommon.makeSpan)(options.sizingClasses(baseOptions), [groupNode], options);
-
- var multiplier = options.sizeMultiplier / baseOptions.sizeMultiplier;
-
- groupNode.height *= multiplier;
- groupNode.depth *= multiplier;
- }
-
- return groupNode;
- } else {
- throw new _ParseError2.default("Got group of unknown type: '" + group.type + "'");
- }
- };
-
- /**
- * Take an entire parse tree, and build it into an appropriate set of HTML
- * nodes.
- */
- var buildHTML = function buildHTML(tree, options) {
- // buildExpression is destructive, so we need to make a clone
- // of the incoming tree so that it isn't accidentally changed
- tree = JSON.parse((0, _stringify2.default)(tree));
-
- // Build the expression contained in the tree
- var expression = buildExpression(tree, options, true);
- var body = (0, _buildCommon.makeSpan)(["base"], expression, options);
-
- // Add struts, which ensure that the top of the HTML element falls at the
- // height of the expression, and the bottom of the HTML element falls at the
- // depth of the expression.
- var topStrut = (0, _buildCommon.makeSpan)(["strut"]);
- var bottomStrut = (0, _buildCommon.makeSpan)(["strut", "bottom"]);
-
- topStrut.style.height = body.height + "em";
- bottomStrut.style.height = body.height + body.depth + "em";
- // We'd like to use `vertical-align: top` but in IE 9 this lowers the
- // baseline of the box to the bottom of this strut (instead staying in the
- // normal place) so we use an absolute value for vertical-align instead
- bottomStrut.style.verticalAlign = -body.depth + "em";
-
- // Wrap the struts and body together
- var htmlNode = (0, _buildCommon.makeSpan)(["katex-html"], [topStrut, bottomStrut, body]);
-
- htmlNode.setAttribute("aria-hidden", "true");
-
- return htmlNode;
- };
-
- module.exports = buildHTML;
-
- },{"./ParseError":29,"./Style":33,"./buildCommon":34,"./delimiter":38,"./domTree":39,"./stretchy":47,"./units":50,"./utils":51,"babel-runtime/core-js/json/stringify":2}],36:[function(require,module,exports){
-
- var _buildCommon = require("./buildCommon");
-
- var _buildCommon2 = _interopRequireDefault(_buildCommon);
-
- var _fontMetrics = require("./fontMetrics");
-
- var _fontMetrics2 = _interopRequireDefault(_fontMetrics);
-
- var _mathMLTree = require("./mathMLTree");
-
- var _mathMLTree2 = _interopRequireDefault(_mathMLTree);
-
- var _ParseError = require("./ParseError");
-
- var _ParseError2 = _interopRequireDefault(_ParseError);
-
- var _Style = require("./Style");
-
- var _Style2 = _interopRequireDefault(_Style);
-
- var _symbols = require("./symbols");
-
- var _symbols2 = _interopRequireDefault(_symbols);
-
- var _utils = require("./utils");
-
- var _utils2 = _interopRequireDefault(_utils);
-
- var _stretchy = require("./stretchy");
-
- var _stretchy2 = _interopRequireDefault(_stretchy);
-
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
- /**
- * Takes a symbol and converts it into a MathML text node after performing
- * optional replacement from symbols.js.
- */
- /**
- * This file converts a parse tree into a cooresponding MathML tree. The main
- * entry point is the `buildMathML` function, which takes a parse tree from the
- * parser.
- */
-
- var makeText = function makeText(text, mode) {
- if (_symbols2.default[mode][text] && _symbols2.default[mode][text].replace) {
- text = _symbols2.default[mode][text].replace;
- }
-
- return new _mathMLTree2.default.TextNode(text);
- };
-
- /**
- * Returns the math variant as a string or null if none is required.
- */
- var getVariant = function getVariant(group, options) {
- var font = options.font;
- if (!font) {
- return null;
- }
-
- var mode = group.mode;
- if (font === "mathit") {
- return "italic";
- }
-
- var value = group.value;
- if (_utils2.default.contains(["\\imath", "\\jmath"], value)) {
- return null;
- }
-
- if (_symbols2.default[mode][value] && _symbols2.default[mode][value].replace) {
- value = _symbols2.default[mode][value].replace;
- }
-
- var fontName = _buildCommon.fontMap[font].fontName;
- if (_fontMetrics2.default.getCharacterMetrics(value, fontName)) {
- return _buildCommon.fontMap[options.font].variant;
- }
-
- return null;
- };
-
- /**
- * Functions for handling the different types of groups found in the parse
- * tree. Each function should take a parse group and return a MathML node.
- */
- var groupTypes = {};
-
- var defaultVariant = {
- "mi": "italic",
- "mn": "normal",
- "mtext": "normal"
- };
-
- groupTypes.mathord = function (group, options) {
- var node = new _mathMLTree2.default.MathNode("mi", [makeText(group.value, group.mode)]);
-
- var variant = getVariant(group, options) || "italic";
- if (variant !== defaultVariant[node.type]) {
- node.setAttribute("mathvariant", variant);
- }
- return node;
- };
-
- groupTypes.textord = function (group, options) {
- var text = makeText(group.value, group.mode);
-
- var variant = getVariant(group, options) || "normal";
-
- var node = void 0;
- if (group.mode === 'text') {
- node = new _mathMLTree2.default.MathNode("mtext", [text]);
- } else if (/[0-9]/.test(group.value)) {
- // TODO(kevinb) merge adjacent nodes
- // do it as a post processing step
- node = new _mathMLTree2.default.MathNode("mn", [text]);
- } else if (group.value === "\\prime") {
- node = new _mathMLTree2.default.MathNode("mo", [text]);
- } else {
- node = new _mathMLTree2.default.MathNode("mi", [text]);
- }
- if (variant !== defaultVariant[node.type]) {
- node.setAttribute("mathvariant", variant);
- }
-
- return node;
- };
-
- groupTypes.bin = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- return node;
- };
-
- groupTypes.rel = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- return node;
- };
-
- groupTypes.open = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- return node;
- };
-
- groupTypes.close = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- return node;
- };
-
- groupTypes.inner = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- return node;
- };
-
- groupTypes.punct = function (group) {
- var node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value, group.mode)]);
-
- node.setAttribute("separator", "true");
-
- return node;
- };
-
- groupTypes.ordgroup = function (group, options) {
- var inner = buildExpression(group.value, options);
-
- var node = new _mathMLTree2.default.MathNode("mrow", inner);
-
- return node;
- };
-
- groupTypes.text = function (group, options) {
- var body = group.value.body;
-
- // Convert each element of the body into MathML, and combine consecutive
- // outputs into a single tag. In this way, we don't
- // nest non-text items (e.g., $nested-math$) within an .
- var inner = [];
- var currentText = null;
- for (var i = 0; i < body.length; i++) {
- var _group = buildGroup(body[i], options);
- if (_group.type === 'mtext' && currentText != null) {
- Array.prototype.push.apply(currentText.children, _group.children);
- } else {
- inner.push(_group);
- if (_group.type === 'mtext') {
- currentText = _group;
- }
- }
- }
-
- // If there is a single tag in the end (presumably ),
- // just return it. Otherwise, wrap them in an .
- if (inner.length === 1) {
- return inner[0];
- } else {
- return new _mathMLTree2.default.MathNode("mrow", inner);
- }
- };
-
- groupTypes.color = function (group, options) {
- var inner = buildExpression(group.value.value, options);
-
- var node = new _mathMLTree2.default.MathNode("mstyle", inner);
-
- node.setAttribute("mathcolor", group.value.color);
-
- return node;
- };
-
- groupTypes.supsub = function (group, options) {
- // Is the inner group a relevant horizonal brace?
- var isBrace = false;
- var isOver = void 0;
- var isSup = void 0;
- if (group.value.base) {
- if (group.value.base.value.type === "horizBrace") {
- isSup = group.value.sup ? true : false;
- if (isSup === group.value.base.value.isOver) {
- isBrace = true;
- isOver = group.value.base.value.isOver;
- }
- }
- }
-
- var removeUnnecessaryRow = true;
- var children = [buildGroup(group.value.base, options, removeUnnecessaryRow)];
-
- if (group.value.sub) {
- children.push(buildGroup(group.value.sub, options, removeUnnecessaryRow));
- }
-
- if (group.value.sup) {
- children.push(buildGroup(group.value.sup, options, removeUnnecessaryRow));
- }
-
- var nodeType = void 0;
- if (isBrace) {
- nodeType = isOver ? "mover" : "munder";
- } else if (!group.value.sub) {
- nodeType = "msup";
- } else if (!group.value.sup) {
- nodeType = "msub";
- } else {
- var base = group.value.base;
- if (base && base.value.limits && options.style === _Style2.default.DISPLAY) {
- nodeType = "munderover";
- } else {
- nodeType = "msubsup";
- }
- }
-
- var node = new _mathMLTree2.default.MathNode(nodeType, children);
-
- return node;
- };
-
- groupTypes.genfrac = function (group, options) {
- var node = new _mathMLTree2.default.MathNode("mfrac", [buildGroup(group.value.numer, options), buildGroup(group.value.denom, options)]);
-
- if (!group.value.hasBarLine) {
- node.setAttribute("linethickness", "0px");
- }
-
- if (group.value.leftDelim != null || group.value.rightDelim != null) {
- var withDelims = [];
-
- if (group.value.leftDelim != null) {
- var leftOp = new _mathMLTree2.default.MathNode("mo", [new _mathMLTree2.default.TextNode(group.value.leftDelim)]);
-
- leftOp.setAttribute("fence", "true");
-
- withDelims.push(leftOp);
- }
-
- withDelims.push(node);
-
- if (group.value.rightDelim != null) {
- var rightOp = new _mathMLTree2.default.MathNode("mo", [new _mathMLTree2.default.TextNode(group.value.rightDelim)]);
-
- rightOp.setAttribute("fence", "true");
-
- withDelims.push(rightOp);
- }
-
- var outerNode = new _mathMLTree2.default.MathNode("mrow", withDelims);
-
- return outerNode;
- }
-
- return node;
- };
-
- groupTypes.array = function (group, options) {
- return new _mathMLTree2.default.MathNode("mtable", group.value.body.map(function (row) {
- return new _mathMLTree2.default.MathNode("mtr", row.map(function (cell) {
- return new _mathMLTree2.default.MathNode("mtd", [buildGroup(cell, options)]);
- }));
- }));
- };
-
- groupTypes.sqrt = function (group, options) {
- var node = void 0;
- if (group.value.index) {
- node = new _mathMLTree2.default.MathNode("mroot", [buildGroup(group.value.body, options), buildGroup(group.value.index, options)]);
- } else {
- node = new _mathMLTree2.default.MathNode("msqrt", [buildGroup(group.value.body, options)]);
- }
-
- return node;
- };
-
- groupTypes.leftright = function (group, options) {
- var inner = buildExpression(group.value.body, options);
-
- if (group.value.left !== ".") {
- var leftNode = new _mathMLTree2.default.MathNode("mo", [makeText(group.value.left, group.mode)]);
-
- leftNode.setAttribute("fence", "true");
-
- inner.unshift(leftNode);
- }
-
- if (group.value.right !== ".") {
- var rightNode = new _mathMLTree2.default.MathNode("mo", [makeText(group.value.right, group.mode)]);
-
- rightNode.setAttribute("fence", "true");
-
- inner.push(rightNode);
- }
-
- var outerNode = new _mathMLTree2.default.MathNode("mrow", inner);
-
- return outerNode;
- };
-
- groupTypes.middle = function (group, options) {
- var middleNode = new _mathMLTree2.default.MathNode("mo", [makeText(group.value.middle, group.mode)]);
- middleNode.setAttribute("fence", "true");
- return middleNode;
- };
-
- groupTypes.accent = function (group, options) {
- var accentNode = void 0;
- if (group.value.isStretchy) {
- accentNode = _stretchy2.default.mathMLnode(group.value.label);
- } else {
- accentNode = new _mathMLTree2.default.MathNode("mo", [makeText(group.value.label, group.mode)]);
- }
-
- var node = new _mathMLTree2.default.MathNode("mover", [buildGroup(group.value.base, options), accentNode]);
-
- node.setAttribute("accent", "true");
-
- return node;
- };
-
- groupTypes.spacing = function (group) {
- var node = void 0;
-
- if (group.value === "\\ " || group.value === "\\space" || group.value === " " || group.value === "~") {
- node = new _mathMLTree2.default.MathNode("mtext", [new _mathMLTree2.default.TextNode("\xA0")]);
- } else {
- node = new _mathMLTree2.default.MathNode("mspace");
-
- node.setAttribute("width", _buildCommon2.default.spacingFunctions[group.value].size);
- }
-
- return node;
- };
-
- groupTypes.op = function (group, options) {
- var node = void 0;
-
- // TODO(emily): handle big operators using the `largeop` attribute
-
- if (group.value.symbol) {
- // This is a symbol. Just add the symbol.
- node = new _mathMLTree2.default.MathNode("mo", [makeText(group.value.body, group.mode)]);
- } else if (group.value.value) {
- // This is an operator with children. Add them.
- node = new _mathMLTree2.default.MathNode("mo", buildExpression(group.value.value, options));
- } else {
- // This is a text operator. Add all of the characters from the
- // operator's name.
- // TODO(emily): Add a space in the middle of some of these
- // operators, like \limsup.
- node = new _mathMLTree2.default.MathNode("mi", [new _mathMLTree2.default.TextNode(group.value.body.slice(1))]);
- }
-
- return node;
- };
-
- groupTypes.mod = function (group, options) {
- var inner = [];
-
- if (group.value.modType === "pod" || group.value.modType === "pmod") {
- inner.push(new _mathMLTree2.default.MathNode("mo", [makeText("(", group.mode)]));
- }
- if (group.value.modType !== "pod") {
- inner.push(new _mathMLTree2.default.MathNode("mo", [makeText("mod", group.mode)]));
- }
- if (group.value.value) {
- var space = new _mathMLTree2.default.MathNode("mspace");
- space.setAttribute("width", "0.333333em");
- inner.push(space);
- inner = inner.concat(buildExpression(group.value.value, options));
- }
- if (group.value.modType === "pod" || group.value.modType === "pmod") {
- inner.push(new _mathMLTree2.default.MathNode("mo", [makeText(")", group.mode)]));
- }
-
- return new _mathMLTree2.default.MathNode("mo", inner);
- };
-
- groupTypes.katex = function (group) {
- var node = new _mathMLTree2.default.MathNode("mtext", [new _mathMLTree2.default.TextNode("KaTeX")]);
-
- return node;
- };
-
- groupTypes.font = function (group, options) {
- var font = group.value.font;
- return buildGroup(group.value.body, options.withFont(font));
- };
-
- groupTypes.delimsizing = function (group) {
- var children = [];
-
- if (group.value.value !== ".") {
- children.push(makeText(group.value.value, group.mode));
- }
-
- var node = new _mathMLTree2.default.MathNode("mo", children);
-
- if (group.value.mclass === "mopen" || group.value.mclass === "mclose") {
- // Only some of the delimsizing functions act as fences, and they
- // return "mopen" or "mclose" mclass.
- node.setAttribute("fence", "true");
- } else {
- // Explicitly disable fencing if it's not a fence, to override the
- // defaults.
- node.setAttribute("fence", "false");
- }
-
- return node;
- };
-
- groupTypes.styling = function (group, options) {
- // Figure out what style we're changing to.
- // TODO(kevinb): dedupe this with buildHTML.js
- // This will be easier of handling of styling nodes is in the same file.
- var styleMap = {
- "display": _Style2.default.DISPLAY,
- "text": _Style2.default.TEXT,
- "script": _Style2.default.SCRIPT,
- "scriptscript": _Style2.default.SCRIPTSCRIPT
- };
-
- var newStyle = styleMap[group.value.style];
- var newOptions = options.havingStyle(newStyle);
-
- var inner = buildExpression(group.value.value, newOptions);
-
- var node = new _mathMLTree2.default.MathNode("mstyle", inner);
-
- var styleAttributes = {
- "display": ["0", "true"],
- "text": ["0", "false"],
- "script": ["1", "false"],
- "scriptscript": ["2", "false"]
- };
-
- var attr = styleAttributes[group.value.style];
-
- node.setAttribute("scriptlevel", attr[0]);
- node.setAttribute("displaystyle", attr[1]);
-
- return node;
- };
-
- groupTypes.sizing = function (group, options) {
- var newOptions = options.havingSize(group.value.size);
- var inner = buildExpression(group.value.value, newOptions);
-
- var node = new _mathMLTree2.default.MathNode("mstyle", inner);
-
- // TODO(emily): This doesn't produce the correct size for nested size
- // changes, because we don't keep state of what style we're currently
- // in, so we can't reset the size to normal before changing it. Now
- // that we're passing an options parameter we should be able to fix
- // this.
- node.setAttribute("mathsize", newOptions.sizeMultiplier + "em");
-
- return node;
- };
-
- groupTypes.overline = function (group, options) {
- var operator = new _mathMLTree2.default.MathNode("mo", [new _mathMLTree2.default.TextNode("\u203E")]);
- operator.setAttribute("stretchy", "true");
-
- var node = new _mathMLTree2.default.MathNode("mover", [buildGroup(group.value.body, options), operator]);
- node.setAttribute("accent", "true");
-
- return node;
- };
-
- groupTypes.underline = function (group, options) {
- var operator = new _mathMLTree2.default.MathNode("mo", [new _mathMLTree2.default.TextNode("\u203E")]);
- operator.setAttribute("stretchy", "true");
-
- var node = new _mathMLTree2.default.MathNode("munder", [buildGroup(group.value.body, options), operator]);
- node.setAttribute("accentunder", "true");
-
- return node;
- };
-
- groupTypes.accentUnder = function (group, options) {
- var accentNode = _stretchy2.default.mathMLnode(group.value.label);
- var node = new _mathMLTree2.default.MathNode("munder", [buildGroup(group.value.body, options), accentNode]);
- node.setAttribute("accentunder", "true");
- return node;
- };
-
- groupTypes.enclose = function (group, options) {
- var node = new _mathMLTree2.default.MathNode("menclose", [buildGroup(group.value.body, options)]);
- var notation = "";
- switch (group.value.label) {
- case "\\bcancel":
- notation = "downdiagonalstrike";
- break;
- case "\\sout":
- notation = "horizontalstrike";
- break;
- case "\\fbox":
- notation = "box";
- break;
- default:
- notation = "updiagonalstrike";
- }
- node.setAttribute("notation", notation);
- return node;
- };
-
- groupTypes.horizBrace = function (group, options) {
- var accentNode = _stretchy2.default.mathMLnode(group.value.label);
- return new _mathMLTree2.default.MathNode(group.value.isOver ? "mover" : "munder", [buildGroup(group.value.base, options), accentNode]);
- };
-
- groupTypes.xArrow = function (group, options) {
- var arrowNode = _stretchy2.default.mathMLnode(group.value.label);
- var node = void 0;
- var lowerNode = void 0;
-
- if (group.value.body) {
- var upperNode = buildGroup(group.value.body, options);
- if (group.value.below) {
- lowerNode = buildGroup(group.value.below, options);
- node = new _mathMLTree2.default.MathNode("munderover", [arrowNode, lowerNode, upperNode]);
- } else {
- node = new _mathMLTree2.default.MathNode("mover", [arrowNode, upperNode]);
- }
- } else if (group.value.below) {
- lowerNode = buildGroup(group.value.below, options);
- node = new _mathMLTree2.default.MathNode("munder", [arrowNode, lowerNode]);
- } else {
- node = new _mathMLTree2.default.MathNode("mover", [arrowNode]);
- }
- return node;
- };
-
- groupTypes.rule = function (group) {
- // TODO(emily): Figure out if there's an actual way to draw black boxes
- // in MathML.
- var node = new _mathMLTree2.default.MathNode("mrow");
-
- return node;
- };
-
- groupTypes.kern = function (group) {
- // TODO(kevin): Figure out if there's a way to add space in MathML
- var node = new _mathMLTree2.default.MathNode("mrow");
-
- return node;
- };
-
- groupTypes.llap = function (group, options) {
- var node = new _mathMLTree2.default.MathNode("mpadded", [buildGroup(group.value.body, options)]);
-
- node.setAttribute("lspace", "-1width");
- node.setAttribute("width", "0px");
-
- return node;
- };
-
- groupTypes.rlap = function (group, options) {
- var node = new _mathMLTree2.default.MathNode("mpadded", [buildGroup(group.value.body, options)]);
-
- node.setAttribute("width", "0px");
-
- return node;
- };
-
- groupTypes.phantom = function (group, options) {
- var inner = buildExpression(group.value.value, options);
- return new _mathMLTree2.default.MathNode("mphantom", inner);
- };
-
- groupTypes.mclass = function (group, options) {
- var inner = buildExpression(group.value.value, options);
- return new _mathMLTree2.default.MathNode("mstyle", inner);
- };
-
- /**
- * Takes a list of nodes, builds them, and returns a list of the generated
- * MathML nodes. A little simpler than the HTML version because we don't do any
- * previous-node handling.
- */
- var buildExpression = function buildExpression(expression, options) {
- var groups = [];
- for (var i = 0; i < expression.length; i++) {
- var group = expression[i];
- groups.push(buildGroup(group, options));
- }
-
- // TODO(kevinb): combine \\not with mrels and mords
-
- return groups;
- };
-
- /**
- * Takes a group from the parser and calls the appropriate groupTypes function
- * on it to produce a MathML node.
- */
- // TODO(kevinb): determine if removeUnnecessaryRow should always be true
- var buildGroup = function buildGroup(group, options) {
- var removeUnnecessaryRow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
-
- if (!group) {
- return new _mathMLTree2.default.MathNode("mrow");
- }
-
- if (groupTypes[group.type]) {
- // Call the groupTypes function
- var result = groupTypes[group.type](group, options);
- if (removeUnnecessaryRow) {
- if (result.type === "mrow" && result.children.length === 1) {
- return result.children[0];
- }
- }
- return result;
- } else {
- throw new _ParseError2.default("Got group of unknown type: '" + group.type + "'");
- }
- };
-
- /**
- * Takes a full parse tree and settings and builds a MathML representation of
- * it. In particular, we put the elements from building the parse tree into a
- * tag so we can also include that TeX source as an annotation.
- *
- * Note that we actually return a domTree element with a `
Overview
This blog post introduces a new perspective to understanding the Random Feature Attention (RFA) mechanism. We show that 1) the conventional softmax attention can be equivalently rewritten as an expectation over RFAs, and that 2) RFA is in fact a self-normalized importance sampler to estimate conventional softmax attention. This new perspective grounds the heuristic RFA approximation and also sheds light on how to generalize further and improve RFAs. More details can be found in our ICML paper .
Attention
The attention mechanism has become a ubiquitous building block in modern deep learning models and brought great success across various domains, including natural language processing (NLP), computer vision (CV), bioinformatics, reinforcement learning, etc. Attention mechanisms take three different kinds of inputs: a set of $N$ query vectors $\mbQ \in \R^{N \times D}$, $M$ key vectors $\mbK \in \R^{M \times D}$ and value vectors $\mbV \in \R^{M \times D}$. In this work we focus on self-attention, where $M=N$ and all of queries, keys and values are obtained by projecting tokens of the same input sequence.
For each query $\mbq_n$, conventional softmax attention computes the following quantity, We omit the commonly used scaling factor $1 / \sqrt{d}$ for simplicity as it can be merged into the computation of queries or keys. \begin{equation} \mathsf{SoftmaxAttn}\left(\mbq_{n},\mbK,\mbV\right)\coloneqq\sum_{m=1}^M\frac{\exp\left(\mbq_{n}^\top \mbk_{m} \right)}{\sum_{m’=1}^M \exp\left(\mbq_{n}^\top \mbk_{m’} \right)} \mbv_{m}^{\top}. \end{equation} Intuitively, softmax attention first compares the query against each key and then computes the average over value vectors weighted by the normalized query-key similarities. It is effective in capturing long-term dependencies across sequence elements and producing contextualized representations; however, it suffers from quadratic time and memory complexity due to the explicit computation of all $NM$ query-key pairs.
Random Feature Attention
To reduce the computational complexity of softmax attention, researchers proposed to use random features (RF) to linearize softmax attention. In particular, they make use of the following identity to rewrite the exponential kernel as an expectation, \begin{equation} \exp(\mbx^\top \mby) = \mathbb{E}_{\omega \sim \mathcal{N}(\omega;0,\mathbf{I})}\left[\xi(\mbx,\omega)^\top\xi(\mby, \omega)\right], \label{eqn:identity} \end{equation} where $\xi(\cdot, \cdot): \R^D \times \R^D \rightarrow \R^l$, $l\geq 1$, is a non-linear randomized mapping projecting the input vector to a $l$-dimensional vector via a randomly drawn $\omega \sim \mathcal{N}(\omega;0,\mathbf{I})$. There are several parameterization choices of $\xi(\mbx,\omega)$ for the identity to hold; in this work we focus on the positive type $\xi(\mbx,\omega) = \exp{\left(\omega^\top \mbx - \frac{1}{2}\norm{\mbx}^2\right)}$ as proposed in . A classical choice of randomized mappings is to let $\xi(\mbx,\omega) = \exp{\left( \frac{1}{2}\norm{\mbx}^2\right)}\left[\sin{\left(\omega^\top \mbx\right)},\cos{\left(\omega^\top \mbx\right)}\right]^\top$ . Besides, there are other advanced randomized mappings enjoying more appealing properties; see for a more in-depth study.
To estimate the expectation in \eqref{eqn:identity}, one can draw multiple Monte Carlo samples from $\mathcal{N}(\omega;0,\mathbf{I})$ such that $\exp(\mbx^{\top} \mby) \approx \frac{1}{S}\sum_{s=1}^S \xi(\mbx,\omega_s)^{\top}\xi(\mby, \omega_s)$. By substituting such approximation into the softmax attention, we obtain random feature attention (RFA) (also called Performer), $$ \begin{align} \frac{\sum_{m=1}^M\exp\left(\mbq_{n}^\top \mbk_{m} \right)\mbv_{m}^{\top}}{\sum_{m'=1}^M \exp\left(\mbq_{n}^\top \mbk_{m'} \right)} &\approx \frac{\sum_{m=1}^M \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{m'=1}^M\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\xi(\mbk_{m'}, \omega_s)} \notag \\ &=\frac{ \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)} \label{eqn:rfa}\\ &\coloneqq \mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right) \notag. \end{align} $$ Thanks to the linearized formulation, one can first pre-compute the corresponding key-value statistics $\sum_{m=1}^M\xi(\mbk_{m},\omega_s)\mbv_{m}^{\top}$ and $\sum_{m=1}^M\xi(\mbk_{m},\omega_s)$ once, and then reuse them for each query. Consequently, it achieves linear complexity in both time and memory with respect to the sequence length.
Why it is called random feature attention? This is due to the fact that the sample average can be written as $\mbphi(\mbx,\mbw)^\top \mbphi(\mby,\mbw)$, where $\mbphi(\mbx,\mbw) \coloneqq 1/\sqrt{S}[\xi(\mbx,\omega_1), \dots, \xi(\mbx, \omega_S)]^\top \in \R^{lS}$. The $\mbphi(\cdot,\cdot)$ can be considered as a feature map transforming the input vector to a new vector representation; as a result, $\mbphi(\cdot,\cdot)$ are conveniently referred to as random features.
The Biasedness of RFA
RFA suffers from significant performance degradation across various tasks, as observed in many previous studies (e.g., see here). Although computationally efficient, the reduced modeling capacity of RFA greatly limits its practical usage. Researchers try to improve the performance from different perspectives, such as
developing better random feature types ,
connecting it with fast weight programmers ,
incorporating relative information , and so on.
In this work, we explore an orthogonal axis by re-examining the estimation bias of RFA. Our key observation is that RFA is a heuristic approximation to the whole softmax attention. Although the estimation of individual exponential kernels is unbiased, such estimation of a ratio of exponential kernels is not unbiased anymore. This is due to the non-linearity of ratios,
Such bias not only incurs a potentially large approximation gap between RFA and softmax attention but also bottlenecks the effectiveness of unbiased kernel estimation.
Our work aims to address the following research question: Given that we already know how to unbiasedly estimate exponential kernels, how do we construct an unbiased estimator for the whole softmax attention?
Randomized Attention: An Unbiased Estimator for Softmax Attention
We answer this question in the affirmative and prove that softmax attention can be rewritten as an expectation of simple RFAs, $$ \begin{equation} \mathsf{SoftmaxAttn}(\mbq_n, \mbK,\mbV) = \sum_{m} \frac{\exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m} \right)}{\sum_{m'} \exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m'} \right)} \mathbf{v}_{m}^{\top} = \mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right],\label{eqn:softmax_as_expectation} \end{equation} $$ where $$ \begin{align} p_n(\omega) &= \sum_{m=1}^M \frac{\exp\left( \mbq_n^\top\mbk_m \right)}{\sum_{m'=1}^M\exp\left( \mbq_n^\top\mbk_{m'} \right)} \mathcal{N}(\omega; \mbq_n + \mbk_m, \mathbf{I}), \label{eqn:ra-density} \\ f_n(\omega) &= \frac{\xi(\mbq_n,\omega)^\top \sum_{m=1}^M \xi(\mbk_m, \omega) \mbv_{m}^{\top}}{\xi(\mbq_n,\omega)^\top \sum_{m'=1}^M \xi(\mbk_{m'}, \omega)} \label{eqn:ra-function}. \end{align} $$ Intuitively,
$p_n(\omega)$ is a Gaussian mixture distribution whose component weights are exactly attention scores, while
$f_n(\omega)$ is an RFA, except that the linearized similarity between queries and keys is computed via individual randomized mappings (or equivalently, one-dimensional random features).
Notably, our result can be viewed as a neat generalization of random feature approximation, which exhibits a high degree of symmetry: $$ \begin{align} \exp(\mbq_n^\top \mbk_m)\mbv_m^\top &= \mathbb{E}_{q(\omega)}\left[\xi(\mbq_n,\omega)^\top\xi(\mbk_m, \omega)\mbv_m^\top\right] \notag \\ \sum_{m} \frac{\exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m} \right)}{\sum_{m'} \exp \left(\mathbf{q}_{n}^\top \mathbf{k}_{m'} \right)} \mathbf{v}_{m}^{\top} &= \mathbb{E}_{p_n(\omega)}\left[\frac{\xi(\mbq_n,\omega)^\top \sum_{m=1}^M \xi(\mbk_m, \omega) \mbv_{m}^{\top}}{\xi(\mbq_n,\omega)^\top \sum_{m'=1}^M \xi(\mbk_{m'}, \omega)}\right].\notag \end{align} $$ Another implication is that we can construct a Monte Carlo estimator to approximate softmax attention in an unbiased way. By drawing $\omega_n \sim p_n(\omega)$, we obtain $$ \begin{align} \mathsf{SoftmaxAttn}(\mbq_n, \mbK,\mbV) &\approx \frac{\xi(\mbq_n,\omega_n)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_n) \mbv_{m}^{\top}}{ \xi(\mbq_n,\omega_n)^\top \sum_{m'=1}^M\xi(\mbk_{m'}, \omega_n)} \label{eqn:ra}\\ &\coloneqq \mathsf{RA}\left(\mbq_{n},\mbK,\mbV\right) \notag \end{align} $$ We name such estimator Randomized Attention (RA) since it computes similarity scores with individual randomized mappings (instead of concatenated features). To the best of our knowledge, this is the first result that generalizes the unbiased kernel estimation to unbiased attention estimation.
Remark: The proof of \eqref{eqn:softmax_as_expectation} is done by first reverse-engineering the formulation of RFA, equating it with self-normalized importance sampling (see below) and then completing the square of Gaussians to derive the density $p_n(\omega)$. The function $f_n(\omega)$ can be solved by substituting the density $p_n(\omega)$ into the equation. See the paper for a detailed proof.
RFA as a Self-normalized Importance Sampler
The analysis above further reveals that RFA is a specific self-normalized importance sampling estimator to softmax attention.
Self-normalized Importance Sampling (SNIS)
Importance sampling (IS) is a general approach to approximating expectation $\mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right]$ when it is difficult to directly draw samples from $p_n(\omega)$. In importance sampling, we use a proposal distribution $q(\omega)$ to draw samples and estimate the quantity as $$ \mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right] = \mathbb{E}_{\omega \sim q(\omega)}\left[\frac{p_n(\omega)}{q(\omega)}f_n(\omega)\right] \approx \frac{1}{S} \sum_{s=1}^S \frac{p_n(\omega)}{q(\omega)} f_n(\omega_s), $$ where $\omega_1, \dots, \omega_S \sim q(\omega)$. The self-normalized importance sampling (SNIS) is defined as $$ \begin{equation} \mathbb{E}_{p_n(\omega)}\left[f_n(\omega)\right] \approx \frac{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}f(\omega_s)}{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}} = \sum_{s=1}^S\frac{\frac{p_n(\omega_s)}{q(\omega_s)}}{\sum_{s=1}^S\frac{p_n(\omega_s)}{q(\omega_s)}}f(\omega_s). \label{eqn:snis} \end{equation} $$ The name self-normalized comes from the fact that the importance weights $p_n(\omega)/q(\omega)$ are explicitly normalized and sum to 1.
RFA as SNIS
Our key finding here is that the formulation of RFA can be exactly derived from SNIS. Supposing $p_n(\omega)$ and $f_n(\omega)$ are given in \eqref{eqn:ra-density} and \eqref{eqn:ra-function} respectively, and $q(\omega) = \mathcal{N}(\omega;0,\mathbf{I})$, we have $$ \begin{align} \mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\sum_{s=1}^S\textcolor{strings}{\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}}{\sum_{s=1}^S \textcolor{keywords}{\xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)}} = \frac{ \sum_{s=1}^S\textcolor{strings}{\frac{p_n(\omega_s)}{q(\omega_s)} f(\omega_s)}}{ \sum_{s=1}^S\textcolor{keywords}{\frac{p_n(\omega_s)}{q(\omega_s)}}}. \label{eqn:rfa-as-snis} \end{align} $$ This formulation provides a new understanding of RFA: it is just a specific instantiation of SNIS estimators for softmax attention, whose proposal distribution $q(\omega)$ is chosen to be standard Gaussian. This reveals one of the possible reasons why RFA does not work well in practice: The plain standard Gaussian proposal in RFA is far away from the true Gaussian mixture (as in RA), which might lead to a large approximation gap. More importantly, this view implies that we can generalize and extend RFA by using other proposal distributions or adopting other estimating schemes!
LARA: Generalizing Both RA and RFA
So far, we have two types of estimators available for approximating softmax attention: unbiased RA and biased RFA. Besides the theoretical biasedness, how do they differ in terms of practical modeling behavior? We list a comprehensive comparison to better illustrate their main differences.
In terms of expressiveness:
✔️ RA directly draws from the true distribution $p_n(\omega)$ \eqref{eqn:ra-density}. This makes the mechanism adaptive and query-specific, since the sampling distribution depends on the query vector. As a result, RA can specialize to each query and process the whole sequence at a finer-grained level.
❌ RFA suffers from limited capacity, since there is a large discrepancy between the used proposal $q(\omega) = \mathcal{N}(\omega;0,\mathbf{I})$ and the true distribution $p_n(\omega)$; furthermore, $q(\omega)$ captures no contextual information, leading to low sample efficiency.
In terms of efficiency:
❌ RA suffers from quadratic computational costs. Since the sampling distribution is distinct for each query, we have to draw at least $\mathcal{O}(N)$ samples for all queries; at the same time, we needs to sum over all $M$ key-value pairs at each sampled $\omega_n$ (see \eqref{eqn:ra}), which leads to $\mathcal{O}(NM)$ complexity overall, as is the case for softmax attention;
✔️ RFA uses SNIS to avoid computing or sampling from $p_n(\omega)$, which require quadratic-time computation. Drawing from a simpler proposal distribution allows samples to be shared across queries and still resulting in a $\mathcal{O}(M)$ complexity.
Motivated by the comparison, we propose LineAr-time Randomized Attention (LARA) that attempts to get the best of both worlds, combining both the efficiency of RFA and the expressiveness of RA.
On the one hand, LARA inherits the SNIS formulation as in RFA to achieve linear complexity;
On the other hand, its expressiveness is significantly improved towards RA via the following modifications:
The proposal distribution is data-dependent so that LARA can be adaptive with respect to the contextual information;
LARA adopts multiple proposal distributions, which can be combined in a query-specific manner.
LARA takes the following form $$ \begin{align} \mathsf{LARA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\sum_{c=1}^C\alpha_{nc}(\omega_c)\frac{p_n(\omega_c)}{q_c(\omega_c)} f_n(\omega_c)}{\sum_{c=1}^C\alpha_{nc}(\omega_c)\frac{p_n(\omega_c)}{q_c(\omega_c)}}.\label{eqn:lara} \end{align} $$ Here,
$q_1(\omega), \dots, q_C(\omega)$ are $C$ different proposals that depend on different query and key information;
$\{\alpha_{nc}(\cdot)\}_{c=1}^C$ is a set of weights that controls the contribution of different proposals, which is exclusive to each query and satisfies $\sum_{c=1}^C \alpha_{nc}(\omega) = 1$;
as long as $C$ is smaller than $N$, the computational complexity of LARA is linear, that is, $\mathcal{O}(CN+CM)$.
Remark: We provide a detailed discussion about the parameterization of our proposal distributions in Appendix G.3 of our paper. To summarize, we find the key is to let different proposals depend on different sets of query information so that they could be as query-specific as possible. A good default is to divide the whole sequence into $C$ chunks, compute the mean of queries $\{\widetilde{\mbq}_c\}_{c=1}^C$ and keys $\{\widetilde{\mbk}_c\}_{c=1}^C$ within the same chunk, and set $q_c(\omega) = \mcN(\omega;\widetilde{\mbq}_c + \widetilde{\mbk}_c, \mathbf{I})$. We find this choice works well across various benchmarks.
A Unified View of LARA, RA, and RFA
LARA can be equivalently written in a similar way to RA and RFA. We spell it out here to see a systematic comparison among RA, LARA, and RFA: $$ \begin{align} \mathsf{RA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\xi(\mbq_n,\omega_n)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_n) \mbv_{m}^{\top}}{ \xi(\mbq_n,\omega_n)^\top \sum_{m'=1}^M\xi(\mbk_{m'}, \omega_n)}, &&\textcolor{keywords}{\omega_n \sim p_n(\omega)}\notag\\ \mathsf{LARA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{\sum_{c=1}^C \textcolor{strings}{\alpha'_{nc}(\omega_c)} \xi(\mbq_n,\omega_c)^\top \sum_{m=1}^M\xi(\mbk_m, \omega_c) \mbv_{m}^{\top}}{\sum_{c=1}^C \textcolor{strings}{\alpha'_{nc}(\omega_c)} \xi(\mbq_n,\omega_c)^\top \sum_{m=1}^M \xi(\mbk_{m}, \omega_c)}, &&\textcolor{keywords}{\omega_c \sim q_c(\omega)}\notag\\ \mathsf{RFA}\left(\mbq_{n},\mbK,\mbV\right) &= \frac{ \sum_{s=1}^S\xi(\mbq_n,\omega_s)^{\top}\sum_{m=1}^M\xi(\mbk_m, \omega_s)\mbv_{m}^{\top}}{\sum_{s=1}^S \xi(\mbq_n,\omega_s)^{\top}\sum_{m'=1}^M\xi(\mbk_{m'}, \omega_s)}, &&\textcolor{keywords}{\omega_1,\dots,\omega_S \sim \mcN(\omega;0, \mathbf{I})} \notag \end{align} $$ where we denote $\alpha'_{nc}(\omega_c) \coloneqq \alpha_{nc}(\omega_c)\mcN(\omega_c;0, \mathbf{I})/q_c(\omega_c)$ to simplify the notation. Note that their major difference lies in the choice of sampling distributions. LARA is not designed to be a simple interpolation between RA and RFA; instead, it is a generalized estimation framework that includes both RA and RFA as its special cases. To see this,
LARA is equivalent to RA if $C = N$, $q_n(\omega) = p_n(\omega)$ and $\alpha_{nc}(\omega) = \delta_{nc}$ (that is, $\alpha_{nc}(\omega) = 1$ if $n = c$ and $0$ otherwise);
LARA is equivalent to RFA if $q_c(\omega) = \mcN(\omega;0,\mathbf{I})$ and $\alpha_{nc}(\cdot)$ is constant for all $c = 1,\dots,C$ and $n = 1,\dots,N$.
With general proposals and weighting functions, LARA approximates softmax attention in a query-specific manner as in RA while achieving linear complexity as in RFA, effectively combining the advantages of both estimators. It is also easy to implement with a couple of lines of code.
Experimental Results
To demonstrate the effectiveness of our approach, we first visualize the approximation error of LARA to the true softmax attention outputs. Our unbiased estimate, RA, achieves the lowest MSE among these three methods and gets very close to the true softmax attention; RFA (Performer) soon plateaus at large approximation error and does not improve even with more samples, possibly due to low sample efficiency. On the other hand, LARA exhibits much lower MSE than RFA and the approximation error continually decreases as the number of proposals increases.
We further verify the improved performance of LARA by conducting experiments across a wide range of data modalities, including images, videos, natural language texts, and a long-sequence benchmark. From the Table below, we observe that
RA performs competitively with conventional softmax attention, and
LARA greatly improves the performance of RFA and significantly reduces the performance gap between RFA and softmax attention.
Model
Complexity
Image Classification on ImageNet (🠅)
Video Recognition on SSv2 (🠅)
Machine Translation on WMT (🠅)
Long Range Arena suite (🠅)
Softmax
$\mathcal{O}(N^2)$
79.9
66.5
27.5
59.08
RA
$\mathcal{O}(N^2)$
80.0
64.9
27.8
59.30
RFA
$\mathcal{O}(N)$
74.3
53.1
23.7
57.63
LARA
$\mathcal{O}(N)$
79.5
63.7
27.0
59.12
LARA also enjoys much better scalability and could achieve SOTA results for image classification when applying it to advanced transformer architectures.
Finally, we evaluate the empirical efficiency of different attention methods. We note that RA runs almost twice slower than softmax attention, while its linear variant LARA runs much faster and brings marginal computational overheads compared to RFA.
Conclusion and Limitation
In this work, we generalize the random feature attention (RFA) algorithm in two aspects:
On the one hand, we generalize the unbiased kernel estimation (RFA) to unbiased attention estimation (RA);
On the other hand, we uncover the self-normalized importance sampling nature of RFA and propose a general framework LARA that includes both RA and RFA as its special cases.
LARA greatly improves the performance of RFA while also maintaining its efficiency of RFA. Our framework provides a novel perspective for understanding and improving RF-based attention approximation, which is also orthogonal to most previous work. At the same time, there are several limitations of our approach:
The choice of proposal distributions is sub-optimal. Although our modeling strategy enables a query-specific treatment as desired in RA, it needs to evaluate all the $C$ samples for each key-value pair, incurring a potential waste of computing. Future work might include more sophisticated implementations that use variable sample sets for different key-value pairs.
Currently, LARA is still a biased (but consistent) estimator for softmax attention. It would be interesting to adopt advanced sampling strategies (e.g., Markov chain Monte Carlo (MCMC), etc.) to derive lower-bias lower-variance estimators.
The proposal distribution should be carefully designed when dealing with auto-regressive modeling since it is non-trivial to apply the causal masking mechanism to LARA as in conventional softmax attention. Adapting the importance sampling formulation of LARA to support arbitrary auto-regressive modeling is also an interesting research direction.
]]>Lin Zheng
\ No newline at end of file
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..5e0d7d0
--- /dev/null
+++ b/index.html
@@ -0,0 +1 @@
+ HKU NLP Group
The current focus of the NLP group in HKU includes: • Pretraining algorithms, including novel objectives, neural network architectures and distillation methods; • Semantic parsing, natural language interfaces, human-computer interaction (HCI); • Dialog systems, long text generation and automatic evaluation; • Machine Translation, especially in the settings of simultaneous and multimodal MT.
news
Aug 31, 2023
Welcome the arrival of new students.
Aug 31, 2022
Welcome the arrival of new students.
You can even add a little note about which of these is the best way to reach you.
\ No newline at end of file
diff --git a/news/announcement_1/index.html b/news/announcement_1/index.html
new file mode 100644
index 0000000..41e1a79
--- /dev/null
+++ b/news/announcement_1/index.html
@@ -0,0 +1 @@
+ Announcement_1 | HKU NLP Group
\ No newline at end of file
diff --git a/news/announcement_2/index.html b/news/announcement_2/index.html
new file mode 100644
index 0000000..e8154ec
--- /dev/null
+++ b/news/announcement_2/index.html
@@ -0,0 +1 @@
+ Announcement_2 | HKU NLP Group
\ No newline at end of file
diff --git a/people/bowen_wang/index.html b/people/bowen_wang/index.html
new file mode 100644
index 0000000..48e54e2
--- /dev/null
+++ b/people/bowen_wang/index.html
@@ -0,0 +1 @@
+ Bowen Wang | HKU NLP Group
Bowen Wang
PhD Student
\ No newline at end of file
diff --git a/people/chang_ma/index.html b/people/chang_ma/index.html
new file mode 100644
index 0000000..cf72517
--- /dev/null
+++ b/people/chang_ma/index.html
@@ -0,0 +1 @@
+ Chang Ma | HKU NLP Group
Chang Ma
PhD Student
\ No newline at end of file
diff --git a/people/chenxin_an/index.html b/people/chenxin_an/index.html
new file mode 100644
index 0000000..3339e63
--- /dev/null
+++ b/people/chenxin_an/index.html
@@ -0,0 +1 @@
+ Chenxin An | HKU NLP Group
Chenxin An
PhD Student
\ No newline at end of file
diff --git a/people/hongjing_su/index.html b/people/hongjing_su/index.html
new file mode 100644
index 0000000..8023680
--- /dev/null
+++ b/people/hongjing_su/index.html
@@ -0,0 +1 @@
+ Hongjin Su | HKU NLP Group
Hongjin Su
PhD Student
\ No newline at end of file
diff --git a/people/index.html b/people/index.html
new file mode 100644
index 0000000..3723266
--- /dev/null
+++ b/people/index.html
@@ -0,0 +1 @@
+ People | HKU NLP Group
\ No newline at end of file
diff --git a/people/jiacheng_ye/index.html b/people/jiacheng_ye/index.html
new file mode 100644
index 0000000..f2ecdd1
--- /dev/null
+++ b/people/jiacheng_ye/index.html
@@ -0,0 +1 @@
+ Jiacheng Ye | HKU NLP Group
Jiacheng Ye
PhD Student
\ No newline at end of file
diff --git a/people/jiahui_gao/index.html b/people/jiahui_gao/index.html
new file mode 100644
index 0000000..c303239
--- /dev/null
+++ b/people/jiahui_gao/index.html
@@ -0,0 +1 @@
+ Jiahui Gao | HKU NLP Group
Jiahui Gao
PhD 2023
\ No newline at end of file
diff --git a/people/lei_li/index.html b/people/lei_li/index.html
new file mode 100644
index 0000000..9196f3a
--- /dev/null
+++ b/people/lei_li/index.html
@@ -0,0 +1 @@
+ Lei Li | HKU NLP Group
Lei Li
PhD Student
\ No newline at end of file
diff --git a/people/lin_zheng/index.html b/people/lin_zheng/index.html
new file mode 100644
index 0000000..a16d0cf
--- /dev/null
+++ b/people/lin_zheng/index.html
@@ -0,0 +1 @@
+ Lin Zheng | HKU NLP Group
Lin Zheng
PhD Student
\ No newline at end of file
diff --git a/people/lingpeng_kong/index.html b/people/lingpeng_kong/index.html
new file mode 100644
index 0000000..4adba6a
--- /dev/null
+++ b/people/lingpeng_kong/index.html
@@ -0,0 +1 @@
+ Lingpeng Kong | HKU NLP Group
Lingpeng Kong
Assistant Professor
\ No newline at end of file
diff --git a/people/mukao_li/index.html b/people/mukao_li/index.html
new file mode 100644
index 0000000..e665122
--- /dev/null
+++ b/people/mukao_li/index.html
@@ -0,0 +1 @@
+ Mukai Li | HKU NLP Group
Mukai Li
PhD student
\ No newline at end of file
diff --git a/people/qi_liu/index.html b/people/qi_liu/index.html
new file mode 100644
index 0000000..9df1fdc
--- /dev/null
+++ b/people/qi_liu/index.html
@@ -0,0 +1 @@
+ Qi Liu | HKU NLP Group
Qi Liu
Assistant Professor
\ No newline at end of file
diff --git a/people/qintong_li/index.html b/people/qintong_li/index.html
new file mode 100644
index 0000000..288d82c
--- /dev/null
+++ b/people/qintong_li/index.html
@@ -0,0 +1 @@
+ Qintong Li | HKU NLP Group
Qintong Li
PhD Student
\ No newline at end of file
diff --git a/people/sansa_gong/index.html b/people/sansa_gong/index.html
new file mode 100644
index 0000000..1db5844
--- /dev/null
+++ b/people/sansa_gong/index.html
@@ -0,0 +1 @@
+ Shansan Gong | HKU NLP Group
Shansan Gong
PhD Student
\ No newline at end of file
diff --git a/people/sheng_wang/index.html b/people/sheng_wang/index.html
new file mode 100644
index 0000000..457ecba
--- /dev/null
+++ b/people/sheng_wang/index.html
@@ -0,0 +1 @@
+ Sheng Wang | HKU NLP Group
Sheng Wang
PhD Student
\ No newline at end of file
diff --git a/people/tao_yu/index.html b/people/tao_yu/index.html
new file mode 100644
index 0000000..39faeac
--- /dev/null
+++ b/people/tao_yu/index.html
@@ -0,0 +1 @@
+ Tao Yu | HKU NLP Group
Tao Yu
Assistant Professor
\ No newline at end of file
diff --git a/people/tianbao_xie/index.html b/people/tianbao_xie/index.html
new file mode 100644
index 0000000..3096c20
--- /dev/null
+++ b/people/tianbao_xie/index.html
@@ -0,0 +1 @@
+ Tianbao Xie | HKU NLP Group
Tianbao Xie
PhD Student
\ No newline at end of file
diff --git a/people/who_next/index.html b/people/who_next/index.html
new file mode 100644
index 0000000..94c8ae2
--- /dev/null
+++ b/people/who_next/index.html
@@ -0,0 +1 @@
+ Join HKUNLP! | HKU NLP Group
Join HKUNLP!
\ No newline at end of file
diff --git a/people/xiachong_feng/index.html b/people/xiachong_feng/index.html
new file mode 100644
index 0000000..2c38109
--- /dev/null
+++ b/people/xiachong_feng/index.html
@@ -0,0 +1 @@
+ Xiachong Feng | HKU NLP Group
Xiachong Feng
Postdoc
\ No newline at end of file
diff --git a/people/xijia_tao/index.html b/people/xijia_tao/index.html
new file mode 100644
index 0000000..1161c12
--- /dev/null
+++ b/people/xijia_tao/index.html
@@ -0,0 +1 @@
+ Xijia Tao | HKU NLP Group
Xijia Tao
PhD Student
\ No newline at end of file
diff --git a/people/xinyuan_wang/index.html b/people/xinyuan_wang/index.html
new file mode 100644
index 0000000..980ab25
--- /dev/null
+++ b/people/xinyuan_wang/index.html
@@ -0,0 +1 @@
+ Xinyuan Wang | HKU NLP Group
Xinyuan Wang
Phd Student
\ No newline at end of file
diff --git a/people/xueliang_zhao/index.html b/people/xueliang_zhao/index.html
new file mode 100644
index 0000000..1374da4
--- /dev/null
+++ b/people/xueliang_zhao/index.html
@@ -0,0 +1 @@
+ Xueliang Zhao | HKU NLP Group
Xueliang Zhao
PhD Student
\ No newline at end of file
diff --git a/people/yazheng_yang/index.html b/people/yazheng_yang/index.html
new file mode 100644
index 0000000..f5b5167
--- /dev/null
+++ b/people/yazheng_yang/index.html
@@ -0,0 +1 @@
+ Yazheng Yang | HKU NLP Group
Yazheng Yang
PhD Student
\ No newline at end of file
diff --git a/people/yiheng_xu/index.html b/people/yiheng_xu/index.html
new file mode 100644
index 0000000..a31da77
--- /dev/null
+++ b/people/yiheng_xu/index.html
@@ -0,0 +1 @@
+ Yiheng Xu | HKU NLP Group
Yiheng Xu
PhD Student
\ No newline at end of file
diff --git a/people/zhihui_xie/index.html b/people/zhihui_xie/index.html
new file mode 100644
index 0000000..6bb2a5a
--- /dev/null
+++ b/people/zhihui_xie/index.html
@@ -0,0 +1 @@
+ Zhihui Xie | HKU NLP Group
Zhihui Xie
PhD Student
\ No newline at end of file
diff --git a/people/zhiyong_wu/index.html b/people/zhiyong_wu/index.html
new file mode 100644
index 0000000..88b8989
--- /dev/null
+++ b/people/zhiyong_wu/index.html
@@ -0,0 +1 @@
+ Zhiyong Wu | HKU NLP Group
\ No newline at end of file
diff --git a/projects/1_project/index.html b/projects/1_project/index.html
new file mode 100644
index 0000000..c6e42d3
--- /dev/null
+++ b/projects/1_project/index.html
@@ -0,0 +1,15 @@
+ project 1 | HKU NLP Group
project 1
a project with a background image
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/projects/2_project/index.html b/projects/2_project/index.html
new file mode 100644
index 0000000..c0312c9
--- /dev/null
+++ b/projects/2_project/index.html
@@ -0,0 +1,15 @@
+ project 2 | HKU NLP Group
project 2
a project with a background image
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/projects/3_project/index.html b/projects/3_project/index.html
new file mode 100644
index 0000000..d74669b
--- /dev/null
+++ b/projects/3_project/index.html
@@ -0,0 +1,15 @@
+ project 3 | HKU NLP Group
project 3
a project that redirects to another website
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/projects/4_project/index.html b/projects/4_project/index.html
new file mode 100644
index 0000000..130b7c1
--- /dev/null
+++ b/projects/4_project/index.html
@@ -0,0 +1,15 @@
+ project 4 | HKU NLP Group
project 4
another without an image
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/projects/5_project/index.html b/projects/5_project/index.html
new file mode 100644
index 0000000..517f03f
--- /dev/null
+++ b/projects/5_project/index.html
@@ -0,0 +1,15 @@
+ project 5 | HKU NLP Group
project 5
a project with a background image
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/projects/6_project/index.html b/projects/6_project/index.html
new file mode 100644
index 0000000..dddf08d
--- /dev/null
+++ b/projects/6_project/index.html
@@ -0,0 +1,15 @@
+ project 6 | HKU NLP Group
project 6
a project with no image
Every project has a beautiful feature showcase page. It’s easy to include images in a flexible 3-column grid format. Make your photos 1/3, 2/3, or full width.
To give your project a background in the portfolio page, just add the img tag to the front matter like so:
---
+layout: page
+title: project
+description: a project with a background image
+img: /assets/img/12.jpg
+---
+
Caption photos easily. On the left, a road goes through a tunnel. Middle, leaves artistically fall in a hipster photoshoot. Right, in another hipster photoshoot, a lumberjack grasps a handful of pine needles.
This image can also have a caption. It's like magic.
You can also put regular text between your rows of images. Say you wanted to write a little bit about your project before you posted the rest of the images. You describe how you toiled, sweated, bled for your project, and then… you reveal it’s glory in the next row of images.
You can also have artistically styled 2/3 + 1/3 images, like these.
The code is simple. Just wrap your images with <div class="col-sm"> and place them inside <div class="row"> (read more about the Bootstrap Grid system). To make images responsive, add img-fluid class to each; for rounded corners and shadows use rounded and z-depth-1 classes. Here’s the code for the last row of images above:
\ No newline at end of file
diff --git a/publications/index.html b/publications/index.html
new file mode 100644
index 0000000..e772a82
--- /dev/null
+++ b/publications/index.html
@@ -0,0 +1 @@
+ Publications | HKU NLP Group
Publications
2024
OpenAgents: An Open Platform for Language Agents in the Wild
Tianbao Xie, Fan Zhou, Zhoujun Cheng, Peng Shi, Luoxuan Weng, Yitao Liu, Toh Jing Hua, Junning Zhao, Qian Liu, Che Liu, Leo Z. Liu, Yiheng Xu, and 4 more authors