mirror of
https://github.com/Fechin/reference.git
synced 2026-11-20 21:23:11 +03:00
feat: modernize development toolchain
- Add comprehensive development tooling: * ESLint configuration with modern JavaScript rules * Prettier for consistent code formatting * Husky for Git hooks automation * lint-staged for pre-commit checks * Conventional Commits with commitlint * Stylelint for CSS code quality - Fix CSS issues: * Resolve duplicate selectors in layout_note.css * Merge duplicate selectors in layout_list.css * Ensure stylelint compliance - Apply consistent code formatting: * Format all JavaScript, CSS, and Markdown files * Standardize code style across the project * Fix console statement warnings in main.js - Update project documentation: * Enhance README with modern development practices * Update package.json with new scripts and dependencies This modernization establishes a robust development environment with automated code quality checks, consistent formatting~
This commit is contained in:
1 parent
a2a26f618c
commit
172342c8a3
78 files changed
+14986
-3626
No files matched your search
@@ -0,0 +1,50 @@
|
||||
module.exports = {
|
||||
extends: ['@commitlint/config-conventional'],
|
||||
rules: {
|
||||
'type-enum': [
|
||||
2,
|
||||
'always',
|
||||
[
|
||||
'feat', // new feature
|
||||
'fix', // bug fix
|
||||
'docs', // documentation update
|
||||
'style', // code formatting, no logic changes
|
||||
'refactor', // code refactoring
|
||||
'perf', // performance optimization
|
||||
'test', // add tests
|
||||
'chore', // build process or auxiliary tool changes
|
||||
'ci', // CI/CD related changes
|
||||
'build', // build system or external dependency changes
|
||||
'revert' // revert commit
|
||||
]
|
||||
],
|
||||
'scope-enum': [
|
||||
2,
|
||||
'always',
|
||||
[
|
||||
'search', // search functionality
|
||||
'theme', // theme related
|
||||
'css', // style files
|
||||
'js', // JavaScript files
|
||||
'content', // content files
|
||||
'build', // build related
|
||||
'deps', // dependency updates
|
||||
'config', // configuration files
|
||||
'docs', // documentation
|
||||
'layout', // layout templates
|
||||
'widget', // components
|
||||
'gulp', // Gulp tasks
|
||||
'hexo', // Hexo related
|
||||
'markdown', // Markdown processing
|
||||
'seo', // SEO optimization
|
||||
'a11y', // accessibility
|
||||
'perf' // performance related
|
||||
]
|
||||
],
|
||||
'subject-case': [2, 'never', ['start-case', 'pascal-case', 'upper-case']],
|
||||
'subject-empty': [2, 'never'],
|
||||
'subject-full-stop': [2, 'never', '.'],
|
||||
'type-case': [2, 'always', 'lower-case'],
|
||||
'type-empty': [2, 'never']
|
||||
}
|
||||
};
|
||||
@@ -1,7 +0,0 @@
|
||||
root = true
|
||||
|
||||
[*.md]
|
||||
charset = utf-8
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
insert_final_newline = true
|
||||
@@ -0,0 +1,13 @@
|
||||
node_modules/
|
||||
public/
|
||||
themes/coo/source/js/fuse_6.4.6.js
|
||||
themes/coo/scripts/
|
||||
*.min.js
|
||||
gulpfile.js
|
||||
.eslintrc.js
|
||||
.prettierrc.js
|
||||
.stylelintrc.js
|
||||
.commitlintrc.js
|
||||
.lintstagedrc.js
|
||||
postcss.config.js
|
||||
tailwind.config.js
|
||||
@@ -0,0 +1,52 @@
|
||||
module.exports = {
|
||||
env: {
|
||||
browser: true,
|
||||
es2022: true,
|
||||
node: true
|
||||
},
|
||||
extends: ['eslint:recommended', 'prettier'],
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module'
|
||||
},
|
||||
rules: {
|
||||
// Error level rules
|
||||
'no-console': 'warn',
|
||||
'no-debugger': 'error',
|
||||
'no-unused-vars': [
|
||||
'error',
|
||||
{
|
||||
argsIgnorePattern: '^_',
|
||||
varsIgnorePattern: '^_'
|
||||
}
|
||||
],
|
||||
|
||||
// ES6+ best practices
|
||||
'prefer-const': 'error',
|
||||
'no-var': 'error',
|
||||
'object-shorthand': 'error',
|
||||
'prefer-template': 'error',
|
||||
'prefer-arrow-callback': 'error',
|
||||
|
||||
// Best practices
|
||||
eqeqeq: ['error', 'always'],
|
||||
curly: ['error', 'all'],
|
||||
'no-eval': 'error',
|
||||
'no-implied-eval': 'error',
|
||||
'no-new-func': 'error',
|
||||
'no-script-url': 'error',
|
||||
|
||||
// Function related
|
||||
'func-style': ['error', 'declaration', { allowArrowFunctions: true }],
|
||||
'no-loop-func': 'error',
|
||||
|
||||
// Objects and arrays
|
||||
'dot-notation': 'error'
|
||||
},
|
||||
|
||||
globals: {
|
||||
hexo: 'readonly',
|
||||
Utils: 'readonly',
|
||||
Fuse: 'readonly'
|
||||
}
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: Cheatsheet request
|
||||
about: For request cheatsheet and reference.
|
||||
title: "Cheatsheet request: "
|
||||
title: 'Cheatsheet request: '
|
||||
labels: request
|
||||
assignees: Fechin
|
||||
---
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
# <type>[optional scope]: <description>
|
||||
#
|
||||
# [optional body]
|
||||
#
|
||||
# [optional footer(s)]
|
||||
#
|
||||
# Commit Types:
|
||||
# feat: New feature
|
||||
# fix: Bug fix
|
||||
# docs: Documentation update
|
||||
# style: Code formatting, no logic changes
|
||||
# refactor: Code refactoring, neither new feature nor bug fix
|
||||
# perf: Performance optimization
|
||||
# test: Add tests
|
||||
# chore: Build process or auxiliary tool changes
|
||||
# ci: CI/CD related changes
|
||||
# build: Build system or external dependency changes
|
||||
# revert: Revert commit
|
||||
#
|
||||
# Scope Examples:
|
||||
# search, theme, css, js, content, build, deps, config, docs
|
||||
# layout, widget, gulp, hexo, markdown, seo, a11y, perf
|
||||
#
|
||||
# Examples:
|
||||
# feat(search): add fuzzy search with highlighting
|
||||
# fix(css): resolve mobile layout overflow issue
|
||||
# docs(readme): update installation instructions
|
||||
# chore(deps): upgrade tailwindcss to v3.4.0
|
||||
# perf(js): optimize search performance with debouncing
|
||||
# style(css): format tailwind classes according to prettier
|
||||
#
|
||||
# Guidelines:
|
||||
# - Use imperative mood: "add" not "added" or "adds"
|
||||
# - Start with lowercase
|
||||
# - No period at the end
|
||||
# - Keep description concise, under 50 characters
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
npx commitlint --edit $1
|
||||
Executable
+1
@@ -0,0 +1 @@
|
||||
npx lint-staged
|
||||
@@ -0,0 +1,10 @@
|
||||
module.exports = {
|
||||
// JavaScript files
|
||||
'*.{js,mjs}': ['eslint --fix', 'prettier --write'],
|
||||
|
||||
// CSS files
|
||||
'*.css': ['stylelint --fix', 'prettier --write'],
|
||||
|
||||
// All other files that Prettier supports
|
||||
'*.{md,json,yml,yaml}': ['prettier --write']
|
||||
};
|
||||
@@ -1,12 +0,0 @@
|
||||
{
|
||||
"MD003": false,
|
||||
"MD013": false,
|
||||
"MD014": false,
|
||||
"MD024": false,
|
||||
"MD033": false,
|
||||
"MD040": false,
|
||||
"MD010": {
|
||||
"code_blocks": true,
|
||||
"spaces_per_tab": 2
|
||||
}
|
||||
}
|
||||
+44
-3
@@ -1,3 +1,44 @@
|
||||
# Minimized files
|
||||
**.min.css
|
||||
fuse_*.js
|
||||
# Dependencies
|
||||
node_modules/
|
||||
pnpm-lock.yaml
|
||||
package-lock.json
|
||||
|
||||
# Build outputs
|
||||
public/
|
||||
dist/
|
||||
.hexo/
|
||||
|
||||
# Generated files
|
||||
db.json
|
||||
themes/coo/source/css/style.css
|
||||
|
||||
# Third-party libraries
|
||||
themes/coo/source/js/fuse_*.js
|
||||
*.min.js
|
||||
*.min.css
|
||||
|
||||
# Large asset files
|
||||
source/assets/image/
|
||||
source/assets/icon/
|
||||
*.png
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.gif
|
||||
*.svg
|
||||
*.ico
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.temp
|
||||
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"proseWrap": "always",
|
||||
"plugins": ["prettier-plugin-tailwindcss"]
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
module.exports = {
|
||||
// Basic configuration
|
||||
semi: true,
|
||||
trailingComma: 'none',
|
||||
singleQuote: true,
|
||||
printWidth: 100,
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
endOfLine: 'lf',
|
||||
|
||||
// Plugin configuration
|
||||
plugins: ['prettier-plugin-tailwindcss'],
|
||||
|
||||
// File-specific configuration
|
||||
overrides: [
|
||||
{
|
||||
files: '*.md',
|
||||
options: {
|
||||
proseWrap: 'preserve',
|
||||
printWidth: 80
|
||||
}
|
||||
},
|
||||
{
|
||||
files: '*.yml',
|
||||
options: {
|
||||
singleQuote: false
|
||||
}
|
||||
},
|
||||
{
|
||||
files: '*.json',
|
||||
options: {
|
||||
trailingComma: 'none'
|
||||
}
|
||||
},
|
||||
{
|
||||
files: ['themes/coo/source/css/*.css'],
|
||||
options: {
|
||||
printWidth: 120
|
||||
}
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
module.exports = {
|
||||
extends: ['stylelint-config-standard'],
|
||||
rules: {
|
||||
// Tailwind CSS compatibility
|
||||
'at-rule-no-unknown': [
|
||||
true,
|
||||
{
|
||||
ignoreAtRules: ['tailwind', 'apply', 'variants', 'responsive', 'screen', 'layer']
|
||||
}
|
||||
],
|
||||
'no-descending-specificity': null,
|
||||
'selector-class-pattern': null // Allow camelCase class names
|
||||
},
|
||||
ignoreFiles: [
|
||||
'node_modules/**/*',
|
||||
'public/**/*',
|
||||
'themes/coo/source/css/highlightjs/**/*',
|
||||
'**/*.min.css'
|
||||
]
|
||||
};
|
||||
@@ -12,9 +12,10 @@ sheet that could be improved, feel free to submit a [pull request](#-contributin
|
||||
|
||||
## 👀 Live Demonstration
|
||||
|
||||
Note: The original domain for this project was quickref.me, which was acquired by a US-based company. Since then, cheatsheets.zip is the primary and maintained domain (All within the bounds of the agreements).
|
||||
Note: The original domain for this project was quickref.me, which was acquired by a US-based company. Since then,
|
||||
cheatsheets.zip is the primary and maintained domain (All within the bounds of the agreements).
|
||||
|
||||
You can view the most up-to-date cheat sheets live at [https://cheatsheets.zip](https://cheatsheets.zip/).
|
||||
You can view the most up-to-date cheat sheets live at [https://cheatsheets.zip](https://cheatsheets.zip/).
|
||||
|
||||
[](https://cheatsheets.zip)
|
||||
|
||||
@@ -25,33 +26,58 @@ Reference provides cheat sheets for the following:
|
||||
<details>
|
||||
<summary>Programming</summary>
|
||||
|
||||
- [Bash](https://cheatsheets.zip/bash.html): This is a quick reference cheat sheet to getting started with Linux bash shell scripting.
|
||||
- [Bash](https://cheatsheets.zip/bash.html): This is a quick reference cheat sheet to getting started with Linux bash
|
||||
shell scripting.
|
||||
- [C](https://cheatsheets.zip/c.html): C quick reference cheat sheet that provides basic syntax and methods.
|
||||
- [C++](https://cheatsheets.zip/cpp.html): C++ quick reference cheat sheet that provides basic syntax and methods.
|
||||
- [C#](https://cheatsheets.zip/cs.html): C# quick reference cheat sheet that provides basic syntax and methods.
|
||||
- [CSS 3](https://cheatsheets.zip/css.html): This is a quick reference cheat sheet for CSS goodness, listing selector syntax, properties, units and other useful bits of information.
|
||||
- [Dart](https://cheatsheets.zip/dart.html): A Dart cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
|
||||
- [Docker](https://cheatsheets.zip/docker.html): This is a quick reference cheat sheet for [Docker](https://docs.docker.com/get-started/). And you can find the most common Docker commands here.
|
||||
- [ES6](https://cheatsheets.zip/es6.html): A quick reference cheat sheet of what’s new in JavaScript for ES2015, ES2016, ES2017, ES2018 and beyond
|
||||
- [Go](https://cheatsheets.zip/go.html): This cheat sheet provided basic syntax and methods to help you using [Go](https://go.dev/).
|
||||
- [GraphQL](https://cheatsheets.zip/graphql.html): This quick reference cheat sheet provides a brief overview of GraphQL.
|
||||
- [Hook](https://cheatsheets.zip/hook.html): The [Hook](https://github.com/hook-lang/hook/) cheat sheet is a one-page reference sheet for the Hook programming language.
|
||||
- [HTML](https://cheatsheets.zip/html.html): This HTML quick reference cheat sheet lists the common HTML and HTML5 tags in readable layout.
|
||||
- [INI](https://cheatsheets.zip/ini.html): This is a quick reference cheat sheet for understanding and writing INI-format configuration files.
|
||||
- [Java](https://cheatsheets.zip/java.html): This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language.
|
||||
- [JavaScript](https://cheatsheets.zip/javascript.html): A JavaScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
|
||||
- [jQuery](https://cheatsheets.zip/jquery.html): This [jQuery](https://jquery.com/) cheat sheet is a great reference for both beginners and experienced developers.
|
||||
- [Kubernetes](https://cheatsheets.zip/kubernetes.html): This page contains a list of commonly used kubectl commands and flags.
|
||||
- [LaTeX](https://cheatsheets.zip/latex.html): This cheat sheet summarizes a reference list of [LaTeX](https://www.latex-project.org/) commonly used display math notation and some application examples of [KaTeX](https://katex.org/).
|
||||
- [Laravel](https://cheatsheets.zip/laravel.html): [Laravel](https://laravel.com/docs/8.x/) is an expressive and progressive web application framework for PHP. This cheat sheet provides a reference for common commands and features for Laravel 8.
|
||||
- [MATLAB](https://cheatsheets.zip/matlab.html): This quick reference cheat sheet provides an example introduction to using the [MATLAB](https://mathworks.cn/) scientific computing language to get started quickly
|
||||
- [CSS 3](https://cheatsheets.zip/css.html): This is a quick reference cheat sheet for CSS goodness, listing selector
|
||||
syntax, properties, units and other useful bits of information.
|
||||
- [Dart](https://cheatsheets.zip/dart.html): A Dart cheat sheet with the most important concepts, functions, methods,
|
||||
and more. A complete quick reference for beginners.
|
||||
- [Docker](https://cheatsheets.zip/docker.html): This is a quick reference cheat sheet for
|
||||
[Docker](https://docs.docker.com/get-started/). And you can find the most common Docker commands here.
|
||||
- [ES6](https://cheatsheets.zip/es6.html): A quick reference cheat sheet of what’s new in JavaScript for ES2015, ES2016,
|
||||
ES2017, ES2018 and beyond
|
||||
- [Go](https://cheatsheets.zip/go.html): This cheat sheet provided basic syntax and methods to help you using
|
||||
[Go](https://go.dev/).
|
||||
- [GraphQL](https://cheatsheets.zip/graphql.html): This quick reference cheat sheet provides a brief overview of
|
||||
GraphQL.
|
||||
- [Hook](https://cheatsheets.zip/hook.html): The [Hook](https://github.com/hook-lang/hook/) cheat sheet is a one-page
|
||||
reference sheet for the Hook programming language.
|
||||
- [HTML](https://cheatsheets.zip/html.html): This HTML quick reference cheat sheet lists the common HTML and HTML5 tags
|
||||
in readable layout.
|
||||
- [INI](https://cheatsheets.zip/ini.html): This is a quick reference cheat sheet for understanding and writing
|
||||
INI-format configuration files.
|
||||
- [Java](https://cheatsheets.zip/java.html): This cheat sheet is a crash course for Java beginners and help review the
|
||||
basic syntax of the Java language.
|
||||
- [JavaScript](https://cheatsheets.zip/javascript.html): A JavaScript cheat sheet with the most important concepts,
|
||||
functions, methods, and more. A complete quick reference for beginners.
|
||||
- [jQuery](https://cheatsheets.zip/jquery.html): This [jQuery](https://jquery.com/) cheat sheet is a great reference for
|
||||
both beginners and experienced developers.
|
||||
- [Kubernetes](https://cheatsheets.zip/kubernetes.html): This page contains a list of commonly used kubectl commands and
|
||||
flags.
|
||||
- [LaTeX](https://cheatsheets.zip/latex.html): This cheat sheet summarizes a reference list of
|
||||
[LaTeX](https://www.latex-project.org/) commonly used display math notation and some application examples of
|
||||
[KaTeX](https://katex.org/).
|
||||
- [Laravel](https://cheatsheets.zip/laravel.html): [Laravel](https://laravel.com/docs/8.x/) is an expressive and
|
||||
progressive web application framework for PHP. This cheat sheet provides a reference for common commands and features
|
||||
for Laravel 8.
|
||||
- [MATLAB](https://cheatsheets.zip/matlab.html): This quick reference cheat sheet provides an example introduction to
|
||||
using the [MATLAB](https://mathworks.cn/) scientific computing language to get started quickly
|
||||
- [Markdown](https://cheatsheets.zip/markdown.html): This is a quick reference cheat sheet to the Markdown syntax.
|
||||
- [PHP](https://cheatsheets.zip/php.html): This [PHP](https://www.php.net/manual/en/) cheat sheet provides a reference for quickly looking up the correct syntax for the code you use most frequently.
|
||||
- [Python](https://cheatsheets.zip/python.html): The [Python](https://www.python.org/) cheat sheet is a one-page reference sheet for the Python 3 programming language.
|
||||
- [Rust](https://cheatsheets.zip/rust.html): The Rust quick reference cheat sheet that aims at providing help on writing basic syntax and methods.
|
||||
- [Sass](https://cheatsheets.zip/sass.html): This is a quick reference cheat sheet that lists the most useful features of [SASS](https://sass-lang.com).
|
||||
- [TOML](https://cheatsheets.zip/toml.html): This is a quick reference cheat sheet to the TOML format configuration file syntax.
|
||||
- [YAML](https://cheatsheets.zip/yaml.html): This is a quick reference cheat sheet for understanding and writing YAML format configuration files.
|
||||
- [PHP](https://cheatsheets.zip/php.html): This [PHP](https://www.php.net/manual/en/) cheat sheet provides a reference
|
||||
for quickly looking up the correct syntax for the code you use most frequently.
|
||||
- [Python](https://cheatsheets.zip/python.html): The [Python](https://www.python.org/) cheat sheet is a one-page
|
||||
reference sheet for the Python 3 programming language.
|
||||
- [Rust](https://cheatsheets.zip/rust.html): The Rust quick reference cheat sheet that aims at providing help on writing
|
||||
basic syntax and methods.
|
||||
- [Sass](https://cheatsheets.zip/sass.html): This is a quick reference cheat sheet that lists the most useful features
|
||||
of [SASS](https://sass-lang.com).
|
||||
- [TOML](https://cheatsheets.zip/toml.html): This is a quick reference cheat sheet to the TOML format configuration file
|
||||
syntax.
|
||||
- [YAML](https://cheatsheets.zip/yaml.html): This is a quick reference cheat sheet for understanding and writing YAML
|
||||
format configuration files.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -116,18 +142,23 @@ Reference provides cheat sheets for the following:
|
||||
|
||||
- [NumPy](https://cheatsheets.zip/numpy.html): [NumPy](https://numpy.org/) is the fundamental package for scientific
|
||||
computing with Python. This cheat sheet is a quick reference for NumPy beginners.
|
||||
- [Pandas](https://cheatsheets.zip/pandas.html): [Pandas](https://pandas.pydata.org/) is a powerful data analysis and manipulation library for Python. This quick reference cheat sheet provides an overview of essential Pandas functions, methods, and DataFrame operations.
|
||||
- [Pandas](https://cheatsheets.zip/pandas.html): [Pandas](https://pandas.pydata.org/) is a powerful data analysis and
|
||||
manipulation library for Python. This quick reference cheat sheet provides an overview of essential Pandas functions,
|
||||
methods, and DataFrame operations.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Database</summary>
|
||||
|
||||
- [MySQL](https://cheatsheets.zip/mysql.html): The SQL cheat sheet provides you with the most commonly used SQL statements for your reference.
|
||||
- [Neo4j](https://cheatsheets.zip/neo4j.html): A Neo4j cheat sheet with getting started resources and information on how to query the database with Cypher.
|
||||
- [PostgreSQL](https://cheatsheets.zip/postgres.html): The [PostgreSQL](https://www.postgresql.org/docs/current/) cheat sheet provides you with the common PostgreSQL commands and statements.
|
||||
- [Redis](https://cheatsheets.zip/redis.html): This is a [Redis](https://redis.io/) quick reference cheat sheet that lists examples of redis commands
|
||||
|
||||
- [MySQL](https://cheatsheets.zip/mysql.html): The SQL cheat sheet provides you with the most commonly used SQL
|
||||
statements for your reference.
|
||||
- [Neo4j](https://cheatsheets.zip/neo4j.html): A Neo4j cheat sheet with getting started resources and information on how
|
||||
to query the database with Cypher.
|
||||
- [PostgreSQL](https://cheatsheets.zip/postgres.html): The [PostgreSQL](https://www.postgresql.org/docs/current/) cheat
|
||||
sheet provides you with the common PostgreSQL commands and statements.
|
||||
- [Redis](https://cheatsheets.zip/redis.html): This is a [Redis](https://redis.io/) quick reference cheat sheet that
|
||||
lists examples of redis commands
|
||||
|
||||
</details>
|
||||
|
||||
@@ -267,28 +298,39 @@ Reference provides cheat sheets for the following:
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
<details>
|
||||
<summary>Shaders</summary>
|
||||
|
||||
- [Unity Shader Graph](https://cheatsheets.zip/unity-shader-graph.html): This is a visual cheat-sheet for the Unity Shader Graph. This tool is used to create custom shaders material in Unity, a popular game engine.
|
||||
- [Unity Shader Graph](https://cheatsheets.zip/unity-shader-graph.html): This is a visual cheat-sheet for the Unity
|
||||
Shader Graph. This tool is used to create custom shaders material in Unity, a popular game engine.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
<details>
|
||||
<summary>Other</summary>
|
||||
|
||||
- [ASCII Code](https://cheatsheets.zip/ascii-code.html): This cheat sheet is a complete list of ASCII Code Table with their numbers and names.
|
||||
- [Aspect Ratio](https://cheatsheets.zip/aspect-ratio.html): This cheat sheet lists some common aspect ratios and their pixel resolutions. Always confirm your final delivery ratio when shooting.
|
||||
- [CheatSheets](https://cheatsheets.zip/quickref.html): This is the magic syntax variant manual that you can use on CheatSheets.zip, It’s a good practice for contributors.
|
||||
- [Emoji](https://cheatsheets.zip/emoji.html): Some of the emoji codes are not super easy to remember, so here is a little cheat sheet.
|
||||
- [Google Search](https://cheatsheets.zip/google-search.html): This quick reference cheat sheet lists of Google advanced search operators.
|
||||
- [HTML Characters Entities](https://cheatsheets.zip/html-char.html): This cheat sheet is a complete list of HTML entities with their numbers and names. Also included is a full list of ASCII characters that can be represented in HTML.
|
||||
- [ISO 639-1 Language Code](https://cheatsheets.zip/iso-639-1.html): This is a list of the ISO language codes that conform to the ISO 639-1 standard, it provide reference for multi-language website.
|
||||
- [HTTP Status Code](https://cheatsheets.zip/http-status-code.html): The http status codes cheat sheet. A quick reference to every HTTP status code.
|
||||
- [MIME types](https://cheatsheets.zip/mime.html): This cheat sheet lists some common MIME types for the Web. You can look in the [IANA/MIME Media Types registry](http://www.iana.org/assignments/media-types/index.html) which contains all registered MIME types.
|
||||
- [Resolutions](https://cheatsheets.zip/resolutions.html): This cheat sheet lists screen sizes, viewport size and CSS media queries for popular Phones, Tablets, Laptops and Watches
|
||||
- [ASCII Code](https://cheatsheets.zip/ascii-code.html): This cheat sheet is a complete list of ASCII Code Table with
|
||||
their numbers and names.
|
||||
- [Aspect Ratio](https://cheatsheets.zip/aspect-ratio.html): This cheat sheet lists some common aspect ratios and their
|
||||
pixel resolutions. Always confirm your final delivery ratio when shooting.
|
||||
- [CheatSheets](https://cheatsheets.zip/quickref.html): This is the magic syntax variant manual that you can use on
|
||||
CheatSheets.zip, It’s a good practice for contributors.
|
||||
- [Emoji](https://cheatsheets.zip/emoji.html): Some of the emoji codes are not super easy to remember, so here is a
|
||||
little cheat sheet.
|
||||
- [Google Search](https://cheatsheets.zip/google-search.html): This quick reference cheat sheet lists of Google advanced
|
||||
search operators.
|
||||
- [HTML Characters Entities](https://cheatsheets.zip/html-char.html): This cheat sheet is a complete list of HTML
|
||||
entities with their numbers and names. Also included is a full list of ASCII characters that can be represented in
|
||||
HTML.
|
||||
- [ISO 639-1 Language Code](https://cheatsheets.zip/iso-639-1.html): This is a list of the ISO language codes that
|
||||
conform to the ISO 639-1 standard, it provide reference for multi-language website.
|
||||
- [HTTP Status Code](https://cheatsheets.zip/http-status-code.html): The http status codes cheat sheet. A quick
|
||||
reference to every HTTP status code.
|
||||
- [MIME types](https://cheatsheets.zip/mime.html): This cheat sheet lists some common MIME types for the Web. You can
|
||||
look in the [IANA/MIME Media Types registry](http://www.iana.org/assignments/media-types/index.html) which contains
|
||||
all registered MIME types.
|
||||
- [Resolutions](https://cheatsheets.zip/resolutions.html): This cheat sheet lists screen sizes, viewport size and CSS
|
||||
media queries for popular Phones, Tablets, Laptops and Watches
|
||||
|
||||
</details>
|
||||
|
||||
@@ -317,10 +359,13 @@ Reference provides cheat sheets for the following:
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
We would like to extend our gratitude to you for considering a contribution to Reference. Your support is what makes
|
||||
this project a truly resource. Please note that the primary domain for accessing the most up-to-date content is
|
||||
[cheatsheets.zip](https://cheatsheets.zip). Feel free to
|
||||
[submit issues](https://github.com/Fechin/reference/issues/new?assignee=Fechin) and enhancement requests.
|
||||
|
||||
We would like to extend our gratitude to you for considering a contribution to Reference. Your support is what makes this project a truly resource. Please note that the primary domain for accessing the most up-to-date content is [cheatsheets.zip](https://cheatsheets.zip). Feel free to [submit issues](https://github.com/Fechin/reference/issues/new?assignee=Fechin) and enhancement requests.
|
||||
|
||||
For consistency, we encourage you to refer to the [https://cheatsheets.zip/quickref](https://cheatsheets.zip/quickref) when creating or editing cheat sheets. To get started with development, follow these steps:
|
||||
For consistency, we encourage you to refer to the [https://cheatsheets.zip/quickref](https://cheatsheets.zip/quickref)
|
||||
when creating or editing cheat sheets. To get started with development, follow these steps:
|
||||
|
||||
1. Clone Github repo `git clone https://github.com/Fechin/reference.git`
|
||||
2. Install `npm` package manager (Read
|
||||
@@ -352,8 +397,6 @@ Only the `title` and `intro` fields are required, and the other options can be l
|
||||
<img src="https://contrib.rocks/image?repo=Fechin/reference" />
|
||||
</a>
|
||||
|
||||
|
||||
|
||||
## 🐦 Follow us on Twitter
|
||||
|
||||
[](https://twitter.com/FechinLi)
|
||||
@@ -365,5 +408,5 @@ It's the perfect way to stay in the loop.
|
||||
|
||||
## 📃 License
|
||||
|
||||
The project is licensed under the [GPL-3.0](https://github.com/Fechin/reference/blob/main/LICENSE) License and is maintained
|
||||
by [Fechin](https://github.com/Fechin).
|
||||
The project is licensed under the [GPL-3.0](https://github.com/Fechin/reference/blob/main/LICENSE) License and is
|
||||
maintained by [Fechin](https://github.com/Fechin).
|
||||
+20
-20
@@ -1,44 +1,44 @@
|
||||
const gulp = require("gulp");
|
||||
const htmlmin = require("gulp-htmlmin");
|
||||
const htmlclean = require("gulp-htmlclean");
|
||||
const version = require("gulp-version-number");
|
||||
const terser = require("gulp-terser");
|
||||
const gulp = require('gulp');
|
||||
const htmlmin = require('gulp-htmlmin');
|
||||
const htmlclean = require('gulp-htmlclean');
|
||||
const version = require('gulp-version-number');
|
||||
const terser = require('gulp-terser');
|
||||
|
||||
// Compress js files
|
||||
gulp.task("js", function () {
|
||||
gulp.task('js', function () {
|
||||
return gulp
|
||||
.src(["./public/js/main.js"])
|
||||
.src(['./public/js/main.js'])
|
||||
.pipe(
|
||||
terser({
|
||||
compress: true,
|
||||
}),
|
||||
compress: true
|
||||
})
|
||||
)
|
||||
.pipe(gulp.dest("./public/js"));
|
||||
.pipe(gulp.dest('./public/js'));
|
||||
});
|
||||
|
||||
// Build html files
|
||||
gulp.task("html", function () {
|
||||
gulp.task('html', function () {
|
||||
return gulp
|
||||
.src("./public/**/*.html")
|
||||
.src('./public/**/*.html')
|
||||
.pipe(htmlclean())
|
||||
.pipe(
|
||||
htmlmin({
|
||||
removeComments: true,
|
||||
minifyJS: true,
|
||||
minifyCSS: true,
|
||||
minifyURLs: true,
|
||||
}),
|
||||
minifyURLs: true
|
||||
})
|
||||
)
|
||||
.pipe(
|
||||
version({
|
||||
append: {
|
||||
key: "_v",
|
||||
key: '_v',
|
||||
cover: 1,
|
||||
to: ["css", "js", "png", "jpg", "woff2"],
|
||||
},
|
||||
}),
|
||||
to: ['css', 'js', 'png', 'jpg', 'woff2']
|
||||
}
|
||||
})
|
||||
)
|
||||
.pipe(gulp.dest("./public"));
|
||||
.pipe(gulp.dest('./public'));
|
||||
});
|
||||
|
||||
gulp.task("default", gulp.parallel("js", "html"));
|
||||
gulp.task('default', gulp.parallel('js', 'html'));
|
||||
+39
-20
@@ -12,20 +12,26 @@
|
||||
"build:css": "npx postcss themes/coo/source/css/style.tailwindcss -o themes/coo/source/css/style.css",
|
||||
"build:generate": "npx hexo generate",
|
||||
"build:gulp": "npx gulp --max-old-space-size=4096",
|
||||
"format": "prettier --write"
|
||||
"format": "prettier --write .",
|
||||
"format:check": "prettier --check .",
|
||||
"lint": "eslint themes/coo/source/js/**/*.js --fix",
|
||||
"lint:check": "eslint themes/coo/source/js/**/*.js",
|
||||
"lint:css": "stylelint **/*.css --fix",
|
||||
"test": "run-s lint:check format:check",
|
||||
"prepare": "husky",
|
||||
"commit": "cz"
|
||||
},
|
||||
"hexo": {
|
||||
"version": "5.4.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"eslint": "^8.27.0",
|
||||
"gulp": "^4.0.2",
|
||||
"gulp-cli": "^2.3.0",
|
||||
"gulp": "^5.0.0",
|
||||
"gulp-cli": "^3.0.0",
|
||||
"gulp-ext-replace": "^0.3.0",
|
||||
"gulp-htmlclean": "^2.7.22",
|
||||
"gulp-htmlmin": "^5.0.1",
|
||||
"gulp-minify-css": "^1.2.4",
|
||||
"gulp-postcss": "^9.0.1",
|
||||
"gulp-postcss": "^10.0.0",
|
||||
"gulp-uglify-es": "^3.0.0",
|
||||
"gulp-version-number": "^0.2.4",
|
||||
"hexo": "^5.4.0",
|
||||
@@ -58,23 +64,36 @@
|
||||
"markdown-it-task-lists": "^2.1.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"autoprefixer": "^10.4.0",
|
||||
"@commitlint/cli": "^19.5.0",
|
||||
"@commitlint/config-conventional": "^19.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"commitizen": "^4.3.1",
|
||||
"cssnano": "^7.0.7",
|
||||
"cz-conventional-changelog": "^3.3.0",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-prettier": "^10.1.5",
|
||||
"gulp-clean-css": "^4.3.0",
|
||||
"gulp-filesize": "^0.0.6",
|
||||
"gulp-javascript-obfuscator": "^1.1.6",
|
||||
"gulp-replace": "^1.1.3",
|
||||
"gulp-rev": "^9.0.0",
|
||||
"gulp-replace": "^1.1.4",
|
||||
"gulp-rev": "^10.0.0",
|
||||
"gulp-terser": "^2.1.0",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"postcss": "^8.4.4",
|
||||
"postcss-cli": "^9.1.0",
|
||||
"postcss-import": "^14.0.2",
|
||||
"postcss-minify": "^1.1.0",
|
||||
"prettier": "^3.2.5",
|
||||
"prettier-plugin-tailwindcss": "^0.5.14",
|
||||
"sync-request": "^6.1.0",
|
||||
"tailwindcss": "^3.0.1",
|
||||
"tailwindcss-animate": "^1.0.5",
|
||||
"tailwindcss-cli": "^0.1.2"
|
||||
"husky": "^9.1.6",
|
||||
"lint-staged": "^15.2.10",
|
||||
"npm-run-all2": "^6.2.6",
|
||||
"postcss": "^8.5.6",
|
||||
"postcss-cli": "^11.0.0",
|
||||
"postcss-import": "^16.1.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier-plugin-tailwindcss": "^0.6.8",
|
||||
"stylelint": "^16.10.0",
|
||||
"stylelint-config-standard": "^36.0.1",
|
||||
"tailwindcss": "^3.4.14",
|
||||
"tailwindcss-animate": "^1.0.7"
|
||||
},
|
||||
"config": {
|
||||
"commitizen": {
|
||||
"path": "./node_modules/cz-conventional-changelog"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+10590
File diff suppressed because it is too large.
Load diff
+4
-4
@@ -1,8 +1,8 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
"postcss-import": { path: "themes/coo/source/css" },
|
||||
tailwindcss: { config: "./tailwind.config.js" },
|
||||
'postcss-import': { path: 'themes/coo/source/css' },
|
||||
tailwindcss: { config: './tailwind.config.js' },
|
||||
autoprefixer: {},
|
||||
"postcss-minify": {},
|
||||
},
|
||||
...(process.env.NODE_ENV === 'production' ? { cssnano: {} } : {})
|
||||
}
|
||||
};
|
||||
@@ -4,12 +4,14 @@ date: 2024-03-20 12:00:00
|
||||
icon: icon-alpine
|
||||
background: bg-blue-600
|
||||
tags:
|
||||
- linux
|
||||
- server
|
||||
- container
|
||||
- linux
|
||||
- server
|
||||
- container
|
||||
categories:
|
||||
- Operating System
|
||||
intro: A comprehensive cheatsheet for Alpine Linux, covering package management, system administration, networking, and more. Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox.
|
||||
- Operating System
|
||||
intro:
|
||||
A comprehensive cheatsheet for Alpine Linux, covering package management, system administration, networking, and more.
|
||||
Alpine Linux is a security-oriented, lightweight Linux distribution based on musl libc and busybox.
|
||||
---
|
||||
|
||||
# Alpine Linux Cheatsheet
|
||||
@@ -17,6 +19,7 @@ intro: A comprehensive cheatsheet for Alpine Linux, covering package management,
|
||||
## Package Management (apk)
|
||||
|
||||
### Basic Package Operations
|
||||
|
||||
```bash
|
||||
# Update package index
|
||||
apk update
|
||||
@@ -41,6 +44,7 @@ apk list --installed
|
||||
```
|
||||
|
||||
### Advanced Package Operations
|
||||
|
||||
```bash
|
||||
# Add package from testing repository
|
||||
apk add --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/edge/testing <package-name>
|
||||
@@ -55,6 +59,7 @@ apk cache clean
|
||||
## System Administration
|
||||
|
||||
### Service Management (OpenRC)
|
||||
|
||||
```bash
|
||||
# Start a service
|
||||
rc-service <service-name> start
|
||||
@@ -76,6 +81,7 @@ rc-status
|
||||
```
|
||||
|
||||
### System Information
|
||||
|
||||
```bash
|
||||
# Show system information
|
||||
uname -a
|
||||
@@ -94,6 +100,7 @@ uptime
|
||||
```
|
||||
|
||||
### Network Configuration
|
||||
|
||||
```bash
|
||||
# Show network interfaces
|
||||
ip addr show
|
||||
@@ -112,6 +119,7 @@ vi /etc/network/interfaces
|
||||
```
|
||||
|
||||
### User Management
|
||||
|
||||
```bash
|
||||
# Add a new user
|
||||
adduser <username>
|
||||
@@ -132,6 +140,7 @@ cat /etc/passwd
|
||||
## File System Operations
|
||||
|
||||
### Basic File Operations
|
||||
|
||||
```bash
|
||||
# Create directory
|
||||
mkdir <directory-name>
|
||||
@@ -155,6 +164,7 @@ chown <user>:<group> <file>
|
||||
## Container Operations
|
||||
|
||||
### Docker Support
|
||||
|
||||
```bash
|
||||
# Install Docker
|
||||
apk add docker
|
||||
@@ -169,6 +179,7 @@ rc-update add docker default
|
||||
## System Maintenance
|
||||
|
||||
### Disk Operations
|
||||
|
||||
```bash
|
||||
# Check disk space
|
||||
df -h
|
||||
@@ -184,6 +195,7 @@ umount /mnt/<mountpoint>
|
||||
```
|
||||
|
||||
### Backup and Restore
|
||||
|
||||
```bash
|
||||
# Create tar archive
|
||||
tar -czf backup.tar.gz /path/to/backup
|
||||
@@ -198,6 +210,7 @@ lbu package /media/backup.apkovl.tar.gz
|
||||
## Tips and Tricks
|
||||
|
||||
### Common Configuration Files
|
||||
|
||||
- `/etc/apk/repositories` - Package repositories
|
||||
- `/etc/network/interfaces` - Network configuration
|
||||
- `/etc/hostname` - System hostname
|
||||
@@ -205,6 +218,7 @@ lbu package /media/backup.apkovl.tar.gz
|
||||
- `/etc/resolv.conf` - DNS configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
```bash
|
||||
# Set environment variable
|
||||
export VARIABLE=value
|
||||
@@ -217,6 +231,7 @@ echo "export VARIABLE=value" >> ~/.profile
|
||||
```
|
||||
|
||||
### System Logs
|
||||
|
||||
```bash
|
||||
# View system logs
|
||||
less /var/log/messages
|
||||
@@ -231,6 +246,7 @@ tail -f /var/log/messages
|
||||
## Security
|
||||
|
||||
### Firewall (using iptables)
|
||||
|
||||
```bash
|
||||
# Install iptables
|
||||
apk add iptables
|
||||
@@ -246,6 +262,7 @@ iptables -A INPUT -p tcp --dport 22 -j ACCEPT
|
||||
```
|
||||
|
||||
### SSH Configuration
|
||||
|
||||
```bash
|
||||
# Generate SSH key
|
||||
ssh-keygen -t rsa -b 4096
|
||||
@@ -260,6 +277,7 @@ vi /etc/ssh/sshd_config
|
||||
## Troubleshooting
|
||||
|
||||
### Common Commands
|
||||
|
||||
```bash
|
||||
# Check system logs for errors
|
||||
dmesg | grep -i error
|
||||
@@ -275,4 +293,4 @@ netstat -tuln
|
||||
|
||||
# Check disk health
|
||||
smartctl -a /dev/sda # Requires smartmontools package
|
||||
```
|
||||
```
|
||||
@@ -3,8 +3,7 @@ title: Arduino Programming
|
||||
date: 2024-05-29 8:58:31
|
||||
background: bg-[#387f83]
|
||||
label:
|
||||
tags: -cpp
|
||||
-I/O
|
||||
tags: -cpp -I/O
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
@@ -42,7 +41,8 @@ plugins:
|
||||
|
||||
- Select the Port:
|
||||
|
||||
- Go to Tools > Port and select the port that the Arduino is connected to (it usually shows as COMx on Windows, /dev/cu.usbmodemxxxx on macOS, and /dev/ttyUSBx on Linux).
|
||||
- Go to Tools > Port and select the port that the Arduino is connected to (it usually shows as COMx on Windows,
|
||||
/dev/cu.usbmodemxxxx on macOS, and /dev/ttyUSBx on Linux).
|
||||
|
||||
## Basic Structure
|
||||
|
||||
|
||||
+243
-238
@@ -1,238 +1,243 @@
|
||||
---
|
||||
title: HTML Canvas
|
||||
date: 2024-05-28 22:16:42
|
||||
background: bg-[#cc5534]
|
||||
tags:
|
||||
- web
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
This HTML Canvas quick reference cheat sheet lists the common HTML5 Canvas design tags in readable layout.
|
||||
plugins:
|
||||
- copyCode
|
||||
- runCode
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Basic Setup
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Canvas Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<canvas id="myCanvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Getting the Context
|
||||
|
||||
```js
|
||||
const canvas = document.getElementById("myCanvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
```
|
||||
|
||||
## Drawing Shapes
|
||||
|
||||
### Rectangles
|
||||
|
||||
```js
|
||||
ctx.fillStyle = "red";
|
||||
ctx.fillRect(10, 10, 150, 100); // x, y, width, height
|
||||
|
||||
ctx.strokeStyle = "blue";
|
||||
ctx.lineWidth = 5;
|
||||
ctx.strokeRect(200, 10, 150, 100); // x, y, width, height
|
||||
|
||||
ctx.clearRect(15, 15, 30, 30); // x, y, width, height
|
||||
```
|
||||
|
||||
## Paths
|
||||
|
||||
### Lines
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 50); // Starting point
|
||||
ctx.lineTo(200, 50); // Ending point
|
||||
ctx.lineTo(200, 200); // Next line ending point
|
||||
ctx.closePath(); // Connects the end point to the start point
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Circles
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.arc(150, 150, 75, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
|
||||
ctx.fillStyle = "green";
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Arcs
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.arc(150, 150, 75, 0, Math.PI); // x, y, radius, startAngle, endAngle
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
## Bezier and Quadratic Curves
|
||||
|
||||
### Quadratic Curve
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 250);
|
||||
ctx.quadraticCurveTo(200, 100, 400, 250); // cpX, cpY, endX, endY
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Bezier Curve
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 300);
|
||||
ctx.bezierCurveTo(150, 100, 350, 500, 450, 300); // cp1X, cp1Y, cp2X, cp2Y, endX, endY
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Text
|
||||
|
||||
```js
|
||||
ctx.font = "30px Arial";
|
||||
ctx.fillStyle = "black";
|
||||
ctx.fillText("Hello Canvas", 10, 50); // text, x, y
|
||||
|
||||
ctx.strokeText("Hello Canvas", 10, 100); // text, x, y
|
||||
```
|
||||
|
||||
### Images
|
||||
|
||||
```js
|
||||
const img = new Image();
|
||||
img.src = "path/to/image.jpg";
|
||||
img.onload = () => {
|
||||
ctx.drawImage(img, 10, 10); // img, x, y
|
||||
ctx.drawImage(img, 50, 50, 100, 100); // img, x, y, width, height
|
||||
ctx.drawImage(img, 100, 100, 100, 100, 150, 150, 200, 200); // img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
|
||||
};
|
||||
```
|
||||
|
||||
## Transformations
|
||||
|
||||
### Translation
|
||||
|
||||
```js
|
||||
ctx.translate(100, 100); // x, y
|
||||
ctx.fillRect(0, 0, 50, 50);
|
||||
```
|
||||
|
||||
### Rotation
|
||||
|
||||
```js
|
||||
ctx.rotate((Math.PI / 180) * 45); // Angle in radians
|
||||
ctx.fillRect(100, 100, 50, 50);
|
||||
```
|
||||
|
||||
### Scaling
|
||||
|
||||
```js
|
||||
ctx.scale(2, 2); // x, y
|
||||
ctx.fillRect(50, 50, 50, 50);
|
||||
```
|
||||
|
||||
## Gradients
|
||||
|
||||
### Linear Gradient
|
||||
|
||||
```js
|
||||
const linearGradient = ctx.createLinearGradient(0, 0, 200, 0); // x0, y0, x1, y1
|
||||
linearGradient.addColorStop(0, "red");
|
||||
linearGradient.addColorStop(1, "blue");
|
||||
ctx.fillStyle = linearGradient;
|
||||
ctx.fillRect(10, 10, 200, 100);
|
||||
```
|
||||
|
||||
### Radial Gradient
|
||||
|
||||
```js
|
||||
const radialGradient = ctx.createRadialGradient(75, 50, 5, 90, 60, 100); // x0, y0, r0, x1, y1, r1
|
||||
radialGradient.addColorStop(0, "red");
|
||||
radialGradient.addColorStop(1, "blue");
|
||||
ctx.fillStyle = radialGradient;
|
||||
ctx.fillRect(10, 10, 200, 100);
|
||||
```
|
||||
|
||||
### Patterns
|
||||
|
||||
```js
|
||||
const img = new Image();
|
||||
img.src = "path/to/image.jpg";
|
||||
img.onload = () => {
|
||||
const pattern = ctx.createPattern(img, "repeat"); // 'repeat', 'repeat-x', 'repeat-y', 'no-repeat'
|
||||
ctx.fillStyle = pattern;
|
||||
ctx.fillRect(0, 0, 300, 300);
|
||||
};
|
||||
```
|
||||
|
||||
### Shadows
|
||||
|
||||
```js
|
||||
ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
|
||||
ctx.shadowBlur = 10;
|
||||
ctx.shadowOffsetX = 5;
|
||||
ctx.shadowOffsetY = 5;
|
||||
|
||||
ctx.fillStyle = "red";
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
```
|
||||
|
||||
## Compositing
|
||||
|
||||
### Global Alpha
|
||||
|
||||
```js
|
||||
ctx.globalAlpha = 0.5;
|
||||
ctx.fillStyle = "red";
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
|
||||
ctx.fillStyle = "blue";
|
||||
ctx.fillRect(150, 150, 100, 100);
|
||||
```
|
||||
|
||||
### Global Composite Operation
|
||||
|
||||
```js
|
||||
ctx.globalCompositeOperation = "source-over"; // Default
|
||||
ctx.fillStyle = "red";
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
|
||||
ctx.globalCompositeOperation = "destination-over";
|
||||
ctx.fillStyle = "blue";
|
||||
ctx.fillRect(150, 150, 100, 100);
|
||||
```
|
||||
|
||||
### Animations
|
||||
|
||||
```js
|
||||
let x = 0;
|
||||
function draw() {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = "blue";
|
||||
ctx.fillRect(x, 100, 50, 50);
|
||||
x += 2;
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
draw();
|
||||
```
|
||||
|
||||
## Also read
|
||||
|
||||
- [MDN doc ](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
|
||||
---
|
||||
title: HTML Canvas
|
||||
date: 2024-05-28 22:16:42
|
||||
background: bg-[#cc5534]
|
||||
tags:
|
||||
- web
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
This HTML Canvas quick reference cheat sheet lists the common HTML5 Canvas design tags in readable layout.
|
||||
plugins:
|
||||
- copyCode
|
||||
- runCode
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Basic Setup
|
||||
|
||||
```html
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Canvas Example</title>
|
||||
</head>
|
||||
<body>
|
||||
<canvas
|
||||
id="myCanvas"
|
||||
width="500"
|
||||
height="400"
|
||||
style="border:1px solid #000000;"
|
||||
></canvas>
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Getting the Context
|
||||
|
||||
```js
|
||||
const canvas = document.getElementById('myCanvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
```
|
||||
|
||||
## Drawing Shapes
|
||||
|
||||
### Rectangles
|
||||
|
||||
```js
|
||||
ctx.fillStyle = 'red';
|
||||
ctx.fillRect(10, 10, 150, 100); // x, y, width, height
|
||||
|
||||
ctx.strokeStyle = 'blue';
|
||||
ctx.lineWidth = 5;
|
||||
ctx.strokeRect(200, 10, 150, 100); // x, y, width, height
|
||||
|
||||
ctx.clearRect(15, 15, 30, 30); // x, y, width, height
|
||||
```
|
||||
|
||||
## Paths
|
||||
|
||||
### Lines
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 50); // Starting point
|
||||
ctx.lineTo(200, 50); // Ending point
|
||||
ctx.lineTo(200, 200); // Next line ending point
|
||||
ctx.closePath(); // Connects the end point to the start point
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Circles
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.arc(150, 150, 75, 0, 2 * Math.PI); // x, y, radius, startAngle, endAngle
|
||||
ctx.fillStyle = 'green';
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Arcs
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.arc(150, 150, 75, 0, Math.PI); // x, y, radius, startAngle, endAngle
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
## Bezier and Quadratic Curves
|
||||
|
||||
### Quadratic Curve
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 250);
|
||||
ctx.quadraticCurveTo(200, 100, 400, 250); // cpX, cpY, endX, endY
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Bezier Curve
|
||||
|
||||
```js
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(50, 300);
|
||||
ctx.bezierCurveTo(150, 100, 350, 500, 450, 300); // cp1X, cp1Y, cp2X, cp2Y, endX, endY
|
||||
ctx.stroke();
|
||||
```
|
||||
|
||||
### Text
|
||||
|
||||
```js
|
||||
ctx.font = '30px Arial';
|
||||
ctx.fillStyle = 'black';
|
||||
ctx.fillText('Hello Canvas', 10, 50); // text, x, y
|
||||
|
||||
ctx.strokeText('Hello Canvas', 10, 100); // text, x, y
|
||||
```
|
||||
|
||||
### Images
|
||||
|
||||
```js
|
||||
const img = new Image();
|
||||
img.src = 'path/to/image.jpg';
|
||||
img.onload = () => {
|
||||
ctx.drawImage(img, 10, 10); // img, x, y
|
||||
ctx.drawImage(img, 50, 50, 100, 100); // img, x, y, width, height
|
||||
ctx.drawImage(img, 100, 100, 100, 100, 150, 150, 200, 200); // img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight
|
||||
};
|
||||
```
|
||||
|
||||
## Transformations
|
||||
|
||||
### Translation
|
||||
|
||||
```js
|
||||
ctx.translate(100, 100); // x, y
|
||||
ctx.fillRect(0, 0, 50, 50);
|
||||
```
|
||||
|
||||
### Rotation
|
||||
|
||||
```js
|
||||
ctx.rotate((Math.PI / 180) * 45); // Angle in radians
|
||||
ctx.fillRect(100, 100, 50, 50);
|
||||
```
|
||||
|
||||
### Scaling
|
||||
|
||||
```js
|
||||
ctx.scale(2, 2); // x, y
|
||||
ctx.fillRect(50, 50, 50, 50);
|
||||
```
|
||||
|
||||
## Gradients
|
||||
|
||||
### Linear Gradient
|
||||
|
||||
```js
|
||||
const linearGradient = ctx.createLinearGradient(0, 0, 200, 0); // x0, y0, x1, y1
|
||||
linearGradient.addColorStop(0, 'red');
|
||||
linearGradient.addColorStop(1, 'blue');
|
||||
ctx.fillStyle = linearGradient;
|
||||
ctx.fillRect(10, 10, 200, 100);
|
||||
```
|
||||
|
||||
### Radial Gradient
|
||||
|
||||
```js
|
||||
const radialGradient = ctx.createRadialGradient(75, 50, 5, 90, 60, 100); // x0, y0, r0, x1, y1, r1
|
||||
radialGradient.addColorStop(0, 'red');
|
||||
radialGradient.addColorStop(1, 'blue');
|
||||
ctx.fillStyle = radialGradient;
|
||||
ctx.fillRect(10, 10, 200, 100);
|
||||
```
|
||||
|
||||
### Patterns
|
||||
|
||||
```js
|
||||
const img = new Image();
|
||||
img.src = 'path/to/image.jpg';
|
||||
img.onload = () => {
|
||||
const pattern = ctx.createPattern(img, 'repeat'); // 'repeat', 'repeat-x', 'repeat-y', 'no-repeat'
|
||||
ctx.fillStyle = pattern;
|
||||
ctx.fillRect(0, 0, 300, 300);
|
||||
};
|
||||
```
|
||||
|
||||
### Shadows
|
||||
|
||||
```js
|
||||
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
|
||||
ctx.shadowBlur = 10;
|
||||
ctx.shadowOffsetX = 5;
|
||||
ctx.shadowOffsetY = 5;
|
||||
|
||||
ctx.fillStyle = 'red';
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
```
|
||||
|
||||
## Compositing
|
||||
|
||||
### Global Alpha
|
||||
|
||||
```js
|
||||
ctx.globalAlpha = 0.5;
|
||||
ctx.fillStyle = 'red';
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
|
||||
ctx.fillStyle = 'blue';
|
||||
ctx.fillRect(150, 150, 100, 100);
|
||||
```
|
||||
|
||||
### Global Composite Operation
|
||||
|
||||
```js
|
||||
ctx.globalCompositeOperation = 'source-over'; // Default
|
||||
ctx.fillStyle = 'red';
|
||||
ctx.fillRect(100, 100, 100, 100);
|
||||
|
||||
ctx.globalCompositeOperation = 'destination-over';
|
||||
ctx.fillStyle = 'blue';
|
||||
ctx.fillRect(150, 150, 100, 100);
|
||||
```
|
||||
|
||||
### Animations
|
||||
|
||||
```js
|
||||
let x = 0;
|
||||
function draw() {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
ctx.fillStyle = 'blue';
|
||||
ctx.fillRect(x, 100, 50, 50);
|
||||
x += 2;
|
||||
requestAnimationFrame(draw);
|
||||
}
|
||||
draw();
|
||||
```
|
||||
|
||||
## Also read
|
||||
|
||||
- [MDN doc ](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API)
|
||||
+285
-76
@@ -15,82 +15,125 @@ plugins:
|
||||
---
|
||||
|
||||
## Overview
|
||||
### Glossary
|
||||
|
||||
### Terminology
|
||||
|
||||
- Prompt: input text that guides an AI model’s response.
|
||||
- Tokens: the smallest units of text processed by an AI model.
|
||||
- Token Limit: the max number of tokens an AI model can process in one request.
|
||||
- Artificial intelligence (AI): machines that imitate human intelligence.
|
||||
- AI Model: a program trained on datasets to recognize patterns and make decisions without human intervention.
|
||||
- Large language model (LLM): a transformer-based AI model trained on large text datasets to understand and generate human-like language.
|
||||
- Large language model (LLM): a transformer-based AI model trained on large text datasets to understand and generate
|
||||
human-like language.
|
||||
- Hallucination: when an AI model generates responses that are false or misleading but presented as fact.
|
||||
- Jailbreak: exploiting AI model vulnerabilities to bypass ethical guidelines and perform restricted actions.
|
||||
|
||||
### Prompt Tips
|
||||
#### Efficiency
|
||||
### Tips
|
||||
|
||||
Prompt Efficiency
|
||||
|
||||
- Focus on achieving the desired output efficiently with minimal words in the prompt.
|
||||
- Specify general instructions at the start of a conversation or when changing direction to avoid constantly restating them in each new prompt.
|
||||
- Specify general instructions at the start of a conversation or when changing direction to avoid constantly restating
|
||||
them in each new prompt.
|
||||
|
||||
```{.wrap}
|
||||
Example: specify the role once at the start of a conversation.
|
||||
```
|
||||
|
||||
- Restructure text to eliminate filler words that don’t add meaning:
|
||||
|
||||
```{.wrap}
|
||||
Example: “provide a breakdown" -> "provide sales breakdown”.
|
||||
```
|
||||
- Do not explicitly refer to the item being processed unless addressing a specific part of it as what you provide will typically speak for itself:
|
||||
|
||||
- Do not explicitly refer to the item being processed unless addressing a specific part of it as what you provide will
|
||||
typically speak for itself:
|
||||
|
||||
```{.wrap}
|
||||
Example: “Filter this piece of text" -> "Filter text”
|
||||
```
|
||||
|
||||
- Do not explicitly ask the AI for help:
|
||||
|
||||
```{.wrap}
|
||||
Example: “can you help me x”.
|
||||
```
|
||||
|
||||
- Do not explicitly reference yourself unless clarifying multiple entities:
|
||||
|
||||
```{.wrap}
|
||||
Example: "do X for me".
|
||||
Example: ”I want to x”.
|
||||
```
|
||||
|
||||
- Do not be polite to the AI:
|
||||
|
||||
```{.wrap}
|
||||
Example: "please do X".
|
||||
Example: “thanks”.
|
||||
```
|
||||
|
||||
#### Clarity
|
||||
- Consider breaking up complex ideas into granular bullet points to improve clarity, avoid searching for text, and eliminate comma lists and conjunctions (e.g., and).
|
||||
Prompt Clarity
|
||||
|
||||
- Consider breaking up complex ideas into granular bullet points to improve clarity, avoid searching for text, and
|
||||
eliminate comma lists and conjunctions (e.g., and).
|
||||
- Avoid vague or close ended questions.
|
||||
|
||||
```{.wrap}
|
||||
Example: “Do you think our site is good" -> "Explain flaws in the designs of each webpage”
|
||||
```
|
||||
|
||||
- Ensure prompts are specific
|
||||
|
||||
```{.wrap}
|
||||
Example: “explain our sales" -> "explain a breakdown of our sales performance for the last quarter”.
|
||||
```
|
||||
|
||||
#### Response Refinement
|
||||
Response Refinement
|
||||
|
||||
- If the AI model misunderstands your request then specify the intended action.
|
||||
- Provide sufficient context so the AI model can understand the scenario.
|
||||
|
||||
#### Security And Privacy
|
||||
- Never share sensitive information with AI models as you can't be certain how it's stored, whether it will be shared, of if a data breach may occur.
|
||||
Privacy And Security
|
||||
|
||||
- Never share sensitive information with AI model's as you can't be certain how it's stored, whether it will be shared,
|
||||
of if a data breach may occur.
|
||||
|
||||
## Prompt Engineering
|
||||
### Prompt Frameworks
|
||||
- Only use prompt components relevant to your needs
|
||||
|
||||
#### General Purpose
|
||||
~~~
|
||||
[role] [task] [style] [output format] [constraint]
|
||||
~~~
|
||||
### Prompt Frameworks
|
||||
|
||||
Only use prompt components that are relevant for your needs.
|
||||
|
||||
```
|
||||
General Purpose
|
||||
[role] [task] [tone] [format] [restriction]
|
||||
```
|
||||
|
||||
### Role
|
||||
|
||||
Standard
|
||||
|
||||
- Act as [occupation]
|
||||
- [List of roles](https://github.com/f/awesome-chatgpt-prompts) _(github.com)_
|
||||
|
||||
Common Standard Roles
|
||||
|
||||
- Personal Coach
|
||||
- Consultant
|
||||
- Entrepreneur
|
||||
- Proofreader
|
||||
- Therapist
|
||||
|
||||
Also See
|
||||
|
||||
- [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) _(github.com)_
|
||||
|
||||
Roleplay
|
||||
|
||||
- Act as [figure] with [appearance] [personality] [behaviour examples] [lore] in [scenario]
|
||||
|
||||
### Task
|
||||
|
||||
[verb] [task] [specifics]
|
||||
|
||||
#### 5W1H Questions
|
||||
@@ -218,40 +261,88 @@ Chat Memory
|
||||
|
||||
#### Database CRUD Operations
|
||||
Create
|
||||
- Generate [quantity] dummy entries following [fields]
|
||||
- Create new entry with [data]
|
||||
|
||||
- [Write content about X|suggest ideas about X|suggest titles about X]
|
||||
- Write content about X in the style of [style]
|
||||
- Write better
|
||||
- Write email to [entity] about X
|
||||
- [Continue|expand]
|
||||
- [Explain how to do X|create roadmap for X]
|
||||
- [Suggest best practices for X|suggest improvements|what am I doing right?|what am I doing wrong?]
|
||||
- Show list of emojis about X
|
||||
- [Create|generate|imagine] image about X
|
||||
|
||||
Read
|
||||
- Select records where [condition]
|
||||
- Select the [top | last | random] [quantity] entries
|
||||
|
||||
- [Summarise|write concise main points]
|
||||
- [Explain|elaborate]
|
||||
- Explain what [entity|text] meant by X
|
||||
- Identify themes in X
|
||||
- Write outline about X
|
||||
- Extract keywords
|
||||
- Get up-to-date [facts|news|data] on X
|
||||
- Is this true?
|
||||
- Suggest [media] [about|similar to] X
|
||||
- Pick best from [options]
|
||||
|
||||
Update
|
||||
- Update entries where [condition] with [data]
|
||||
- Replace X with Y
|
||||
|
||||
- For all X do [action]
|
||||
- For X do [action] if matching [criteria]
|
||||
- Reformat everything as [format]
|
||||
|
||||
Delete
|
||||
- Delete entries where [condition]
|
||||
- Delete duplicate items
|
||||
- Delete items with missing or null values
|
||||
|
||||
### Style
|
||||
Using [style]
|
||||
- Delete [quantity] of X matching [criteria]
|
||||
- Delete everything except X
|
||||
- Delete [item] [number]
|
||||
- Delete duplicate items from X
|
||||
|
||||
#### Imitate
|
||||
- Using style of [person | brand | genre | character]
|
||||
Compare
|
||||
|
||||
- Identify [simlarities|diffirences] between X and Y
|
||||
- Identify gaps in X
|
||||
- Evaluate pros and cons of X
|
||||
- X [comparison operator] Y. It could be abstractly expressed as "are apples bigger than walnuts?"
|
||||
|
||||
Filter
|
||||
|
||||
- Filter X by [criteria]
|
||||
- Exclude X by [criteria]. Everything is excluded by default.
|
||||
|
||||
Select
|
||||
|
||||
- Select [quantity] of X based on [criteria|randomly]
|
||||
|
||||
Simplify
|
||||
|
||||
- Explain X like I’m 5
|
||||
- Explain in simple terms
|
||||
|
||||
Sort
|
||||
|
||||
- Sort X by [key] in [alphabetical|chronological|ascending|descending|lexicographical|custom] order
|
||||
|
||||
Translate
|
||||
|
||||
- Translate into [language]. For programming languages it's specifically called transpile
|
||||
|
||||
### Tone
|
||||
|
||||
Using [tone] tone
|
||||
|
||||
Formality
|
||||
|
||||
#### Formality
|
||||
- Formal
|
||||
- Informal
|
||||
|
||||
#### Directness
|
||||
Directness
|
||||
|
||||
- Direct
|
||||
- Indirect
|
||||
|
||||
#### Tones
|
||||
- This is not an exhaustive list of tones
|
||||
Positive Tones
|
||||
|
||||
Positive
|
||||
- Optimistic
|
||||
- Appreciative
|
||||
- Assertive
|
||||
@@ -262,7 +353,8 @@ Positive
|
||||
- Humorous
|
||||
- Inspirational
|
||||
|
||||
Negative
|
||||
Negative Tones
|
||||
|
||||
- Pessimistic
|
||||
- Accusatory
|
||||
- Concerned
|
||||
@@ -271,12 +363,13 @@ Negative
|
||||
- Sarcastic
|
||||
- Urgent
|
||||
|
||||
### Output Format
|
||||
In [output format]
|
||||
### Format
|
||||
|
||||
#### Text
|
||||
In [format]
|
||||
|
||||
List
|
||||
Presentation
|
||||
|
||||
- Plain text
|
||||
- Bullet point list
|
||||
- Numbered list
|
||||
- Check list
|
||||
@@ -285,13 +378,18 @@ Code
|
||||
- Code
|
||||
|
||||
Process
|
||||
|
||||
- Step-by-step instructions
|
||||
|
||||
Response
|
||||
|
||||
- Question and answer
|
||||
- Dialogue
|
||||
|
||||
Creative
|
||||
|
||||
- Poetry
|
||||
- Music lyrics
|
||||
- Script
|
||||
- Comic strip dialogue
|
||||
- Poetry
|
||||
@@ -299,45 +397,34 @@ Creative
|
||||
- Riddle
|
||||
|
||||
Game
|
||||
|
||||
- Quiz
|
||||
- RPG
|
||||
- Choose-Your-Own-Adventure
|
||||
|
||||
#### Visual
|
||||
### Restriction
|
||||
|
||||
Data Visualization
|
||||
- Table
|
||||
- [Chart] chart ***(Chart type examples: gantt, bubble, error, contour, area, scatter, KDE, box, histogram, bar, line, 3D, joint, surface, polar, pie, cat, pair, strip, swarm, heatmap, hexbin)***
|
||||
But [restriction]
|
||||
|
||||
Creative
|
||||
- Emojis
|
||||
- Word cloud
|
||||
Length Constraints
|
||||
|
||||
#### File Format
|
||||
- Plain text
|
||||
- Markdown
|
||||
- CSV
|
||||
- XML
|
||||
- JSON
|
||||
- PDF
|
||||
- Concise
|
||||
- In N words
|
||||
- In N sentences
|
||||
|
||||
### Constraint
|
||||
But [constraint]
|
||||
Language Constraints
|
||||
|
||||
Length
|
||||
- Be [extremely detailed | concise]
|
||||
- In [quantity] [words | sentences]
|
||||
- No jargon or technical terms
|
||||
|
||||
Language
|
||||
- No jargon or technical terms
|
||||
Structural Constraints
|
||||
|
||||
Structure
|
||||
- Show [quantity] [examples | options]
|
||||
- No headers
|
||||
- No pretext titles
|
||||
- Show N options
|
||||
- No examples
|
||||
- No headers
|
||||
- No pretext titles
|
||||
|
||||
Content Constraints
|
||||
|
||||
Content
|
||||
- Use [first-person | second-person | third-person] narrative voice
|
||||
- Don't change the wording
|
||||
- Permit [minor | major] edits
|
||||
- Use pop culture references
|
||||
@@ -345,431 +432,555 @@ Content
|
||||
- Only show [changed | unchanged] content
|
||||
|
||||
## Examples
|
||||
|
||||
### Job
|
||||
|
||||
Name Business
|
||||
|
||||
```{.wrap}
|
||||
Suggest creative name for tech startup
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest catchy names for bakery business
|
||||
```
|
||||
|
||||
Interview Questions
|
||||
|
||||
```{.wrap}
|
||||
Suggest common software engineer interview questions
|
||||
```
|
||||
|
||||
Create Course Outline
|
||||
|
||||
```{.wrap}
|
||||
Create course outline on web development for beginners
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create training program outline for customer service workshop
|
||||
```
|
||||
|
||||
### Relationship
|
||||
|
||||
Gift Ideas
|
||||
|
||||
```{.wrap}
|
||||
Suggest gift ideas for clients
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest gift ideas for clients who work as flourists
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest gift ideas for my wife who loves steampunk art and crafts, mystery sci-fi, journalling
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest creative ideas for 10 year old’s birthday
|
||||
```
|
||||
|
||||
### Competition
|
||||
|
||||
Select Contest Winners
|
||||
|
||||
```{.wrap}
|
||||
Randomly select 1 name from this list
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Randomly select 5 email addresses from this list
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Select top 3 records with the shortest lap times from this list
|
||||
```
|
||||
|
||||
### Programming
|
||||
|
||||
Create Code
|
||||
|
||||
```{.wrap}
|
||||
Create program to calculate the factorial of given number in python
|
||||
```
|
||||
|
||||
Create Regular Expressions
|
||||
|
||||
```{.wrap}
|
||||
Create regex to match all email addresses in list
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create regex to match all words that start with "ban"
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create regex to match 8-digit password
|
||||
```
|
||||
|
||||
Explain Code
|
||||
|
||||
```{.wrap}
|
||||
Explain why code not working
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Explain what code does
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Explain how to make a HTTP request in javascript
|
||||
```
|
||||
|
||||
Update Code
|
||||
|
||||
```{.wrap}
|
||||
Add code comments
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Add class "header" to header tag
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Update CSS to change font color to blue
|
||||
```
|
||||
|
||||
Translate
|
||||
- Specifically called transpile when addressing programming languages.
|
||||
Transpile
|
||||
|
||||
```{.wrap}
|
||||
Translate code to Python
|
||||
```
|
||||
|
||||
### Email
|
||||
|
||||
Create Emails
|
||||
|
||||
```{.wrap}
|
||||
Write email inviting Jack to dinner on the weekend
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Write email sequence for our new customer onboarding process
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Write email to inform staff of elevator maintenance on 23 June 2025, elevators unavailable for 24 hours, apologise for inconvenience
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest response to message asking about project status
|
||||
```
|
||||
|
||||
Format Email
|
||||
|
||||
```{.wrap}
|
||||
Proofread and format email
|
||||
```
|
||||
|
||||
Email Marketing
|
||||
|
||||
```{.wrap}
|
||||
Suggest tips to increase open and click-through rates for my email campaigns
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest ways to make my email content more engaging and relevant to my subscribers
|
||||
```
|
||||
|
||||
Extract Data
|
||||
|
||||
```{.wrap}
|
||||
Extract all email addresses in text
|
||||
```
|
||||
|
||||
### Spreadsheet
|
||||
|
||||
Create Something
|
||||
|
||||
```{.wrap}
|
||||
Create excel formula to calculate sum of cells A1 to A10
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Generate spreadsheet dummy data as a placeholder
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create macro to calculate average of cells B1 to B10 and insert result in cell C1
|
||||
```
|
||||
|
||||
Explain Something
|
||||
|
||||
```{.wrap}
|
||||
Explain formula =SUM(A1:A10) in simple terms
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest tips to improve spreadsheet efficiency
|
||||
```
|
||||
|
||||
### Social Media
|
||||
|
||||
Create Content
|
||||
|
||||
```{.wrap}
|
||||
Suggest meme ideas for dogs
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest climate change post ideas to engage my followers
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Generate hashtags and caption for a picture of scenic sunset
|
||||
```
|
||||
|
||||
### Reading
|
||||
|
||||
Text Analysis
|
||||
|
||||
```{.wrap}
|
||||
Summarize article
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Write concise main points
|
||||
```
|
||||
|
||||
Translate
|
||||
|
||||
```{.wrap}
|
||||
Translate to spanish
|
||||
```
|
||||
|
||||
Recommendations
|
||||
|
||||
```{.wrap}
|
||||
Recommend books similar to Hunger Games
|
||||
```
|
||||
|
||||
### Design
|
||||
|
||||
Design Prompts
|
||||
|
||||
```{.wrap}
|
||||
Create design prompt of logo for new sports brand
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest eye-catching thumbnail designs for youtube video on healthy eating
|
||||
```
|
||||
|
||||
Aesthetic Pairings
|
||||
|
||||
```{.wrap}
|
||||
Suggest font pairing for travel blog header design
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest color palette for wedding photography website
|
||||
```
|
||||
|
||||
### Data Analysis
|
||||
|
||||
Data Extraction
|
||||
|
||||
```{.wrap}
|
||||
Extract all numbers from text
|
||||
```
|
||||
|
||||
Data Filtering
|
||||
|
||||
```{.wrap}
|
||||
Filter list based on [condition]
|
||||
```
|
||||
|
||||
Data Presentation
|
||||
|
||||
```{.wrap}
|
||||
Create table from data
|
||||
```
|
||||
|
||||
### Paid Ads
|
||||
|
||||
Create Ad
|
||||
|
||||
```{.wrap}
|
||||
Suggest creative ideas for new product launch
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest ad copy for travel company
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create headlines, body text, and calls to action for new fitness program ad
|
||||
```
|
||||
|
||||
Ad Targeting
|
||||
|
||||
```{.wrap}
|
||||
Recommend target Facebook audience for clothing line ad campaign
|
||||
```
|
||||
|
||||
Ad Technical Support
|
||||
|
||||
```{.wrap}
|
||||
Review tag manager code for errors
|
||||
```
|
||||
|
||||
### Amazon FBA
|
||||
|
||||
Product Content
|
||||
|
||||
```{.wrap}
|
||||
Write compelling product description for latest item
|
||||
```
|
||||
|
||||
Communication
|
||||
|
||||
```{.wrap}
|
||||
Rewrite appeal letter to make it more persuasive
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Write effective email to reach out to potential suppliers
|
||||
```
|
||||
|
||||
Product Strategy
|
||||
|
||||
```{.wrap}
|
||||
Suggest items that would make a good bundle for our customers
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Organize product and pricing information into a neat and manageable spreadsheet
|
||||
```
|
||||
|
||||
### Writing
|
||||
|
||||
Name Something
|
||||
|
||||
```{.wrap}
|
||||
Suggest titles for short story
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest titles for article 10 options
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest domain name for gardening blog
|
||||
```
|
||||
|
||||
Content Creation
|
||||
|
||||
```{.wrap}
|
||||
Create outline for essay on exercise
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest ideas for blog on sustainable fashion
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create blog post on financial planning
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Expand jazz music sentence
|
||||
```
|
||||
|
||||
Editing And Formatting
|
||||
|
||||
```{.wrap}
|
||||
Change report tone to conversational
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Proofread article
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Format headings for blog post
|
||||
```
|
||||
|
||||
Evaluation
|
||||
|
||||
```{.wrap}
|
||||
Check for bias
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Check for plagiarism
|
||||
```
|
||||
|
||||
### Teacher
|
||||
|
||||
Teaching Support
|
||||
|
||||
```{.wrap}
|
||||
Convert work history fact list into multiple-choice quiz
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest ideas for history assignment on American Revolution
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Divide list of 30 students into groups of 6
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create grading curve for class based on their test scores
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Grade history essay and provide feedback on any areas for improvement
|
||||
```
|
||||
|
||||
### YouTube
|
||||
|
||||
Content Creation
|
||||
|
||||
```{.wrap}
|
||||
Create timestamps for podcast episode transcript
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Convert youtube cooking video into blog post with headings and bullet points
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Create outline for a video about the benefits of meditation
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest thumbnail ideas for video on "DIY home decor"
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Suggest fashion video ideas for individual episodes
|
||||
```
|
||||
|
||||
Analyse
|
||||
|
||||
```{.wrap}
|
||||
What is the script tone for environmental issues video
|
||||
```
|
||||
|
||||
Communication
|
||||
|
||||
```{.wrap}
|
||||
Create thoughtful and polite response to negative comment on youtube video
|
||||
```
|
||||
|
||||
### Research
|
||||
|
||||
History Research
|
||||
|
||||
```{.wrap}
|
||||
Explain events leading up to American Civil War
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Provide key details about printing press invention
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Research olympic games history
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Provide key details about French Revolution
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Explain history of Byzantine Empire
|
||||
```
|
||||
|
||||
Science Reseearch
|
||||
|
||||
```{.wrap}
|
||||
Explain quantum computing in simple terms
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Explain rocket science like i'm five
|
||||
```
|
||||
|
||||
### SEO
|
||||
|
||||
Keywords
|
||||
|
||||
```{.wrap}
|
||||
Find best keywords for [topic] with low competition
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Generate list of keywords targeting multiple geographic locations
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Generate list of keyword synonyms for [topic]
|
||||
```
|
||||
|
||||
Content Optimization
|
||||
|
||||
```{.wrap}
|
||||
Find opportunities for internal linking related to [topic]
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Research industry-specific terminology for use in [topic] content
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Find best time to publish content related to [topic]
|
||||
```
|
||||
|
||||
Link Building
|
||||
|
||||
```{.wrap}
|
||||
Find authoritative websites to acquire backlinks for [topic] content
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
Research best external linking strategies for [topic]
|
||||
```
|
||||
|
||||
Tools
|
||||
|
||||
```{.wrap}
|
||||
Find most popular tools used for [topic] seo
|
||||
```
|
||||
|
||||
Tactics
|
||||
|
||||
```{.wrap}
|
||||
Research best tactics for [topic] mobile optimization
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
What are the best tactics for [topic] international seo?
|
||||
```
|
||||
|
||||
Competitors
|
||||
|
||||
```{.wrap}
|
||||
Research competitor strategies related to [topic]
|
||||
```
|
||||
|
||||
```{.wrap}
|
||||
What are the best affiliate marketing websites for [topic]?
|
||||
```
|
||||
|
||||
### Roleplay
|
||||
|
||||
Simulate Character
|
||||
|
||||
```{.wrap}
|
||||
Act as William Shakespeare
|
||||
|
||||
@@ -797,14 +1008,12 @@ Scenario:
|
||||
- Lead actor is missing and staff are concerned about how to achieve the performance.
|
||||
```
|
||||
|
||||
## References (Used For Ideas)
|
||||
- [General Purpose Framework](https://www.linkedin.com/posts/denis-panjuta_the-ultimate-chatgpt-40-guide-roles-activity-7231208824680976384-bdlY/)
|
||||
- [General Info](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/2b88d101-e659-4adc-a63a-560b2b70179a/_FINAL__The_ChatGPT_Cheat_Sheet__1_.png)
|
||||
- [Data Visualization](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/0a928290-8e99-414e-b847-5b2dff35ec55/ChatGPT_-_Code_Interpreter_In_a_Nutshell___1_.png)
|
||||
- [Comprehensive Cheatsheet](https://github.com/bg-write/chatGPT-cheatsheet)
|
||||
## Any Suggestions?
|
||||
|
||||
- [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md)
|
||||
|
||||
<style>
|
||||
em { font-size: 0.785em; }
|
||||
strong {font-weight: 400;}
|
||||
ul.collapsible > li > pre { padding-left: 0; padding-right: 0; font-size: 0.925em;}
|
||||
</style>
|
||||
</style>
|
||||
+5
-5
@@ -221,11 +221,11 @@ lengthOfString.Contains("How"); // => true
|
||||
|
||||
### General .NET Terms {.col-span-2}
|
||||
|
||||
| Term | Definition |
|
||||
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Runtime | A collection of services that are required to execute a given compiled unit of code. |
|
||||
| Term | Definition |
|
||||
| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Runtime | A collection of services that are required to execute a given compiled unit of code. |
|
||||
| Common Language Runtime (CLR) | Primarily locates, loads, and managed .NET objects. The CLR also handles memory management, application hosting, coordination of threads, performing security checks, and other low-level details. |
|
||||
| Managed code | Code that compiles and runs on .NET runtime. C#/F#/VB are examples. |
|
||||
| Unmanaged code | Code that compiles straight to machine code and cannot be directly hosted by the .NET runtime. Contains no free memory management, garbage collection, etc. DLLs created from C/C++ are examples. |
|
||||
| Managed code | Code that compiles and runs on .NET runtime. C#/F#/VB are examples. |
|
||||
| Unmanaged code | Code that compiles straight to machine code and cannot be directly hosted by the .NET runtime. Contains no free memory management, garbage collection, etc. DLLs created from C/C++ are examples. |
|
||||
|
||||
{.show-header}
|
||||
+17
-12
@@ -49,7 +49,7 @@ CSS is rich in capabilities and is more than simply laying out pages.
|
||||
|
||||
```html
|
||||
<div class="classname"></div>
|
||||
<div class="class1 ... classn"></div>
|
||||
<div class="class1 classn ..."></div>
|
||||
```
|
||||
|
||||
Support multiple classes on one element.
|
||||
@@ -94,8 +94,8 @@ See: [Colors](#css-colors)
|
||||
|
||||
```css
|
||||
background-color: blue;
|
||||
background-image: url("nyan-cat.gif");
|
||||
background-image: url("../image.png");
|
||||
background-image: url('nyan-cat.gif');
|
||||
background-image: url('../image.png');
|
||||
```
|
||||
|
||||
See: [Backgrounds](#css-backgrounds)
|
||||
@@ -106,7 +106,7 @@ See: [Backgrounds](#css-backgrounds)
|
||||
.page-title {
|
||||
font-weight: bold;
|
||||
font-size: 30px;
|
||||
font-family: "Courier New";
|
||||
font-family: 'Courier New';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -216,7 +216,7 @@ h3.section-heading {
|
||||
#### Attribute Selector
|
||||
|
||||
```css
|
||||
div[attribute="SomeValue"] {
|
||||
div[attribute='SomeValue'] {
|
||||
background-color: red;
|
||||
}
|
||||
```
|
||||
@@ -395,8 +395,8 @@ text-transform: lowercase;
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "Glegoo";
|
||||
src: url("../Glegoo.woff");
|
||||
font-family: 'Glegoo';
|
||||
src: url('../Glegoo.woff');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -484,7 +484,12 @@ background:
|
||||
url(paper.gif) left top repeat;
|
||||
|
||||
background: rgb(2, 0, 36);
|
||||
background: linear-gradient(90deg, rgba(2, 0, 36, 1) 0%, rgba(13, 232, 230, 1) 35%, rgba(0, 212, 255, 1) 100%);
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(2, 0, 36, 1) 0%,
|
||||
rgba(13, 232, 230, 1) 35%,
|
||||
rgba(0, 212, 255, 1) 100%
|
||||
);
|
||||
```
|
||||
|
||||
## CSS The Box Model
|
||||
@@ -914,8 +919,8 @@ Any legal length value, like px or %. 0 is the default value
|
||||
.grid-container {
|
||||
display: grid;
|
||||
grid-template-areas:
|
||||
"nav nav . ."
|
||||
"nav nav . .";
|
||||
'nav nav . .'
|
||||
'nav nav . .';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1003,7 +1008,7 @@ body {
|
||||
|
||||
h3::before {
|
||||
counter-increment: section;
|
||||
content: "Section." counter(section);
|
||||
content: 'Section.' counter(section);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1015,7 +1020,7 @@ ol {
|
||||
|
||||
li::before {
|
||||
counter-increment: section;
|
||||
content: counters(section, ".") " ";
|
||||
content: counters(section, '.') ' ';
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -89,6 +89,7 @@ print(upperCase); //Print: NICOLA
|
||||
|
||||
/* Comments like these are also supported. */
|
||||
```
|
||||
|
||||
### multiline String
|
||||
|
||||
```dart
|
||||
@@ -99,7 +100,6 @@ print('''My long string''');
|
||||
//this will help for only long strings
|
||||
```
|
||||
|
||||
|
||||
### Imports
|
||||
|
||||
```dart
|
||||
@@ -227,7 +227,6 @@ for(var number in numbers){
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
### for in loop
|
||||
|
||||
```dart
|
||||
@@ -248,7 +247,6 @@ for(var number in numbers){
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## Collections {.cols-2}
|
||||
|
||||
### Lists
|
||||
@@ -286,7 +284,7 @@ Set<String> names = {}; // This works, too.
|
||||
// a map is an object that associates keys and values
|
||||
var person = Map<String, String>();
|
||||
// To initialize the map, do this:
|
||||
|
||||
|
||||
person['lastName'] = 'Tesla';
|
||||
|
||||
print(person); //Print: {firstName: Nicola, lastName: Tesla}
|
||||
@@ -664,7 +662,9 @@ userObject?.userName?.toString()
|
||||
|
||||
// The preceeding code returns null and never calls toString() if either userObject or userObject.userName is null
|
||||
```
|
||||
|
||||
### enum in dart
|
||||
|
||||
```dart
|
||||
defination: An enum (short for "enumeration") is a special data type that enables a variable to be a set of predefined constants. Enums are used to define variables that can only take one out of a small set of possible values. They help make code more readable and less error-prone by providing meaningful names to these sets of values.
|
||||
|
||||
@@ -700,5 +700,3 @@ void main() {
|
||||
|
||||
|
||||
```
|
||||
|
||||
|
||||
+10
-7
@@ -255,8 +255,10 @@ class Customer(models.Model)
|
||||
|
||||
#### To access the ChoiceField value in the template, we need to do the following in the template:
|
||||
|
||||
- In Django templates you can use the "`get_FOO_display()`" method, that will return the readable alias for the field, where `'FOO'` is the name of the field.
|
||||
- If the choices are stored in the variable `CHOICES` and the model field storing the selected choice is `'type'` then you can directly use
|
||||
- In Django templates you can use the "`get_FOO_display()`" method, that will return the readable alias for the field,
|
||||
where `'FOO'` is the name of the field.
|
||||
- If the choices are stored in the variable `CHOICES` and the model field storing the selected choice is `'type'` then
|
||||
you can directly use
|
||||
|
||||
```html
|
||||
<!-- Here, X is the model instance -->
|
||||
@@ -891,9 +893,8 @@ class ArticleForm(ModelForm):
|
||||
|
||||
```html
|
||||
<form action="" method="post" enctype="multipart/form-data">
|
||||
{% csrf_token %}
|
||||
{{ form.as_p }}
|
||||
<button type="submit">{% trans 'Submit' %}</button>
|
||||
{% csrf_token %} {{ form.as_p }}
|
||||
<button type="submit">{% trans 'Submit' %}</button>
|
||||
</form>
|
||||
```
|
||||
|
||||
@@ -955,7 +956,8 @@ messages.error(request, 'Login error')
|
||||
|
||||
```html
|
||||
<!-- Display flash messages in template -->
|
||||
{% if messages %} {% for message in messages %} {% message %} {% message.tags %} {% endfor %} {% endif %}
|
||||
{% if messages %} {% for message in messages %} {% message %} {% message.tags %}
|
||||
{% endfor %} {% endif %}
|
||||
```
|
||||
|
||||
## User Model
|
||||
@@ -1086,7 +1088,8 @@ urlpatterns += path('', include('django.contrib.auth.urls'))
|
||||
<a href="{% url 'logout' %}">Logout</a>
|
||||
|
||||
<!-- Check if user login -->
|
||||
{% if request.user.is_authenticated %} Logged in as: {{ request.user.username }} {% endif %}
|
||||
{% if request.user.is_authenticated %} Logged in as: {{ request.user.username }}
|
||||
{% endif %}
|
||||
```
|
||||
|
||||
#### Authorization: LoginRequiredMixin and login_required
|
||||
|
||||
+16
-17
@@ -8,8 +8,7 @@ tags:
|
||||
- Framework
|
||||
categories:
|
||||
- Programming
|
||||
intro:
|
||||
EJS(Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript.
|
||||
intro: EJS(Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript.
|
||||
plugins:
|
||||
- copyCode
|
||||
- runCode
|
||||
@@ -45,9 +44,9 @@ $ ejs hello.ejs -o hello.html
|
||||
### Render with Data
|
||||
|
||||
```js
|
||||
let ejs = require("ejs");
|
||||
let ejs = require('ejs');
|
||||
|
||||
let people = ["geddy", "neil", "alex"];
|
||||
let people = ['geddy', 'neil', 'alex'];
|
||||
let tpl = '<%= people.join(", "); %>';
|
||||
|
||||
let html = ejs.render(tpl, { people: people });
|
||||
@@ -61,7 +60,7 @@ Pass EJS a template string and some data.
|
||||
```html
|
||||
<script src="https://unpkg.com/ejs"></script>
|
||||
<script>
|
||||
let people = ["geddy", "neil", "alex"];
|
||||
let people = ['geddy', 'neil', 'alex'];
|
||||
let html = ejs.render('<%= people.join(", "); %>', { people: people });
|
||||
console.log(html);
|
||||
</script>
|
||||
@@ -110,7 +109,7 @@ $ ejs hello.ejs -f data.json -o hello.html
|
||||
### Method {.col-span-2}
|
||||
|
||||
```js
|
||||
let ejs = require("ejs");
|
||||
let ejs = require('ejs');
|
||||
let template = ejs.compile(str, options);
|
||||
|
||||
template(data);
|
||||
@@ -176,15 +175,15 @@ To include a template, needs a file name option, paths are relative
|
||||
### Custom delimiters
|
||||
|
||||
```js
|
||||
let ejs = require("ejs"),
|
||||
users = ["geddy", "neil", "alex"];
|
||||
let ejs = require('ejs'),
|
||||
users = ['geddy', 'neil', 'alex'];
|
||||
|
||||
// Just one template
|
||||
ejs.render('<?= users.join(" | "); ?>', { users: users }, { delimiter: "?" });
|
||||
ejs.render('<?= users.join(" | "); ?>', { users: users }, { delimiter: '?' });
|
||||
// => 'geddy | neil | alex'
|
||||
|
||||
// Or globally
|
||||
ejs.delimiter = "$";
|
||||
ejs.delimiter = '$';
|
||||
ejs.render('<$= users.join(" | "); $>', { users: users });
|
||||
// => 'geddy | neil | alex'
|
||||
```
|
||||
@@ -192,8 +191,8 @@ ejs.render('<$= users.join(" | "); $>', { users: users });
|
||||
### Caching
|
||||
|
||||
```js
|
||||
let ejs = require("ejs"),
|
||||
LRU = require("lru-cache");
|
||||
let ejs = require('ejs'),
|
||||
LRU = require('lru-cache');
|
||||
|
||||
// LRU cache with 100-item limit
|
||||
ejs.cache = LRU(100);
|
||||
@@ -202,9 +201,9 @@ ejs.cache = LRU(100);
|
||||
### Custom file loader
|
||||
|
||||
```js
|
||||
let ejs = require("ejs");
|
||||
let ejs = require('ejs');
|
||||
let myFileLoader = function (filePath) {
|
||||
return "myFileLoader: " + fs.readFileSync(filePath);
|
||||
return 'myFileLoader: ' + fs.readFileSync(filePath);
|
||||
};
|
||||
|
||||
ejs.fileLoader = myFileLoader;
|
||||
@@ -232,12 +231,12 @@ ejs.fileLoader = myFileLoader;
|
||||
<div id="output"></div>
|
||||
<script src="ejs.min.js"></script>
|
||||
<script>
|
||||
let people = ["geddy", "neil", "alex"],
|
||||
let people = ['geddy', 'neil', 'alex'],
|
||||
html = ejs.render('<%= people.join(", "); %>', { people: people });
|
||||
// With jQuery:
|
||||
$("#output").html(html);
|
||||
$('#output').html(html);
|
||||
// Vanilla JS:
|
||||
document.getElementById("output").innerHTML = html;
|
||||
document.getElementById('output').innerHTML = html;
|
||||
</script>
|
||||
```
|
||||
|
||||
|
||||
+44
-44
@@ -79,13 +79,13 @@ Same as: Math.pow(2, 8)
|
||||
#### New string methods
|
||||
|
||||
```js
|
||||
"hello".repeat(3);
|
||||
"hello".includes("ll");
|
||||
"hello".startsWith("he");
|
||||
"hello".padStart(8); // "hello"
|
||||
"hello".padEnd(8); // "hello"
|
||||
"hello".padEnd(8, "!"); // hello!!!
|
||||
"\u1E9B\u0323".normalize("NFC");
|
||||
'hello'.repeat(3);
|
||||
'hello'.includes('ll');
|
||||
'hello'.startsWith('he');
|
||||
'hello'.padStart(8); // "hello"
|
||||
'hello'.padEnd(8); // "hello"
|
||||
'hello'.padEnd(8, '!'); // hello!!!
|
||||
'\u1E9B\u0323'.normalize('NFC');
|
||||
```
|
||||
|
||||
#### New Number Methods
|
||||
@@ -93,7 +93,7 @@ Same as: Math.pow(2, 8)
|
||||
```js
|
||||
Number.EPSILON;
|
||||
Number.isInteger(Infinity); // false
|
||||
Number.isNaN("NaN"); // false
|
||||
Number.isNaN('NaN'); // false
|
||||
```
|
||||
|
||||
#### New Math methods
|
||||
@@ -108,7 +108,7 @@ Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2); // 2
|
||||
|
||||
```js
|
||||
//return a real array
|
||||
Array.from(document.querySelectorAll("*"));
|
||||
Array.from(document.querySelectorAll('*'));
|
||||
//similar to new Array(...), but without the special single-argument behavior
|
||||
Array.of(1, 2, 3);
|
||||
```
|
||||
@@ -171,7 +171,7 @@ class Dog {
|
||||
}
|
||||
}
|
||||
|
||||
const dog = new Dog("putty");
|
||||
const dog = new Dog('putty');
|
||||
//console.log(this.#name)
|
||||
//Private identifiers are not allowed outside class bodies.
|
||||
dog.printName();
|
||||
@@ -256,15 +256,15 @@ async function run () {
|
||||
#### Arrays
|
||||
|
||||
```js {1}
|
||||
const [first, last] = ["Nikola", "Tesla"];
|
||||
const [first, last] = ['Nikola', 'Tesla'];
|
||||
```
|
||||
|
||||
#### Objects
|
||||
|
||||
```js {1}
|
||||
let { title, author } = {
|
||||
title: "The Silkworm",
|
||||
author: "R. Galbraith",
|
||||
title: 'The Silkworm',
|
||||
author: 'R. Galbraith'
|
||||
};
|
||||
```
|
||||
|
||||
@@ -297,7 +297,7 @@ function greet({ name, greeting }) {
|
||||
---
|
||||
|
||||
```js
|
||||
greet({ name: "Larry", greeting: "Ahoy" });
|
||||
greet({ name: 'Larry', greeting: 'Ahoy' });
|
||||
```
|
||||
|
||||
Destructuring of objects and arrays can also be done in function parameters
|
||||
@@ -305,7 +305,7 @@ Destructuring of objects and arrays can also be done in function parameters
|
||||
### Defaults
|
||||
|
||||
```js {1}
|
||||
function greet({ name = "Rauno" } = {}) {
|
||||
function greet({ name = 'Rauno' } = {}) {
|
||||
console.log(`Hi ${name}!`);
|
||||
}
|
||||
```
|
||||
@@ -314,7 +314,7 @@ function greet({ name = "Rauno" } = {}) {
|
||||
|
||||
```js
|
||||
greet(); // Hi Rauno!
|
||||
greet({ name: "Larry" }); // Hi Larry!
|
||||
greet({ name: 'Larry' }); // Hi Larry!
|
||||
```
|
||||
|
||||
### Reassign keys
|
||||
@@ -360,7 +360,7 @@ Use the `rest(...)` operator to extract some keys individually and the rest of t
|
||||
```js {2}
|
||||
const options = {
|
||||
...defaults,
|
||||
visible: true,
|
||||
visible: true
|
||||
};
|
||||
```
|
||||
|
||||
@@ -388,7 +388,7 @@ const users = [
|
||||
#### No array expansion
|
||||
|
||||
```js
|
||||
const users = admins.concat(editors).concat(["rstacruz"]);
|
||||
const users = admins.concat(editors).concat(['rstacruz']);
|
||||
```
|
||||
|
||||
The spread operator allows you to build new arrays in the same way. See:
|
||||
@@ -401,7 +401,7 @@ The spread operator allows you to build new arrays in the same way. See:
|
||||
#### Default parameters
|
||||
|
||||
```js {1}
|
||||
function greet(name = "Jerry") {
|
||||
function greet(name = 'Jerry') {
|
||||
return `Hello ${name}`;
|
||||
}
|
||||
```
|
||||
@@ -460,13 +460,13 @@ Like a function, but preserves `this`. See: [Arrow functions](https://babeljs.io
|
||||
### Parameter setting default value
|
||||
|
||||
```js
|
||||
function log(x, y = "World") {
|
||||
function log(x, y = 'World') {
|
||||
console.log(x, y);
|
||||
}
|
||||
|
||||
log("Hello"); // Hello World
|
||||
log("Hello", "China"); // Hello China
|
||||
log("Hello", ""); // Hello
|
||||
log('Hello'); // Hello World
|
||||
log('Hello', 'China'); // Hello China
|
||||
log('Hello', ''); // Hello
|
||||
```
|
||||
|
||||
### Used in conjunction with destructuring assignment defaults
|
||||
@@ -506,7 +506,7 @@ same below:
|
||||
```js
|
||||
module.exports = {
|
||||
hello: hello,
|
||||
bye: bye,
|
||||
bye: bye
|
||||
};
|
||||
```
|
||||
|
||||
@@ -517,8 +517,8 @@ See: [Object Literals Enhanced](https://babeljs.io/learn-es2015/#enhanced-object
|
||||
```js {2}
|
||||
const App = {
|
||||
start() {
|
||||
console.log("running");
|
||||
},
|
||||
console.log('running');
|
||||
}
|
||||
};
|
||||
//Same as: App = { start: function () {···} }
|
||||
```
|
||||
@@ -543,9 +543,9 @@ See: [Object Literals Enhanced](https://babeljs.io/learn-es2015/#enhanced-object
|
||||
### Computed property name
|
||||
|
||||
```js {3}
|
||||
let event = "click";
|
||||
let event = 'click';
|
||||
let handlers = {
|
||||
[`on${event}`]: true,
|
||||
[`on${event}`]: true
|
||||
};
|
||||
//Same as: handlers = { 'onclick': true }
|
||||
```
|
||||
@@ -567,35 +567,35 @@ Object.entries(fatherJS)
|
||||
### Imports import
|
||||
|
||||
```js
|
||||
import "helpers";
|
||||
import 'helpers';
|
||||
//aka: require('···')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```js
|
||||
import Express from "express";
|
||||
import Express from 'express';
|
||||
//aka: const Express = require('···').default || require('···')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```js
|
||||
import { indent } from "helpers";
|
||||
import { indent } from 'helpers';
|
||||
//aka: const indent = require('···').indent
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```js
|
||||
import * as Helpers from "helpers";
|
||||
import * as Helpers from 'helpers';
|
||||
//aka: const Helpers = require('···')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
```js
|
||||
import { indentSpaces as indent } from "helpers";
|
||||
import { indentSpaces as indent } from 'helpers';
|
||||
//aka: const indent = require('···').indentSpaces
|
||||
```
|
||||
|
||||
@@ -625,8 +625,8 @@ export const pi = 3.14159;
|
||||
---
|
||||
|
||||
```js
|
||||
const firstName = "Michael";
|
||||
const lastName = "Jackson";
|
||||
const firstName = 'Michael';
|
||||
const lastName = 'Jackson';
|
||||
const year = 1958;
|
||||
export { firstName, lastName, year };
|
||||
```
|
||||
@@ -634,7 +634,7 @@ export { firstName, lastName, year };
|
||||
---
|
||||
|
||||
```js
|
||||
export * from "lib/math";
|
||||
export * from 'lib/math';
|
||||
```
|
||||
|
||||
`export` is the new `module.exports`. See: [Module exports](https://babeljs.io/learn-es2015/#modules)
|
||||
@@ -662,8 +662,8 @@ export {
|
||||
### Dynamically load modules
|
||||
|
||||
```js
|
||||
button.addEventListener("click", (event) => {
|
||||
import("./dialogBox.js")
|
||||
button.addEventListener('click', (event) => {
|
||||
import('./dialogBox.js')
|
||||
.then((dialogBox) => {
|
||||
dialogBox.open();
|
||||
})
|
||||
@@ -678,7 +678,7 @@ button.addEventListener("click", (event) => {
|
||||
### import() allows module paths to be dynamically generated
|
||||
|
||||
```js
|
||||
const main = document.querySelector("main");
|
||||
const main = document.querySelector('main');
|
||||
|
||||
import(`./modules/${someVariable}.js`)
|
||||
.then((module) => {
|
||||
@@ -695,7 +695,7 @@ import(`./modules/${someVariable}.js`)
|
||||
which returns the meta information of the current module
|
||||
|
||||
```js
|
||||
new URL("data.txt", import.meta.url);
|
||||
new URL('data.txt', import.meta.url);
|
||||
```
|
||||
|
||||
In the Node.js environment, `import.meta.url` always returns a local path, that is, a string of the `file:URL` protocol,
|
||||
@@ -706,14 +706,14 @@ such as `file:/// home/user/foo.js`
|
||||
#### static import
|
||||
|
||||
```js
|
||||
import json from "./package.json" assert { type: "json" };
|
||||
import json from './package.json' assert { type: 'json' };
|
||||
//Import all objects in the json file
|
||||
```
|
||||
|
||||
#### Dynamic Import
|
||||
|
||||
```js
|
||||
const json = await import("./package.json", { assert: { type: "json" } });
|
||||
const json = await import('./package.json', { assert: { type: 'json' } });
|
||||
```
|
||||
|
||||
## Generators
|
||||
@@ -751,9 +751,9 @@ let fibonacci = {
|
||||
next() {
|
||||
[pre, cur] = [cur, pre + cur];
|
||||
return { done: false, value: cur };
|
||||
},
|
||||
}
|
||||
};
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
for (var n of fibonacci) {
|
||||
|
||||
+42
-42
@@ -34,11 +34,11 @@ plugins:
|
||||
- Entry file `index.js` add code:
|
||||
|
||||
```js
|
||||
const express = require("express");
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
app.get("/", (req, res) => {
|
||||
res.send("Hello World!");
|
||||
app.get('/', (req, res) => {
|
||||
res.send('Hello World!');
|
||||
});
|
||||
app.listen(port, () => {
|
||||
console.log(`Listening port on ${port}`);
|
||||
@@ -103,7 +103,7 @@ $ DEBUG=myapp:*npm start
|
||||
### Application
|
||||
|
||||
```js
|
||||
var express = require("express");
|
||||
var express = require('express');
|
||||
var app = express();
|
||||
|
||||
console.dir(app.locals.title);
|
||||
@@ -192,9 +192,9 @@ console.dir(app.locals.email);
|
||||
### Response
|
||||
|
||||
```js
|
||||
app.get("/", function (req, res) {
|
||||
app.get('/', function (req, res) {
|
||||
console.dir(res.headersSent); //false
|
||||
res.send("OK");
|
||||
res.send('OK');
|
||||
console.dir(res.headersSent); //true
|
||||
});
|
||||
```
|
||||
@@ -250,7 +250,7 @@ will handle any request ending in `/events`
|
||||
|
||||
```js
|
||||
//depends on where the router "use()"
|
||||
router.get("/events", (req, res, next) => {
|
||||
router.get('/events', (req, res, next) => {
|
||||
//..
|
||||
});
|
||||
```
|
||||
@@ -260,8 +260,8 @@ router.get("/events", (req, res, next) => {
|
||||
The `res` object represents the HTTP response sent by the `Express` application when it receives an HTTP request
|
||||
|
||||
```js
|
||||
app.get("/user/:id", (req, res) => {
|
||||
res.send("user" + req.params.id);
|
||||
app.get('/user/:id', (req, res) => {
|
||||
res.send('user' + req.params.id);
|
||||
});
|
||||
```
|
||||
|
||||
@@ -271,8 +271,8 @@ A `req` object represents an `HTTP` request and has properties for the request q
|
||||
headers, etc.
|
||||
|
||||
```js
|
||||
app.get("/user/:id", (req, res) => {
|
||||
res.send("user" + req.params.id);
|
||||
app.get('/user/:id', (req, res) => {
|
||||
res.send('user' + req.params.id);
|
||||
});
|
||||
```
|
||||
|
||||
@@ -290,15 +290,15 @@ End the response process. This method actually comes from the Node core, specifi
|
||||
|
||||
```js
|
||||
res.json(null);
|
||||
res.json({ user: "tobi" });
|
||||
res.status(500).json({ error: "message" });
|
||||
res.json({ user: 'tobi' });
|
||||
res.status(500).json({ error: 'message' });
|
||||
```
|
||||
|
||||
### app.all
|
||||
|
||||
```js
|
||||
app.all("/secret", function (req, res, next) {
|
||||
console.log("access secret section...");
|
||||
app.all('/secret', function (req, res, next) {
|
||||
console.log('access secret section...');
|
||||
next(); // Pass control to the next handler
|
||||
});
|
||||
```
|
||||
@@ -306,43 +306,43 @@ app.all("/secret", function (req, res, next) {
|
||||
### app.delete
|
||||
|
||||
```js
|
||||
app.delete("/", function (req, res) {
|
||||
res.send("DELETE request to homepage");
|
||||
app.delete('/', function (req, res) {
|
||||
res.send('DELETE request to homepage');
|
||||
});
|
||||
```
|
||||
|
||||
### app.disable(name)
|
||||
|
||||
```js
|
||||
app.disable("trust proxy");
|
||||
app.get("trust proxy");
|
||||
app.disable('trust proxy');
|
||||
app.get('trust proxy');
|
||||
// => false
|
||||
```
|
||||
|
||||
### app.disabled(name)
|
||||
|
||||
```js
|
||||
app.disabled("trust proxy");
|
||||
app.disabled('trust proxy');
|
||||
// => true
|
||||
|
||||
app.enable("trust proxy");
|
||||
app.disabled("trust proxy");
|
||||
app.enable('trust proxy');
|
||||
app.disabled('trust proxy');
|
||||
// => false
|
||||
```
|
||||
|
||||
### app.engine(ext, callback)
|
||||
|
||||
```js
|
||||
var engines = require("consolidate");
|
||||
var engines = require('consolidate');
|
||||
|
||||
app.engine("haml", engines.haml);
|
||||
app.engine("html", engines.hogan);
|
||||
app.engine('haml', engines.haml);
|
||||
app.engine('html', engines.hogan);
|
||||
```
|
||||
|
||||
### app.listen([port[, host[, backlog]]][, callback])
|
||||
|
||||
```js
|
||||
var express = require("express");
|
||||
var express = require('express');
|
||||
|
||||
var app = express();
|
||||
app.listen(3000);
|
||||
@@ -351,24 +351,24 @@ app.listen(3000);
|
||||
### Routing
|
||||
|
||||
```js
|
||||
const express = require("express");
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
|
||||
//Respond to "hello world" when making a GET request to the homepage
|
||||
app.get("/", (req, res) => {
|
||||
res.send("hello world");
|
||||
app.get('/', (req, res) => {
|
||||
res.send('hello world');
|
||||
});
|
||||
```
|
||||
|
||||
```js
|
||||
// GET method routing
|
||||
app.get("/", (req, res) => {
|
||||
res.send("GET request to the homepage");
|
||||
app.get('/', (req, res) => {
|
||||
res.send('GET request to the homepage');
|
||||
});
|
||||
|
||||
// POST method routing
|
||||
app.post("/", (req, res) => {
|
||||
res.send("POST request to the homepage");
|
||||
app.post('/', (req, res) => {
|
||||
res.send('POST request to the homepage');
|
||||
});
|
||||
```
|
||||
|
||||
@@ -376,26 +376,26 @@ app.post("/", (req, res) => {
|
||||
|
||||
```js
|
||||
function logOriginalUrl(req, res, next) {
|
||||
console.log("ReqURL:", req.originalUrl);
|
||||
console.log('ReqURL:', req.originalUrl);
|
||||
next();
|
||||
}
|
||||
|
||||
function logMethod(req, res, next) {
|
||||
console.log("Request Type:", req.method);
|
||||
console.log('Request Type:', req.method);
|
||||
next();
|
||||
}
|
||||
|
||||
const log = [logOriginalUrl, logMethod];
|
||||
|
||||
app.get("/user/:id", log, (req, res, next) => {
|
||||
res.send("User Info");
|
||||
app.get('/user/:id', log, (req, res, next) => {
|
||||
res.send('User Info');
|
||||
});
|
||||
```
|
||||
|
||||
### Using templates
|
||||
|
||||
```js
|
||||
app.set("view engine", "pug");
|
||||
app.set('view engine', 'pug');
|
||||
```
|
||||
|
||||
Create a `Pug` template file named `index.pug` in the `views` directory with the following content
|
||||
@@ -412,10 +412,10 @@ Create a route to render the `index.pug` file. If the view engine property is no
|
||||
must be specified
|
||||
|
||||
```js
|
||||
app.get("/", (req, res) => {
|
||||
res.render("index", {
|
||||
title: "Hey",
|
||||
message: "Hello there!",
|
||||
app.get('/', (req, res) => {
|
||||
res.render('index', {
|
||||
title: 'Hey',
|
||||
message: 'Hello there!'
|
||||
});
|
||||
});
|
||||
```
|
||||
@@ -61,7 +61,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: "14"
|
||||
node-version: '14'
|
||||
- run: npm install -g bats
|
||||
- run: bats -v
|
||||
```
|
||||
@@ -192,7 +192,7 @@ jobs:
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v2
|
||||
with:
|
||||
node-version: "14"
|
||||
node-version: '14'
|
||||
|
||||
# step 3
|
||||
- name: Install dependencies
|
||||
@@ -242,7 +242,7 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CUSTOM_VARIABLE: "Hello, World!" # Custom variable defined using env:
|
||||
CUSTOM_VARIABLE: 'Hello, World!' # Custom variable defined using env:
|
||||
steps:
|
||||
- name: Check environment variable
|
||||
run: echo "Value of CUSTOM_VAR is $CUSTOM_VAR"
|
||||
|
||||
@@ -16,11 +16,11 @@ intro: |
|
||||
|
||||
### Actions
|
||||
|
||||
| Shortcut | Action |
|
||||
| -------------- | ------------------- |
|
||||
| `Alt+Super+8` | Turn zoom on or off |
|
||||
| `Alt+Super+=` | Zoom in |
|
||||
| `Alt+Super+-` | Zoom out |
|
||||
| Shortcut | Action |
|
||||
| ------------- | ------------------- |
|
||||
| `Alt+Super+8` | Turn zoom on or off |
|
||||
| `Alt+Super+=` | Zoom in |
|
||||
| `Alt+Super+-` | Zoom out |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
@@ -35,86 +35,84 @@ intro: |
|
||||
|
||||
### Screenshots
|
||||
|
||||
| Shortcut | Action |
|
||||
| ------------------- | --------------------------------- |
|
||||
| `Shift+Ctrl+Alt+R` | Record a screencast interactively |
|
||||
| `Shift+Print` | Take a screenshot |
|
||||
| `Print` | Take a screenshot interactively |
|
||||
| `Alt+Print` | Take a screenshot of a window |
|
||||
| Shortcut | Action |
|
||||
| ------------------ | --------------------------------- |
|
||||
| `Shift+Ctrl+Alt+R` | Record a screencast interactively |
|
||||
| `Shift+Print` | Take a screenshot |
|
||||
| `Print` | Take a screenshot interactively |
|
||||
| `Alt+Print` | Take a screenshot of a window |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### System
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------- | ------------------------------ |
|
||||
| `Super+N` | Focus the active notification |
|
||||
| `Super+L` | Lock screen |
|
||||
| `Ctrl+Alt+Del` | Log out |
|
||||
| `Super+F10` | Open the application menu |
|
||||
| `Super+Escape` | Restore the keyboard shortcuts |
|
||||
| `Super+A` | Show all applications |
|
||||
| `Super+V` | Show the notification list |
|
||||
| `Super+S` | Show the overview |
|
||||
| `Alt+F2` | Show the run command prompt |
|
||||
| Shortcut | Action |
|
||||
| -------------- | ------------------------------ |
|
||||
| `Super+N` | Focus the active notification |
|
||||
| `Super+L` | Lock screen |
|
||||
| `Ctrl+Alt+Del` | Log out |
|
||||
| `Super+F10` | Open the application menu |
|
||||
| `Super+Escape` | Restore the keyboard shortcuts |
|
||||
| `Super+A` | Show all applications |
|
||||
| `Super+V` | Show the notification list |
|
||||
| `Super+S` | Show the overview |
|
||||
| `Alt+F2` | Show the run command prompt |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Typing
|
||||
|
||||
| Shortcut | Action |
|
||||
| ---------------------- | ------------------------------- |
|
||||
| `Super+space` | Switch to next typing source |
|
||||
| `Shift+Super+Space` | Switch to previous input source |
|
||||
| Shortcut | Action |
|
||||
| ------------------- | ------------------------------- |
|
||||
| `Super+space` | Switch to next typing source |
|
||||
| `Shift+Super+Space` | Switch to previous input source |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Windows
|
||||
|
||||
| Shortcut | Action |
|
||||
| -------------- | ------------------------- |
|
||||
| `Alt+Space` | Activate the window menu |
|
||||
| `Alt+F1` | Close the window |
|
||||
| `Super+H` | Hide window |
|
||||
| `Super+Up` | Maximize window |
|
||||
| `Alt+F7` | Move window |
|
||||
| `Alt+F8` | Resize Window |
|
||||
| `Super+Down` | Restore window |
|
||||
| `Alt+F10` | Toggle maximization state |
|
||||
| `Super+Left` | View split on left |
|
||||
| `Super+Right` | View split on right |
|
||||
| Shortcut | Action |
|
||||
| ------------- | ------------------------- |
|
||||
| `Alt+Space` | Activate the window menu |
|
||||
| `Alt+F1` | Close the window |
|
||||
| `Super+H` | Hide window |
|
||||
| `Super+Up` | Maximize window |
|
||||
| `Alt+F7` | Move window |
|
||||
| `Alt+F8` | Resize Window |
|
||||
| `Super+Down` | Restore window |
|
||||
| `Alt+F10` | Toggle maximization state |
|
||||
| `Super+Left` | View split on left |
|
||||
| `Super+Right` | View split on right |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Navigation
|
||||
|
||||
| Shortcut | Action |
|
||||
| ------------------------- | -------------------------------------- |
|
||||
| `Ctrl+Super+D` | Hide all normal windows |
|
||||
| `Super+Page Up` | Move to workspace on the left |
|
||||
| `Super+Page Down` | Move to workspace on the right |
|
||||
| `Shift+Super+Down` | Move window one monitor down |
|
||||
| `Shift+Super+Left` | Move window one monitor to the left |
|
||||
| `Shift+Super+Right` | Move window one monitor to the right |
|
||||
| `Shift+Super+Up` | Move window one monitor up |
|
||||
| `Shift+Super+Page Up` | Move window one workspace to the left |
|
||||
| `Shift+Super+Page Down` | Move window one workspace to the right |
|
||||
| `Shift+Super+End` | Move window to last workspace |
|
||||
| `Shift+Super+Home` | Move window to workspace 1 |
|
||||
| `Super+Tab` | Switch applications |
|
||||
| `Ctrl+Alt+Tab` | Switch system controls |
|
||||
| `Ctrl+Alt+Escape` | Switch system controls directly |
|
||||
| `Super+End` | Switch to last workspace |
|
||||
| `Super+Home` | Switch to workspace 1 |
|
||||
| `Alt+Tab` | Switch windows |
|
||||
| `Alt+Escape` | Switch windows directly |
|
||||
| `Alt+F6` | Switch windows of an app directly |
|
||||
| `Super+` | Switch windows of an application |
|
||||
| Shortcut | Action |
|
||||
| ----------------------- | -------------------------------------- |
|
||||
| `Ctrl+Super+D` | Hide all normal windows |
|
||||
| `Super+Page Up` | Move to workspace on the left |
|
||||
| `Super+Page Down` | Move to workspace on the right |
|
||||
| `Shift+Super+Down` | Move window one monitor down |
|
||||
| `Shift+Super+Left` | Move window one monitor to the left |
|
||||
| `Shift+Super+Right` | Move window one monitor to the right |
|
||||
| `Shift+Super+Up` | Move window one monitor up |
|
||||
| `Shift+Super+Page Up` | Move window one workspace to the left |
|
||||
| `Shift+Super+Page Down` | Move window one workspace to the right |
|
||||
| `Shift+Super+End` | Move window to last workspace |
|
||||
| `Shift+Super+Home` | Move window to workspace 1 |
|
||||
| `Super+Tab` | Switch applications |
|
||||
| `Ctrl+Alt+Tab` | Switch system controls |
|
||||
| `Ctrl+Alt+Escape` | Switch system controls directly |
|
||||
| `Super+End` | Switch to last workspace |
|
||||
| `Super+Home` | Switch to workspace 1 |
|
||||
| `Alt+Tab` | Switch windows |
|
||||
| `Alt+Escape` | Switch windows directly |
|
||||
| `Alt+F6` | Switch windows of an app directly |
|
||||
| `Super+` | Switch windows of an application |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
|
||||
## Also see
|
||||
|
||||
- [Gnome Shell Cheatsheet](https://wiki.gnome.org/Projects/GnomeShell/CheatSheet)
|
||||
_(www.gnome.org)_
|
||||
- [Gnome Shell Cheatsheet](https://wiki.gnome.org/Projects/GnomeShell/CheatSheet) _(www.gnome.org)_
|
||||
@@ -2,20 +2,21 @@
|
||||
title: GnuPG
|
||||
categories:
|
||||
- Linux Command
|
||||
intro:
|
||||
A cheatsheet for GnuPG, the encryption and signing software.
|
||||
intro: A cheatsheet for GnuPG, the encryption and signing software.
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Software
|
||||
|
||||
Gpg4win and the GPG Suite have OS-specific features.
|
||||
|
||||
* [GnuPG](https://gnupg.org/)
|
||||
* [Gpg4win](https://www.gpg4win.org/) (Windows)
|
||||
* [GPG Suite](https://gpgtools.org/) (macOS)
|
||||
- [GnuPG](https://gnupg.org/)
|
||||
- [Gpg4win](https://www.gpg4win.org/) (Windows)
|
||||
- [GPG Suite](https://gpgtools.org/) (macOS)
|
||||
|
||||
Sometimes GPG keys are referred as PGP keys. They're interchangeable, as they follow the [OpenPGP Standard](https://www.rfc-editor.org/rfc/rfc9580.html).
|
||||
Sometimes GPG keys are referred as PGP keys. They're interchangeable, as they follow the
|
||||
[OpenPGP Standard](https://www.rfc-editor.org/rfc/rfc9580.html).
|
||||
|
||||
### Create a key-pair
|
||||
|
||||
@@ -210,8 +211,8 @@ $ gpg --export --armor <ID>
|
||||
|
||||
### PowerShell Commands
|
||||
|
||||
When you do a full restart, the GPG agent might not automatically start. Add
|
||||
the GnuPG's IPC tool to Startup Apps using PowerShell:
|
||||
When you do a full restart, the GPG agent might not automatically start. Add the GnuPG's IPC tool to Startup Apps using
|
||||
PowerShell:
|
||||
|
||||
```shell script
|
||||
$ $shell = New-Object -ComObject WScript.Shell
|
||||
|
||||
+19
-1
@@ -1030,7 +1030,9 @@ func main() {
|
||||
## Go File I/O {.cols-2}
|
||||
|
||||
### Reading a File
|
||||
|
||||
Read the contents of a file into memory.
|
||||
|
||||
```go
|
||||
data, err := os.ReadFile("file.txt")
|
||||
if err != nil {
|
||||
@@ -1039,7 +1041,9 @@ if err != nil {
|
||||
```
|
||||
|
||||
### Writing to a File
|
||||
|
||||
Write data to a file with specific permissions (e.g., 0644 for read-write).
|
||||
|
||||
```go
|
||||
err := os.WriteFile("file.txt", []byte("Hello, Go!"), 0644)
|
||||
```
|
||||
@@ -1047,7 +1051,9 @@ err := os.WriteFile("file.txt", []byte("Hello, Go!"), 0644)
|
||||
## Go Testing {.cols-2}
|
||||
|
||||
### Unit Test
|
||||
|
||||
Unit Test: A basic unit test follows the below naming convention and uses t.Errorf() to report failures.
|
||||
|
||||
```go
|
||||
func TestAdd(t *testing.T) {
|
||||
result := add(2, 3)
|
||||
@@ -1058,7 +1064,9 @@ func TestAdd(t *testing.T) {
|
||||
```
|
||||
|
||||
### Unit Test
|
||||
|
||||
Benchmark: Benchmark tests measure performance, using b.N to control iterations.
|
||||
|
||||
```go
|
||||
func BenchmarkAdd(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
@@ -1069,15 +1077,18 @@ func BenchmarkAdd(b *testing.B) {
|
||||
|
||||
## Go JSON Handling {.cols-2}
|
||||
|
||||
### JSON Encoding
|
||||
|
||||
### JSON Encoding
|
||||
Convert a Go struct to JSON.
|
||||
|
||||
```go
|
||||
data, _ := json.Marshal(person)
|
||||
```
|
||||
|
||||
### JSON Decoding
|
||||
|
||||
Parse JSON data into a Go struct.
|
||||
|
||||
```go
|
||||
json.Unmarshal(data, &person)
|
||||
```
|
||||
@@ -1085,6 +1096,7 @@ json.Unmarshal(data, &person)
|
||||
## Go Server {.cols-2}
|
||||
|
||||
### net/http (Standard Library)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -1107,6 +1119,7 @@ func main() {
|
||||
```
|
||||
|
||||
### gorilla/mux
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -1130,6 +1143,7 @@ func main() {
|
||||
```
|
||||
|
||||
### chi
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -1152,6 +1166,7 @@ func main() {
|
||||
```
|
||||
|
||||
### gin
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -1172,6 +1187,7 @@ func main() {
|
||||
```
|
||||
|
||||
### fiber
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
@@ -1190,7 +1206,9 @@ func main() {
|
||||
app.Listen(":8084")
|
||||
}
|
||||
```
|
||||
|
||||
### beego
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
|
||||
@@ -90,49 +90,49 @@ intro: |
|
||||
|
||||
### Search on emails
|
||||
|
||||
| Operator | Description | Category |
|
||||
| ----------------- | ----------------------------------------------------------------------------------------------------- | ---------- |
|
||||
| `+` | Prefix - Force exact match on single phrase | Basic,Mail |
|
||||
| `()` | Allows grouping of operators and helps dictate order | Basic,Mail |
|
||||
| `-` | Excludes a word from results | Basic,Mail |
|
||||
| `""` | Allows searching for a specific phrase - exact match search. Individual word prevents synonyms | Basic,Mail |
|
||||
| `OR`/`AND` | Boolean search function for OR searches as Google defaults to AND between words - must be all caps | Basic,Mail |
|
||||
| `after:` | Allows you to search drive or mail for files modified or mail sent/received anytime after a set date | Drive,Mail |
|
||||
| `before:` | Allows you to search drive or mail for files modified or mail sent/received before a certain date | Drive,Mail |
|
||||
| `is:starred` | Searches only items that have been starred in drive | Drive,Mail |
|
||||
| `from:` | Specify the sender in google mail | Mail |
|
||||
| `to:` | Specify the recipient in google mail | Mail |
|
||||
| `cc:` | Search by a recipient that was copied into an email | Mail |
|
||||
| `bcc:` | Search by a recipient that was blind copied into an email | Mail |
|
||||
| `older:` | Search for messages older than a certain date | Mail |
|
||||
| `newer:` | Search for messages newer than a certain date | Mail |
|
||||
| `Search` | for a message with a google sheet attached | Mail |
|
||||
| `Search` | for a message with a google presentation attached | Mail |
|
||||
| `AROUND` | Similar to the normal google search function, allows you to search for keywords near each other. | Mail |
|
||||
| `subject:` | Search by keywords featured in the subject line | Mail |
|
||||
| `{}` | Use for OR in mail instead of the OR function | Mail |
|
||||
| `label:` | Search for messages that have a certain label | Mail |
|
||||
| `has:attachment` | Search for messages that have an item attached | Mail |
|
||||
| `has:drive` | Search for messages with a google drive attached | Mail |
|
||||
| `has:document` | Search for messages with a google doc attached | Mail |
|
||||
| `has:youtube` | Search for a message containing a youtube video | Mail |
|
||||
| `list:` | Search for all messages from a particular mailing list | Mail |
|
||||
| `in:anywhere` | Includes all folders in your search, including spam and bin | Mail |
|
||||
| `is:important` | Search for messages that have been marked as important | Mail |
|
||||
| `label:important` | Same as is:important | Mail |
|
||||
| `is:snoozed` | Searches for messages that have been snoozed | Mail |
|
||||
| `is:unread` | Searches for unread messages | Mail |
|
||||
| `is:read` | searches for read messages only | Mail |
|
||||
| `has:yellow-star` | Searches for messages with coloured star icon | Mail |
|
||||
| `has:blue-info` | Searches for messages with colourd icon | Mail |
|
||||
| `is:chat` | Searches for messagse from chat | Mail |
|
||||
| `deliveredto:` | Search by email address for delivered messages | Mail |
|
||||
| `category:` | Searches by messages based on category. Follow the colon with the categoy name, i.e. category:primary | Mail |
|
||||
| `size:` | Messages larger than a certain size in bytes | Mail |
|
||||
| `larger:` | Messages larger than a certain size in bytes | Mail |
|
||||
| `smaller:` | Messages smaller than a certain size in bytes | Mail |
|
||||
| `has:userlabels` | Search for messages that have custom user labels | Mail |
|
||||
| `has:nouserlabels`| Search for messages that have no custom user labels | Mail |
|
||||
| Operator | Description | Category |
|
||||
| ------------------ | ----------------------------------------------------------------------------------------------------- | ---------- |
|
||||
| `+` | Prefix - Force exact match on single phrase | Basic,Mail |
|
||||
| `()` | Allows grouping of operators and helps dictate order | Basic,Mail |
|
||||
| `-` | Excludes a word from results | Basic,Mail |
|
||||
| `""` | Allows searching for a specific phrase - exact match search. Individual word prevents synonyms | Basic,Mail |
|
||||
| `OR`/`AND` | Boolean search function for OR searches as Google defaults to AND between words - must be all caps | Basic,Mail |
|
||||
| `after:` | Allows you to search drive or mail for files modified or mail sent/received anytime after a set date | Drive,Mail |
|
||||
| `before:` | Allows you to search drive or mail for files modified or mail sent/received before a certain date | Drive,Mail |
|
||||
| `is:starred` | Searches only items that have been starred in drive | Drive,Mail |
|
||||
| `from:` | Specify the sender in google mail | Mail |
|
||||
| `to:` | Specify the recipient in google mail | Mail |
|
||||
| `cc:` | Search by a recipient that was copied into an email | Mail |
|
||||
| `bcc:` | Search by a recipient that was blind copied into an email | Mail |
|
||||
| `older:` | Search for messages older than a certain date | Mail |
|
||||
| `newer:` | Search for messages newer than a certain date | Mail |
|
||||
| `Search` | for a message with a google sheet attached | Mail |
|
||||
| `Search` | for a message with a google presentation attached | Mail |
|
||||
| `AROUND` | Similar to the normal google search function, allows you to search for keywords near each other. | Mail |
|
||||
| `subject:` | Search by keywords featured in the subject line | Mail |
|
||||
| `{}` | Use for OR in mail instead of the OR function | Mail |
|
||||
| `label:` | Search for messages that have a certain label | Mail |
|
||||
| `has:attachment` | Search for messages that have an item attached | Mail |
|
||||
| `has:drive` | Search for messages with a google drive attached | Mail |
|
||||
| `has:document` | Search for messages with a google doc attached | Mail |
|
||||
| `has:youtube` | Search for a message containing a youtube video | Mail |
|
||||
| `list:` | Search for all messages from a particular mailing list | Mail |
|
||||
| `in:anywhere` | Includes all folders in your search, including spam and bin | Mail |
|
||||
| `is:important` | Search for messages that have been marked as important | Mail |
|
||||
| `label:important` | Same as is:important | Mail |
|
||||
| `is:snoozed` | Searches for messages that have been snoozed | Mail |
|
||||
| `is:unread` | Searches for unread messages | Mail |
|
||||
| `is:read` | searches for read messages only | Mail |
|
||||
| `has:yellow-star` | Searches for messages with coloured star icon | Mail |
|
||||
| `has:blue-info` | Searches for messages with colourd icon | Mail |
|
||||
| `is:chat` | Searches for messagse from chat | Mail |
|
||||
| `deliveredto:` | Search by email address for delivered messages | Mail |
|
||||
| `category:` | Searches by messages based on category. Follow the colon with the categoy name, i.e. category:primary | Mail |
|
||||
| `size:` | Messages larger than a certain size in bytes | Mail |
|
||||
| `larger:` | Messages larger than a certain size in bytes | Mail |
|
||||
| `smaller:` | Messages smaller than a certain size in bytes | Mail |
|
||||
| `has:userlabels` | Search for messages that have custom user labels | Mail |
|
||||
| `has:nouserlabels` | Search for messages that have no custom user labels | Mail |
|
||||
|
||||
### Some other useful search operators
|
||||
|
||||
|
||||
+20
-20
@@ -38,7 +38,7 @@ Hook features a modern syntax similar to `C`.
|
||||
### Hello, world!
|
||||
|
||||
```js
|
||||
println("Hello, World!");
|
||||
println('Hello, World!');
|
||||
// Hello, World!
|
||||
```
|
||||
|
||||
@@ -99,9 +99,9 @@ Numbers can be integers or floating-point.
|
||||
### Strings
|
||||
|
||||
```js
|
||||
let empty = "";
|
||||
let empty = '';
|
||||
|
||||
let name = "John";
|
||||
let name = 'John';
|
||||
|
||||
let message = 'Hello, "John"!';
|
||||
```
|
||||
@@ -122,7 +122,7 @@ Ranges are a sequence of integers.
|
||||
### Arrays
|
||||
|
||||
```js
|
||||
let fruits = ["apple", "banana", "cherry"];
|
||||
let fruits = ['apple', 'banana', 'cherry'];
|
||||
|
||||
println(fruits);
|
||||
// ["apple", "banana", "cherry"]
|
||||
@@ -200,9 +200,9 @@ Semi-colons are required and empty statements are not allowed.
|
||||
|
||||
```js
|
||||
{
|
||||
println("Hello");
|
||||
println('Hello');
|
||||
{
|
||||
println("World");
|
||||
println('World');
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -242,7 +242,7 @@ Identifiers are case-sensitive.
|
||||
```js
|
||||
var x; // x contains nil
|
||||
x = 5; // now, x contains a number
|
||||
x = "foo"; // a string
|
||||
x = 'foo'; // a string
|
||||
|
||||
println(x);
|
||||
```
|
||||
@@ -380,7 +380,7 @@ In Hook, the ternary operator is `if else`.
|
||||
let x = 10;
|
||||
|
||||
if (x > 5) {
|
||||
println("x is greater than 5");
|
||||
println('x is greater than 5');
|
||||
}
|
||||
// x is greater than 5
|
||||
```
|
||||
@@ -393,11 +393,11 @@ The `if` statement.
|
||||
let x = 11;
|
||||
|
||||
if (x == 5) {
|
||||
println("x is 5");
|
||||
println('x is 5');
|
||||
} else if (x == 10) {
|
||||
println("x is 10");
|
||||
println('x is 10');
|
||||
} else {
|
||||
println("x is neither 5 nor 10");
|
||||
println('x is neither 5 nor 10');
|
||||
}
|
||||
// x is neither 5 nor 10
|
||||
```
|
||||
@@ -514,7 +514,7 @@ Use `continue` to skip the rest of the loop body.
|
||||
### Indexing a string
|
||||
|
||||
```js
|
||||
let s = "Hello";
|
||||
let s = 'Hello';
|
||||
|
||||
println(s[0]); // H
|
||||
println(s[1]); // e
|
||||
@@ -537,7 +537,7 @@ Pass a range to slice a string.
|
||||
### Concatening strings
|
||||
|
||||
```js
|
||||
let greeting = "Hi" + " there!";
|
||||
let greeting = 'Hi' + ' there!';
|
||||
|
||||
println(greeting);
|
||||
// Hi there!
|
||||
@@ -731,9 +731,9 @@ Recursion is supported.
|
||||
```js
|
||||
println(type(5));
|
||||
// number
|
||||
println("1" + to_string(2));
|
||||
println('1' + to_string(2));
|
||||
// 12
|
||||
println(len("foo"));
|
||||
println(len('foo'));
|
||||
// 3
|
||||
```
|
||||
|
||||
@@ -922,7 +922,7 @@ import hashing as h;
|
||||
```
|
||||
|
||||
```js
|
||||
let d = h.sha256("Hello, world!");
|
||||
let d = h.sha256('Hello, world!');
|
||||
|
||||
println(hex(d));
|
||||
// 315f5bdb76d078c43b8ac0064e4a...
|
||||
@@ -953,7 +953,7 @@ Use `json` module for working with JSON.
|
||||
### Errors {.col-span-2}
|
||||
|
||||
```js
|
||||
println(to_int("foo"));
|
||||
println(to_int('foo'));
|
||||
|
||||
// runtime error: type error: argument #1 is not a convertible string
|
||||
// at to_int() in <native>
|
||||
@@ -965,7 +965,7 @@ Hook uses panic mode for error handling. When an error occurs, the interpreter s
|
||||
### Syntax error
|
||||
|
||||
```js
|
||||
println("Hello, World!");
|
||||
println('Hello, World!');
|
||||
|
||||
// syntax error: unexpected end of file
|
||||
// at main() in example.hk:1,25
|
||||
@@ -976,7 +976,7 @@ Hook has a strict syntax.
|
||||
### Panic
|
||||
|
||||
```js
|
||||
panic("Something went wrong");
|
||||
panic('Something went wrong');
|
||||
|
||||
// panic: Something went wrong
|
||||
// at main() in example.hk:1
|
||||
@@ -987,7 +987,7 @@ Use the `panic` built-in function to raise an error.
|
||||
### Assert {.col-span-2}
|
||||
|
||||
```js
|
||||
assert(5 > 10, "5 is not greater than 10");
|
||||
assert(5 > 10, '5 is not greater than 10');
|
||||
|
||||
// assert: 5 is not greater than 10
|
||||
// at main() in example.hk:1
|
||||
|
||||
+19
-5
@@ -78,7 +78,13 @@ See: [The \<a> Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Ele
|
||||
### Image Tag
|
||||
|
||||
```html {.wrap}
|
||||
<img loading="lazy" src="https://xxx.png" alt="Describe image here" width="400" height="400" />
|
||||
<img
|
||||
loading="lazy"
|
||||
src="https://xxx.png"
|
||||
alt="Describe image here"
|
||||
width="400"
|
||||
height="400"
|
||||
/>
|
||||
```
|
||||
|
||||
---
|
||||
@@ -170,7 +176,7 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM
|
||||
|
||||
```html
|
||||
<script type="text/javascript">
|
||||
let text = "Hello CheatSheets.zip";
|
||||
let text = 'Hello CheatSheets.zip';
|
||||
alert(text);
|
||||
</script>
|
||||
```
|
||||
@@ -277,7 +283,10 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM
|
||||
|
||||
```html {.wrap}
|
||||
<video controls="" width="100%">
|
||||
<source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" type="video/mp4" />
|
||||
<source
|
||||
src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
|
||||
type="video/mp4"
|
||||
/>
|
||||
Sorry, your browser doesn't support embedded videos.
|
||||
</video>
|
||||
```
|
||||
@@ -292,7 +301,10 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM
|
||||
### HTML5 Audio
|
||||
|
||||
```html {.wrap}
|
||||
<audio controls src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3">
|
||||
<audio
|
||||
controls
|
||||
src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"
|
||||
>
|
||||
Your browser does not support the audio element.
|
||||
</audio>
|
||||
```
|
||||
@@ -306,7 +318,9 @@ audio element. </audio>
|
||||
### HTML5 Ruby
|
||||
|
||||
```html {.wrap}
|
||||
<ruby> 汉 <rp>(</rp><rt>hàn</rt><rp>)</rp> 字 <rp>(</rp><rt>zì</rt><rp>)</rp> </ruby>
|
||||
<ruby>
|
||||
汉 <rp>(</rp><rt>hàn</rt><rp>)</rp> 字 <rp>(</rp><rt>zì</rt><rp>)</rp>
|
||||
</ruby>
|
||||
```
|
||||
|
||||
#### ↓ Preview
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
---
|
||||
title: IntelliJ IDEA
|
||||
date: 2020-12-17 21:51:44
|
||||
background:
|
||||
bg-gradient-to-r from-pink-500 via-violet-400 to-blue-400 hover:from-pink-700 hover:via-violet-600 hover:to-blue-500
|
||||
background: bg-gradient-to-r from-pink-500 via-violet-400 to-blue-400 hover:from-pink-700 hover:via-violet-600 hover:to-blue-500
|
||||
tags:
|
||||
- jetbrains
|
||||
- java
|
||||
|
||||
+139
-135
@@ -27,13 +27,13 @@ JavaScript is a lightweight, interpreted programming language.
|
||||
|
||||
```javascript
|
||||
// => Hello world!
|
||||
console.log("Hello world!");
|
||||
console.log('Hello world!');
|
||||
|
||||
// => Hello CheatSheets.zip
|
||||
console.warn("hello %s", "CheatSheets.zip");
|
||||
console.warn('hello %s', 'CheatSheets.zip');
|
||||
|
||||
// Prints error message to stderr
|
||||
console.error(new Error("Oops!"));
|
||||
console.error(new Error('Oops!'));
|
||||
```
|
||||
|
||||
### Numbers
|
||||
@@ -47,7 +47,7 @@ let price = 4.99;
|
||||
|
||||
```javascript
|
||||
let x = null;
|
||||
let name = "Tammy";
|
||||
let name = 'Tammy';
|
||||
const found = false;
|
||||
|
||||
// => Tammy, false, null
|
||||
@@ -60,8 +60,8 @@ console.log(a); // => undefined
|
||||
### Strings
|
||||
|
||||
```javascript
|
||||
let single = "Wheres my bandit hat?";
|
||||
let double = "Wheres my bandit hat?";
|
||||
let single = 'Wheres my bandit hat?';
|
||||
let double = 'Wheres my bandit hat?';
|
||||
|
||||
// => 21
|
||||
console.log(single.length);
|
||||
@@ -107,7 +107,7 @@ console.log(number);
|
||||
let age = 7;
|
||||
|
||||
// String concatenation
|
||||
"Tommy is " + age + " years old.";
|
||||
'Tommy is ' + age + ' years old.';
|
||||
|
||||
// String interpolation
|
||||
`Tommy is ${age} years old.`;
|
||||
@@ -139,7 +139,7 @@ numberOfColumns = 8;
|
||||
const isMailSent = true;
|
||||
|
||||
if (isMailSent) {
|
||||
console.log("Mail sent to recipient");
|
||||
console.log('Mail sent to recipient');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -178,7 +178,7 @@ true && false; // false
|
||||
250 >= 250; // true
|
||||
1 === 1; // true
|
||||
1 === 2; // false
|
||||
1 === "1"; // false
|
||||
1 === '1'; // false
|
||||
```
|
||||
|
||||
#### Logical Operator !
|
||||
@@ -194,12 +194,12 @@ console.log(oppositeValue);
|
||||
#### Nullish coalescing operator ??
|
||||
|
||||
```javascript
|
||||
null ?? "I win"; // 'I win'
|
||||
undefined ?? "Me too"; // 'Me too'
|
||||
null ?? 'I win'; // 'I win'
|
||||
undefined ?? 'Me too'; // 'Me too'
|
||||
|
||||
false ?? "I lose"; // false
|
||||
0 ?? "I lose again"; // 0
|
||||
"" ?? "Damn it"; // ''
|
||||
false ?? 'I lose'; // false
|
||||
0 ?? 'I lose again'; // 0
|
||||
'' ?? 'Damn it'; // ''
|
||||
```
|
||||
|
||||
### else if
|
||||
@@ -208,13 +208,13 @@ false ?? "I lose"; // false
|
||||
const size = 10;
|
||||
|
||||
if (size > 100) {
|
||||
console.log("Big");
|
||||
console.log('Big');
|
||||
} else if (size > 20) {
|
||||
console.log("Medium");
|
||||
console.log('Medium');
|
||||
} else if (size > 4) {
|
||||
console.log("Small");
|
||||
console.log('Small');
|
||||
} else {
|
||||
console.log("Tiny");
|
||||
console.log('Tiny');
|
||||
}
|
||||
// Print: Small
|
||||
```
|
||||
@@ -222,17 +222,17 @@ if (size > 100) {
|
||||
### switch Statement
|
||||
|
||||
```javascript
|
||||
const food = "salad";
|
||||
const food = 'salad';
|
||||
|
||||
switch (food) {
|
||||
case "oyster":
|
||||
console.log("The taste of the sea");
|
||||
case 'oyster':
|
||||
console.log('The taste of the sea');
|
||||
break;
|
||||
case "pizza":
|
||||
console.log("A delicious pie");
|
||||
case 'pizza':
|
||||
console.log('A delicious pie');
|
||||
break;
|
||||
default:
|
||||
console.log("Enjoy your meal");
|
||||
console.log('Enjoy your meal');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -241,12 +241,12 @@ switch (food) {
|
||||
```javascript
|
||||
0 == false; // true
|
||||
0 === false; // false, different type
|
||||
1 == "1"; // true, automatic type conversion
|
||||
1 === "1"; // false, different type
|
||||
1 == '1'; // true, automatic type conversion
|
||||
1 === '1'; // false, different type
|
||||
null == undefined; // true
|
||||
null === undefined; // false
|
||||
"0" == false; // true
|
||||
"0" === false; // false
|
||||
'0' == false; // true
|
||||
'0' === false; // false
|
||||
```
|
||||
|
||||
The `==` just check the value, `===` check both the value and the type.
|
||||
@@ -270,12 +270,12 @@ sum(3, 6); // 9
|
||||
```javascript
|
||||
// Named function
|
||||
function rocketToMars() {
|
||||
return "BOOM!";
|
||||
return 'BOOM!';
|
||||
}
|
||||
|
||||
// Anonymous function
|
||||
const rocketToMars = function () {
|
||||
return "BOOM!";
|
||||
return 'BOOM!';
|
||||
};
|
||||
```
|
||||
|
||||
@@ -294,7 +294,7 @@ console.log(sum(2, 5)); // => 7
|
||||
|
||||
```javascript
|
||||
const printHello = () => {
|
||||
console.log("hello");
|
||||
console.log('hello');
|
||||
};
|
||||
printHello(); // => hello
|
||||
```
|
||||
@@ -349,7 +349,7 @@ sum(2, 4); // 6
|
||||
|
||||
```javascript
|
||||
const dog = function () {
|
||||
return "Woof!";
|
||||
return 'Woof!';
|
||||
};
|
||||
```
|
||||
|
||||
@@ -376,7 +376,7 @@ function add(num1, num2) {
|
||||
|
||||
```javascript
|
||||
function myFunction() {
|
||||
var pizzaName = "Margarita";
|
||||
var pizzaName = 'Margarita';
|
||||
// Code here can use pizzaName
|
||||
}
|
||||
|
||||
@@ -389,7 +389,7 @@ function myFunction() {
|
||||
const isLoggedIn = true;
|
||||
|
||||
if (isLoggedIn == true) {
|
||||
const statusMessage = "Logged in.";
|
||||
const statusMessage = 'Logged in.';
|
||||
}
|
||||
|
||||
// Uncaught ReferenceError...
|
||||
@@ -400,7 +400,7 @@ console.log(statusMessage);
|
||||
|
||||
```javascript
|
||||
// Variable declared globally
|
||||
const color = "blue";
|
||||
const color = 'blue';
|
||||
|
||||
function printColor() {
|
||||
console.log(color);
|
||||
@@ -455,10 +455,10 @@ The variable has its own copy using `let`, and the variable has shared copy usin
|
||||
### Arrays
|
||||
|
||||
```javascript
|
||||
const fruits = ["apple", "orange", "banana"];
|
||||
const fruits = ['apple', 'orange', 'banana'];
|
||||
|
||||
// Different data types
|
||||
const data = [1, "chicken", false];
|
||||
const data = [1, 'chicken', false];
|
||||
```
|
||||
|
||||
### Property .length
|
||||
@@ -494,8 +494,8 @@ console.log(myArray[1]); // 200
|
||||
|
||||
```javascript
|
||||
// Adding a single element:
|
||||
const cart = ["apple", "orange"];
|
||||
cart.push("pear");
|
||||
const cart = ['apple', 'orange'];
|
||||
cart.push('pear');
|
||||
|
||||
// Adding multiple elements:
|
||||
const numbers = [1, 2];
|
||||
@@ -507,7 +507,7 @@ Add items to the end and returns the new array length.
|
||||
### Array.pop()
|
||||
|
||||
```javascript
|
||||
const fruits = ["apple", "orange", "banana"];
|
||||
const fruits = ['apple', 'orange', 'banana'];
|
||||
|
||||
const fruit = fruits.pop(); // 'banana'
|
||||
console.log(fruits); // ["apple", "orange"]
|
||||
@@ -518,7 +518,7 @@ Remove an item from the end and returns the removed item.
|
||||
### Array.shift()
|
||||
|
||||
```javascript
|
||||
let cats = ["Bob", "Willy", "Mini"];
|
||||
let cats = ['Bob', 'Willy', 'Mini'];
|
||||
|
||||
cats.shift(); // ['Willy', 'Mini']
|
||||
```
|
||||
@@ -528,13 +528,13 @@ Remove an item from the beginning and returns the removed item.
|
||||
### Array.unshift()
|
||||
|
||||
```javascript
|
||||
let cats = ["Bob"];
|
||||
let cats = ['Bob'];
|
||||
|
||||
// => ['Willy', 'Bob']
|
||||
cats.unshift("Willy");
|
||||
cats.unshift('Willy');
|
||||
|
||||
// => ['Puff', 'George', 'Willy', 'Bob']
|
||||
cats.unshift("Puff", "George");
|
||||
cats.unshift('Puff', 'George');
|
||||
```
|
||||
|
||||
Add items to the beginning and returns the new array length.
|
||||
@@ -563,7 +563,7 @@ If you want to avoid mutating your original array, you can use concat.
|
||||
const emptySet = new Set();
|
||||
|
||||
// Set Object with values
|
||||
const setObj = new Set([1, true, "hi"]);
|
||||
const setObj = new Set([1, true, 'hi']);
|
||||
```
|
||||
|
||||
### Add
|
||||
@@ -572,19 +572,19 @@ const setObj = new Set([1, true, "hi"]);
|
||||
const emptySet = new Set();
|
||||
|
||||
// add values
|
||||
emptySet.add("a"); // 'a'
|
||||
emptySet.add('a'); // 'a'
|
||||
emptySet.add(1); // 'a', 1
|
||||
emptySet.add(true); // 'a', 1, true
|
||||
emptySet.add("a"); // 'a', 1, true
|
||||
emptySet.add('a'); // 'a', 1, true
|
||||
```
|
||||
|
||||
### Delete
|
||||
|
||||
```javascript
|
||||
const emptySet = new Set([1, true, "a"]);
|
||||
const emptySet = new Set([1, true, 'a']);
|
||||
|
||||
// delete values
|
||||
emptySet.delete("a"); // 1, true
|
||||
emptySet.delete('a'); // 1, true
|
||||
emptySet.delete(true); // 1
|
||||
emptySet.delete(1); //
|
||||
```
|
||||
@@ -592,10 +592,10 @@ emptySet.delete(1); //
|
||||
### Has
|
||||
|
||||
```javascript
|
||||
const setObj = new Set([1, true, "a"]);
|
||||
const setObj = new Set([1, true, 'a']);
|
||||
|
||||
// returns true or false
|
||||
setObj.has("a"); // true
|
||||
setObj.has('a'); // true
|
||||
setObj.has(1); // true
|
||||
setObj.has(false); // false
|
||||
```
|
||||
@@ -603,7 +603,7 @@ setObj.has(false); // false
|
||||
### Clear
|
||||
|
||||
```javascript
|
||||
const setObj = new Set([1, true, "a"]);
|
||||
const setObj = new Set([1, true, 'a']);
|
||||
|
||||
// clears the set
|
||||
console.log(setObj); // 1, true, 'a'
|
||||
@@ -613,7 +613,7 @@ setObj.clear(); //
|
||||
### Size
|
||||
|
||||
```javascript
|
||||
const setObj = new Set([1, true, "a"]);
|
||||
const setObj = new Set([1, true, 'a']);
|
||||
|
||||
consoloe.log(setObj.size); // 3
|
||||
```
|
||||
@@ -621,7 +621,7 @@ consoloe.log(setObj.size); // 3
|
||||
### ForEach
|
||||
|
||||
```javascript
|
||||
const setObj = new Set([1, true, "a"]);
|
||||
const setObj = new Set([1, true, 'a']);
|
||||
|
||||
setObj.forEach(function (value) {
|
||||
console.log(value);
|
||||
@@ -651,7 +651,7 @@ while (i < 5) {
|
||||
### Reverse Loop
|
||||
|
||||
```javascript
|
||||
const fruits = ["apple", "orange", "banana"];
|
||||
const fruits = ['apple', 'orange', 'banana'];
|
||||
|
||||
for (let i = fruits.length - 1; i >= 0; i--) {
|
||||
console.log(`${i}. ${fruits[i]}`);
|
||||
@@ -715,7 +715,7 @@ for (i = 0; i < 10; i++) {
|
||||
if (i === 3) {
|
||||
continue;
|
||||
}
|
||||
text += "The number is " + i + "<br>";
|
||||
text += 'The number is ' + i + '<br>';
|
||||
}
|
||||
```
|
||||
|
||||
@@ -732,7 +732,7 @@ for (let i = 0; i < 2; i += 1) {
|
||||
### for...in loop
|
||||
|
||||
```javascript
|
||||
const fruits = ["apple", "orange", "banana"];
|
||||
const fruits = ['apple', 'orange', 'banana'];
|
||||
|
||||
for (let index in fruits) {
|
||||
console.log(index);
|
||||
@@ -745,7 +745,7 @@ for (let index in fruits) {
|
||||
### for...of loop
|
||||
|
||||
```javascript
|
||||
const fruits = ["apple", "orange", "banana"];
|
||||
const fruits = ['apple', 'orange', 'banana'];
|
||||
|
||||
for (let fruit of fruits) {
|
||||
console.log(fruit);
|
||||
@@ -803,10 +803,10 @@ console.log(sum); // 10
|
||||
### Array.map()
|
||||
|
||||
```javascript
|
||||
const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"];
|
||||
const members = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby'];
|
||||
|
||||
const announcements = members.map((member) => {
|
||||
return member + " joined the contest.";
|
||||
return member + ' joined the contest.';
|
||||
});
|
||||
|
||||
console.log(announcements);
|
||||
@@ -837,8 +837,8 @@ const filteredArray = randomNumbers.filter((n) => {
|
||||
|
||||
```javascript
|
||||
const apple = {
|
||||
color: "Green",
|
||||
price: { bulk: "$3/kg", smallQty: "$4/kg" },
|
||||
color: 'Green',
|
||||
price: { bulk: '$3/kg', smallQty: '$4/kg' }
|
||||
};
|
||||
console.log(apple.color); // => Green
|
||||
console.log(apple.price.bulk); // => $3/kg
|
||||
@@ -862,7 +862,7 @@ const trainSchedule = {
|
||||
|
||||
```javascript
|
||||
const classElection = {
|
||||
date: "January 12",
|
||||
date: 'January 12'
|
||||
};
|
||||
|
||||
console.log(classElection.place); // undefined
|
||||
@@ -872,16 +872,16 @@ console.log(classElection.place); // undefined
|
||||
|
||||
```javascript
|
||||
const student = {
|
||||
name: "Sheldon",
|
||||
name: 'Sheldon',
|
||||
score: 100,
|
||||
grade: "A",
|
||||
grade: 'A'
|
||||
};
|
||||
|
||||
console.log(student);
|
||||
// { name: 'Sheldon', score: 100, grade: 'A' }
|
||||
|
||||
delete student.score;
|
||||
student.grade = "F";
|
||||
student.grade = 'F';
|
||||
console.log(student);
|
||||
// { name: 'Sheldon', grade: 'F' }
|
||||
|
||||
@@ -893,8 +893,8 @@ student = {};
|
||||
|
||||
```javascript
|
||||
const person = {
|
||||
name: "Tom",
|
||||
age: "22",
|
||||
name: 'Tom',
|
||||
age: '22'
|
||||
};
|
||||
const { name, age } = person;
|
||||
console.log(name); // 'Tom'
|
||||
@@ -905,10 +905,10 @@ console.log(age); // '22'
|
||||
|
||||
```javascript
|
||||
const person = {
|
||||
firstName: "Matilda",
|
||||
firstName: 'Matilda',
|
||||
age: 27,
|
||||
hobby: "knitting",
|
||||
goal: "learning JavaScript",
|
||||
hobby: 'knitting',
|
||||
goal: 'learning JavaScript'
|
||||
};
|
||||
|
||||
delete person.hobby; // or delete person[hobby];
|
||||
@@ -927,11 +927,11 @@ console.log(person);
|
||||
|
||||
```javascript
|
||||
const origNum = 8;
|
||||
const origObj = { color: "blue" };
|
||||
const origObj = { color: 'blue' };
|
||||
|
||||
const changeItUp = (num, obj) => {
|
||||
num = 7;
|
||||
obj.color = "red";
|
||||
obj.color = 'red';
|
||||
};
|
||||
|
||||
changeItUp(origNum, origObj);
|
||||
@@ -947,7 +947,7 @@ console.log(origObj.color);
|
||||
### Shorthand object creation
|
||||
|
||||
```javascript
|
||||
const activity = "Surfing";
|
||||
const activity = 'Surfing';
|
||||
const beach = { activity };
|
||||
console.log(beach); // { activity: 'Surfing' }
|
||||
```
|
||||
@@ -956,11 +956,11 @@ console.log(beach); // { activity: 'Surfing' }
|
||||
|
||||
```javascript
|
||||
const cat = {
|
||||
name: "Pipey",
|
||||
name: 'Pipey',
|
||||
age: 8,
|
||||
whatName() {
|
||||
return this.name;
|
||||
},
|
||||
}
|
||||
};
|
||||
console.log(cat.whatName()); // => Pipey
|
||||
```
|
||||
@@ -977,8 +977,8 @@ const dogFactory = (name, age, breed) => {
|
||||
age: age,
|
||||
breed: breed,
|
||||
bark() {
|
||||
console.log("Woof!");
|
||||
},
|
||||
console.log('Woof!');
|
||||
}
|
||||
};
|
||||
};
|
||||
```
|
||||
@@ -993,11 +993,11 @@ const engine = {
|
||||
},
|
||||
// anonymous arrow function expression with no arguments
|
||||
sputter: () => {
|
||||
console.log("The engine sputters...");
|
||||
},
|
||||
console.log('The engine sputters...');
|
||||
}
|
||||
};
|
||||
|
||||
engine.start("noisily");
|
||||
engine.start('noisily');
|
||||
engine.sputter();
|
||||
```
|
||||
|
||||
@@ -1005,20 +1005,20 @@ engine.sputter();
|
||||
|
||||
```javascript
|
||||
const myCat = {
|
||||
_name: "Dottie",
|
||||
_name: 'Dottie',
|
||||
get name() {
|
||||
return this._name;
|
||||
},
|
||||
set name(newName) {
|
||||
this._name = newName;
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
// Reference invokes the getter
|
||||
console.log(myCat.name);
|
||||
|
||||
// Assignment invokes the setter
|
||||
myCat.name = "Yankee";
|
||||
myCat.name = 'Yankee';
|
||||
```
|
||||
|
||||
## JavaScript Classes
|
||||
@@ -1032,16 +1032,16 @@ class Dog {
|
||||
}
|
||||
|
||||
introduce() {
|
||||
console.log("This is " + this._name + " !");
|
||||
console.log('This is ' + this._name + ' !');
|
||||
}
|
||||
|
||||
// A static method
|
||||
static bark() {
|
||||
console.log("Woof!");
|
||||
console.log('Woof!');
|
||||
}
|
||||
}
|
||||
|
||||
const myDog = new Dog("Buster");
|
||||
const myDog = new Dog('Buster');
|
||||
myDog.introduce();
|
||||
|
||||
// Calling the static method
|
||||
@@ -1058,7 +1058,7 @@ class Song {
|
||||
}
|
||||
|
||||
play() {
|
||||
console.log("Song playing!");
|
||||
console.log('Song playing!');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1076,7 +1076,7 @@ class Song {
|
||||
}
|
||||
}
|
||||
|
||||
const mySong = new Song("Bohemian Rhapsody", "Queen");
|
||||
const mySong = new Song('Bohemian Rhapsody', 'Queen');
|
||||
console.log(mySong.title);
|
||||
```
|
||||
|
||||
@@ -1085,11 +1085,11 @@ console.log(mySong.title);
|
||||
```javascript
|
||||
class Song {
|
||||
play() {
|
||||
console.log("Playing!");
|
||||
console.log('Playing!');
|
||||
}
|
||||
|
||||
stop() {
|
||||
console.log("Stopping!");
|
||||
console.log('Stopping!');
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -1114,9 +1114,9 @@ class Song extends Media {
|
||||
}
|
||||
|
||||
const mySong = new Song({
|
||||
artist: "Queen",
|
||||
name: "Bohemian Rhapsody",
|
||||
publishDate: 1975,
|
||||
artist: 'Queen',
|
||||
name: 'Bohemian Rhapsody',
|
||||
publishDate: 1975
|
||||
});
|
||||
```
|
||||
|
||||
@@ -1185,7 +1185,7 @@ module.exports = {
|
||||
add,
|
||||
subtract,
|
||||
multiply,
|
||||
duplicate,
|
||||
duplicate
|
||||
};
|
||||
```
|
||||
|
||||
@@ -1193,7 +1193,7 @@ module.exports = {
|
||||
|
||||
```javascript
|
||||
// main.js
|
||||
const myMath = require("./myMath.js");
|
||||
const myMath = require('./myMath.js');
|
||||
|
||||
console.log(myMath.add(6, 2)); // 8
|
||||
console.log(myMath.subtract(6, 2)); // 4
|
||||
@@ -1210,15 +1210,15 @@ const promise = new Promise((resolve, reject) => {
|
||||
const res = true;
|
||||
// An asynchronous operation.
|
||||
if (res) {
|
||||
resolve("Resolved!");
|
||||
resolve('Resolved!');
|
||||
} else {
|
||||
reject(Error("Error"));
|
||||
reject(Error('Error'));
|
||||
}
|
||||
});
|
||||
|
||||
promise.then(
|
||||
(res) => console.log(res),
|
||||
(err) => console.error(err),
|
||||
(err) => console.error(err)
|
||||
);
|
||||
```
|
||||
|
||||
@@ -1226,7 +1226,7 @@ promise.then(
|
||||
|
||||
```javascript
|
||||
const executorFn = (resolve, reject) => {
|
||||
resolve("Resolved!");
|
||||
resolve('Resolved!');
|
||||
};
|
||||
|
||||
const promise = new Promise(executorFn);
|
||||
@@ -1236,7 +1236,7 @@ const promise = new Promise(executorFn);
|
||||
|
||||
```javascript
|
||||
const loginAlert = () => {
|
||||
console.log("Login");
|
||||
console.log('Login');
|
||||
};
|
||||
|
||||
setTimeout(loginAlert, 6000);
|
||||
@@ -1247,7 +1247,7 @@ setTimeout(loginAlert, 6000);
|
||||
```javascript
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
resolve("Result");
|
||||
resolve('Result');
|
||||
}, 200);
|
||||
});
|
||||
|
||||
@@ -1257,7 +1257,7 @@ promise.then(
|
||||
},
|
||||
(err) => {
|
||||
console.error(err);
|
||||
},
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
@@ -1266,7 +1266,7 @@ promise.then(
|
||||
```javascript
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(Error("Promise Rejected Unconditionally."));
|
||||
reject(Error('Promise Rejected Unconditionally.'));
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
@@ -1320,7 +1320,7 @@ Promise.allSettled([promise1, promise2]).then((res) => {
|
||||
```javascript
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
setTimeout(() => {
|
||||
resolve("*");
|
||||
resolve('*');
|
||||
}, 1000);
|
||||
});
|
||||
|
||||
@@ -1329,7 +1329,7 @@ const twoStars = (star) => {
|
||||
};
|
||||
|
||||
const oneDot = (star) => {
|
||||
return star + ".";
|
||||
return star + '.';
|
||||
};
|
||||
|
||||
const print = (val) => {
|
||||
@@ -1344,7 +1344,7 @@ promise.then(twoStars).then(oneDot).then(print);
|
||||
|
||||
```javascript
|
||||
const executorFn = (resolve, reject) => {
|
||||
console.log("The executor function of the promise!");
|
||||
console.log('The executor function of the promise!');
|
||||
};
|
||||
|
||||
const promise = new Promise(executorFn);
|
||||
@@ -1353,11 +1353,15 @@ const promise = new Promise(executorFn);
|
||||
### Chaining multiple .then()
|
||||
|
||||
```javascript
|
||||
const promise = new Promise((resolve) => setTimeout(() => resolve("dAlan"), 100));
|
||||
const promise = new Promise((resolve) =>
|
||||
setTimeout(() => resolve('dAlan'), 100)
|
||||
);
|
||||
|
||||
promise
|
||||
.then((res) => {
|
||||
return res === "Alan" ? Promise.resolve("Hey Alan!") : Promise.reject("Who are you?");
|
||||
return res === 'Alan'
|
||||
? Promise.resolve('Hey Alan!')
|
||||
: Promise.reject('Who are you?');
|
||||
})
|
||||
.then(
|
||||
(res) => {
|
||||
@@ -1365,7 +1369,7 @@ promise
|
||||
},
|
||||
(err) => {
|
||||
console.error(err);
|
||||
},
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
@@ -1378,7 +1382,7 @@ const mock = (success, timeout = 1000) => {
|
||||
if (success) {
|
||||
resolve({ status: 200, data: {} });
|
||||
} else {
|
||||
reject({ message: "Error" });
|
||||
reject({ message: 'Error' });
|
||||
}
|
||||
}, timeout);
|
||||
});
|
||||
@@ -1400,7 +1404,7 @@ const someEvent = async () => {
|
||||
function helloWorld() {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve("Hello World!");
|
||||
resolve('Hello World!');
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
@@ -1408,13 +1412,13 @@ function helloWorld() {
|
||||
const msg = async function () {
|
||||
//Async Function Expression
|
||||
const msg = await helloWorld();
|
||||
console.log("Message:", msg);
|
||||
console.log('Message:', msg);
|
||||
};
|
||||
|
||||
const msg1 = async () => {
|
||||
//Async Arrow Function
|
||||
const msg = await helloWorld();
|
||||
console.log("Message:", msg);
|
||||
console.log('Message:', msg);
|
||||
};
|
||||
|
||||
msg(); // Message: Hello World! <-- after 2 seconds
|
||||
@@ -1427,7 +1431,7 @@ msg1(); // Message: Hello World! <-- after 2 seconds
|
||||
let pro1 = Promise.resolve(5);
|
||||
let pro2 = 44;
|
||||
let pro3 = new Promise(function (resolve, reject) {
|
||||
setTimeout(resolve, 100, "foo");
|
||||
setTimeout(resolve, 100, 'foo');
|
||||
});
|
||||
|
||||
Promise.all([pro1, pro2, pro3]).then(function (values) {
|
||||
@@ -1442,14 +1446,14 @@ Promise.all([pro1, pro2, pro3]).then(function (values) {
|
||||
function helloWorld() {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve("Hello World!");
|
||||
resolve('Hello World!');
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
async function msg() {
|
||||
const msg = await helloWorld();
|
||||
console.log("Message:", msg);
|
||||
console.log('Message:', msg);
|
||||
}
|
||||
|
||||
msg(); // Message: Hello World! <-- after 2 seconds
|
||||
@@ -1464,7 +1468,7 @@ try {
|
||||
let user = JSON.parse(json); // <-- no errors
|
||||
console.log(user.name); // no name!
|
||||
} catch (e) {
|
||||
console.error("Invalid JSON data!");
|
||||
console.error('Invalid JSON data!');
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1474,14 +1478,14 @@ try {
|
||||
function helloWorld() {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve("Hello World!");
|
||||
resolve('Hello World!');
|
||||
}, 2000);
|
||||
});
|
||||
}
|
||||
|
||||
async function msg() {
|
||||
const msg = await helloWorld();
|
||||
console.log("Message:", msg);
|
||||
console.log('Message:', msg);
|
||||
}
|
||||
|
||||
msg(); // Message: Hello World! <-- after 2 seconds
|
||||
@@ -1505,7 +1509,7 @@ Also see: [JSON cheatsheet](/json)
|
||||
|
||||
```javascript
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("GET", "mysite.com/getjson");
|
||||
xhr.open('GET', 'mysite.com/getjson');
|
||||
```
|
||||
|
||||
`XMLHttpRequest` is a browser-level API that enables the client to script data transfers via JavaScript, NOT part of the
|
||||
@@ -1515,8 +1519,8 @@ JavaScript language.
|
||||
|
||||
```javascript
|
||||
const req = new XMLHttpRequest();
|
||||
req.responseType = "json";
|
||||
req.open("GET", "/getdata?id=65");
|
||||
req.responseType = 'json';
|
||||
req.open('GET', '/getdata?id=65');
|
||||
req.onload = () => {
|
||||
console.log(xhr.response);
|
||||
};
|
||||
@@ -1528,13 +1532,13 @@ req.send();
|
||||
|
||||
```javascript
|
||||
const data = {
|
||||
fish: "Salmon",
|
||||
weight: "1.5 KG",
|
||||
units: 5,
|
||||
fish: 'Salmon',
|
||||
weight: '1.5 KG',
|
||||
units: 5
|
||||
};
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", "/inventory/add");
|
||||
xhr.responseType = "json";
|
||||
xhr.open('POST', '/inventory/add');
|
||||
xhr.responseType = 'json';
|
||||
xhr.send(JSON.stringify(data));
|
||||
|
||||
xhr.onload = () => {
|
||||
@@ -1566,7 +1570,7 @@ fetch(url, {
|
||||
### JSON Formatted
|
||||
|
||||
```javascript
|
||||
fetch("url-that-returns-JSON")
|
||||
fetch('url-that-returns-JSON')
|
||||
.then((response) => response.json())
|
||||
.then((jsonResponse) => {
|
||||
console.log(jsonResponse);
|
||||
@@ -1589,20 +1593,20 @@ fetch('url')
|
||||
### Fetch API Function
|
||||
|
||||
```javascript
|
||||
fetch("https://api-xxx.com/endpoint", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id: "200" }),
|
||||
fetch('https://api-xxx.com/endpoint', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ id: '200' })
|
||||
})
|
||||
.then(
|
||||
(response) => {
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
}
|
||||
throw new Error("Request failed!");
|
||||
throw new Error('Request failed!');
|
||||
},
|
||||
(networkError) => {
|
||||
console.log(networkError.message);
|
||||
},
|
||||
}
|
||||
)
|
||||
.then((jsonResponse) => {
|
||||
console.log(jsonResponse);
|
||||
@@ -1616,7 +1620,7 @@ const getSuggestions = async () => {
|
||||
const wordQuery = inputField.value;
|
||||
const endpoint = `${url}${queryParams}${wordQuery}`;
|
||||
try {
|
||||
const response = await fetch(endpoint, { cache: "no-cache" });
|
||||
const response = await fetch(endpoint, { cache: 'no-cache' });
|
||||
if (response.ok) {
|
||||
const jsonResponse = await response.json();
|
||||
}
|
||||
|
||||
+42
-39
@@ -28,7 +28,10 @@ plugins:
|
||||
#### Official CDN
|
||||
|
||||
```html {.wrap}
|
||||
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
|
||||
<script
|
||||
src="https://code.jquery.com/jquery-3.5.1.min.js"
|
||||
crossorigin="anonymous"
|
||||
></script>
|
||||
```
|
||||
|
||||
### jQuery syntax
|
||||
@@ -40,11 +43,11 @@ $(selector).methodOrFunction();
|
||||
#### Example:
|
||||
|
||||
```javascript
|
||||
$("#menu").on("click", function () {
|
||||
$('#menu').on('click', function () {
|
||||
$(this).hide();
|
||||
});
|
||||
|
||||
$("body").css("background", "red");
|
||||
$('body').css('background', 'red');
|
||||
```
|
||||
|
||||
### jQuery document ready
|
||||
@@ -52,14 +55,14 @@ $("body").css("background", "red");
|
||||
```javascript
|
||||
$(document).ready(function () {
|
||||
// Runs after the DOM is loaded.
|
||||
alert("DOM fully loaded!");
|
||||
alert('DOM fully loaded!');
|
||||
});
|
||||
```
|
||||
|
||||
```javascript
|
||||
$(function () {
|
||||
// Runs after the DOM is loaded.
|
||||
alert("DOM fully loaded!");
|
||||
alert('DOM fully loaded!');
|
||||
});
|
||||
```
|
||||
|
||||
@@ -68,15 +71,15 @@ $(function () {
|
||||
### Examples {.secondary}
|
||||
|
||||
```javascript
|
||||
$("button").click(() => {
|
||||
$(":button").css("color", "red");
|
||||
$('button').click(() => {
|
||||
$(':button').css('color', 'red');
|
||||
});
|
||||
```
|
||||
|
||||
#### Combining selectors
|
||||
|
||||
```javascript
|
||||
$("selector1, selector2 ...selectorn");
|
||||
$('selector1, selector2 ...selectorn');
|
||||
```
|
||||
|
||||
### Basics
|
||||
@@ -175,32 +178,32 @@ $("selector1, selector2 ...selectorn");
|
||||
### Examples {.secondary .row-span-2}
|
||||
|
||||
```javascript
|
||||
$("h2").css({
|
||||
color: "blue",
|
||||
backgroundColor: "gray",
|
||||
fontSize: "24px",
|
||||
$('h2').css({
|
||||
color: 'blue',
|
||||
backgroundColor: 'gray',
|
||||
fontSize: '24px'
|
||||
});
|
||||
```
|
||||
|
||||
#### jQuery addClass
|
||||
|
||||
```javascript
|
||||
$(".button").addClass("active");
|
||||
$('.button').addClass('active');
|
||||
```
|
||||
|
||||
#### jQuery removeClass
|
||||
|
||||
```javascript
|
||||
$(".button").on("mouseleave", (evt) => {
|
||||
$('.button').on('mouseleave', (evt) => {
|
||||
let e = evt.currentTarget;
|
||||
$(e).removeClass("active");
|
||||
$(e).removeClass('active');
|
||||
});
|
||||
```
|
||||
|
||||
#### jQuery .toggleClass
|
||||
|
||||
```javascript
|
||||
$(".choice").toggleClass("highlighted");
|
||||
$('.choice').toggleClass('highlighted');
|
||||
```
|
||||
|
||||
### Attributes
|
||||
@@ -268,15 +271,15 @@ $(".choice").toggleClass("highlighted");
|
||||
|
||||
```javascript
|
||||
/*<span>Span.</span>*/
|
||||
$("span").after("<p>Paragraph.</p>");
|
||||
$('span').after('<p>Paragraph.</p>');
|
||||
/*<span>Span.</span><p>Paragraph.</p>*/
|
||||
|
||||
/*<span>Span.</span>*/
|
||||
$("<span>Span.</span>").replaceAll("p");
|
||||
$('<span>Span.</span>').replaceAll('p');
|
||||
/*<p>Span.</p>*/
|
||||
|
||||
/*<span>This is span.</span>*/
|
||||
$("span").wrap("<p></p>");
|
||||
$('span').wrap('<p></p>');
|
||||
/*<p><span>This is span.</span></p>*/
|
||||
```
|
||||
|
||||
@@ -389,25 +392,25 @@ $("span").wrap("<p></p>");
|
||||
|
||||
```javascript
|
||||
// A mouse event 'click'
|
||||
$("#menu-button").on("click", () => {
|
||||
$("#menu").show();
|
||||
$('#menu-button').on('click', () => {
|
||||
$('#menu').show();
|
||||
});
|
||||
|
||||
// A keyboard event 'keyup'
|
||||
$("#textbox").on("keyup", () => {
|
||||
$("#menu").show();
|
||||
$('#textbox').on('keyup', () => {
|
||||
$('#menu').show();
|
||||
});
|
||||
|
||||
// A scroll event 'scroll'
|
||||
$("#menu-button").on("scroll", () => {
|
||||
$("#menu").show();
|
||||
$('#menu-button').on('scroll', () => {
|
||||
$('#menu').show();
|
||||
});
|
||||
```
|
||||
|
||||
#### Event object
|
||||
|
||||
```javascript
|
||||
$("#menu").on("click", (event) => {
|
||||
$('#menu').on('click', (event) => {
|
||||
$(event.currentTarget).hide();
|
||||
});
|
||||
```
|
||||
@@ -415,19 +418,19 @@ $("#menu").on("click", (event) => {
|
||||
#### Method chaining
|
||||
|
||||
```javascript
|
||||
$("#menu-btn")
|
||||
.on("mouseenter", () => {
|
||||
$("#menu").show();
|
||||
$('#menu-btn')
|
||||
.on('mouseenter', () => {
|
||||
$('#menu').show();
|
||||
})
|
||||
.on("mouseleave", () => {
|
||||
$("#menu").hide();
|
||||
.on('mouseleave', () => {
|
||||
$('#menu').hide();
|
||||
});
|
||||
```
|
||||
|
||||
#### Prevents the event
|
||||
|
||||
```javascript
|
||||
$("p").click(function (event) {
|
||||
$('p').click(function (event) {
|
||||
event.stopPropagation();
|
||||
// Do something
|
||||
});
|
||||
@@ -537,18 +540,18 @@ $("p").click(function (event) {
|
||||
### Examples {.secondary .row-span-2}
|
||||
|
||||
```javascript
|
||||
$("#menu-button").on("click", () => {
|
||||
$('#menu-button').on('click', () => {
|
||||
// $('#menu').fadeIn(400, 'swing')
|
||||
$("#menu").fadeIn();
|
||||
$('#menu').fadeIn();
|
||||
});
|
||||
```
|
||||
|
||||
#### fadeOut effect
|
||||
|
||||
```javascript
|
||||
$("#menu-button").on("click", () => {
|
||||
$('#menu-button').on('click', () => {
|
||||
// $('#menu').fadeOut(400, 'swing')
|
||||
$("#menu").fadeOut();
|
||||
$('#menu').fadeOut();
|
||||
});
|
||||
```
|
||||
|
||||
@@ -606,13 +609,13 @@ $("#menu-button").on("click", () => {
|
||||
$.ajax({
|
||||
url: this.action,
|
||||
type: this.method,
|
||||
data: $(this).serialize(),
|
||||
data: $(this).serialize()
|
||||
})
|
||||
.done(function (server_data) {
|
||||
console.log("success" + server_data);
|
||||
console.log('success' + server_data);
|
||||
})
|
||||
.fail(function (jqXHR, status, err) {
|
||||
console.log("fail" + err);
|
||||
console.log('fail' + err);
|
||||
});
|
||||
```
|
||||
|
||||
|
||||
+21
-21
@@ -213,12 +213,12 @@ Begins with `[` and ends with `]`
|
||||
|
||||
```javascript
|
||||
let myObject = {
|
||||
name: "Jason",
|
||||
last: "Doe",
|
||||
name: 'Jason',
|
||||
last: 'Doe',
|
||||
age: 39,
|
||||
gender: "M",
|
||||
gender: 'M',
|
||||
salary: 70000,
|
||||
married: true,
|
||||
married: true
|
||||
};
|
||||
```
|
||||
|
||||
@@ -242,10 +242,10 @@ let myObject = {
|
||||
age: 2,
|
||||
gender: 3,
|
||||
salary: 4,
|
||||
married: 5,
|
||||
married: 5
|
||||
},
|
||||
jdoe: ["Jason", "Doe", 39, "M", 70000, true],
|
||||
jsmith: ["Tom", "Smith", 42, "F", 80000, true],
|
||||
jdoe: ['Jason', 'Doe', 39, 'M', 70000, true],
|
||||
jsmith: ['Tom', 'Smith', 42, 'F', 80000, true]
|
||||
};
|
||||
```
|
||||
|
||||
@@ -264,29 +264,29 @@ let myObject = {
|
||||
```javascript
|
||||
let myArray = [
|
||||
{
|
||||
name: "Jason",
|
||||
last: "Doe",
|
||||
name: 'Jason',
|
||||
last: 'Doe',
|
||||
age: 39,
|
||||
gender: "M",
|
||||
gender: 'M',
|
||||
salary: 70000,
|
||||
married: true,
|
||||
married: true
|
||||
},
|
||||
{
|
||||
name: "Tom",
|
||||
last: "Smith",
|
||||
name: 'Tom',
|
||||
last: 'Smith',
|
||||
age: 42,
|
||||
gender: "F",
|
||||
gender: 'F',
|
||||
salary: 80000,
|
||||
married: true,
|
||||
married: true
|
||||
},
|
||||
{
|
||||
name: "Amy",
|
||||
last: "Burnquist",
|
||||
name: 'Amy',
|
||||
last: 'Burnquist',
|
||||
age: 29,
|
||||
gender: "F",
|
||||
gender: 'F',
|
||||
salary: 60000,
|
||||
married: false,
|
||||
},
|
||||
married: false
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
@@ -303,7 +303,7 @@ let myArray = [
|
||||
### Access Array
|
||||
|
||||
```javascript
|
||||
let myArray = ["Jason", "Doe", 39, "M", 70000, true];
|
||||
let myArray = ['Jason', 'Doe', 39, 'M', 70000, true];
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -909,7 +909,6 @@ x = \begin{cases}
|
||||
\end{itemize}
|
||||
```
|
||||
|
||||
|
||||
### Ordered List
|
||||
|
||||
<!--rehype:style=flex:1;-->
|
||||
|
||||
@@ -143,7 +143,7 @@ ___
|
||||
|
||||
````markdown
|
||||
```javascript
|
||||
console.log("This is a block code");
|
||||
console.log('This is a block code');
|
||||
```
|
||||
````
|
||||
|
||||
@@ -228,7 +228,7 @@ A markdown table generator: [tableconvert.com](https://tableconvert.com/)
|
||||
```markdown
|
||||
![alt text][logo]
|
||||
|
||||
[logo]: /images/logo.png "Logo Title"
|
||||
[logo]: /images/logo.png 'Logo Title'
|
||||
```
|
||||
|
||||
### Backslash escapes
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
---
|
||||
title: MongoDB
|
||||
date: 2023-04-05
|
||||
background:
|
||||
bg-gradient-to-r from-green-900 via-green-600 to-green-400 hover:from-green-900 hover:via-green-700 hover:to-green-500
|
||||
background: bg-gradient-to-r from-green-900 via-green-600 to-green-400 hover:from-green-900 hover:via-green-700 hover:to-green-500
|
||||
tags:
|
||||
- NoSQL
|
||||
- DB
|
||||
@@ -91,14 +90,14 @@ db.coll.findOneAndDelete({"name": "Max"})
|
||||
|
||||
```mongosh
|
||||
db.coll.updateMany({"_id": 1}, {$set: {"year": 2016}}) // WARNING! Replaces the entire document where "_id" = 1
|
||||
db.coll.updateOne({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
|
||||
db.coll.updateOne({"_id": 1}, {$unset: {"year": 1}})
|
||||
db.coll.updateOne({"_id": 1}, {$rename: {"year": "date"} })
|
||||
db.coll.updateOne({"_id": 1}, {$inc: {"year": 5}})
|
||||
db.coll.updateOne({"_id": 1}, {$mul: {price: 2}})
|
||||
db.coll.updateOne({"_id": 1}, {$set: {"year": 2016, name: "Max"}})
|
||||
db.coll.updateOne({"_id": 1}, {$unset: {"year": 1}})
|
||||
db.coll.updateOne({"_id": 1}, {$rename: {"year": "date"} })
|
||||
db.coll.updateOne({"_id": 1}, {$inc: {"year": 5}})
|
||||
db.coll.updateOne({"_id": 1}, {$mul: {price: 2}})
|
||||
db.coll.updateOne({"_id": 1}, {$min: {"imdb": 5}})
|
||||
db.coll.updateOne({"_id": 1}, {$max: {"imdb": 8}})
|
||||
db.coll.updateMany({"_id": {$lt: 10}}, {$set: {"lastModified": ISODate()}})
|
||||
db.coll.updateOne({"_id": 1}, {$max: {"imdb": 8}})
|
||||
db.coll.updateMany({"_id": {$lt: 10}}, {$set: {"lastModified": ISODate()}})
|
||||
```
|
||||
|
||||
### Array {.row-span-2}
|
||||
|
||||
+122
-112
@@ -12,7 +12,8 @@ categories:
|
||||
- Productivity
|
||||
- Software
|
||||
intro:
|
||||
A comprehensive quick reference guide for Notion keyboard shortcuts on Desktop and Web, designed to boost your productivity.
|
||||
A comprehensive quick reference guide for Notion keyboard shortcuts on Desktop and Web, designed to boost your
|
||||
productivity.
|
||||
plugins:
|
||||
- copyCode
|
||||
---
|
||||
@@ -22,26 +23,30 @@ plugins:
|
||||
## Most Popular / Essential {.col-span-3}
|
||||
|
||||
### Create & Navigate
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :--------------------------- | :------------------------ | :----------------------- |
|
||||
| Create a new page | `Cmd` `N` | `Ctrl` `N` |
|
||||
| Open new Notion window | `Cmd` `Shift` `N` | `Ctrl` `Shift` `N` |
|
||||
| Quick Find (Search) | `Cmd` `P` | `Ctrl` `P` |
|
||||
| Go back in page history | `Cmd` `[` | `Ctrl` `[` |
|
||||
| Go forward in page history | `Cmd` `]` | `Ctrl` `]` |
|
||||
| Go to parent page | `Cmd` `Shift` `U` | `Ctrl` `Shift` `U` |
|
||||
| Open Page Link in New Tab | `Cmd` `Click` | `Ctrl` `Click` |
|
||||
| Open Page Link in New Window | `Option` `Shift` `Click` | `Alt` `Shift` `Click` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :--------------------------- | :----------------------- | :--------------------- |
|
||||
| Create a new page | `Cmd` `N` | `Ctrl` `N` |
|
||||
| Open new Notion window | `Cmd` `Shift` `N` | `Ctrl` `Shift` `N` |
|
||||
| Quick Find (Search) | `Cmd` `P` | `Ctrl` `P` |
|
||||
| Go back in page history | `Cmd` `[` | `Ctrl` `[` |
|
||||
| Go forward in page history | `Cmd` `]` | `Ctrl` `]` |
|
||||
| Go to parent page | `Cmd` `Shift` `U` | `Ctrl` `Shift` `U` |
|
||||
| Open Page Link in New Tab | `Cmd` `Click` | `Ctrl` `Click` |
|
||||
| Open Page Link in New Window | `Option` `Shift` `Click` | `Alt` `Shift` `Click` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
### View & Mode
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :--------------------------- | :------------------------ | :----------------------- |
|
||||
| Toggle Dark/Light Mode | `Cmd` `Shift` `L` | `Ctrl` `Shift` `L` |
|
||||
| Lock/Unlock current page | `Cmd` `Shift` `L` (Hold) | `Ctrl` `Shift` `L` (Hold)|
|
||||
| Zoom In | `Cmd` `+` | `Ctrl` `+` |
|
||||
| Zoom Out | `Cmd` `-` | `Ctrl` `-` |
|
||||
| Reset Zoom | `Cmd` `0` | `Ctrl` `0` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :----------------------- | :----------------------- | :------------------------ |
|
||||
| Toggle Dark/Light Mode | `Cmd` `Shift` `L` | `Ctrl` `Shift` `L` |
|
||||
| Lock/Unlock current page | `Cmd` `Shift` `L` (Hold) | `Ctrl` `Shift` `L` (Hold) |
|
||||
| Zoom In | `Cmd` `+` | `Ctrl` `+` |
|
||||
| Zoom Out | `Cmd` `-` | `Ctrl` `-` |
|
||||
| Reset Zoom | `Cmd` `0` | `Ctrl` `0` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
---
|
||||
@@ -49,64 +54,58 @@ plugins:
|
||||
# Markdown Style Formatting {.cols-1}
|
||||
|
||||
### On New Lines
|
||||
|
||||
Type the following at the beginning of an empty line, then press `Space`:
|
||||
|
||||
* `*`, `-`, or `+` : Bulleted list
|
||||
* `[]` : To-do checkbox (Note: just the characters, no `Cmd`/`Ctrl`)
|
||||
* `1.` : Numbered list
|
||||
* `#` : H1 heading
|
||||
* `##` : H2 heading
|
||||
* `###` : H3 heading
|
||||
* `>` : Toggle list
|
||||
* `"` : Quote block
|
||||
* `---` : Divider (three hyphens)
|
||||
* ```` ```` : Code block (three backticks)
|
||||
- `*`, `-`, or `+` : Bulleted list
|
||||
- `[]` : To-do checkbox (Note: just the characters, no `Cmd`/`Ctrl`)
|
||||
- `1.` : Numbered list
|
||||
- `#` : H1 heading
|
||||
- `##` : H2 heading
|
||||
- `###` : H3 heading
|
||||
- `>` : Toggle list
|
||||
- `"` : Quote block
|
||||
- `---` : Divider (three hyphens)
|
||||
- ` ` : Code block (three backticks)
|
||||
|
||||
### Inline
|
||||
* Wrap text with `**` or `__` for **Bold**.
|
||||
* Wrap text with `*` or `_` for *Italics*.
|
||||
* Wrap text with `~` for ~~Strikethrough~~.
|
||||
* Wrap text with `` ` `` for `inline code`.
|
||||
|
||||
- Wrap text with `**` or `__` for **Bold**.
|
||||
- Wrap text with `*` or `_` for _Italics_.
|
||||
- Wrap text with `~` for ~~Strikethrough~~.
|
||||
- Wrap text with `` ` `` for `inline code`.
|
||||
|
||||
---
|
||||
|
||||
# Text Formatting & Editing {.cols-2}
|
||||
|
||||
### Basic Formatting
|
||||
Select text first, then use the shortcut:
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :------------------------ | :----------------------- |
|
||||
| Bold | `Cmd` `B` | `Ctrl` `B` |
|
||||
| Italic | `Cmd` `I` | `Ctrl` `I` |
|
||||
| Underline | `Cmd` `U` | `Ctrl` `U` |
|
||||
| Strikethrough | `Cmd` `Shift` `S` | `Ctrl` `Shift` `S` |
|
||||
| Inline Code | `Cmd` `E` | `Ctrl` `E` |
|
||||
| Create Link | `Cmd` `K` | `Ctrl` `K` |
|
||||
| Change Color / Highlight | `Cmd` `Shift` `H` | `Ctrl` `Shift` `H` |
|
||||
| Clear Formatting | `Cmd` `\` | `Ctrl` `\` |
|
||||
{.show-header .shortcuts}
|
||||
|
||||
Select text first, then use the shortcut: | Action | Mac Shortcut | Windows/Linux Shortcut | |
|
||||
:------------------------- | :------------------------ | :----------------------- | | Bold | `Cmd` `B` | `Ctrl` `B` | |
|
||||
Italic | `Cmd` `I` | `Ctrl` `I` | | Underline | `Cmd` `U` | `Ctrl` `U` | | Strikethrough | `Cmd` `Shift` `S` | `Ctrl`
|
||||
`Shift` `S` | | Inline Code | `Cmd` `E` | `Ctrl` `E` | | Create Link | `Cmd` `K` | `Ctrl` `K` | | Change Color /
|
||||
Highlight | `Cmd` `Shift` `H` | `Ctrl` `Shift` `H` | | Clear Formatting | `Cmd` `\` | `Ctrl` `\` | {.show-header
|
||||
.shortcuts}
|
||||
|
||||
### Block Type Conversion
|
||||
Select the block(s) first, then use the shortcut:
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :------------------------ | :----------------------- |
|
||||
| Turn into Text block | `Cmd` `Option` `0` | `Ctrl` `Alt` `0` |
|
||||
| Turn into H1 Heading | `Cmd` `Option` `1` | `Ctrl` `Alt` `1` |
|
||||
| Turn into H2 Heading | `Cmd` `Option` `2` | `Ctrl` `Alt` `2` |
|
||||
| Turn into H3 Heading | `Cmd` `Option` `3` | `Ctrl` `Alt` `3` |
|
||||
| Turn into To-do list | `Cmd` `Option` `4` | `Ctrl` `Alt` `4` |
|
||||
| Turn into Bulleted list | `Cmd` `Option` `5` | `Ctrl` `Alt` `5` |
|
||||
| Turn into Numbered list | `Cmd` `Option` `6` | `Ctrl` `Alt` `6` |
|
||||
| Turn into Toggle list | `Cmd` `Option` `7` | `Ctrl` `Alt` `7` |
|
||||
| Turn into Code block | `Cmd` `Option` `8` | `Ctrl` `Alt` `8` |
|
||||
| Turn into Page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` |
|
||||
| Turn into Callout | `Cmd` `Option` `C` | `Ctrl` `Alt` `C` |
|
||||
{.show-header .shortcuts}
|
||||
|
||||
Select the block(s) first, then use the shortcut: | Action | Mac Shortcut | Windows/Linux Shortcut | |
|
||||
:------------------------- | :------------------------ | :----------------------- | | Turn into Text block | `Cmd`
|
||||
`Option` `0` | `Ctrl` `Alt` `0` | | Turn into H1 Heading | `Cmd` `Option` `1` | `Ctrl` `Alt` `1` | | Turn into H2
|
||||
Heading | `Cmd` `Option` `2` | `Ctrl` `Alt` `2` | | Turn into H3 Heading | `Cmd` `Option` `3` | `Ctrl` `Alt` `3` | |
|
||||
Turn into To-do list | `Cmd` `Option` `4` | `Ctrl` `Alt` `4` | | Turn into Bulleted list | `Cmd` `Option` `5` | `Ctrl`
|
||||
`Alt` `5` | | Turn into Numbered list | `Cmd` `Option` `6` | `Ctrl` `Alt` `6` | | Turn into Toggle list | `Cmd` `Option`
|
||||
`7` | `Ctrl` `Alt` `7` | | Turn into Code block | `Cmd` `Option` `8` | `Ctrl` `Alt` `8` | | Turn into Page | `Cmd`
|
||||
`Option` `9` | `Ctrl` `Alt` `9` | | Turn into Callout | `Cmd` `Option` `C` | `Ctrl` `Alt` `C` | {.show-header
|
||||
.shortcuts}
|
||||
|
||||
### Editing
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :------------------------ | :----------------------- |
|
||||
| New Line within same block | `Shift` `Enter` | `Shift` `Enter` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :-------------- | :--------------------- |
|
||||
| New Line within same block | `Shift` `Enter` | `Shift` `Enter` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
---
|
||||
@@ -114,32 +113,35 @@ Select the block(s) first, then use the shortcut:
|
||||
# Creating & Modifying Blocks {.cols-2}
|
||||
|
||||
### Creation & Selection
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------------------------ | :------------------------------- | :------------------------------ |
|
||||
| Create new text block below | `Enter` | `Enter` |
|
||||
| Open the `/` command menu | `/` | `/` |
|
||||
| Select current block | `Esc` | `Esc` |
|
||||
| Select parent block | `Shift` `Esc` | `Shift` `Esc` |
|
||||
| Select block above/below | `Up` / `Down` | `Up` / `Down` |
|
||||
| Select multiple blocks | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` |
|
||||
| Select all blocks | `Cmd` `A` | `Ctrl` `A` |
|
||||
| Edit selected block (or text within block) | `Enter` | `Enter` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :----------------------------------------- | :------------------ | :--------------------- |
|
||||
| Create new text block below | `Enter` | `Enter` |
|
||||
| Open the `/` command menu | `/` | `/` |
|
||||
| Select current block | `Esc` | `Esc` |
|
||||
| Select parent block | `Shift` `Esc` | `Shift` `Esc` |
|
||||
| Select block above/below | `Up` / `Down` | `Up` / `Down` |
|
||||
| Select multiple blocks | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` |
|
||||
| Select all blocks | `Cmd` `A` | `Ctrl` `A` |
|
||||
| Edit selected block (or text within block) | `Enter` | `Enter` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
|
||||
### Moving & Structuring
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------------------------ | :------------------------------- | :------------------------------ |
|
||||
| Duplicate selected block(s) | `Cmd` `D` | `Ctrl` `D` |
|
||||
| Move selected block(s) up/down | `Cmd` `Shift` `Up`/`Down` | `Ctrl` `Shift` `Up`/`Down` |
|
||||
| Indent block (nest) | `Tab` | `Tab` |
|
||||
| Un-indent block | `Shift` `Tab` | `Shift` `Tab` |
|
||||
| Expand/Collapse toggle list | `Cmd` `Option` `T` | `Ctrl` `Alt` `T` |
|
||||
| Expand/Collapse all toggles | `Cmd` `Option` `Shift` `T` | `Ctrl` `Alt` `Shift` `T` |
|
||||
| Open page from selected link/page block | `Cmd` `Enter` | `Ctrl` `Enter` |
|
||||
| Delete selected block(s) | `Delete` or `Backspace` | `Delete` or `Backspace` |
|
||||
| Turn block into a page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` |
|
||||
| Move block(s) to another page | `Cmd` `Option` `Shift` `M` | `Ctrl` `Alt` `Shift` `M` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :-------------------------------------- | :------------------------- | :------------------------- |
|
||||
| Duplicate selected block(s) | `Cmd` `D` | `Ctrl` `D` |
|
||||
| Move selected block(s) up/down | `Cmd` `Shift` `Up`/`Down` | `Ctrl` `Shift` `Up`/`Down` |
|
||||
| Indent block (nest) | `Tab` | `Tab` |
|
||||
| Un-indent block | `Shift` `Tab` | `Shift` `Tab` |
|
||||
| Expand/Collapse toggle list | `Cmd` `Option` `T` | `Ctrl` `Alt` `T` |
|
||||
| Expand/Collapse all toggles | `Cmd` `Option` `Shift` `T` | `Ctrl` `Alt` `Shift` `T` |
|
||||
| Open page from selected link/page block | `Cmd` `Enter` | `Ctrl` `Enter` |
|
||||
| Delete selected block(s) | `Delete` or `Backspace` | `Delete` or `Backspace` |
|
||||
| Turn block into a page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` |
|
||||
| Move block(s) to another page | `Cmd` `Option` `Shift` `M` | `Ctrl` `Alt` `Shift` `M` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
---
|
||||
@@ -147,24 +149,29 @@ Select the block(s) first, then use the shortcut:
|
||||
# Comments & Mentions {.cols-2}
|
||||
|
||||
### Comments
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :------------------------ | :----------------------- |
|
||||
| Add comment to selection | `Cmd` `Shift` `M` | `Ctrl` `Shift` `M` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :----------------------- | :---------------- | :--------------------- |
|
||||
| Add comment to selection | `Cmd` `Shift` `M` | `Ctrl` `Shift` `M` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
### Mentions & Links (Type in block)
|
||||
* `@` + person's name: Mention a person
|
||||
* `@` + page title: Mention/link a page
|
||||
* `[[` + page title: Link another page
|
||||
* `+` + page title: Link another page (alternative)
|
||||
* `@` + date (e.g., `@today`, `@next tuesday`, `@1/15`): Add a date mention
|
||||
* `@remind` + date + time (optional): Set a reminder
|
||||
|
||||
- `@` + person's name: Mention a person
|
||||
- `@` + page title: Mention/link a page
|
||||
- `[[` + page title: Link another page
|
||||
- `+` + page title: Link another page (alternative)
|
||||
- `@` + date (e.g., `@today`, `@next tuesday`, `@1/15`): Add a date mention
|
||||
- `@remind` + date + time (optional): Set a reminder
|
||||
|
||||
### Emoji
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :------------------------ | :----------------------- |
|
||||
| Emoji Picker (System) | `Cmd` `Ctrl` `Space` | `Win` `.` or `Win` `;` |
|
||||
| Emoji Picker (Notion) | `:` + emoji name + `:` | `:` + emoji name + `:` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :-------------------- | :--------------------- | :--------------------- |
|
||||
| Emoji Picker (System) | `Cmd` `Ctrl` `Space` | `Win` `.` or `Win` `;` |
|
||||
| Emoji Picker (Notion) | `:` + emoji name + `:` | `:` + emoji name + `:` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
---
|
||||
@@ -172,26 +179,29 @@ Select the block(s) first, then use the shortcut:
|
||||
# Database Shortcuts {.cols-2}
|
||||
|
||||
### Navigation & Selection
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :---------------------------------------- | :--------------------- | :---------------------- |
|
||||
| Select row above/below | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` |
|
||||
| Open selected page(s) | `Cmd` `Enter` | `Ctrl` `Enter` |
|
||||
| Edit property | `Enter` | `Enter` |
|
||||
| Move to cell above/below | `Shift` `Enter` | `Shift` `Enter` |
|
||||
| Move to cell left/right | `Tab` / `Shift` `Tab` | `Tab` / `Shift` `Tab` |
|
||||
| Select column | `Cmd` `Shift` `K` | `Ctrl` `Shift` `K` |
|
||||
| Select multiple cards/rows | `Shift` `Click` | `Shift` `Click` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :-------------------- | :--------------------- |
|
||||
| Select row above/below | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` |
|
||||
| Open selected page(s) | `Cmd` `Enter` | `Ctrl` `Enter` |
|
||||
| Edit property | `Enter` | `Enter` |
|
||||
| Move to cell above/below | `Shift` `Enter` | `Shift` `Enter` |
|
||||
| Move to cell left/right | `Tab` / `Shift` `Tab` | `Tab` / `Shift` `Tab` |
|
||||
| Select column | `Cmd` `Shift` `K` | `Ctrl` `Shift` `K` |
|
||||
| Select multiple cards/rows | `Shift` `Click` | `Shift` `Click` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
### Other
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :---------------------------------------- | :--------------------- | :---------------------- |
|
||||
| Quick Find within Database | `Cmd` `Shift` `P` | `Ctrl` `Shift` `P` |
|
||||
|
||||
| Action | Mac Shortcut | Windows/Linux Shortcut |
|
||||
| :------------------------- | :---------------- | :--------------------- |
|
||||
| Quick Find within Database | `Cmd` `Shift` `P` | `Ctrl` `Shift` `P` |
|
||||
|
||||
{.show-header .shortcuts}
|
||||
|
||||
---
|
||||
|
||||
## Also see
|
||||
|
||||
- [Official Notion Keyboard Shortcuts](https://www.notion.so/help/keyboard-shortcuts)
|
||||
_(notion.so)_
|
||||
- [Official Notion Keyboard Shortcuts](https://www.notion.so/help/keyboard-shortcuts) _(notion.so)_
|
||||
+26
-27
@@ -53,7 +53,7 @@ $ opam install hex
|
||||
#### Global Open
|
||||
|
||||
```ml
|
||||
open Hex
|
||||
open Hex
|
||||
```
|
||||
|
||||
#### Local Open
|
||||
@@ -61,7 +61,7 @@ open Hex
|
||||
```ml
|
||||
Hex.of_string "hex string"
|
||||
|
||||
let open Hex in
|
||||
let open Hex in
|
||||
of_string "to hex"
|
||||
```
|
||||
|
||||
@@ -73,7 +73,7 @@ let open Hex in
|
||||
(* A single line comment *)
|
||||
|
||||
(* A multi-line comment
|
||||
* where we want to explain
|
||||
* where we want to explain
|
||||
* something complex *)
|
||||
|
||||
(* Outer comment
|
||||
@@ -201,7 +201,7 @@ Lists are immutable
|
||||
Bundle related data
|
||||
|
||||
```ml
|
||||
type person = {
|
||||
type person = {
|
||||
name: string;
|
||||
age: int
|
||||
}
|
||||
@@ -215,7 +215,7 @@ val zeno : person = {name = "Zeno"; age = 30}
|
||||
Several different, but related types
|
||||
|
||||
```ml
|
||||
type shape =
|
||||
type shape =
|
||||
| Circle of float
|
||||
| Rectangle of float * float
|
||||
|
||||
@@ -225,8 +225,7 @@ type shape =
|
||||
|
||||
#### Aliases
|
||||
|
||||
Provide meaningful name
|
||||
to complex or commonly used types
|
||||
Provide meaningful name to complex or commonly used types
|
||||
|
||||
```ml
|
||||
type point = float * float
|
||||
@@ -242,7 +241,7 @@ val origin : point = (0., 0.)
|
||||
#### Single parameter
|
||||
|
||||
```ml
|
||||
let add_one x =
|
||||
let add_one x =
|
||||
let result = x + 1 in
|
||||
result
|
||||
|
||||
@@ -265,10 +264,10 @@ let sum x y =
|
||||
|
||||
```ml
|
||||
let str_concat (x, y) =
|
||||
x ^ " " ^ y
|
||||
x ^ " " ^ y
|
||||
|
||||
# str_concat ("Hello", "OCaml") ;;
|
||||
- : string = "Hello Ocaml"
|
||||
- : string = "Hello Ocaml"
|
||||
```
|
||||
|
||||
### Recursive Functions
|
||||
@@ -278,7 +277,7 @@ let str_concat (x, y) =
|
||||
All recusive functions use the rec keyword
|
||||
|
||||
```ml
|
||||
let rec factorial n =
|
||||
let rec factorial n =
|
||||
if n < 1 then 1 else n * factorial (n - 1)
|
||||
```
|
||||
|
||||
@@ -289,7 +288,7 @@ The above can cause stackoverflow.
|
||||
Makes use of a helper function and the acc argument.
|
||||
|
||||
```ml
|
||||
let rec factorial_helper n acc =
|
||||
let rec factorial_helper n acc =
|
||||
if n = 0 then acc
|
||||
else factorial_helper (n - 1) (n * acc)
|
||||
```
|
||||
@@ -316,7 +315,7 @@ Read from right to left, the first operation is `sum 2 3`
|
||||
|
||||
```ml
|
||||
(* find log((x + y)!) *)
|
||||
# sum 2 3
|
||||
# sum 2 3
|
||||
|> factorial
|
||||
|> float_of_int
|
||||
|> log ;;
|
||||
@@ -332,26 +331,26 @@ Read from right to left, the first operation is `sum 2 3`
|
||||
#### If Statement
|
||||
|
||||
```ml
|
||||
let is_pos x =
|
||||
let is_pos x =
|
||||
if x > 0 then "positive" else "negative"
|
||||
```
|
||||
|
||||
#### If else if
|
||||
|
||||
```ml
|
||||
let f x =
|
||||
let f x =
|
||||
if x > 3 then "gt 3"
|
||||
else if x < 3 then "lt 3"
|
||||
else "eq 3"
|
||||
else "eq 3"
|
||||
```
|
||||
|
||||
#### Pattern Matching
|
||||
|
||||
```ml
|
||||
let is_pos x =
|
||||
match x > 0 with
|
||||
let is_pos x =
|
||||
match x > 0 with
|
||||
| true -> "positive"
|
||||
| false -> "negative"
|
||||
| false -> "negative"
|
||||
```
|
||||
|
||||
### Loops
|
||||
@@ -360,7 +359,7 @@ let is_pos x =
|
||||
|
||||
```ml
|
||||
for i = 1 to 5 do
|
||||
print_int i
|
||||
print_int i
|
||||
done
|
||||
```
|
||||
|
||||
@@ -369,7 +368,7 @@ done
|
||||
Notice the `ref` is needed to have the while condition eventually become false.
|
||||
|
||||
```ml
|
||||
let i = ref 0 in
|
||||
let i = ref 0 in
|
||||
while !i < 5 do
|
||||
print_int !i;
|
||||
i := !i + 1
|
||||
@@ -393,7 +392,7 @@ let i = ref 0 in
|
||||
|
||||
```ml
|
||||
(* int operator float operator *)
|
||||
+ +. (* addition *)
|
||||
+ +. (* addition *)
|
||||
- -. (* subtraction *)
|
||||
* *. (* multiplication *)
|
||||
/ /. (* division *)
|
||||
@@ -440,7 +439,7 @@ List.fold_left (+) 0 lst
|
||||
#### Definition and Access
|
||||
|
||||
```ml
|
||||
let scores =
|
||||
let scores =
|
||||
[("math", 91); ("phil", 89); ("stats", 94)]
|
||||
|
||||
# List.assoc "stats" scores;;
|
||||
@@ -499,7 +498,7 @@ Maps are immutable key-value association tables.
|
||||
(* the Map.Make functor creates the custom map module *)
|
||||
# module StringMap = Map.Make(String);;
|
||||
|
||||
let books =
|
||||
let books =
|
||||
StringMap.empty
|
||||
|> StringMap.add "Dune" ("Herbet", 1965)
|
||||
|> StringMap.add "Neuromancer" ("Gibson", 1984)
|
||||
@@ -522,17 +521,17 @@ let books =
|
||||
Creates a new map since maps are immutable
|
||||
|
||||
```ml
|
||||
let more_books = books
|
||||
let more_books = books
|
||||
|> StringMap.add "Foundation" ("Isaac Asimov", 1951)
|
||||
|
||||
let less_books =
|
||||
let less_books =
|
||||
|> StringMap.remove "Dune"
|
||||
```
|
||||
|
||||
Filtering
|
||||
|
||||
```ml
|
||||
let eighties_books =
|
||||
let eighties_books =
|
||||
StringMap.filter
|
||||
(fun _ (_, year) -> year > 1980 & number < 1990) books
|
||||
```
|
||||
|
||||
+82
-84
@@ -1,5 +1,4 @@
|
||||
---
|
||||
|
||||
title: Pandas
|
||||
date: 2024-07-04
|
||||
background: bg-[#110750]
|
||||
@@ -12,7 +11,6 @@ intro: |
|
||||
[Pandas](https://pandas.pydata.org/) is a powerful data analysis and manipulation library for Python. This cheat sheet is a quick reference for Pandas beginners.
|
||||
plugins:
|
||||
- copyCode
|
||||
|
||||
---
|
||||
|
||||
## Getting Started {.cols-2}
|
||||
@@ -27,112 +25,112 @@ import pandas as pd
|
||||
|
||||
### Creating DataFrames
|
||||
|
||||
| - | - |
|
||||
| -------------------------------------------------------------- | --------------------------------------------------- |
|
||||
| `pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})` | From a dictionary |
|
||||
| `pd.DataFrame(data=[{'a': 1, 'b': 2}, {'a': 3, 'b': 4}])` | From a list of dictionaries |
|
||||
| `pd.read_csv('file.csv')` | From a CSV file |
|
||||
| `pd.read_excel('file.xlsx')` | From an Excel file |
|
||||
| - | - |
|
||||
| --------------------------------------------------------- | --------------------------- |
|
||||
| `pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})` | From a dictionary |
|
||||
| `pd.DataFrame(data=[{'a': 1, 'b': 2}, {'a': 3, 'b': 4}])` | From a list of dictionaries |
|
||||
| `pd.read_csv('file.csv')` | From a CSV file |
|
||||
| `pd.read_excel('file.xlsx')` | From an Excel file |
|
||||
|
||||
### Inspecting Data {.row-span-2}
|
||||
|
||||
| - | - |
|
||||
| ----------------------- | ------------------------------- |
|
||||
| `df.head()` | First 5 rows |
|
||||
| `df.tail()` | Last 5 rows |
|
||||
| `df.shape` | Number of rows and columns |
|
||||
| `df.info()` | Info on DataFrame |
|
||||
| `df.describe()` | Summary statistics |
|
||||
| `df.columns` | Column names |
|
||||
| `df.index` | Index |
|
||||
| `df.dtypes` | Data types of columns |
|
||||
| - | - |
|
||||
| --------------- | -------------------------- |
|
||||
| `df.head()` | First 5 rows |
|
||||
| `df.tail()` | Last 5 rows |
|
||||
| `df.shape` | Number of rows and columns |
|
||||
| `df.info()` | Info on DataFrame |
|
||||
| `df.describe()` | Summary statistics |
|
||||
| `df.columns` | Column names |
|
||||
| `df.index` | Index |
|
||||
| `df.dtypes` | Data types of columns |
|
||||
|
||||
### Selecting Data
|
||||
|
||||
| - | - |
|
||||
| ------------------------ | ------------------------------------------------- |
|
||||
| `df['col1']` | Select column |
|
||||
| `df[['col1', 'col2']]` | Select multiple columns |
|
||||
| `df.loc[0]` | Select row by index |
|
||||
| `df.loc[:, 'col1']` | Select all rows for 'col1' |
|
||||
| `df.iloc[0]` | Select row by position |
|
||||
| `df.iloc[0, 1]` | Select specific value |
|
||||
| `df[df['col1'] > 2]` | Select rows based on condition |
|
||||
| - | - |
|
||||
| ---------------------- | ------------------------------ |
|
||||
| `df['col1']` | Select column |
|
||||
| `df[['col1', 'col2']]` | Select multiple columns |
|
||||
| `df.loc[0]` | Select row by index |
|
||||
| `df.loc[:, 'col1']` | Select all rows for 'col1' |
|
||||
| `df.iloc[0]` | Select row by position |
|
||||
| `df.iloc[0, 1]` | Select specific value |
|
||||
| `df[df['col1'] > 2]` | Select rows based on condition |
|
||||
|
||||
### Data Cleaning
|
||||
|
||||
| - | - |
|
||||
| ---------------------------- | -------------------------------------- |
|
||||
| `df.dropna()` | Drop rows with any missing values |
|
||||
| `df.dropna(axis=1)` | Drop columns with any missing values |
|
||||
| `df.fillna(0)` | Replace missing values with 0 |
|
||||
| `df.drop_duplicates()` | Drop duplicate rows |
|
||||
| `df.rename(columns={'old_name': 'new_name'})` | Rename columns |
|
||||
| `df.astype('int')` | Change data type |
|
||||
| - | - |
|
||||
| --------------------------------------------- | ------------------------------------ |
|
||||
| `df.dropna()` | Drop rows with any missing values |
|
||||
| `df.dropna(axis=1)` | Drop columns with any missing values |
|
||||
| `df.fillna(0)` | Replace missing values with 0 |
|
||||
| `df.drop_duplicates()` | Drop duplicate rows |
|
||||
| `df.rename(columns={'old_name': 'new_name'})` | Rename columns |
|
||||
| `df.astype('int')` | Change data type |
|
||||
|
||||
### Adding/Removing Data {.row-span-2}
|
||||
|
||||
| - | - |
|
||||
| ----------------------------------- | ------------------------------ |
|
||||
| `df['col3'] = df['col1'] + df['col2']` | Add new column |
|
||||
| `df.drop('col1', axis=1)` | Drop column |
|
||||
| `df.append(new_row)` | Add new row |
|
||||
| `df.insert(2, 'new_col', new_data)` | Insert new column at position 2|
|
||||
| - | - |
|
||||
| -------------------------------------- | ------------------------------- |
|
||||
| `df['col3'] = df['col1'] + df['col2']` | Add new column |
|
||||
| `df.drop('col1', axis=1)` | Drop column |
|
||||
| `df.append(new_row)` | Add new row |
|
||||
| `df.insert(2, 'new_col', new_data)` | Insert new column at position 2 |
|
||||
|
||||
### Combining Data
|
||||
|
||||
| - | - |
|
||||
| --------------------------------------------- | ------------------------------------------------ |
|
||||
| `pd.concat([df1, df2])` | Concatenate rows |
|
||||
| `pd.concat([df1, df2], axis=1)` | Concatenate columns |
|
||||
| `pd.merge(df1, df2, on='key')` | Merge DataFrames on key |
|
||||
| `pd.merge(df1, df2, left_on='key1', right_on='key2')` | Merge on different keys |
|
||||
| `df1.join(df2, lsuffix='_left', rsuffix='_right')` | Join DataFrames |
|
||||
| - | - |
|
||||
| ----------------------------------------------------- | ----------------------- |
|
||||
| `pd.concat([df1, df2])` | Concatenate rows |
|
||||
| `pd.concat([df1, df2], axis=1)` | Concatenate columns |
|
||||
| `pd.merge(df1, df2, on='key')` | Merge DataFrames on key |
|
||||
| `pd.merge(df1, df2, left_on='key1', right_on='key2')` | Merge on different keys |
|
||||
| `df1.join(df2, lsuffix='_left', rsuffix='_right')` | Join DataFrames |
|
||||
|
||||
### Aggregating Data
|
||||
|
||||
| - | - |
|
||||
| ------------------------------------ | ------------------------------------------------ |
|
||||
| `df['col1'].sum()` | Sum of values in column |
|
||||
| `df['col1'].mean()` | Mean of values in column |
|
||||
| `df['col1'].count()` | Count of values in column |
|
||||
| `df['col1'].min()` | Minimum value in column |
|
||||
| `df['col1'].max()` | Maximum value in column |
|
||||
| `df['col1'].std()` | Standard deviation |
|
||||
| `df['col1'].var()` | Variance |
|
||||
| `df.groupby('col1').sum()` | Group by and sum |
|
||||
| `df.groupby('col1').mean()` | Group by and mean |
|
||||
| `df.groupby(['col1', 'col2']).count()` | Group by multiple columns |
|
||||
| - | - |
|
||||
| -------------------------------------- | ------------------------- |
|
||||
| `df['col1'].sum()` | Sum of values in column |
|
||||
| `df['col1'].mean()` | Mean of values in column |
|
||||
| `df['col1'].count()` | Count of values in column |
|
||||
| `df['col1'].min()` | Minimum value in column |
|
||||
| `df['col1'].max()` | Maximum value in column |
|
||||
| `df['col1'].std()` | Standard deviation |
|
||||
| `df['col1'].var()` | Variance |
|
||||
| `df.groupby('col1').sum()` | Group by and sum |
|
||||
| `df.groupby('col1').mean()` | Group by and mean |
|
||||
| `df.groupby(['col1', 'col2']).count()` | Group by multiple columns |
|
||||
|
||||
### Applying Functions {.row-span-2}
|
||||
|
||||
| - | - |
|
||||
| ---------------------------------- | ------------------------------------ |
|
||||
| `df.apply(np.sqrt)` | Apply function to all values |
|
||||
| `df['col1'].apply(lambda x: x ** 2)`| Apply function to column |
|
||||
| `df.applymap(str)` | Apply function to DataFrame elements |
|
||||
| `df['col1'].map({'a': 1, 'b': 2})` | Map values |
|
||||
| `df['col1'].replace('a', 1)` | Replace values |
|
||||
| - | - |
|
||||
| ------------------------------------ | ------------------------------------ |
|
||||
| `df.apply(np.sqrt)` | Apply function to all values |
|
||||
| `df['col1'].apply(lambda x: x ** 2)` | Apply function to column |
|
||||
| `df.applymap(str)` | Apply function to DataFrame elements |
|
||||
| `df['col1'].map({'a': 1, 'b': 2})` | Map values |
|
||||
| `df['col1'].replace('a', 1)` | Replace values |
|
||||
|
||||
### Handling Dates
|
||||
|
||||
| - | - |
|
||||
| ------------------------------------ | ------------------------------------------ |
|
||||
| `df['date'] = pd.to_datetime(df['date'])` | Convert to datetime |
|
||||
| `df['year'] = df['date'].dt.year` | Extract year |
|
||||
| `df['month'] = df['date'].dt.month` | Extract month |
|
||||
| `df['day'] = df['date'].dt.day` | Extract day |
|
||||
| `df.set_index('date', inplace=True)` | Set date as index |
|
||||
| - | - |
|
||||
| ----------------------------------------- | ------------------- |
|
||||
| `df['date'] = pd.to_datetime(df['date'])` | Convert to datetime |
|
||||
| `df['year'] = df['date'].dt.year` | Extract year |
|
||||
| `df['month'] = df['date'].dt.month` | Extract month |
|
||||
| `df['day'] = df['date'].dt.day` | Extract day |
|
||||
| `df.set_index('date', inplace=True)` | Set date as index |
|
||||
|
||||
### Input/Output
|
||||
|
||||
| - | - |
|
||||
| ------------------------------------ | ------------------------------------------------ |
|
||||
| `df.to_csv('file.csv')` | Save DataFrame to CSV |
|
||||
| `df = pd.read_csv('file.csv')` | Load DataFrame from CSV |
|
||||
| `df.to_excel('file.xlsx')` | Save DataFrame to Excel |
|
||||
| `df = pd.read_excel('file.xlsx')` | Load DataFrame from Excel |
|
||||
| `from sqlalchemy import create_engine`| Import SQLAlchemy for SQL operations |
|
||||
| `engine = create_engine('sqlite:///:memory:')` | Create SQL engine |
|
||||
| `df.to_sql('table_name', engine)` | Save to SQL table |
|
||||
| `df = pd.read_sql('table_name', engine)` | Load from SQL table |
|
||||
| - | - |
|
||||
| ---------------------------------------------- | ------------------------------------ |
|
||||
| `df.to_csv('file.csv')` | Save DataFrame to CSV |
|
||||
| `df = pd.read_csv('file.csv')` | Load DataFrame from CSV |
|
||||
| `df.to_excel('file.xlsx')` | Save DataFrame to Excel |
|
||||
| `df = pd.read_excel('file.xlsx')` | Load DataFrame from Excel |
|
||||
| `from sqlalchemy import create_engine` | Import SQLAlchemy for SQL operations |
|
||||
| `engine = create_engine('sqlite:///:memory:')` | Create SQL engine |
|
||||
| `df.to_sql('table_name', engine)` | Save to SQL table |
|
||||
| `df = pd.read_sql('table_name', engine)` | Load from SQL table |
|
||||
+1122
-1122
File diff suppressed because it is too large.
Load diff
@@ -7,8 +7,7 @@ tags:
|
||||
- reference
|
||||
categories:
|
||||
- Other
|
||||
intro:
|
||||
This is the magic syntax variant manual that you can use on CheatSheets.zip, It's a good practice for contributors.
|
||||
intro: This is the magic syntax variant manual that you can use on CheatSheets.zip, It's a good practice for contributors.
|
||||
plugins:
|
||||
- copyCode
|
||||
---
|
||||
|
||||
+90
-55
@@ -29,13 +29,13 @@ let emptyHeading = <h1 />;
|
||||
### JSX Expressions
|
||||
|
||||
```javascript
|
||||
let name = "Josh Perez";
|
||||
let name = 'Josh Perez';
|
||||
let element = <h1>Hello, {name}</h1>;
|
||||
|
||||
function fullName(firstName, lastName) {
|
||||
return firstName + " " + lastName;
|
||||
return firstName + ' ' + lastName;
|
||||
}
|
||||
let element = <h1>Hello, {fullName("Julie", "Johnson")}</h1>;
|
||||
let element = <h1>Hello, {fullName('Julie', 'Johnson')}</h1>;
|
||||
```
|
||||
|
||||
### JSX Attributes
|
||||
@@ -62,7 +62,7 @@ return (
|
||||
### JSX Conditional Rendering {.col-span-2}
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import React from 'react';
|
||||
function Weather(props) {
|
||||
if (props.temperature >= 20) {
|
||||
return (
|
||||
@@ -89,7 +89,7 @@ Note: A component must always return something.
|
||||
### Functional Component
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import React from 'react';
|
||||
|
||||
export default function UserProfile() {
|
||||
return (
|
||||
@@ -106,8 +106,8 @@ Note: Every component needs one root element
|
||||
### Embed an internal Component
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import UserAvatar from "./UserAvatar";
|
||||
import React from 'react';
|
||||
import UserAvatar from './UserAvatar';
|
||||
|
||||
export default function UserProfile() {
|
||||
return (
|
||||
@@ -124,8 +124,8 @@ Note: Assuming UserAvatar is declared in UserAvatar.js
|
||||
### Embed an external Component
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import ComponentName from "component-name";
|
||||
import React from 'react';
|
||||
import ComponentName from 'component-name';
|
||||
|
||||
export default function UserProfile() {
|
||||
return (
|
||||
@@ -141,7 +141,7 @@ Note: External components are found on npmjs.com and need to be imported first.
|
||||
### Advanced Functional Components
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import React from 'react';
|
||||
|
||||
function Hello(props) {
|
||||
function fullName() {
|
||||
@@ -170,7 +170,7 @@ export default () => <Hello firstName="Matt" lastName="Delac" />;
|
||||
### Assigning the Properties from a Component
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import React from 'react';
|
||||
|
||||
export default function Student(props) {
|
||||
return (
|
||||
@@ -186,12 +186,12 @@ export default function Student(props) {
|
||||
### React State
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
import React, { useState } from 'react';
|
||||
|
||||
export default function Hello(props) {
|
||||
let [name, setName] = useState("Julie");
|
||||
let [name, setName] = useState('Julie');
|
||||
function updateName() {
|
||||
let newName = prompt("What is your name?");
|
||||
let newName = prompt('What is your name?');
|
||||
setName(newName);
|
||||
}
|
||||
|
||||
@@ -209,12 +209,12 @@ export default function Hello(props) {
|
||||
### Event Listener
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import React from 'react';
|
||||
|
||||
export default function Hello() {
|
||||
function handleClick(event) {
|
||||
event.preventDefault();
|
||||
alert("Hello World");
|
||||
alert('Hello World');
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -232,7 +232,7 @@ Note: The most common event listeners are onClick for links/buttons and onSubmit
|
||||
### Looping through an Array
|
||||
|
||||
```javascript
|
||||
let elements = ["one", "two", "three"];
|
||||
let elements = ['one', 'two', 'three'];
|
||||
|
||||
return (
|
||||
<ul>
|
||||
@@ -250,17 +250,17 @@ Note: Each list item inside a map loop needs a key attribute with a unique value
|
||||
```javascript
|
||||
let elements = [
|
||||
{
|
||||
name: "one",
|
||||
value: 1,
|
||||
name: 'one',
|
||||
value: 1
|
||||
},
|
||||
{
|
||||
name: "two",
|
||||
value: 2,
|
||||
name: 'two',
|
||||
value: 2
|
||||
},
|
||||
{
|
||||
name: "three",
|
||||
value: 3,
|
||||
},
|
||||
name: 'three',
|
||||
value: 3
|
||||
}
|
||||
];
|
||||
return (
|
||||
<ul>
|
||||
@@ -282,11 +282,11 @@ Note: Each list item inside a map loop needs a key attribute with a unique value
|
||||
### React Forms
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
import React, { useState } from 'react';
|
||||
|
||||
export default function LoginForm() {
|
||||
let [username, setUsername] = useState("");
|
||||
let [password, setPassword] = useState("");
|
||||
let [username, setUsername] = useState('');
|
||||
let [password, setPassword] = useState('');
|
||||
|
||||
function handleSubmit(event) {
|
||||
event.preventDefault();
|
||||
@@ -316,8 +316,8 @@ export default function LoginForm() {
|
||||
### CSS in a React Component
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import "./Student.css";
|
||||
import React from 'react';
|
||||
import './Student.css';
|
||||
|
||||
export default function Student() {
|
||||
return <div className="Student">Julie Johnson</div>;
|
||||
@@ -331,8 +331,8 @@ Note: You'll then have to crate a css file called Student.css
|
||||
### AJAX Request with Axios
|
||||
|
||||
```javascript
|
||||
import React from "react";
|
||||
import axios from "axios";
|
||||
import React from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
export default function Weather(props) {
|
||||
function handleResponse(response) {
|
||||
@@ -356,7 +356,7 @@ Note: Make sure to import Axios first to your project.
|
||||
### useState Hook
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
import React, { useState } from 'react';
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
@@ -378,11 +378,11 @@ way to declare state variables and update them within a functional component. Ex
|
||||
### Multiple State Variable Declaration
|
||||
|
||||
```javascript
|
||||
import React, { useState } from "react";
|
||||
import React, { useState } from 'react';
|
||||
|
||||
function Counter() {
|
||||
const [count, setCount] = useState(0);
|
||||
const [name, setName] = useState("");
|
||||
const [name, setName] = useState('');
|
||||
const [isCompleted, setIsCompleted] = useState(false);
|
||||
|
||||
const handleIncrement = () => {
|
||||
@@ -402,10 +402,19 @@ function Counter() {
|
||||
<p>Count: {count}</p>
|
||||
<button onClick={handleIncrement}>Increment</button>
|
||||
|
||||
<input type="text" value={name} onChange={handleNameChange} placeholder="Enter your name" />
|
||||
<input
|
||||
type="text"
|
||||
value={name}
|
||||
onChange={handleNameChange}
|
||||
placeholder="Enter your name"
|
||||
/>
|
||||
|
||||
<label>
|
||||
<input type="checkbox" checked={isCompleted} onChange={toggleCompletion} />
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isCompleted}
|
||||
onChange={toggleCompletion}
|
||||
/>
|
||||
Completed
|
||||
</label>
|
||||
</div>
|
||||
@@ -421,10 +430,14 @@ component. Each call to useState manages a separate piece of state.
|
||||
### Input State Management
|
||||
|
||||
```javascript
|
||||
import { useState } from "react";
|
||||
import { useState } from 'react';
|
||||
|
||||
function FormExample() {
|
||||
const [formData, setFormData] = useState({ name: "", email: "", message: "" });
|
||||
const [formData, setFormData] = useState({
|
||||
name: '',
|
||||
email: '',
|
||||
message: ''
|
||||
});
|
||||
|
||||
const handleChange = (event) => {
|
||||
const { name, value } = event.target;
|
||||
@@ -433,19 +446,38 @@ function FormExample() {
|
||||
|
||||
const handleSubmit = (event) => {
|
||||
event.preventDefault();
|
||||
alert(`Name: ${formData.name}, Email: ${formData.email}, Message: ${formData.message}`);
|
||||
alert(
|
||||
`Name: ${formData.name}, Email: ${formData.email}, Message: ${formData.message}`
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label htmlFor="name">Name:</label>
|
||||
<input type="text" id="name" name="name" value={formData.name} onChange={handleChange} />
|
||||
<input
|
||||
type="text"
|
||||
id="name"
|
||||
name="name"
|
||||
value={formData.name}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
|
||||
<label htmlFor="email">Email:</label>
|
||||
<input type="email" id="email" name="email" value={formData.email} onChange={handleChange} />
|
||||
<input
|
||||
type="email"
|
||||
id="email"
|
||||
name="email"
|
||||
value={formData.email}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
|
||||
<label htmlFor="message">Message:</label>
|
||||
<textarea id="message" name="message" value={formData.message} onChange={handleChange} />
|
||||
<textarea
|
||||
id="message"
|
||||
name="message"
|
||||
value={formData.message}
|
||||
onChange={handleChange}
|
||||
/>
|
||||
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
@@ -458,7 +490,7 @@ export default FormExample;
|
||||
### useEffect Hook
|
||||
|
||||
```javascript
|
||||
import React, { useState, useEffect } from "react";
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
function Timer() {
|
||||
const [seconds, setSeconds] = useState(0);
|
||||
@@ -483,20 +515,20 @@ code based on component lifecycle events like mounting, updating, and unmounting
|
||||
### Fetch API using useEffect
|
||||
|
||||
```javascript
|
||||
import React, { useState, useEffect } from "react";
|
||||
import axios from "axios";
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import axios from 'axios';
|
||||
|
||||
function UserList() {
|
||||
const [users, setUsers] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
axios
|
||||
.get("https://jsonplaceholder.typicode.com/users")
|
||||
.get('https://jsonplaceholder.typicode.com/users')
|
||||
.then((response) => {
|
||||
setUsers(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("Error fetching users:", error);
|
||||
console.error('Error fetching users:', error);
|
||||
});
|
||||
}, []);
|
||||
|
||||
@@ -520,7 +552,7 @@ Note: Make sure to import Axios first to your project.
|
||||
### Custom Hook creation useLocalStorage
|
||||
|
||||
```javascript
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
function useLocalStorage(key, initialValue) {
|
||||
const [value, setValue] = useState(() => {
|
||||
@@ -544,7 +576,7 @@ to extract stateful logic from components into standalone functions.
|
||||
### Creating Refs in Class Components
|
||||
|
||||
```javascript
|
||||
import React, { Component } from "react";
|
||||
import React, { Component } from 'react';
|
||||
|
||||
class MyComponent extends Component {
|
||||
constructor(props) {
|
||||
@@ -567,7 +599,7 @@ export default MyComponent;
|
||||
### Using Refs in Functional Components
|
||||
|
||||
```javascript
|
||||
import React, { useRef, useEffect } from "react";
|
||||
import React, { useRef, useEffect } from 'react';
|
||||
|
||||
function MyComponent() {
|
||||
const myRef = useRef(null);
|
||||
@@ -585,7 +617,7 @@ export default MyComponent;
|
||||
### Callback Refs
|
||||
|
||||
```javascript
|
||||
import React, { Component } from "react";
|
||||
import React, { Component } from 'react';
|
||||
|
||||
class MyComponent extends Component {
|
||||
constructor(props) {
|
||||
@@ -628,7 +660,7 @@ const ref = React.createRef();
|
||||
### Accessing DOM Elements with Refs
|
||||
|
||||
```javascript
|
||||
import React, { useRef, useEffect } from "react";
|
||||
import React, { useRef, useEffect } from 'react';
|
||||
|
||||
function FocusInput() {
|
||||
const inputRef = useRef(null);
|
||||
@@ -643,19 +675,21 @@ function FocusInput() {
|
||||
|
||||
export default FocusInput;
|
||||
```
|
||||
Note: Refs are often used to access and interact with DOM elements directly. Here's an example where we focus an input element using a ref.
|
||||
|
||||
Note: Refs are often used to access and interact with DOM elements directly. Here's an example where we focus an input
|
||||
element using a ref.
|
||||
|
||||
### Managing Focus with Refs
|
||||
|
||||
```javascript
|
||||
import React, { useRef } from "react";
|
||||
import React, { useRef } from 'react';
|
||||
|
||||
function Form() {
|
||||
const firstInputRef = useRef(null);
|
||||
const secondInputRef = useRef(null);
|
||||
|
||||
const handleKeyDown = (e) => {
|
||||
if (e.key === "Enter") {
|
||||
if (e.key === 'Enter') {
|
||||
secondInputRef.current.focus();
|
||||
}
|
||||
};
|
||||
@@ -670,4 +704,5 @@ function Form() {
|
||||
|
||||
export default Form;
|
||||
```
|
||||
|
||||
Note: You can also manage focus between multiple elements using refs.
|
||||
+27
-27
@@ -64,23 +64,23 @@ This is a quick cheat sheet to getting started with regular expressions.
|
||||
| `a*+` | Possessive quantifier |
|
||||
|
||||
### Common Metacharacters
|
||||
| Pattern | Description |
|
||||
| -------- | :----------------------------------------- |
|
||||
| `^` | Matches the start of a string. |
|
||||
| `{` | Starts a quantifier for the number of occurrences. |
|
||||
| `+` | Matches one or more of the preceding element. |
|
||||
| `<` | Not a standard regex meta character (commonly used in HTML). |
|
||||
| `[` | Starts a character class. |
|
||||
| `*` | Matches zero or more of the preceding element. |
|
||||
| `)` | Ends a capturing group. |
|
||||
| `>` | Not a standard regex meta character (commonly used in HTML). |
|
||||
| `.` | Matches any character except a newline. |
|
||||
| `(` | Starts a capturing group. |
|
||||
| `|` | Acts as a logical OR within a regex pattern. |
|
||||
| `$` | Matches the end of a string. |
|
||||
| `\` | Escapes a meta character, giving it literal meaning. |
|
||||
| `?` | Matches zero or one of the preceding element. |
|
||||
|
||||
| Pattern | Description |
|
||||
| ------- | :----------------------------------------------------------- | -------------------------------------------- |
|
||||
| `^` | Matches the start of a string. |
|
||||
| `{` | Starts a quantifier for the number of occurrences. |
|
||||
| `+` | Matches one or more of the preceding element. |
|
||||
| `<` | Not a standard regex meta character (commonly used in HTML). |
|
||||
| `[` | Starts a character class. |
|
||||
| `*` | Matches zero or more of the preceding element. |
|
||||
| `)` | Ends a capturing group. |
|
||||
| `>` | Not a standard regex meta character (commonly used in HTML). |
|
||||
| `.` | Matches any character except a newline. |
|
||||
| `(` | Starts a capturing group. |
|
||||
| ` | ` | Acts as a logical OR within a regex pattern. |
|
||||
| `$` | Matches the end of a string. |
|
||||
| `\` | Escapes a meta character, giving it literal meaning. |
|
||||
| `?` | Matches zero or one of the preceding element. |
|
||||
|
||||
{.cols-3 .marker-none}
|
||||
|
||||
@@ -530,8 +530,8 @@ False
|
||||
### test()
|
||||
|
||||
```javascript
|
||||
let textA = "I like APPles very much";
|
||||
let textB = "I like APPles";
|
||||
let textA = 'I like APPles very much';
|
||||
let textB = 'I like APPles';
|
||||
let regex = /apples$/i;
|
||||
|
||||
// Output: false
|
||||
@@ -544,7 +544,7 @@ console.log(regex.test(textB));
|
||||
### search()
|
||||
|
||||
```javascript
|
||||
let text = "I like APPles very much";
|
||||
let text = 'I like APPles very much';
|
||||
let regexA = /apples/;
|
||||
let regexB = /apples/i;
|
||||
|
||||
@@ -558,7 +558,7 @@ console.log(text.search(regexB));
|
||||
### exec()
|
||||
|
||||
```javascript
|
||||
let text = "Do you like apples?";
|
||||
let text = 'Do you like apples?';
|
||||
let regex = /apples/;
|
||||
|
||||
// Output: apples
|
||||
@@ -571,7 +571,7 @@ console.log(regex.exec(text).input);
|
||||
### match()
|
||||
|
||||
```javascript
|
||||
let text = "Here are apples and apPleS";
|
||||
let text = 'Here are apples and apPleS';
|
||||
let regex = /apples/gi;
|
||||
|
||||
// Output: [ "apples", "apPleS" ]
|
||||
@@ -581,7 +581,7 @@ console.log(text.match(regex));
|
||||
### split() {.col-span-2}
|
||||
|
||||
```javascript
|
||||
let text = "This 593 string will be brok294en at places where d1gits are.";
|
||||
let text = 'This 593 string will be brok294en at places where d1gits are.';
|
||||
let regex = /\d+/g;
|
||||
|
||||
// Output: [ "This ", " string will be brok", "en at places where d", "gits are." ]
|
||||
@@ -592,7 +592,7 @@ console.log(text.split(regex));
|
||||
|
||||
```javascript
|
||||
let regex = /t(e)(st(\d?))/g;
|
||||
let text = "test1test2";
|
||||
let text = 'test1test2';
|
||||
let array = [...text.matchAll(regex)];
|
||||
|
||||
// Output: ["test1", "e", "st1", "1"]
|
||||
@@ -605,11 +605,11 @@ console.log(array[1]);
|
||||
### replace()
|
||||
|
||||
```javascript {.wrap}
|
||||
let text = "Do you like aPPles?";
|
||||
let text = 'Do you like aPPles?';
|
||||
let regex = /apples/i;
|
||||
|
||||
// Output: Do you like mangoes?
|
||||
let result = text.replace(regex, "mangoes");
|
||||
let result = text.replace(regex, 'mangoes');
|
||||
console.log(result);
|
||||
```
|
||||
|
||||
@@ -617,10 +617,10 @@ console.log(result);
|
||||
|
||||
```javascript
|
||||
let regex = /apples/gi;
|
||||
let text = "Here are apples and apPleS";
|
||||
let text = 'Here are apples and apPleS';
|
||||
|
||||
// Output: Here are mangoes and mangoes
|
||||
let result = text.replaceAll(regex, "mangoes");
|
||||
let result = text.replaceAll(regex, 'mangoes');
|
||||
console.log(result);
|
||||
```
|
||||
|
||||
|
||||
@@ -108,11 +108,11 @@ text: {
|
||||
### @import
|
||||
|
||||
```scss
|
||||
@import "./other_sass_file";
|
||||
@import "/code", "lists";
|
||||
@import './other_sass_file';
|
||||
@import '/code', 'lists';
|
||||
|
||||
// Plain CSS @imports
|
||||
@import "theme.css";
|
||||
@import 'theme.css';
|
||||
@import url(theme);
|
||||
```
|
||||
|
||||
@@ -349,7 +349,7 @@ $menu-items: home about contact;
|
||||
|
||||
@each $item in $menu-items {
|
||||
.photo-#{$item} {
|
||||
background: url("#{$item}.jpg");
|
||||
background: url('#{$item}.jpg');
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -357,7 +357,7 @@ $menu-items: home about contact;
|
||||
### Each loops (nested)
|
||||
|
||||
```scss
|
||||
$backgrounds: (home, "home.jpg"), (about, "about.jpg");
|
||||
$backgrounds: (home, 'home.jpg'), (about, 'about.jpg');
|
||||
|
||||
@each $id, $image in $backgrounds {
|
||||
.photo-#{$id} {
|
||||
@@ -383,10 +383,10 @@ $i: 6;
|
||||
### Conditionals {.row-span-2}
|
||||
|
||||
```scss
|
||||
@if $position == "left" {
|
||||
@if $position == 'left' {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
} @else if $position == "right" {
|
||||
} @else if $position == 'right' {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
} @else {
|
||||
|
||||
+9
-14
@@ -143,12 +143,7 @@ Note: External components should be installed via npm first.
|
||||
### Passing Properties to a Component
|
||||
|
||||
```js
|
||||
<Student
|
||||
firstName="Zehan"
|
||||
lastName="Khan"
|
||||
age={23}
|
||||
pro={true}
|
||||
/>
|
||||
<Student firstName="Zehan" lastName="Khan" age={23} pro={true} />
|
||||
```
|
||||
|
||||
### Assigning the Properties from a Component
|
||||
@@ -304,6 +299,7 @@ Note: Use `onMount` for side effects like API calls.
|
||||
## Lifecycle Hooks {.cols-1}
|
||||
|
||||
### onMount
|
||||
|
||||
```js
|
||||
<script>
|
||||
import { onMount } from 'svelte';
|
||||
@@ -315,6 +311,7 @@ Note: Use `onMount` for side effects like API calls.
|
||||
```
|
||||
|
||||
### beforeUpdate
|
||||
|
||||
```js
|
||||
<script>
|
||||
import { beforeUpdate } from 'svelte';
|
||||
@@ -326,6 +323,7 @@ Note: Use `onMount` for side effects like API calls.
|
||||
```
|
||||
|
||||
### afterUpdate
|
||||
|
||||
```js
|
||||
<script>
|
||||
import { afterUpdate } from 'svelte';
|
||||
@@ -337,6 +335,7 @@ Note: Use `onMount` for side effects like API calls.
|
||||
```
|
||||
|
||||
### onDestroy
|
||||
|
||||
```js
|
||||
<script>
|
||||
import { onDestroy } from 'svelte';
|
||||
@@ -346,8 +345,9 @@ Note: Use `onMount` for side effects like API calls.
|
||||
});
|
||||
</script>
|
||||
```
|
||||
Note: Svelte lifecycle functions are similar to React Hooks, but they are imported individually and used directly in the `<script>` block.
|
||||
|
||||
Note: Svelte lifecycle functions are similar to React Hooks, but they are imported individually and used directly in the
|
||||
`<script>` block.
|
||||
|
||||
## More Svelte Features {.cols-1}
|
||||
|
||||
@@ -358,7 +358,7 @@ Note: Svelte lifecycle functions are similar to React Hooks, but they are import
|
||||
import { writable, derived } from 'svelte/store';
|
||||
|
||||
export const count = writable(0);
|
||||
export const double = derived(count, $count => $count * 2);
|
||||
export const double = derived(count, ($count) => $count * 2);
|
||||
```
|
||||
|
||||
```js
|
||||
@@ -402,11 +402,7 @@ export const time = readable(new Date(), function start(set) {
|
||||
### Reactive Statements with Side Effects
|
||||
|
||||
```js
|
||||
<script>
|
||||
let name = 'Zehan';
|
||||
|
||||
$: console.log('Name changed to', name);
|
||||
</script>
|
||||
<script>let name = 'Zehan'; $: console.log('Name changed to', name);</script>
|
||||
```
|
||||
|
||||
### Bind to DOM Properties
|
||||
@@ -488,4 +484,3 @@ export async function load({ fetch }) {
|
||||
```
|
||||
|
||||
Note: Requires SvelteKit setup for SSR routes.
|
||||
|
||||
+17
-8
@@ -1571,11 +1571,13 @@ enum ShirtSize: String {
|
||||
|
||||
### What are extensions?
|
||||
|
||||
Extensions is a way to add new add new functionality to existing classes, structures, enumerations, or protocol types. This includes adding new methods, properties, initializers, and more.
|
||||
Extensions is a way to add new add new functionality to existing classes, structures, enumerations, or protocol types.
|
||||
This includes adding new methods, properties, initializers, and more.
|
||||
|
||||
### Why use extensions?
|
||||
|
||||
Extensions are particularly useful for organizing and modularizing our code without needing to modify the original type, especially when we don't have access to the original source code.
|
||||
Extensions are particularly useful for organizing and modularizing our code without needing to modify the original type,
|
||||
especially when we don't have access to the original source code.
|
||||
|
||||
### Extension syntax
|
||||
|
||||
@@ -1657,7 +1659,8 @@ print("Swift"[4]) // Output: t
|
||||
|
||||
### Protocol extensions {.row-span-2}
|
||||
|
||||
It works pretty much like abstract classes when regarding a functionality we want to be available in all the classes that implements some protocol (without having to inherit from a base common class).
|
||||
It works pretty much like abstract classes when regarding a functionality we want to be available in all the classes
|
||||
that implements some protocol (without having to inherit from a base common class).
|
||||
|
||||
```swift
|
||||
// Define a protocol
|
||||
@@ -1701,7 +1704,8 @@ print(employee.describe()) // Output: This is a generic description
|
||||
|
||||
### Constraints for extensions
|
||||
|
||||
This is especially useful when we want to add functionality to a type that conforms to a specific protocol or has certain conditions.
|
||||
This is especially useful when we want to add functionality to a type that conforms to a specific protocol or has
|
||||
certain conditions.
|
||||
|
||||
```swift
|
||||
extension Array where Element: Numeric {
|
||||
@@ -1723,7 +1727,8 @@ print(doubles.sum()) // Output: 7.5
|
||||
|
||||
### Organizing code with extensions
|
||||
|
||||
Extensions are not limited to adding functionality; they are also handy for code organization. We can group related methods, properties or views in separate extensions.
|
||||
Extensions are not limited to adding functionality; they are also handy for code organization. We can group related
|
||||
methods, properties or views in separate extensions.
|
||||
|
||||
```swift
|
||||
import SwiftUI
|
||||
@@ -1752,11 +1757,13 @@ extension HomeView {
|
||||
|
||||
### What are generics?
|
||||
|
||||
Generics in Swift are a feature that allows us to create functions, classes, structures, and protocols that can work with any data type.
|
||||
Generics in Swift are a feature that allows us to create functions, classes, structures, and protocols that can work
|
||||
with any data type.
|
||||
|
||||
### Why use generics?
|
||||
|
||||
Generics enable us to write clear and concise code that works with any data type. By using placeholders (like `T`), this reduces the risk of introducing bugs.
|
||||
Generics enable us to write clear and concise code that works with any data type. By using placeholders (like `T`), this
|
||||
reduces the risk of introducing bugs.
|
||||
|
||||
### Type parameters {.row-span-2}
|
||||
|
||||
@@ -1831,7 +1838,9 @@ protocol Foo {
|
||||
}
|
||||
```
|
||||
|
||||
Associated types are used in protocols to define a placeholder for a type that will be specified later. They act as a generic placeholder. The exact type isn't defined in the protocol itself; instead, it's determined when a class, struct, or enum conforms to the protocol.
|
||||
Associated types are used in protocols to define a placeholder for a type that will be specified later. They act as a
|
||||
generic placeholder. The exact type isn't defined in the protocol itself; instead, it's determined when a class, struct,
|
||||
or enum conforms to the protocol.
|
||||
|
||||
### Generic Protocols {.row-span-2}
|
||||
|
||||
|
||||
@@ -100,15 +100,13 @@ $ tmux show-options -g
|
||||
| `q` | Quit copy mode |
|
||||
| `Ctrl+b` `]` | Paste contents of buffer_0 |
|
||||
|
||||
-------------
|
||||
For tmux version 3.5a on MacOS 15.3.1 Sequoia 'Copy Mode' functions lil bit differently
|
||||
Below I've written the differences
|
||||
| Command | Description |
|
||||
| ------------ | -------------------------- |
|
||||
| `Ctrl + <Space>` | Start selection |
|
||||
| `Ctrl + w` | Copy selection |
|
||||
---
|
||||
|
||||
-------------
|
||||
For tmux version 3.5a on MacOS 15.3.1 Sequoia 'Copy Mode' functions lil bit differently Below I've written the
|
||||
differences | Command | Description | | ------------ | -------------------------- | | `Ctrl + <Space>` | Start selection
|
||||
| | `Ctrl + w` | Copy selection |
|
||||
|
||||
---
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
|
||||
+331
-327
@@ -1,327 +1,331 @@
|
||||
---
|
||||
title: TypeScript
|
||||
date: 2024-05-28 22:12:25
|
||||
background: bg-[#4476c0]
|
||||
tags:
|
||||
- ts
|
||||
- web
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
A TypeScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
|
||||
plugins:
|
||||
- copyCode
|
||||
- runCode
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installing the Compiler
|
||||
|
||||
```shell
|
||||
npm install typescript --save-dev
|
||||
npm tsc
|
||||
```
|
||||
|
||||
## Basic DataTypes
|
||||
|
||||
### basic types
|
||||
|
||||
```ts
|
||||
let isDone: boolean = false;
|
||||
let age: number = 30;
|
||||
let userName: string = "John";
|
||||
let list: number[] = [1, 2, 3];
|
||||
let tuple: [string, number] = ["hello", 10];
|
||||
let notSure: any = 4;
|
||||
notSure = "maybe a string instead";
|
||||
```
|
||||
|
||||
### enums
|
||||
|
||||
```ts
|
||||
enum Color {
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
let c: Color = Color.Green;
|
||||
```
|
||||
|
||||
### interface
|
||||
|
||||
```ts
|
||||
interface Person {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
age?: number; // Optional property
|
||||
}
|
||||
|
||||
function greet(person: Person) {
|
||||
return "Hello, " + person.firstName + " " + person.lastName;
|
||||
}
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
```ts
|
||||
function add(x: number, y: number): number {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
let myAdd = function (x: number, y: number): number {
|
||||
return x + y;
|
||||
};
|
||||
|
||||
let myArrowAdd = (x: number, y: number): number => x + y;
|
||||
|
||||
function buildName(firstName: string, lastName = "Smith") {
|
||||
return firstName + " " + lastName;
|
||||
}
|
||||
|
||||
function buildFullName(firstName: string, ...restOfName: string[]) {
|
||||
return firstName + " " + restOfName.join(" ");
|
||||
}
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
```ts
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
greet() {
|
||||
return "Hello, " + this.greeting;
|
||||
}
|
||||
}
|
||||
|
||||
let greeter = new Greeter("world");
|
||||
```
|
||||
|
||||
### Inheritance
|
||||
|
||||
```ts
|
||||
class Animal {
|
||||
move(distance: number = 0) {
|
||||
console.log(`Animal moved ${distance} meters.`);
|
||||
}
|
||||
}
|
||||
|
||||
class Dog extends Animal {
|
||||
bark() {
|
||||
console.log("Woof! Woof!");
|
||||
}
|
||||
}
|
||||
|
||||
const dog = new Dog();
|
||||
dog.bark();
|
||||
dog.move(10);
|
||||
dog.bark();
|
||||
```
|
||||
|
||||
### Generics
|
||||
|
||||
```ts
|
||||
function identity<T>(arg: T): T {
|
||||
return arg;
|
||||
}
|
||||
|
||||
let output1 = identity<string>("myString");
|
||||
let output2 = identity<number>(42);
|
||||
```
|
||||
|
||||
### Type Assertions
|
||||
|
||||
```ts
|
||||
let someValue: any = "this is a string";
|
||||
let strLength: number = (<string>someValue).length;
|
||||
// or
|
||||
let strLength2: number = (someValue as string).length;
|
||||
```
|
||||
|
||||
## Modules
|
||||
|
||||
### Export
|
||||
|
||||
```ts
|
||||
export interface StringValidator {
|
||||
isAcceptable(s: string): boolean;
|
||||
}
|
||||
|
||||
export class ZipCodeValidator implements StringValidator {
|
||||
isAcceptable(s: string) {
|
||||
return s.length === 5;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Import
|
||||
|
||||
```ts
|
||||
import { ZipCodeValidator } from "./ZipCodeValidator";
|
||||
|
||||
let myValidator = new ZipCodeValidator();
|
||||
```
|
||||
|
||||
### Namespaces
|
||||
|
||||
```ts
|
||||
namespace Validation {
|
||||
export interface StringValidator {
|
||||
isAcceptable(s: string): boolean;
|
||||
}
|
||||
|
||||
export class LettersOnlyValidator implements StringValidator {
|
||||
isAcceptable(s: string) {
|
||||
return /^[A-Za-z]+$/.test(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let validator = new Validation.LettersOnlyValidator();
|
||||
```
|
||||
|
||||
## Union and Intersection Types
|
||||
|
||||
### Union Types
|
||||
|
||||
```ts
|
||||
function padLeft(value: string, padding: string | number) {
|
||||
if (typeof padding === "number") {
|
||||
return Array(padding + 1).join(" ") + value;
|
||||
}
|
||||
if (typeof padding === "string") {
|
||||
return padding + value;
|
||||
}
|
||||
throw new Error(`Expected string or number, got '${padding}'.`);
|
||||
}
|
||||
```
|
||||
|
||||
### Intersection Types
|
||||
|
||||
```ts
|
||||
interface ErrorHandling {
|
||||
success: boolean;
|
||||
error?: { message: string };
|
||||
}
|
||||
|
||||
interface ArtworksData {
|
||||
artworks: { title: string }[];
|
||||
}
|
||||
|
||||
type ArtworksResponse = ArtworksData & ErrorHandling;
|
||||
|
||||
const response: ArtworksResponse = {
|
||||
success: true,
|
||||
artworks: [{ title: "Mona Lisa" }],
|
||||
};
|
||||
```
|
||||
|
||||
## Utility Types
|
||||
|
||||
### Partial
|
||||
|
||||
```ts
|
||||
interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
|
||||
let partialUser: Partial<User> = {
|
||||
name: "Alice",
|
||||
};
|
||||
```
|
||||
|
||||
### Readonly
|
||||
|
||||
```ts
|
||||
let readonlyUser: Readonly<User> = {
|
||||
id: 1,
|
||||
name: "Bob",
|
||||
age: 25,
|
||||
};
|
||||
|
||||
// readonlyUser.age = 26; // Error: cannot reassign a readonly property
|
||||
```
|
||||
|
||||
### Pick
|
||||
|
||||
```ts
|
||||
type UserName = Pick<User, "name">;
|
||||
|
||||
let userName: UserName = {
|
||||
name: "Charlie",
|
||||
};
|
||||
```
|
||||
|
||||
### Omit
|
||||
|
||||
```ts
|
||||
type UserWithoutAge = Omit<User, "age">;
|
||||
|
||||
let userWithoutAge: UserWithoutAge = {
|
||||
id: 2,
|
||||
name: "Dave",
|
||||
};
|
||||
```
|
||||
|
||||
## Decorators
|
||||
|
||||
### Class Decorator
|
||||
|
||||
```ts
|
||||
function sealed(constructor: Function) {
|
||||
Object.seal(constructor);
|
||||
Object.seal(constructor.prototype);
|
||||
}
|
||||
|
||||
@sealed
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
greet() {
|
||||
return "Hello, " + this.greeting;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Method Decorator
|
||||
|
||||
```ts
|
||||
function enumerable(value: boolean) {
|
||||
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
|
||||
descriptor.enumerable = value;
|
||||
};
|
||||
}
|
||||
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
|
||||
@enumerable(false)
|
||||
greet() {
|
||||
return "Hello, " + this.greeting;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Async/Await
|
||||
|
||||
```ts
|
||||
async function fetchData(url: string) {
|
||||
let response = await fetch(url);
|
||||
let data = await response.json();
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
## Also read
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/docs/)
|
||||
---
|
||||
title: TypeScript
|
||||
date: 2024-05-28 22:12:25
|
||||
background: bg-[#4476c0]
|
||||
tags:
|
||||
- ts
|
||||
- web
|
||||
categories:
|
||||
- Programming
|
||||
intro: |
|
||||
A TypeScript cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
|
||||
plugins:
|
||||
- copyCode
|
||||
- runCode
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Installing the Compiler
|
||||
|
||||
```shell
|
||||
npm install typescript --save-dev
|
||||
npm tsc
|
||||
```
|
||||
|
||||
## Basic DataTypes
|
||||
|
||||
### basic types
|
||||
|
||||
```ts
|
||||
let isDone: boolean = false;
|
||||
let age: number = 30;
|
||||
let userName: string = 'John';
|
||||
let list: number[] = [1, 2, 3];
|
||||
let tuple: [string, number] = ['hello', 10];
|
||||
let notSure: any = 4;
|
||||
notSure = 'maybe a string instead';
|
||||
```
|
||||
|
||||
### enums
|
||||
|
||||
```ts
|
||||
enum Color {
|
||||
Red,
|
||||
Green,
|
||||
Blue
|
||||
}
|
||||
let c: Color = Color.Green;
|
||||
```
|
||||
|
||||
### interface
|
||||
|
||||
```ts
|
||||
interface Person {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
age?: number; // Optional property
|
||||
}
|
||||
|
||||
function greet(person: Person) {
|
||||
return 'Hello, ' + person.firstName + ' ' + person.lastName;
|
||||
}
|
||||
```
|
||||
|
||||
### Functions
|
||||
|
||||
```ts
|
||||
function add(x: number, y: number): number {
|
||||
return x + y;
|
||||
}
|
||||
|
||||
let myAdd = function (x: number, y: number): number {
|
||||
return x + y;
|
||||
};
|
||||
|
||||
let myArrowAdd = (x: number, y: number): number => x + y;
|
||||
|
||||
function buildName(firstName: string, lastName = 'Smith') {
|
||||
return firstName + ' ' + lastName;
|
||||
}
|
||||
|
||||
function buildFullName(firstName: string, ...restOfName: string[]) {
|
||||
return firstName + ' ' + restOfName.join(' ');
|
||||
}
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
```ts
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
greet() {
|
||||
return 'Hello, ' + this.greeting;
|
||||
}
|
||||
}
|
||||
|
||||
let greeter = new Greeter('world');
|
||||
```
|
||||
|
||||
### Inheritance
|
||||
|
||||
```ts
|
||||
class Animal {
|
||||
move(distance: number = 0) {
|
||||
console.log(`Animal moved ${distance} meters.`);
|
||||
}
|
||||
}
|
||||
|
||||
class Dog extends Animal {
|
||||
bark() {
|
||||
console.log('Woof! Woof!');
|
||||
}
|
||||
}
|
||||
|
||||
const dog = new Dog();
|
||||
dog.bark();
|
||||
dog.move(10);
|
||||
dog.bark();
|
||||
```
|
||||
|
||||
### Generics
|
||||
|
||||
```ts
|
||||
function identity<T>(arg: T): T {
|
||||
return arg;
|
||||
}
|
||||
|
||||
let output1 = identity<string>('myString');
|
||||
let output2 = identity<number>(42);
|
||||
```
|
||||
|
||||
### Type Assertions
|
||||
|
||||
```ts
|
||||
let someValue: any = 'this is a string';
|
||||
let strLength: number = (<string>someValue).length;
|
||||
// or
|
||||
let strLength2: number = (someValue as string).length;
|
||||
```
|
||||
|
||||
## Modules
|
||||
|
||||
### Export
|
||||
|
||||
```ts
|
||||
export interface StringValidator {
|
||||
isAcceptable(s: string): boolean;
|
||||
}
|
||||
|
||||
export class ZipCodeValidator implements StringValidator {
|
||||
isAcceptable(s: string) {
|
||||
return s.length === 5;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Import
|
||||
|
||||
```ts
|
||||
import { ZipCodeValidator } from './ZipCodeValidator';
|
||||
|
||||
let myValidator = new ZipCodeValidator();
|
||||
```
|
||||
|
||||
### Namespaces
|
||||
|
||||
```ts
|
||||
namespace Validation {
|
||||
export interface StringValidator {
|
||||
isAcceptable(s: string): boolean;
|
||||
}
|
||||
|
||||
export class LettersOnlyValidator implements StringValidator {
|
||||
isAcceptable(s: string) {
|
||||
return /^[A-Za-z]+$/.test(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let validator = new Validation.LettersOnlyValidator();
|
||||
```
|
||||
|
||||
## Union and Intersection Types
|
||||
|
||||
### Union Types
|
||||
|
||||
```ts
|
||||
function padLeft(value: string, padding: string | number) {
|
||||
if (typeof padding === 'number') {
|
||||
return Array(padding + 1).join(' ') + value;
|
||||
}
|
||||
if (typeof padding === 'string') {
|
||||
return padding + value;
|
||||
}
|
||||
throw new Error(`Expected string or number, got '${padding}'.`);
|
||||
}
|
||||
```
|
||||
|
||||
### Intersection Types
|
||||
|
||||
```ts
|
||||
interface ErrorHandling {
|
||||
success: boolean;
|
||||
error?: { message: string };
|
||||
}
|
||||
|
||||
interface ArtworksData {
|
||||
artworks: { title: string }[];
|
||||
}
|
||||
|
||||
type ArtworksResponse = ArtworksData & ErrorHandling;
|
||||
|
||||
const response: ArtworksResponse = {
|
||||
success: true,
|
||||
artworks: [{ title: 'Mona Lisa' }]
|
||||
};
|
||||
```
|
||||
|
||||
## Utility Types
|
||||
|
||||
### Partial
|
||||
|
||||
```ts
|
||||
interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
age: number;
|
||||
}
|
||||
|
||||
let partialUser: Partial<User> = {
|
||||
name: 'Alice'
|
||||
};
|
||||
```
|
||||
|
||||
### Readonly
|
||||
|
||||
```ts
|
||||
let readonlyUser: Readonly<User> = {
|
||||
id: 1,
|
||||
name: 'Bob',
|
||||
age: 25
|
||||
};
|
||||
|
||||
// readonlyUser.age = 26; // Error: cannot reassign a readonly property
|
||||
```
|
||||
|
||||
### Pick
|
||||
|
||||
```ts
|
||||
type UserName = Pick<User, 'name'>;
|
||||
|
||||
let userName: UserName = {
|
||||
name: 'Charlie'
|
||||
};
|
||||
```
|
||||
|
||||
### Omit
|
||||
|
||||
```ts
|
||||
type UserWithoutAge = Omit<User, 'age'>;
|
||||
|
||||
let userWithoutAge: UserWithoutAge = {
|
||||
id: 2,
|
||||
name: 'Dave'
|
||||
};
|
||||
```
|
||||
|
||||
## Decorators
|
||||
|
||||
### Class Decorator
|
||||
|
||||
```ts
|
||||
function sealed(constructor: Function) {
|
||||
Object.seal(constructor);
|
||||
Object.seal(constructor.prototype);
|
||||
}
|
||||
|
||||
@sealed
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
greet() {
|
||||
return 'Hello, ' + this.greeting;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Method Decorator
|
||||
|
||||
```ts
|
||||
function enumerable(value: boolean) {
|
||||
return function (
|
||||
target: any,
|
||||
propertyKey: string,
|
||||
descriptor: PropertyDescriptor
|
||||
) {
|
||||
descriptor.enumerable = value;
|
||||
};
|
||||
}
|
||||
|
||||
class Greeter {
|
||||
greeting: string;
|
||||
constructor(message: string) {
|
||||
this.greeting = message;
|
||||
}
|
||||
|
||||
@enumerable(false)
|
||||
greet() {
|
||||
return 'Hello, ' + this.greeting;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Async/Await
|
||||
|
||||
```ts
|
||||
async function fetchData(url: string) {
|
||||
let response = await fetch(url);
|
||||
let data = await response.json();
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
## Also read
|
||||
|
||||
- [TypeScript](https://www.typescriptlang.org/docs/)
|
||||
+408
-288
File diff suppressed because it is too large.
Load diff
@@ -5,110 +5,109 @@ tags:
|
||||
- unreal
|
||||
- engine
|
||||
categories:
|
||||
- Keyboard Shortcuts
|
||||
intro:
|
||||
A visual cheat-sheet for many keyboard shortcuts found in Unreal Engine 5
|
||||
- Keyboard Shortcuts
|
||||
intro: A visual cheat-sheet for many keyboard shortcuts found in Unreal Engine 5
|
||||
---
|
||||
|
||||
## Level Editor
|
||||
|
||||
### Viewport Transformation
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------------- |
|
||||
| `W` | Translate |
|
||||
| `E` | Rotate |
|
||||
| `R` | Scale |
|
||||
| `Space Bar` | Toggle Transform Mode |
|
||||
| `[` | Decrease Position Grid Size |
|
||||
| `]` | Increase Position Grid Size |
|
||||
| `Shift` `[` | Decrease Rotation Grid Size |
|
||||
| `Shift` `]` | Increase Rotation Grid Size |
|
||||
| Shortcut | Action |
|
||||
| ----------- | --------------------------- |
|
||||
| `W` | Translate |
|
||||
| `E` | Rotate |
|
||||
| `R` | Scale |
|
||||
| `Space Bar` | Toggle Transform Mode |
|
||||
| `[` | Decrease Position Grid Size |
|
||||
| `]` | Increase Position Grid Size |
|
||||
| `Shift` `[` | Decrease Rotation Grid Size |
|
||||
| `Shift` `]` | Increase Rotation Grid Size |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### View Modes
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `Alt` `2` | Wireframe |
|
||||
| `Alt` `3` | Unlit |
|
||||
| `Alt` `4` | Lit |
|
||||
| `Alt` `5` | Detail Lighting |
|
||||
| `Alt` `6` | Lighting Only |
|
||||
| `Alt` `7` | Light Complexity |
|
||||
| `Alt` `8` | Shader Complexity |
|
||||
| `Alt` `0` | Lightmap Density |
|
||||
| Shortcut | Action |
|
||||
| --------- | ----------------- |
|
||||
| `Alt` `2` | Wireframe |
|
||||
| `Alt` `3` | Unlit |
|
||||
| `Alt` `4` | Lit |
|
||||
| `Alt` `5` | Detail Lighting |
|
||||
| `Alt` `6` | Lighting Only |
|
||||
| `Alt` `7` | Light Complexity |
|
||||
| `Alt` `8` | Shader Complexity |
|
||||
| `Alt` `0` | Lightmap Density |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Level Editor General {.row-span-2}
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | ---------------------------- |
|
||||
| `Esc` | Deselect All |
|
||||
| `H` | Hide Selected |
|
||||
| `Ctrl` `H` | Unhide All |
|
||||
| `F` | Focus on Actor |
|
||||
| `F9` | Screenshot |
|
||||
| `F11` | Immersive Mode |
|
||||
| `G` | Game View |
|
||||
| `T` | Toggle Translucent Selection |
|
||||
| `(right click)` | Asset Menu |
|
||||
| `Ctrl` `E` | Edit Selected Asset |
|
||||
| `Ctrl` `P` | Open Asset |
|
||||
| `P` | Toggle Navmesh |
|
||||
| `Ctrl` `Shift` `,` | Profile GPU |
|
||||
| `Ctrl` `Shift` `H` | Toggle FPS |
|
||||
| `~` | Command Console |
|
||||
| Shortcut | Action |
|
||||
| ------------------ | ---------------------------- |
|
||||
| `Esc` | Deselect All |
|
||||
| `H` | Hide Selected |
|
||||
| `Ctrl` `H` | Unhide All |
|
||||
| `F` | Focus on Actor |
|
||||
| `F9` | Screenshot |
|
||||
| `F11` | Immersive Mode |
|
||||
| `G` | Game View |
|
||||
| `T` | Toggle Translucent Selection |
|
||||
| `(right click)` | Asset Menu |
|
||||
| `Ctrl` `E` | Edit Selected Asset |
|
||||
| `Ctrl` `P` | Open Asset |
|
||||
| `P` | Toggle Navmesh |
|
||||
| `Ctrl` `Shift` `,` | Profile GPU |
|
||||
| `Ctrl` `Shift` `H` | Toggle FPS |
|
||||
| `~` | Command Console |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Camera Navigation
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `Alt` `G` | Perspective View |
|
||||
| `Alt` `H` | Front View |
|
||||
| `Alt` `J` | Top View |
|
||||
| `Alt` `K` | Side View |
|
||||
| `Ctrl` `0-9` | Set Bookmark |
|
||||
| `0-9` | Jump to Bookmark |
|
||||
| Shortcut | Action |
|
||||
| ------------ | ---------------- |
|
||||
| `Alt` `G` | Perspective View |
|
||||
| `Alt` `H` | Front View |
|
||||
| `Alt` `J` | Top View |
|
||||
| `Alt` `K` | Side View |
|
||||
| `Ctrl` `0-9` | Set Bookmark |
|
||||
| `0-9` | Jump to Bookmark |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Editing Modes
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `Shift` `1` | Selection Mode |
|
||||
| `Shift` `2` | Landscape Mode |
|
||||
| `Shift` `3` | Foliage Mode |
|
||||
| `Shift` `4` | Modeling Mode |
|
||||
| `Shift` `5` | Brush Editing Mode |
|
||||
| `Shift` `6` | Animation Mode |
|
||||
| Shortcut | Action |
|
||||
| ----------- | ------------------ |
|
||||
| `Shift` `1` | Selection Mode |
|
||||
| `Shift` `2` | Landscape Mode |
|
||||
| `Shift` `3` | Foliage Mode |
|
||||
| `Shift` `4` | Modeling Mode |
|
||||
| `Shift` `5` | Brush Editing Mode |
|
||||
| `Shift` `6` | Animation Mode |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Snapping
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `End` | Snap to Floor |
|
||||
| `Alt` `End` | Snap Pivot to Floor |
|
||||
| `Shift` `End` | Snap Bounds to Floor |
|
||||
| `Ctrl` `End` | Snap to World Grid |
|
||||
| Shortcut | Action |
|
||||
| ------------- | -------------------- |
|
||||
| `End` | Snap to Floor |
|
||||
| `Alt` `End` | Snap Pivot to Floor |
|
||||
| `Shift` `End` | Snap Bounds to Floor |
|
||||
| `Ctrl` `End` | Snap to World Grid |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Play in Editor (PIE)
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `Alt` `P` | Start PIE Session |
|
||||
| `Pause` | Pause |
|
||||
| `F8 ` | Eject from Player |
|
||||
| `Esc` | Stop PIE Session |
|
||||
| Shortcut | Action |
|
||||
| --------- | ----------------- |
|
||||
| `Alt` `P` | Start PIE Session |
|
||||
| `Pause` | Pause |
|
||||
| `F8 ` | Eject from Player |
|
||||
| `Esc` | Stop PIE Session |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
@@ -116,11 +115,11 @@ intro:
|
||||
|
||||
Note: You need to select assets first for these shortcuts to work
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | --------------------- |
|
||||
| `Alt` `Shift` `A` | Audit Assets |
|
||||
| `Alt` `Shift` `R` | Reference Viewer |
|
||||
| `Alt` `Shift` `M` | Size Map |
|
||||
| Shortcut | Action |
|
||||
| ----------------- | ---------------- |
|
||||
| `Alt` `Shift` `A` | Audit Assets |
|
||||
| `Alt` `Shift` `R` | Reference Viewer |
|
||||
| `Alt` `Shift` `M` | Size Map |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
@@ -128,21 +127,21 @@ Note: You need to select assets first for these shortcuts to work
|
||||
|
||||
### Blueprints {.row-span-2}
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | ------------------------------- |
|
||||
| `B` | Add Branch |
|
||||
| `S` | Add Sequence |
|
||||
| `D` | Add Delay |
|
||||
| `F` | Add For Each Loop |
|
||||
| `G` | Add Gate |
|
||||
| `M` | Add Multi Gate |
|
||||
| `O` | Add Do Once |
|
||||
| `N` | Add Do N |
|
||||
| `C` | Add Comment |
|
||||
| `F7` | Compile Blueprint |
|
||||
| `F9` | Add Breakpoint to selected node |
|
||||
| `Ctrl` `Shift` `F9` | Remove all Breakpoints |
|
||||
| `Home` | Zoom to selected node |
|
||||
| Shortcut | Action |
|
||||
| ------------------- | ------------------------------- |
|
||||
| `B` | Add Branch |
|
||||
| `S` | Add Sequence |
|
||||
| `D` | Add Delay |
|
||||
| `F` | Add For Each Loop |
|
||||
| `G` | Add Gate |
|
||||
| `M` | Add Multi Gate |
|
||||
| `O` | Add Do Once |
|
||||
| `N` | Add Do N |
|
||||
| `C` | Add Comment |
|
||||
| `F7` | Compile Blueprint |
|
||||
| `F9` | Add Breakpoint to selected node |
|
||||
| `Ctrl` `Shift` `F9` | Remove all Breakpoints |
|
||||
| `Home` | Zoom to selected node |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
@@ -150,21 +149,21 @@ Note: You need to select assets first for these shortcuts to work
|
||||
|
||||
Used in the viewport for the Mesh Editor, Material Editor, Blueprint Editor, etc.
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | ---------------------- |
|
||||
| `I` | Toggle Environment |
|
||||
| `O` | Toggle Floor |
|
||||
| `P` | Toggle Post Processing |
|
||||
| Shortcut | Action |
|
||||
| -------- | ---------------------- |
|
||||
| `I` | Toggle Environment |
|
||||
| `O` | Toggle Floor |
|
||||
| `P` | Toggle Post Processing |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Static Meshes
|
||||
|
||||
| Shortcut | Action |
|
||||
| --------------------- | ------------------------- |
|
||||
| `Ctrl` `N` | Show Nanite Fallback Mesh |
|
||||
| `Alt` `N` | Toggle Normals |
|
||||
| `Alt` `S` | Toggle Sockets |
|
||||
| Shortcut | Action |
|
||||
| ---------- | ------------------------- |
|
||||
| `Ctrl` `N` | Show Nanite Fallback Mesh |
|
||||
| `Alt` `N` | Toggle Normals |
|
||||
| `Alt` `S` | Toggle Sockets |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
@@ -189,4 +188,4 @@ Used in the viewport for the Mesh Editor, Material Editor, Blueprint Editor, etc
|
||||
- [Unreal Engine Editor Hotkey Cheat Sheet](https://uecasts.com/resources/unreal-engine-5-editor-hotkeys-cheat-sheet)
|
||||
_(uecasts.com)_
|
||||
- [Unreal Engine Actor Snapping Shortcuts](https://unrealdirective.com/tips/actor-snapping-shortcuts)
|
||||
_(unrealdirective.com)_
|
||||
_(unrealdirective.com)_
|
||||
@@ -383,7 +383,7 @@ See `:help text-objects`
|
||||
| `<C-w>` `-` _/_ `+` | Decrease/Increase height |
|
||||
| `<C-w>` `<` _/_ `>` | Decrease/Increase width |
|
||||
| `<C-w>` <code>\|</code> | Max out the width |
|
||||
| `<C-w>` `_` | Max out the height |
|
||||
| `<C-w>` `_` | Max out the height |
|
||||
| `<C-w>` `=` | Equally high and wide |
|
||||
| `<C-w>` `h` _/_ `l` | Go to the left/right window |
|
||||
| `<C-w>` `j` _/_ `k` | Go to the up/down window |
|
||||
|
||||
@@ -323,7 +323,7 @@ Jack:
|
||||
hobby:
|
||||
- a
|
||||
- b
|
||||
location: { country: "A", city: "A-A" }
|
||||
location: { country: 'A', city: 'A-A' }
|
||||
```
|
||||
|
||||
#### ↓ Equivalent JSON
|
||||
@@ -349,7 +349,7 @@ Jack:
|
||||
set1: !!set
|
||||
? one
|
||||
? two
|
||||
set2: !!set { "one", "two" }
|
||||
set2: !!set { 'one', 'two' }
|
||||
```
|
||||
|
||||
#### ↓ Equivalent JSON
|
||||
|
||||
+63
-62
@@ -16,97 +16,98 @@ intro: A visual cheat-sheet for the 50 keyboard shortcuts found in the Zed text
|
||||
|
||||
### Zed
|
||||
|
||||
| Shortcut | Action |
|
||||
|------------------------|------------------------|
|
||||
| `Ctrl` `,` | Open settings |
|
||||
| `Ctrl` `Shift` `X` | Open Extensions store |
|
||||
| `Ctrl` `Q` | Quit Zed |
|
||||
| Shortcut | Action |
|
||||
| ------------------ | --------------------- |
|
||||
| `Ctrl` `,` | Open settings |
|
||||
| `Ctrl` `Shift` `X` | Open Extensions store |
|
||||
| `Ctrl` `Q` | Quit Zed |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### File
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------------------------|---------------------|
|
||||
| `Ctrl` `N` | New file |
|
||||
| `Ctrl` `Shift` `N` | New Window |
|
||||
| `Ctrl` `O` | Open folder |
|
||||
| `Ctrl` `Alt` `Shift` `O` | Open remote folder |
|
||||
| `Ctrl` `S` | Save |
|
||||
| `Ctrl` `Shift` `S` | Save As... |
|
||||
| `Ctrl` `Alt` `S` | Save All |
|
||||
| `Ctrl` `Shift` `W` | Close Window |
|
||||
| Shortcut | Action |
|
||||
| ------------------------ | ------------------ |
|
||||
| `Ctrl` `N` | New file |
|
||||
| `Ctrl` `Shift` `N` | New Window |
|
||||
| `Ctrl` `O` | Open folder |
|
||||
| `Ctrl` `Alt` `Shift` `O` | Open remote folder |
|
||||
| `Ctrl` `S` | Save |
|
||||
| `Ctrl` `Shift` `S` | Save As... |
|
||||
| `Ctrl` `Alt` `S` | Save All |
|
||||
| `Ctrl` `Shift` `W` | Close Window |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Edit
|
||||
|
||||
| Shortcut | Action |
|
||||
|------------------------|---------------------|
|
||||
| `Ctrl` `Z` | Undo |
|
||||
| `Ctrl` `Shift` `Z` | Redo |
|
||||
| `Ctrl` `X` | Cut |
|
||||
| `Ctrl` `C` | Copy |
|
||||
| `Ctrl` `V` | Paste |
|
||||
| `Ctrl` `Shift` `F` | Find in project |
|
||||
| `Ctrl` `/` | Toggle line comment |
|
||||
| Shortcut | Action |
|
||||
| ------------------ | ------------------- |
|
||||
| `Ctrl` `Z` | Undo |
|
||||
| `Ctrl` `Shift` `Z` | Redo |
|
||||
| `Ctrl` `X` | Cut |
|
||||
| `Ctrl` `C` | Copy |
|
||||
| `Ctrl` `V` | Paste |
|
||||
| `Ctrl` `Shift` `F` | Find in project |
|
||||
| `Ctrl` `/` | Toggle line comment |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Selection
|
||||
|
||||
| Shortcut | Action |
|
||||
|--------------------------|-------------------------|
|
||||
| `Ctrl` `A` | Select all |
|
||||
| `Alt` `Shift` `Right` | Expand selection |
|
||||
| `Alt` `Shift` `Left` | Shrink selection |
|
||||
| `Alt` `Shift` `Up` | Add cursor above |
|
||||
| `Alt` `Shift` `Down` | Add cursor below |
|
||||
| `Ctrl` `Shift` `Down` | Select next Occurrence |
|
||||
| `Alt` `Up` | Move line up |
|
||||
| `Alt` `Down` | Move line down |
|
||||
| `Ctrl` `Shift` `D` | Duplicate selection |
|
||||
| Shortcut | Action |
|
||||
| --------------------- | ---------------------- |
|
||||
| `Ctrl` `A` | Select all |
|
||||
| `Alt` `Shift` `Right` | Expand selection |
|
||||
| `Alt` `Shift` `Left` | Shrink selection |
|
||||
| `Alt` `Shift` `Up` | Add cursor above |
|
||||
| `Alt` `Shift` `Down` | Add cursor below |
|
||||
| `Ctrl` `Shift` `Down` | Select next Occurrence |
|
||||
| `Alt` `Up` | Move line up |
|
||||
| `Alt` `Down` | Move line down |
|
||||
| `Ctrl` `Shift` `D` | Duplicate selection |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### View
|
||||
|
||||
| Shortcut | Action |
|
||||
|------------------------|----------------------|
|
||||
| `Ctrl` `B` | Toggle Left Dock |
|
||||
| `Ctrl` `Alt` `B` | Toggle Right Dock |
|
||||
| `Ctrl` `J` | Toggle Bottom Dock |
|
||||
| `Ctrl` `Alt` `Y` | Close All Docks |
|
||||
| `Ctrl` `K` `Up` | Split Up |
|
||||
| `Ctrl` `K` `Down` | Split Down |
|
||||
| `Ctrl` `K` `Left` | Split Left |
|
||||
| `Ctrl` `K` `Right` | Split Right |
|
||||
| `Ctrl` `Shift` `E` | Project Panel |
|
||||
| `Ctrl` `Shift` `B` | Outline Panel |
|
||||
| `Ctrl` `Shift` `C` | Collab Panel |
|
||||
| `Ctrl` ``` ` ``` | Terminal Panel |
|
||||
| `Ctrl` `Shift` `M` | Diagnostics |
|
||||
| Shortcut | Action |
|
||||
| ------------------ | ------------------ |
|
||||
| `Ctrl` `B` | Toggle Left Dock |
|
||||
| `Ctrl` `Alt` `B` | Toggle Right Dock |
|
||||
| `Ctrl` `J` | Toggle Bottom Dock |
|
||||
| `Ctrl` `Alt` `Y` | Close All Docks |
|
||||
| `Ctrl` `K` `Up` | Split Up |
|
||||
| `Ctrl` `K` `Down` | Split Down |
|
||||
| `Ctrl` `K` `Left` | Split Left |
|
||||
| `Ctrl` `K` `Right` | Split Right |
|
||||
| `Ctrl` `Shift` `E` | Project Panel |
|
||||
| `Ctrl` `Shift` `B` | Outline Panel |
|
||||
| `Ctrl` `Shift` `C` | Collab Panel |
|
||||
| `Ctrl` `` ` `` | Terminal Panel |
|
||||
| `Ctrl` `Shift` `M` | Diagnostics |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
### Go
|
||||
|
||||
| Shortcut | Action |
|
||||
|-----------------------|----------------------------|
|
||||
| `Ctrl` `Alt` `-` | Back |
|
||||
| `Ctrl` `Shift` `P` | Command Palette… |
|
||||
| `Ctrl` `E` | Go to File… |
|
||||
| `Ctrl` `Shift` `O` | Go to Symbol in Editor… |
|
||||
| `Ctrl` `G` | Go to Line/Column… |
|
||||
| `F12` | Go to Definition |
|
||||
| `Ctrl` `F12` | Go to Type Definition |
|
||||
| `Alt` `Shift` `F12` | Find All References |
|
||||
| `F8` | Next Problem |
|
||||
| `Shift` `F8` | Previous Problem |
|
||||
| Shortcut | Action |
|
||||
| ------------------- | ----------------------- |
|
||||
| `Ctrl` `Alt` `-` | Back |
|
||||
| `Ctrl` `Shift` `P` | Command Palette… |
|
||||
| `Ctrl` `E` | Go to File… |
|
||||
| `Ctrl` `Shift` `O` | Go to Symbol in Editor… |
|
||||
| `Ctrl` `G` | Go to Line/Column… |
|
||||
| `F12` | Go to Definition |
|
||||
| `Ctrl` `F12` | Go to Type Definition |
|
||||
| `Alt` `Shift` `F12` | Find All References |
|
||||
| `F8` | Next Problem |
|
||||
| `Shift` `F8` | Previous Problem |
|
||||
|
||||
{.shortcuts}
|
||||
|
||||
## Also see
|
||||
|
||||
- [Zed](https://zed.dev/)
|
||||
- [Zed GitHub](https://github.com/zed-industries/zed)
|
||||
- [Zed Documentation](https://zed.dev/docs)
|
||||
@@ -3,9 +3,9 @@ title: About
|
||||
date: 2020-03-26 20:45:53
|
||||
---
|
||||
|
||||
Welcome to [CheatSheets] – your go-to resource for [describing content]. Designed with [developers/students/professionals]
|
||||
in mind, our quick reference provides a comprehensive collection of [topics/sections] to help you [solve problems/learn
|
||||
efficiently/etc.].
|
||||
Welcome to [CheatSheets] – your go-to resource for [describing content]. Designed with
|
||||
[developers/students/professionals] in mind, our quick reference provides a comprehensive collection of
|
||||
[topics/sections] to help you [solve problems/learn efficiently/etc.].
|
||||
|
||||
Our user-friendly interface ensures rapid access to the information you need. Whether you're [coding/studying/working],
|
||||
you'll find [specific benefits or standout features].
|
||||
@@ -24,8 +24,7 @@ Key Features:
|
||||
- By avoiding the need to seek through lengthy documentation, cheat sheets save users valuable time during tasks or
|
||||
learning.
|
||||
- Digital cheat sheets are easily searchable, and users can quickly find what they need by using keywords or phrases.
|
||||
- Cheat sheets act as a rapid review tool, allowing users to refresh their memory on topics they've previously
|
||||
learned.
|
||||
- Cheat sheets act as a rapid review tool, allowing users to refresh their memory on topics they've previously learned.
|
||||
|
||||
Our team of experts has meticulously crafted this reference to provide instant information. We're committed to evolving
|
||||
our content to meet your needs and bring out fascinating upgrades in the future.
|
||||
|
||||
@@ -79,7 +79,7 @@
|
||||
}
|
||||
|
||||
.notfound h1 {
|
||||
font-family: "Quicksand", sans-serif;
|
||||
font-family: 'Quicksand', sans-serif;
|
||||
font-size: 86px;
|
||||
text-transform: uppercase;
|
||||
font-weight: 700;
|
||||
@@ -89,7 +89,7 @@
|
||||
}
|
||||
|
||||
.notfound h2 {
|
||||
font-family: "Quicksand", sans-serif;
|
||||
font-family: 'Quicksand', sans-serif;
|
||||
font-size: 26px;
|
||||
margin: 0;
|
||||
font-weight: 700;
|
||||
@@ -97,7 +97,7 @@
|
||||
}
|
||||
|
||||
.notfound a {
|
||||
font-family: "Quicksand", sans-serif;
|
||||
font-family: 'Quicksand', sans-serif;
|
||||
font-size: 14px;
|
||||
text-decoration: none;
|
||||
text-transform: uppercase;
|
||||
|
||||
+47
-47
@@ -56,47 +56,47 @@
|
||||
const reg_num = /^[0-7]{3}$/; // some regex to check the num input
|
||||
const reg_let = /^([r\-]{1}[w\-]{1}[x\-]{1}){3}$/; // some regex to check the text input
|
||||
|
||||
window.addEventListener("DOMContentLoaded", function () {
|
||||
window.addEventListener('DOMContentLoaded', function () {
|
||||
// loop over all the check boxes
|
||||
for (let i = 1; i < 10; i++) {
|
||||
let checkBox = document.getElementById(`${i}`);
|
||||
checkBox.addEventListener("change", function () {
|
||||
checkBox.addEventListener('change', function () {
|
||||
change_occured(true, false, false);
|
||||
|
||||
// get rid of bad input classes
|
||||
document.getElementById("num").classList.remove("bad-input");
|
||||
document.getElementById('num').classList.remove('bad-input');
|
||||
|
||||
document.getElementById("let").classList.remove("bad-input");
|
||||
document.getElementById('let').classList.remove('bad-input');
|
||||
});
|
||||
}
|
||||
|
||||
// the octal input
|
||||
let num_input = document.getElementById("num");
|
||||
let num_input = document.getElementById('num');
|
||||
let num_fn = function () {
|
||||
// check for bad input
|
||||
if (!reg_num.test(this.value)) {
|
||||
this.classList.add("bad-input");
|
||||
this.classList.add('bad-input');
|
||||
} else {
|
||||
this.classList.remove("bad-input");
|
||||
this.classList.remove('bad-input');
|
||||
change_occured(false, true, false);
|
||||
}
|
||||
};
|
||||
num_input.addEventListener("change", num_fn);
|
||||
num_input.addEventListener("keyup", num_fn);
|
||||
num_input.addEventListener('change', num_fn);
|
||||
num_input.addEventListener('keyup', num_fn);
|
||||
|
||||
// the let input
|
||||
let let_input = document.getElementById("let");
|
||||
let let_input = document.getElementById('let');
|
||||
let let_fn = function () {
|
||||
// check for bad input
|
||||
if (!reg_let.test(this.value)) {
|
||||
this.classList.add("bad-input");
|
||||
this.classList.add('bad-input');
|
||||
} else {
|
||||
this.classList.remove("bad-input");
|
||||
this.classList.remove('bad-input');
|
||||
change_occured(false, false, true);
|
||||
}
|
||||
};
|
||||
let_input.addEventListener("change", let_fn);
|
||||
let_input.addEventListener("keyup", let_fn);
|
||||
let_input.addEventListener('change', let_fn);
|
||||
let_input.addEventListener('keyup', let_fn);
|
||||
});
|
||||
|
||||
/* SETUP
|
||||
@@ -110,7 +110,7 @@
|
||||
let num1 = 0,
|
||||
num2 = 0,
|
||||
num3 = 0; // these are the three numbers for the octal
|
||||
let perm_string = ""; // holds the permision string ex. rw-x--r--
|
||||
let perm_string = ''; // holds the permision string ex. rw-x--r--
|
||||
|
||||
if (caller_was_check) {
|
||||
// loop over all the check boxes and get the permisions
|
||||
@@ -131,16 +131,16 @@
|
||||
}
|
||||
} else {
|
||||
// if not checked
|
||||
perm_string += "-";
|
||||
perm_string += '-';
|
||||
}
|
||||
}
|
||||
|
||||
// set the permision input text
|
||||
document.getElementById("let").value = perm_string;
|
||||
document.getElementById("num").value = `${num1}${num2}${num3}`;
|
||||
document.getElementById('let').value = perm_string;
|
||||
document.getElementById('num').value = `${num1}${num2}${num3}`;
|
||||
} else if (caller_was_num) {
|
||||
// get the individual numbers
|
||||
let num_input_val = document.getElementById("num").value;
|
||||
let num_input_val = document.getElementById('num').value;
|
||||
num1 = num_input_val.substring(0, 1);
|
||||
num2 = num_input_val.substring(1, 2);
|
||||
num3 = num_input_val.substring(2, 3);
|
||||
@@ -151,17 +151,17 @@
|
||||
perm_string += octal_to_check_and_txt(num3, 2); //Owner
|
||||
|
||||
// set the permision input text
|
||||
document.getElementById("let").value = perm_string;
|
||||
document.getElementById('let').value = perm_string;
|
||||
} else if (caller_was_let) {
|
||||
// get the text input
|
||||
let perm_text = document.getElementById("let").value;
|
||||
let perm_text = document.getElementById('let').value;
|
||||
|
||||
num1 = text_to_check_and_octal(perm_text.substring(0, 3), 0);
|
||||
num2 = text_to_check_and_octal(perm_text.substring(3, 6), 3);
|
||||
num3 = text_to_check_and_octal(perm_text.substring(6, 9), 6);
|
||||
|
||||
// set the octal value
|
||||
document.getElementById("num").value = `${num1}${num2}${num3}`;
|
||||
document.getElementById('num').value = `${num1}${num2}${num3}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,38 +169,38 @@
|
||||
// returns perm_num, perm_let
|
||||
function check_to_octal_and_text(check_num) {
|
||||
let perm_num = 0;
|
||||
let perm_let = "-";
|
||||
let perm_let = '-';
|
||||
|
||||
switch (check_num) {
|
||||
case 1:
|
||||
case 4:
|
||||
case 7:
|
||||
perm_num = 4;
|
||||
perm_let = "r";
|
||||
perm_let = 'r';
|
||||
|
||||
break;
|
||||
case 2:
|
||||
case 5:
|
||||
case 8:
|
||||
perm_num = 2;
|
||||
perm_let = "w";
|
||||
perm_let = 'w';
|
||||
|
||||
break;
|
||||
case 3:
|
||||
case 6:
|
||||
case 9:
|
||||
perm_num = 1;
|
||||
perm_let = "x";
|
||||
perm_let = 'x';
|
||||
|
||||
break;
|
||||
default:
|
||||
perm_num = 0;
|
||||
perm_let = "-";
|
||||
perm_let = '-';
|
||||
}
|
||||
// return values
|
||||
return {
|
||||
perm_num,
|
||||
perm_let,
|
||||
perm_let
|
||||
};
|
||||
}
|
||||
|
||||
@@ -213,64 +213,64 @@
|
||||
Returns: perm text (ex. "rwx") and sets the appropriate checkboxes
|
||||
*/
|
||||
function octal_to_check_and_txt(octal_num, class_num) {
|
||||
let perm_text = "";
|
||||
let perm_text = '';
|
||||
let offset = class_num * 3;
|
||||
|
||||
switch (octal_num) {
|
||||
case "1":
|
||||
case '1':
|
||||
document.getElementById(`${1 + offset}`).checked = false;
|
||||
document.getElementById(`${2 + offset}`).checked = false;
|
||||
document.getElementById(`${3 + offset}`).checked = true;
|
||||
perm_text = "--x";
|
||||
perm_text = '--x';
|
||||
break;
|
||||
|
||||
case "2":
|
||||
case '2':
|
||||
document.getElementById(`${1 + offset}`).checked = false;
|
||||
document.getElementById(`${2 + offset}`).checked = true;
|
||||
document.getElementById(`${3 + offset}`).checked = false;
|
||||
perm_text = "-w-";
|
||||
perm_text = '-w-';
|
||||
break;
|
||||
|
||||
case "3":
|
||||
case '3':
|
||||
document.getElementById(`${1 + offset}`).checked = false;
|
||||
document.getElementById(`${2 + offset}`).checked = true;
|
||||
document.getElementById(`${3 + offset}`).checked = true;
|
||||
perm_text = "-wx";
|
||||
perm_text = '-wx';
|
||||
break;
|
||||
|
||||
case "4":
|
||||
case '4':
|
||||
document.getElementById(`${1 + offset}`).checked = true;
|
||||
document.getElementById(`${2 + offset}`).checked = false;
|
||||
document.getElementById(`${3 + offset}`).checked = false;
|
||||
perm_text = "r--";
|
||||
perm_text = 'r--';
|
||||
break;
|
||||
|
||||
case "5":
|
||||
case '5':
|
||||
document.getElementById(`${1 + offset}`).checked = true;
|
||||
document.getElementById(`${2 + offset}`).checked = false;
|
||||
document.getElementById(`${3 + offset}`).checked = true;
|
||||
perm_text = "r-x";
|
||||
perm_text = 'r-x';
|
||||
break;
|
||||
|
||||
case "6":
|
||||
case '6':
|
||||
document.getElementById(`${1 + offset}`).checked = true;
|
||||
document.getElementById(`${2 + offset}`).checked = true;
|
||||
document.getElementById(`${3 + offset}`).checked = false;
|
||||
perm_text = "rw-";
|
||||
perm_text = 'rw-';
|
||||
break;
|
||||
|
||||
case "7":
|
||||
case '7':
|
||||
document.getElementById(`${1 + offset}`).checked = true;
|
||||
document.getElementById(`${2 + offset}`).checked = true;
|
||||
document.getElementById(`${3 + offset}`).checked = true;
|
||||
perm_text = "rwx";
|
||||
perm_text = 'rwx';
|
||||
break;
|
||||
|
||||
default:
|
||||
document.getElementById(`${1 + offset}`).checked = false;
|
||||
document.getElementById(`${2 + offset}`).checked = false;
|
||||
document.getElementById(`${3 + offset}`).checked = false;
|
||||
perm_text = "---";
|
||||
perm_text = '---';
|
||||
}
|
||||
return perm_text;
|
||||
}
|
||||
@@ -285,13 +285,13 @@
|
||||
// add up the oct num and set the check boxes
|
||||
for (let i = 0; i < 3; i++) {
|
||||
current_let = letters.substring(i, i + 1);
|
||||
if (current_let == "r") {
|
||||
if (current_let == 'r') {
|
||||
document.getElementById(`${i + 1 + offset}`).checked = true;
|
||||
perm_num += 4;
|
||||
} else if (current_let == "w") {
|
||||
} else if (current_let == 'w') {
|
||||
document.getElementById(`${i + 1 + offset}`).checked = true;
|
||||
perm_num += 2;
|
||||
} else if (current_let == "x") {
|
||||
} else if (current_let == 'x') {
|
||||
document.getElementById(`${i + 1 + offset}`).checked = true;
|
||||
perm_num += 1;
|
||||
} else {
|
||||
|
||||
+19
-14
@@ -1,26 +1,31 @@
|
||||
module.exports = {
|
||||
darkMode: "class", // or 'media' or 'class'
|
||||
darkMode: 'class', // or 'media' or 'class'
|
||||
plugins: [
|
||||
// https://github.com/jamiebuilds/tailwindcss-animate
|
||||
require("tailwindcss-animate"),
|
||||
require('tailwindcss-animate')
|
||||
],
|
||||
theme: {
|
||||
boxShadow: {
|
||||
/* Customized */
|
||||
DEFAULT: "0 6px 8px rgba(102, 119, 136, 0.03), 0 1px 2px rgba(102, 119, 136, 0.3)",
|
||||
md: "0 4px 6px -1px rgba(102, 119, 136, 0.05), 0 2px 4px -1px rgba(102, 119, 136, 0.35)",
|
||||
DEFAULT: '0 6px 8px rgba(102, 119, 136, 0.03), 0 1px 2px rgba(102, 119, 136, 0.3)',
|
||||
md: '0 4px 6px -1px rgba(102, 119, 136, 0.05), 0 2px 4px -1px rgba(102, 119, 136, 0.35)',
|
||||
|
||||
/* Default */
|
||||
sm: "0 1px 2px 0 rgba(0, 0, 0, 0.05)",
|
||||
lg: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)",
|
||||
xl: "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
|
||||
"2xl": "0 25px 50px -12px rgba(0, 0, 0, 0.25)",
|
||||
"3xl": "0 35px 60px -15px rgba(0, 0, 0, 0.3)",
|
||||
inner: "inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)",
|
||||
none: "none",
|
||||
},
|
||||
sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
|
||||
lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
|
||||
xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
|
||||
'2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
|
||||
'3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)',
|
||||
inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)',
|
||||
none: 'none'
|
||||
}
|
||||
},
|
||||
content: {
|
||||
files: ["**/*.{ejs,md}", "**/widget/*.html", "**/js/main.js"],
|
||||
},
|
||||
files: [
|
||||
'source/**/*.md',
|
||||
'themes/coo/layout/**/*.ejs',
|
||||
'source/widget/*.html',
|
||||
'themes/coo/source/js/main.js'
|
||||
]
|
||||
}
|
||||
};
|
||||
@@ -1,47 +1,47 @@
|
||||
const h2_re = /<h2 id=".*"><a class="h-anchor" href="(#.*)">#<\/a>(.*)<\/h2>/gm;
|
||||
const h3_re = /<h3 id=".*"><a class="h-anchor" href="(#.*)">#<\/a>(.*)<\/h3>/gm;
|
||||
|
||||
hexo.extend.filter.register("after_post_render", function (data) {
|
||||
hexo.extend.filter.register('after_post_render', (data) => {
|
||||
let h2_m;
|
||||
let h2_list = [];
|
||||
const h2_list = [];
|
||||
while ((h2_m = h2_re.exec(data.content)) !== null) {
|
||||
h2_list.push({
|
||||
anchor: h2_m[1].trim(),
|
||||
title: h2_m[2].trim(),
|
||||
start: h2_m.index,
|
||||
start: h2_m.index
|
||||
});
|
||||
}
|
||||
|
||||
let h3_list = [];
|
||||
const h3_list = [];
|
||||
for (let i = 0; i < h2_list.length; i++) {
|
||||
let start = h2_list[i].start;
|
||||
const start = h2_list[i].start;
|
||||
let end = data.content.length;
|
||||
let next = h2_list[i + 1];
|
||||
const next = h2_list[i + 1];
|
||||
if (next !== undefined) {
|
||||
end = next.start;
|
||||
}
|
||||
const h2_section = data.content.substring(start, end);
|
||||
let h3_m;
|
||||
let h3_items = [];
|
||||
const h3_items = [];
|
||||
while ((h3_m = h3_re.exec(h2_section)) !== null) {
|
||||
h3_items.push({
|
||||
anchor: h3_m[1].trim(),
|
||||
title: h3_m[2].trim(),
|
||||
title: h3_m[2].trim()
|
||||
});
|
||||
}
|
||||
h2_list[i] = h2_list[i];
|
||||
// h2_list[i] = h2_list[i]; // Remove self-assignment
|
||||
h3_list.push(h3_items);
|
||||
}
|
||||
|
||||
let cards = [];
|
||||
const cards = [];
|
||||
for (let i = 0; i < h2_list.length; i++) {
|
||||
if (h3_list[i].length === 0) {
|
||||
continue;
|
||||
}
|
||||
delete h2_list[i]["start"];
|
||||
delete h2_list[i].start;
|
||||
cards.push({
|
||||
h2: h2_list[i],
|
||||
h3: h3_list[i],
|
||||
h3: h3_list[i]
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
hexo.extend.helper.register("request_cheatsheet", function () {
|
||||
return `https://github.com/Fechin/reference/issues/new?title=Cheatsheet+request%3A+&labels=request&template=cheatsheet-request.md&assignee=Fechin`;
|
||||
hexo.extend.helper.register('request_cheatsheet', () => {
|
||||
return 'https://github.com/Fechin/reference/issues/new?title=Cheatsheet+request%3A+&labels=request&template=cheatsheet-request.md&assignee=Fechin';
|
||||
});
|
||||
|
||||
hexo.extend.helper.register("contributing", function () {
|
||||
return `https://github.com/Fechin/reference`;
|
||||
hexo.extend.helper.register('contributing', () => {
|
||||
return 'https://github.com/Fechin/reference';
|
||||
});
|
||||
|
||||
hexo.extend.helper.register("edit_page", function () {
|
||||
let postPage = this.page["layout"] === "post";
|
||||
let url = "https://github.com/Fechin/reference";
|
||||
hexo.extend.helper.register('edit_page', function () {
|
||||
const postPage = this.page.layout === 'post';
|
||||
let url = 'https://github.com/Fechin/reference';
|
||||
if (postPage) {
|
||||
url += `/blob/main/source/_posts/${this.page.slug}.md`;
|
||||
}
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
hexo.extend.helper.register("icon", (name) => svgIcon(name));
|
||||
hexo.extend.helper.register('icon', (name) => svgIcon(name));
|
||||
|
||||
hexo.extend.generator.register("json", function (locals) {
|
||||
let searchName = "search.json";
|
||||
let datas = locals.posts.sort("date") || [];
|
||||
hexo.extend.generator.register('json', (locals) => {
|
||||
const searchName = 'search.json';
|
||||
const datas = locals.posts.sort('date') || [];
|
||||
|
||||
let res = [];
|
||||
const res = [];
|
||||
let index = 0;
|
||||
|
||||
datas.each(function (data) {
|
||||
if (data.indexing !== undefined && !data.indexing) return;
|
||||
if (data.layout === "note") return;
|
||||
let temp_data = {};
|
||||
datas.each((data) => {
|
||||
if (data.indexing !== undefined && !data.indexing) {
|
||||
return;
|
||||
}
|
||||
if (data.layout === 'note') {
|
||||
return;
|
||||
}
|
||||
const temp_data = {};
|
||||
|
||||
temp_data.index = index;
|
||||
temp_data.title = data.title;
|
||||
temp_data.path = data.permalink.replace(hexo.config.url, "");
|
||||
temp_data.path = data.permalink.replace(hexo.config.url, '');
|
||||
temp_data.icon = svgIcon(data.slug);
|
||||
temp_data.background = data.background;
|
||||
temp_data.intro = data.intro;
|
||||
@@ -25,7 +29,7 @@ hexo.extend.generator.register("json", function (locals) {
|
||||
// categories
|
||||
temp_data.categories = [];
|
||||
if (data.categories && data.categories.length > 0) {
|
||||
data.categories.forEach(function (category) {
|
||||
data.categories.forEach((category) => {
|
||||
temp_data.categories.push(category.name);
|
||||
});
|
||||
}
|
||||
@@ -33,7 +37,7 @@ hexo.extend.generator.register("json", function (locals) {
|
||||
// tags
|
||||
temp_data.tags = [];
|
||||
if (data.tags && data.tags.length > 0) {
|
||||
data.tags.forEach(function (tag) {
|
||||
data.tags.forEach((tag) => {
|
||||
temp_data.tags.push(tag.name);
|
||||
});
|
||||
}
|
||||
@@ -44,41 +48,41 @@ hexo.extend.generator.register("json", function (locals) {
|
||||
index += 1;
|
||||
});
|
||||
|
||||
let json = JSON.stringify(res);
|
||||
const json = JSON.stringify(res);
|
||||
return { path: searchName, data: json };
|
||||
});
|
||||
|
||||
hexo.extend.generator.register("list", function (locals) {
|
||||
hexo.extend.generator.register('list', (locals) => {
|
||||
const themeConfig = hexo.theme.config;
|
||||
let content = "";
|
||||
let content = '';
|
||||
|
||||
themeConfig.index_categories.forEach(function (category) {
|
||||
themeConfig.index_categories.forEach((category) => {
|
||||
content += `<details>\n<summary>${category}</summary>\n\n`;
|
||||
locals.categories
|
||||
.findOne({ name: category })
|
||||
.posts.sort("-date")
|
||||
.map(function (post) {
|
||||
.posts.sort('-date')
|
||||
.map((post) => {
|
||||
content += `- [${post.title}](https://cheatsheets.zip/${post.path}): ${post.intro.trim()}\n`;
|
||||
});
|
||||
content += `\n</details>\n\n`;
|
||||
content += '\n</details>\n\n';
|
||||
});
|
||||
|
||||
return {
|
||||
path: "list.md",
|
||||
data: content,
|
||||
path: 'list.md',
|
||||
data: content
|
||||
};
|
||||
});
|
||||
|
||||
function svgIcon(name) {
|
||||
// Check file exists
|
||||
let svgPath = path.resolve("./", "source/assets/icon/", `${name}.svg`);
|
||||
const svgPath = path.resolve('./', 'source/assets/icon/', `${name}.svg`);
|
||||
if (fs.existsSync(svgPath)) {
|
||||
return fs.readFileSync(svgPath, "utf8");
|
||||
return fs.readFileSync(svgPath, 'utf8');
|
||||
} else {
|
||||
return (
|
||||
'<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg" fill="currentColor" height="1em" width="1em">\n' +
|
||||
' <path d="M886.25058594 98.67324219L137.8385 98.67324219c-39.31382813 0-71.47256836 29.21941406-71.47256836 68.59713867l0 687.8025c0 39.37675781 32.15786133 71.60036133 71.47256836 71.60036133l754.3764 0c39.31382813 0 68.51162109-32.22360352 68.51162109-71.60036133L960.72652109 167.2703C960.72558594 127.89256836 925.56529297 98.67324219 886.25058594 98.67324219zM354.49103516 200.47132812c60.54662109 0 109.63617188 49.04727539 109.63617187 109.5516211 0 60.50425781-49.08867187 109.55162109-109.63617187 109.55162109s-109.63617188-49.04727539-109.63617188-109.55162109C244.85477539 249.51772461 293.94353516 200.47132812 354.49103516 200.47132812zM167.03632813 839.84574219c-8.22058594 0-16.50506836-2.83227539-23.23441407-8.62646485-14.99308594-12.86279297-16.73912109-35.45727539-3.87632812-50.47286132l164.34720703-247.7241211c12.20396484-14.26860352 33.32970703-16.65448242 48.42896484-5.47286133l145.00977539 107.69668946 259.82191407-295.15227539c12.30925781-15.44036133 77.58448242-88.16853516 115.79036132-5.68529297 0.04227539-0.12779297 0.08551758 109.06110352 0.12779297 220.54948242 0.04227539 116.28272461 0.06389648 284.78162109 0.06389649 284.78162109C872.72808594 839.54603516 167.37646484 839.84574219 167.03632813 839.84574219z"></path>\n' +
|
||||
"</svg>"
|
||||
'</svg>'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,46 +1,47 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
hexo.extend.filter.register("markdown-it:renderer", function (md) {
|
||||
md.use(require("markdown-it-abbr"), {});
|
||||
md.use(require("markdown-it-footnote"), {});
|
||||
md.use(require("markdown-it-ins"), {});
|
||||
md.use(require("markdown-it-sub"), {});
|
||||
md.use(require("markdown-it-sup"), {});
|
||||
md.use(require("markdown-it-task-lists"), {});
|
||||
md.use(require("markdown-it-emoji"), {});
|
||||
md.use(require("markdown-it-attrs"), {});
|
||||
md.use(require("markdown-it-highlightjs"), {});
|
||||
md.use(require("markdown-it-checkbox"), {});
|
||||
md.use(require("markdown-it-multimd-table"), {
|
||||
hexo.extend.filter.register('markdown-it:renderer', (md) => {
|
||||
md.use(require('markdown-it-abbr'), {});
|
||||
md.use(require('markdown-it-footnote'), {});
|
||||
md.use(require('markdown-it-ins'), {});
|
||||
md.use(require('markdown-it-sub'), {});
|
||||
md.use(require('markdown-it-sup'), {});
|
||||
md.use(require('markdown-it-task-lists'), {});
|
||||
md.use(require('markdown-it-emoji'), {});
|
||||
md.use(require('markdown-it-attrs'), {});
|
||||
md.use(require('markdown-it-highlightjs'), {});
|
||||
md.use(require('markdown-it-checkbox'), {});
|
||||
md.use(require('markdown-it-multimd-table'), {
|
||||
multiline: false,
|
||||
rowspan: true,
|
||||
headerless: false,
|
||||
headerless: false
|
||||
});
|
||||
md.use(require("markdown-it-shortcode-tag"), {
|
||||
md.use(require('markdown-it-shortcode-tag'), {
|
||||
widget: {
|
||||
render: function (attrs, env) {
|
||||
let widgetPath = path.resolve(`./source/widget/${attrs.name}.html`);
|
||||
render(attrs, _env) {
|
||||
const widgetPath = path.resolve(`./source/widget/${attrs.name}.html`);
|
||||
if (fs.existsSync(widgetPath)) {
|
||||
return fs.readFileSync(widgetPath, "utf8").trim();
|
||||
return fs.readFileSync(widgetPath, 'utf8').trim();
|
||||
} else {
|
||||
let error = `Error: ${attrs.name} widget not Found!`;
|
||||
const error = `Error: ${attrs.name} widget not Found!`;
|
||||
console.log(error);
|
||||
return error;
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
headerSections(md, {
|
||||
h2: {
|
||||
wrapperClass: "h2-wrap",
|
||||
innerClass: "h3-wrap-list",
|
||||
wrapperClass: 'h2-wrap',
|
||||
innerClass: 'h3-wrap-list'
|
||||
},
|
||||
h3: {
|
||||
wrapperClass: "h3-wrap",
|
||||
innerClass: "section",
|
||||
wrapperClass: 'h3-wrap',
|
||||
innerClass: 'section'
|
||||
},
|
||||
tagName: "div",
|
||||
tagName: 'div'
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,13 +49,13 @@ function headerSections(md, options) {
|
||||
const opts = Object.assign({}, options);
|
||||
|
||||
function addSections(state) {
|
||||
let tokens = []; // output
|
||||
let Token = state.Token;
|
||||
let sections = [];
|
||||
const tokens = []; // output
|
||||
const Token = state.Token;
|
||||
const sections = [];
|
||||
let nestedLevel = 0;
|
||||
|
||||
function openTag(token, parser, classOptName) {
|
||||
let t = new Token(parser, opts.tagName, 1);
|
||||
const t = new Token(parser, opts.tagName, 1);
|
||||
t.block = true;
|
||||
const cls = token && opts[token.tag] && opts[token.tag][classOptName];
|
||||
t.attrs = appendClass(token.attrs, cls);
|
||||
@@ -62,7 +63,7 @@ function headerSections(md, options) {
|
||||
}
|
||||
|
||||
function closeTag(parser) {
|
||||
let t = new Token(parser, opts.tagName, -1);
|
||||
const t = new Token(parser, opts.tagName, -1);
|
||||
t.block = true;
|
||||
return t;
|
||||
}
|
||||
@@ -70,31 +71,31 @@ function headerSections(md, options) {
|
||||
function closeSections(section) {
|
||||
while (last(sections) && section.header <= last(sections).header) {
|
||||
sections.pop();
|
||||
tokens.push(closeTag("section_inner_close"));
|
||||
tokens.push(closeTag("section_wrapper_close"));
|
||||
tokens.push(closeTag('section_inner_close'));
|
||||
tokens.push(closeTag('section_wrapper_close'));
|
||||
}
|
||||
}
|
||||
|
||||
function closeSectionsToCurrentNesting(nesting) {
|
||||
while (last(sections) && nesting < last(sections).nesting) {
|
||||
sections.pop();
|
||||
tokens.push(closeTag("section_inner_close"));
|
||||
tokens.push(closeTag("section_wrapper_close"));
|
||||
tokens.push(closeTag('section_inner_close'));
|
||||
tokens.push(closeTag('section_wrapper_close'));
|
||||
}
|
||||
}
|
||||
|
||||
function closeAllSections() {
|
||||
while (sections.pop()) {
|
||||
tokens.push(closeTag("section_inner_close"));
|
||||
tokens.push(closeTag("section_wrapper_close"));
|
||||
tokens.push(closeTag('section_inner_close'));
|
||||
tokens.push(closeTag('section_wrapper_close'));
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0, l = state.tokens.length; i < l; i++) {
|
||||
let token = state.tokens[i];
|
||||
const token = state.tokens[i];
|
||||
|
||||
// record level of nesting
|
||||
if (token.type.search("heading") !== 0) {
|
||||
if (token.type.search('heading') !== 0) {
|
||||
nestedLevel += token.nesting;
|
||||
}
|
||||
if (last(sections) && nestedLevel < last(sections).nesting) {
|
||||
@@ -102,20 +103,20 @@ function headerSections(md, options) {
|
||||
}
|
||||
|
||||
// add sections before headers
|
||||
let expect = opts.hasOwnProperty(token.tag);
|
||||
if (token.type === "heading_open") {
|
||||
let section = {
|
||||
const expect = Object.prototype.hasOwnProperty.call(opts, token.tag);
|
||||
if (token.type === 'heading_open') {
|
||||
const section = {
|
||||
header: headingLevel(token.tag),
|
||||
nesting: nestedLevel,
|
||||
nesting: nestedLevel
|
||||
};
|
||||
if (last(sections) && section.header <= last(sections).header && expect) {
|
||||
closeSections(section);
|
||||
}
|
||||
if (expect) {
|
||||
tokens.push(openTag(token, "section_wrapper_open", "wrapperClass"));
|
||||
if (token.attrIndex("id") !== -1) {
|
||||
tokens.push(openTag(token, 'section_wrapper_open', 'wrapperClass'));
|
||||
if (token.attrIndex('id') !== -1) {
|
||||
// remove ID from token
|
||||
token.attrs.splice(token.attrIndex("id"), 1);
|
||||
token.attrs.splice(token.attrIndex('id'), 1);
|
||||
}
|
||||
sections.push(section);
|
||||
|
||||
@@ -125,11 +126,11 @@ function headerSections(md, options) {
|
||||
}
|
||||
|
||||
tokens.push(token);
|
||||
} else if (token.type === "heading_close") {
|
||||
} else if (token.type === 'heading_close') {
|
||||
// add inner section after headers
|
||||
tokens.push(token);
|
||||
if (expect) {
|
||||
tokens.push(openTag(token, "section_inner_open", "innerClass"));
|
||||
tokens.push(openTag(token, 'section_inner_open', 'innerClass'));
|
||||
}
|
||||
} else {
|
||||
tokens.push(token);
|
||||
@@ -141,21 +142,21 @@ function headerSections(md, options) {
|
||||
}
|
||||
|
||||
function appendClass(attrs, cls) {
|
||||
if (cls == null) {
|
||||
if (cls === null) {
|
||||
return attrs;
|
||||
}
|
||||
if (attrs == null) {
|
||||
if (attrs === null) {
|
||||
attrs = [];
|
||||
}
|
||||
let appended = false;
|
||||
attrs.forEach(function (x, i) {
|
||||
if (x[0] === "class") {
|
||||
x[1] = cls + " " + x[1];
|
||||
attrs.forEach((x, _i) => {
|
||||
if (x[0] === 'class') {
|
||||
x[1] = `${cls} ${x[1]}`;
|
||||
appended = true;
|
||||
}
|
||||
});
|
||||
if (!appended) {
|
||||
attrs.push(["class", cls.trim()]);
|
||||
attrs.push(['class', cls.trim()]);
|
||||
}
|
||||
return attrs;
|
||||
}
|
||||
@@ -168,5 +169,5 @@ function headerSections(md, options) {
|
||||
return arr.slice(-1)[0];
|
||||
}
|
||||
|
||||
md.core.ruler.push("header_sections", addSections);
|
||||
md.core.ruler.push('header_sections', addSections);
|
||||
}
|
||||
@@ -3,6 +3,6 @@
|
||||
* This fixes an issue with hexo-renderer-stylus, which otherwise ignores these
|
||||
* configuration overrides.
|
||||
*/
|
||||
hexo.on("generateBefore", function () {
|
||||
hexo.on('generateBefore', () => {
|
||||
hexo.theme.config = Object.assign({}, hexo.theme.config, hexo.config.theme_config);
|
||||
});
|
||||
@@ -1,14 +1,14 @@
|
||||
let pagination = require("hexo-pagination");
|
||||
const pagination = require('hexo-pagination');
|
||||
|
||||
hexo.extend.generator.register("notes-pagination", function (locals) {
|
||||
let config = this.config;
|
||||
let posts = locals.posts.filter((post) => post.layout === "note").sort("-date");
|
||||
return pagination("notes", posts, {
|
||||
hexo.extend.generator.register('notes-pagination', function (locals) {
|
||||
const config = this.config;
|
||||
const posts = locals.posts.filter((post) => post.layout === 'note').sort('-date');
|
||||
return pagination('notes', posts, {
|
||||
perPage: config.per_page,
|
||||
layout: ["notes"],
|
||||
format: "%d/",
|
||||
layout: ['notes'],
|
||||
format: '%d/',
|
||||
data: {
|
||||
_isNotePagination: true,
|
||||
},
|
||||
_isNotePagination: true
|
||||
}
|
||||
});
|
||||
});
|
||||
+21
-19
@@ -1,19 +1,19 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
hexo.extend.helper.register("page_title", function () {
|
||||
let title = "";
|
||||
hexo.extend.helper.register('page_title', function () {
|
||||
let title = '';
|
||||
if (this.is_home()) {
|
||||
title = `${this.config.title} - ${this.config.subtitle}`;
|
||||
} else if (this.page.layout === "note") {
|
||||
} else if (this.page.layout === 'note') {
|
||||
title = `${this.page.title} - ${this.config.title}`;
|
||||
} else if (this.is_page()) {
|
||||
title = `${this.page.title} - ${this.config.title}`;
|
||||
} else if (this.is_post()) {
|
||||
title = this.page.title;
|
||||
let hasCommand = this.page.categories.findOne({ name: "Linux Command" });
|
||||
const hasCommand = this.page.categories.findOne({ name: 'Linux Command' });
|
||||
if (hasCommand) {
|
||||
title += " Command";
|
||||
title += ' Command';
|
||||
}
|
||||
title = `${title} Cheat Sheet & Quick Reference`;
|
||||
} else if (this.page._isNotePagination) {
|
||||
@@ -22,41 +22,43 @@ hexo.extend.helper.register("page_title", function () {
|
||||
return title;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register("page_description", function () {
|
||||
hexo.extend.helper.register('page_description', function () {
|
||||
let description;
|
||||
if (this.is_home()) {
|
||||
description = this.config.description;
|
||||
} else if (this.page != null && this.page.intro != null) {
|
||||
} else if (this.page && this.page.intro && this.page.intro.trim()) {
|
||||
description = this.strip_html(this.markdown(this.page.intro)).substring(0, 110);
|
||||
} else {
|
||||
} else if (this.page && this.page.content) {
|
||||
description = this.strip_html(this.page.content).substring(0, 130);
|
||||
} else {
|
||||
description = this.config.description || '';
|
||||
}
|
||||
description = description.replace(/[\r\n\s\s+]+/g, " ");
|
||||
description = description.replace(/[\r\n\s\s+]+/g, ' ');
|
||||
return description;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register("page_keywords", function () {
|
||||
hexo.extend.helper.register('page_keywords', function () {
|
||||
let keywords = this.config.keywords;
|
||||
if (this.page.tags && this.page.tags.each) {
|
||||
this.page.tags.each(function (tag) {
|
||||
keywords += "," + tag.name;
|
||||
this.page.tags.each((tag) => {
|
||||
keywords += `,${tag.name}`;
|
||||
});
|
||||
}
|
||||
return keywords;
|
||||
});
|
||||
|
||||
hexo.extend.helper.register("page_image", function () {
|
||||
let homePng = "preview.png";
|
||||
let postPng = "";
|
||||
hexo.extend.helper.register('page_image', function () {
|
||||
const homePng = 'preview.png';
|
||||
let postPng = '';
|
||||
if (this.is_post()) {
|
||||
postPng = `${this.page.slug}-preview.png`;
|
||||
}
|
||||
|
||||
let version = (Math.random() + 1).toString(36).substring(7);
|
||||
const version = (Math.random() + 1).toString(36).substring(7);
|
||||
let imageURL;
|
||||
|
||||
// Check file exists
|
||||
let postPath = path.resolve("./", "source/assets/image/", postPng);
|
||||
const postPath = path.resolve('./', 'source/assets/image/', postPng);
|
||||
if (fs.existsSync(postPath)) {
|
||||
// Generate image url
|
||||
imageURL = `${this.config.url}/assets/image/${postPng}?v=${version}`;
|
||||
|
||||
+13
-13
@@ -1,30 +1,30 @@
|
||||
const { encodeURL } = require("hexo-util");
|
||||
const { encodeURL } = require('hexo-util');
|
||||
|
||||
hexo.extend.helper.register("share_link", function (type) {
|
||||
let title = this.page_title();
|
||||
let description = this.page_description();
|
||||
let url = this.url_for(this.url);
|
||||
let link = "";
|
||||
hexo.extend.helper.register('share_link', function (type) {
|
||||
const title = this.page_title();
|
||||
const description = this.page_description();
|
||||
const url = this.url_for(this.url);
|
||||
let link = '';
|
||||
switch (type) {
|
||||
case "facebook":
|
||||
case 'facebook':
|
||||
link = `https://facebook.com/sharer/sharer.php?u=${url}`;
|
||||
break;
|
||||
case "twitter":
|
||||
case 'twitter':
|
||||
link = `https://twitter.com/intent/tweet/?text=${description}&url=${url}`;
|
||||
break;
|
||||
case "linkedin":
|
||||
case 'linkedin':
|
||||
link = `https://www.linkedin.com/shareArticle?url=${url}&title=${title}&summary=${description}`;
|
||||
break;
|
||||
case "reddit":
|
||||
case 'reddit':
|
||||
link = `https://reddit.com/submit/?url=${url}&resubmit=true&title=${description}`;
|
||||
break;
|
||||
case "pinterest":
|
||||
case 'pinterest':
|
||||
link = `https://pinterest.com/pin/create/button/?url=${url}&description=${description}`;
|
||||
break;
|
||||
case "mail":
|
||||
case 'mail':
|
||||
link = `mailto:?subject=${title}&body=\n${description}\n\n${url}`;
|
||||
break;
|
||||
case "line":
|
||||
case 'line':
|
||||
link = `https://social-plugins.line.me/lineit/share?url=${url}`;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
const path = require("path");
|
||||
const fs = require("hexo-fs");
|
||||
const path = require('path');
|
||||
const fs = require('hexo-fs');
|
||||
|
||||
const outputFile = path.resolve("./", "source/ga_analytics_tops.json");
|
||||
const outputFile = path.resolve('./', 'source/ga_analytics_tops.json');
|
||||
const cache = new Map();
|
||||
|
||||
hexo.extend.helper.register("topPosts", function (maximum = 4) {
|
||||
hexo.extend.helper.register('topPosts', (maximum = 4) => {
|
||||
let posts = cache.get(outputFile);
|
||||
if (!posts) {
|
||||
let content = fs.readFileSync(outputFile);
|
||||
const content = fs.readFileSync(outputFile);
|
||||
posts = JSON.parse(content);
|
||||
cache.set(outputFile, posts);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
padding-left: 26px;
|
||||
position: relative;
|
||||
border-bottom: solid 1px #ececec94;
|
||||
|
||||
@apply dark:border-slate-700/50;
|
||||
}
|
||||
|
||||
@@ -12,12 +13,12 @@
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section ul:not(.marker-none, .collapsible, .marker-timeline) > li::before {
|
||||
content: "";
|
||||
content: '';
|
||||
position: absolute;
|
||||
display: inline-block;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
background: #556677;
|
||||
background: #567;
|
||||
border-radius: 50%;
|
||||
left: 14px;
|
||||
top: 18px;
|
||||
@@ -28,8 +29,9 @@
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section ul.marker-round > li::before {
|
||||
content: "";
|
||||
content: '';
|
||||
top: 16px;
|
||||
|
||||
@apply inline-block h-2 w-2 rounded-full border border-2 border-emerald-600 bg-white;
|
||||
}
|
||||
|
||||
@@ -45,15 +47,16 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.collapsible > li > strong.arrow-down:before {
|
||||
content: "▼"; /*▼*/
|
||||
.mdLayout .h3-wrap > .section > ul.collapsible > li > strong.arrow-down::before {
|
||||
content: '▼'; /* ▼ */
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.collapsible > li > strong:before {
|
||||
content: "▶"; /*▼*/
|
||||
.mdLayout .h3-wrap > .section > ul.collapsible > li > strong::before {
|
||||
content: '▶'; /* ▼ */
|
||||
position: absolute;
|
||||
left: 10px;
|
||||
font-size: 0.825em;
|
||||
|
||||
@apply text-emerald-500;
|
||||
}
|
||||
|
||||
@@ -70,11 +73,13 @@
|
||||
padding-left: 22px;
|
||||
margin-left: 30px;
|
||||
border-bottom: 0;
|
||||
|
||||
@apply text-slate-900 dark:border-slate-600 dark:text-slate-50;
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.marker-timeline > li:last-child {
|
||||
padding-bottom: 0.8rem;
|
||||
border-image: linear-gradient(to bottom, #48c78e, rgb(0 0 0 / 0%)) 1 100%;
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.marker-timeline > li > pre {
|
||||
@@ -87,6 +92,7 @@
|
||||
content: counter(stepCount);
|
||||
left: -14px;
|
||||
border: 2px solid #48c78e;
|
||||
|
||||
@apply absolute top-0 h-6 w-6 rounded-full bg-white text-center text-sm;
|
||||
@apply dark:border-slate-600 dark:bg-slate-800;
|
||||
}
|
||||
@@ -96,14 +102,11 @@
|
||||
color: white;
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.marker-timeline > li:last-child {
|
||||
border-image: linear-gradient(to bottom, #48c78e, rgba(0, 0, 0, 0)) 1 100%;
|
||||
}
|
||||
|
||||
.mdLayout .h3-wrap > .section > ul.marker-timeline > li > h4 {
|
||||
color: #2a2839;
|
||||
font-family: "Poppins", sans-serif;
|
||||
font-family: Poppins, sans-serif;
|
||||
font-weight: 500;
|
||||
|
||||
@apply dark:text-slate-300;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
.note-content ul > li {
|
||||
@apply py-2.5 md:px-2.5;
|
||||
|
||||
position: relative;
|
||||
}
|
||||
|
||||
@@ -11,25 +12,18 @@
|
||||
color: #34495e;
|
||||
font-display: swap;
|
||||
font-size: 18px;
|
||||
font-family:
|
||||
source sans pro,
|
||||
open sans,
|
||||
helvetica neue,
|
||||
Arial,
|
||||
sans-serif;
|
||||
font-family: 'source sans pro', 'open sans', 'helvetica neue', Arial, sans-serif;
|
||||
line-height: 1.8;
|
||||
/*@apply dark:text-slate-300;*/
|
||||
min-height: 100%;
|
||||
overflow-wrap: break-word;
|
||||
|
||||
/* @apply dark:text-slate-300; */
|
||||
}
|
||||
|
||||
.note-width {
|
||||
max-width: 46rem;
|
||||
}
|
||||
|
||||
.note-content {
|
||||
min-height: 100%;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.note-content ul,
|
||||
.note-content ol {
|
||||
margin: 2px 0 16px;
|
||||
@@ -38,9 +32,6 @@
|
||||
.note-content p {
|
||||
margin: 4px 0;
|
||||
hyphens: auto;
|
||||
-moz-hyphens: auto;
|
||||
-ms-hyphens: auto;
|
||||
-webkit-hyphens: auto;
|
||||
}
|
||||
|
||||
.node-item pre,
|
||||
@@ -67,13 +58,13 @@
|
||||
.note-content h2 {
|
||||
font-weight: 500;
|
||||
font-size: 1.5rem;
|
||||
margin: 24px 0 2px 0;
|
||||
margin: 24px 0 2px;
|
||||
}
|
||||
|
||||
.note-content h3 {
|
||||
font-weight: 400;
|
||||
font-size: 1.3rem;
|
||||
margin: 24px 0 2px 0;
|
||||
margin: 24px 0 2px;
|
||||
}
|
||||
|
||||
.note-content img,
|
||||
@@ -113,9 +104,9 @@
|
||||
color: #a3a3a3;
|
||||
}
|
||||
|
||||
.note-content blockquote footer cite:before {
|
||||
.note-content blockquote footer cite::before {
|
||||
padding: 0 0.5em;
|
||||
content: "—";
|
||||
content: '—';
|
||||
}
|
||||
|
||||
.note-content .h-anchor {
|
||||
@@ -124,6 +115,7 @@
|
||||
|
||||
.note-content ul.popular-posts > li {
|
||||
@apply py-2.5;
|
||||
|
||||
position: relative;
|
||||
border-bottom: solid 1px #ececec94;
|
||||
}
|
||||
@@ -143,10 +135,10 @@
|
||||
float: left;
|
||||
font-size: 12px;
|
||||
margin-right: 10px;
|
||||
background: rgba(102, 128, 153, 0.075);
|
||||
background: rgb(102 128 153 / 7.5%);
|
||||
border-radius: 4px;
|
||||
padding: 2px 5px;
|
||||
color: rgba(44, 63, 81, 0.5);
|
||||
color: rgb(44 63 81 / 50%);
|
||||
}
|
||||
|
||||
.post-tags-list-link {
|
||||
|
||||
@@ -3,12 +3,14 @@
|
||||
}
|
||||
|
||||
.mdLayout .section > table:last-child::after {
|
||||
content: "";
|
||||
content: '';
|
||||
|
||||
@apply block h-2;
|
||||
}
|
||||
|
||||
.mdLayout table tr + tr {
|
||||
border-top: solid 1px #ececec94;
|
||||
|
||||
@apply dark:border-slate-700/50;
|
||||
}
|
||||
|
||||
@@ -52,7 +54,7 @@
|
||||
.mdLayout table td:first-child > code ~ em {
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
color: #556677;
|
||||
color: #567;
|
||||
}
|
||||
|
||||
.mdLayout table thead {
|
||||
@@ -67,28 +69,24 @@
|
||||
.mdLayout ul.shortcuts > li > code,
|
||||
kbd {
|
||||
letter-spacing: 0.075rem;
|
||||
/*margin: 0px 0.1em;*/
|
||||
|
||||
/* margin: 0px 0.1em; */
|
||||
padding: 0.1em 0.54em;
|
||||
border: 1px solid rgb(204, 204, 204);
|
||||
border: 1px solid rgb(204 204 204);
|
||||
line-height: 1.6;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-size: 12px;
|
||||
display: inline-block;
|
||||
background-color: rgb(247 247 247);
|
||||
box-shadow:
|
||||
0px 1px 0px rgb(0 0 0 / 20%),
|
||||
inset 0px 0px 0px 2px #ffffff;
|
||||
background-color: rgb(247, 247, 247);
|
||||
-moz-box-shadow:
|
||||
0 1px 0px rgba(0, 0, 0, 0.2),
|
||||
0 0 0 2px #ffffff inset;
|
||||
-webkit-box-shadow:
|
||||
0 1px 0px rgb(0 0 0 / 20%),
|
||||
0 0 0 2px #ffffff inset;
|
||||
-moz-border-radius: 3px;
|
||||
-webkit-border-radius: 3px;
|
||||
/*text-shadow: 0 1px 0 #fff;*/
|
||||
0 1px 0 rgb(0 0 0 / 20%),
|
||||
0 0 0 2px #fff inset;
|
||||
border-radius: 3px;
|
||||
|
||||
/* text-shadow: 0 1px 0 #fff; */
|
||||
color: #303835;
|
||||
@apply dark:border-slate-700 dark:bg-slate-700/50 dark:text-slate-300 dark:shadow-none dark:shadow-slate-500;
|
||||
|
||||
@apply dark:border-slate-700 dark:bg-slate-700/50 dark:text-slate-300 dark:shadow-none dark:shadow-slate-500;
|
||||
}
|
||||
|
||||
.mdLayout table.left-text tr th,
|
||||
@@ -105,7 +103,7 @@ kbd {
|
||||
|
||||
.mdLayout table.show-header thead {
|
||||
display: table-header-group;
|
||||
border-bottom: solid 1px rgba(85, 102, 119, 0.3);
|
||||
border-bottom: solid 1px rgb(85 102 119 / 30%);
|
||||
}
|
||||
|
||||
.mdLayout table.bold-first tr > td:first-child {
|
||||
@@ -123,6 +121,7 @@ kbd {
|
||||
|
||||
.mdLayout table td em {
|
||||
opacity: 0.6;
|
||||
|
||||
@apply dark:opacity-90;
|
||||
}
|
||||
|
||||
@@ -138,11 +137,11 @@ kbd {
|
||||
}
|
||||
|
||||
.mdLayout table.style-list-arrow td:first-child::before,
|
||||
ul.style-arrow li:before {
|
||||
content: "";
|
||||
ul.style-arrow li::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 0px;
|
||||
height: 0px;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-right: 6px solid transparent;
|
||||
border-top: 5px solid transparent;
|
||||
border-left: 6px solid #228e6c;
|
||||
|
||||
+200
-178
@@ -1,30 +1,34 @@
|
||||
let Utils = (function () {
|
||||
const Utils = (function () {
|
||||
return {
|
||||
LIBRARY: {
|
||||
fuse: {
|
||||
lib: ["/js/fuse_6.4.6.js"],
|
||||
instance: "Fuse",
|
||||
attr: { async: true },
|
||||
},
|
||||
lib: ['/js/fuse_6.4.6.js'],
|
||||
instance: 'Fuse',
|
||||
attr: { async: true }
|
||||
}
|
||||
},
|
||||
loadScripts: function (urls, callback, attr = {}, container = document.head) {
|
||||
let scripts = [];
|
||||
for (let i in urls) {
|
||||
scripts[i] = document.createElement("script");
|
||||
scripts[i].setAttribute("type", "text/javascript");
|
||||
scripts[i].setAttribute("src", urls[i]);
|
||||
Object.keys(attr).forEach(function (key) {
|
||||
loadScripts(urls, callback, attr = {}, container = document.head) {
|
||||
const scripts = [];
|
||||
for (const i in urls) {
|
||||
scripts[i] = document.createElement('script');
|
||||
scripts[i].setAttribute('type', 'text/javascript');
|
||||
scripts[i].setAttribute('src', urls[i]);
|
||||
Object.keys(attr).forEach((key) => {
|
||||
scripts[i].setAttribute(key, attr[key]);
|
||||
});
|
||||
}
|
||||
let loadNextScript = function () {
|
||||
let script = scripts.shift();
|
||||
function loadNextScript() {
|
||||
const script = scripts.shift();
|
||||
let loaded = false;
|
||||
container.appendChild(script);
|
||||
script.onload = script.onreadystatechange = function () {
|
||||
let rs = this.readyState;
|
||||
if (rs && rs !== "complete" && rs !== "loaded") return;
|
||||
if (loaded) return;
|
||||
const rs = this.readyState;
|
||||
if (rs && rs !== 'complete' && rs !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
if (loaded) {
|
||||
return;
|
||||
}
|
||||
loaded = true;
|
||||
if (scripts.length) {
|
||||
loadNextScript();
|
||||
@@ -32,137 +36,139 @@ let Utils = (function () {
|
||||
callback();
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
loadNextScript();
|
||||
},
|
||||
externalLibrary(library) {
|
||||
return new Promise((resolve) => {
|
||||
if (window[library.instance] == null) {
|
||||
if (typeof window[library.instance] === 'undefined' || window[library.instance] === null) {
|
||||
this.loadScripts(
|
||||
library.lib,
|
||||
function () {
|
||||
() => {
|
||||
resolve(window[library.instance]);
|
||||
},
|
||||
library.attr,
|
||||
library.container,
|
||||
library.container
|
||||
);
|
||||
} else {
|
||||
resolve(window[library.instance]);
|
||||
}
|
||||
});
|
||||
},
|
||||
}
|
||||
};
|
||||
})();
|
||||
|
||||
window.addEventListener("load", () => {
|
||||
const isDarkMode = document.documentElement.classList.contains("dark");
|
||||
window.addEventListener('load', () => {
|
||||
const isDarkMode = document.documentElement.classList.contains('dark');
|
||||
if (!isDarkMode) {
|
||||
let icon = document.querySelector("#darkMode > i").classList;
|
||||
icon.toggle("icon-light");
|
||||
icon.toggle("icon-dark");
|
||||
const icon = document.querySelector('#darkMode > i').classList;
|
||||
icon.toggle('icon-light');
|
||||
icon.toggle('icon-dark');
|
||||
}
|
||||
document.querySelector("#darkMode").addEventListener("click", function () {
|
||||
let html = document.documentElement.classList;
|
||||
html.toggle("dark");
|
||||
let icon = document.querySelector("#darkMode > i").classList;
|
||||
icon.toggle("icon-light");
|
||||
icon.toggle("icon-dark");
|
||||
let isDarkMode = html.contains("dark");
|
||||
localStorage.theme = isDarkMode ? "dark" : "";
|
||||
document.querySelector('#darkMode').addEventListener('click', () => {
|
||||
const html = document.documentElement.classList;
|
||||
html.toggle('dark');
|
||||
const icon = document.querySelector('#darkMode > i').classList;
|
||||
icon.toggle('icon-light');
|
||||
icon.toggle('icon-dark');
|
||||
const isDarkMode = html.contains('dark');
|
||||
localStorage.theme = isDarkMode ? 'dark' : '';
|
||||
});
|
||||
|
||||
/******** List Collapsible ***********/
|
||||
document.querySelectorAll("ul.collapsible > li > strong").forEach(function (strong) {
|
||||
let li = strong.parentElement;
|
||||
li.classList.add("active");
|
||||
strong.classList.toggle("arrow-down");
|
||||
strong.addEventListener("click", function () {
|
||||
li.classList.toggle("active");
|
||||
this.classList.toggle("arrow-down");
|
||||
document.querySelectorAll('ul.collapsible > li > strong').forEach((strong) => {
|
||||
const li = strong.parentElement;
|
||||
li.classList.add('active');
|
||||
strong.classList.toggle('arrow-down');
|
||||
strong.addEventListener('click', function () {
|
||||
li.classList.toggle('active');
|
||||
this.classList.toggle('arrow-down');
|
||||
});
|
||||
});
|
||||
|
||||
/******** Remove bottom border noise ********/
|
||||
document.querySelectorAll(".h3-wrap ul").forEach(function (ul, i) {
|
||||
let length = ul.querySelectorAll("li").length;
|
||||
let matches = ul.className.match("cols-([0-9]+)");
|
||||
let cols = matches === null ? 1 : parseInt(matches[1]);
|
||||
let no_border_length = length === 1 || length % cols === 0 ? cols : length % cols;
|
||||
document.querySelectorAll('.h3-wrap ul').forEach((ul) => {
|
||||
const length = ul.querySelectorAll('li').length;
|
||||
const matches = ul.className.match('cols-([0-9]+)');
|
||||
const cols = matches === null ? 1 : parseInt(matches[1]);
|
||||
const no_border_length = length === 1 || length % cols === 0 ? cols : length % cols;
|
||||
for (let j = 1; j <= no_border_length; j++) {
|
||||
let element = ul.querySelector(`li:nth-last-child(${j})`);
|
||||
if (element != null) {
|
||||
element.style.borderBottom = "none";
|
||||
const element = ul.querySelector(`li:nth-last-child(${j})`);
|
||||
if (element !== null) {
|
||||
element.style.borderBottom = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/******** h3-wrap blink ***********/
|
||||
function blinkSection() {
|
||||
let hash = window.location.hash;
|
||||
let anchor = document.querySelector(`a[class="h-anchor"][href="${hash}"]`);
|
||||
if (anchor != null) {
|
||||
let anchorSection = anchor.parentElement.parentElement;
|
||||
document.querySelectorAll(".boxed").forEach((e) => {
|
||||
e.classList.remove("boxed");
|
||||
const hash = window.location.hash;
|
||||
const anchor = document.querySelector(`a[class="h-anchor"][href="${hash}"]`);
|
||||
if (anchor !== null) {
|
||||
const anchorSection = anchor.parentElement.parentElement;
|
||||
document.querySelectorAll('.boxed').forEach((e) => {
|
||||
e.classList.remove('boxed');
|
||||
});
|
||||
let timer = setTimeout(function () {
|
||||
anchorSection.classList.add("boxed");
|
||||
const timer = setTimeout(() => {
|
||||
anchorSection.classList.add('boxed');
|
||||
clearTimeout(timer);
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
|
||||
blinkSection();
|
||||
window.addEventListener("popstate", blinkSection);
|
||||
window.addEventListener('popstate', blinkSection);
|
||||
|
||||
/******** Search ***********/
|
||||
const searchEngine = function (options) {
|
||||
let settings = options ? options : {};
|
||||
let defaultOptions = {
|
||||
trigger: "#mysearch-trigger",
|
||||
container: "#mysearch",
|
||||
dbPath: `${location.protocol}//${location.host}/search.json?v=1.0`,
|
||||
function SearchEngine(options) {
|
||||
const settings = options ? options : {};
|
||||
const defaultOptions = {
|
||||
trigger: '#mysearch-trigger',
|
||||
container: '#mysearch',
|
||||
dbPath: `${location.protocol}//${location.host}/search.json?v=1.0`
|
||||
};
|
||||
this.container = typeof settings.container != "undefined" ? settings.container : defaultOptions.container;
|
||||
this.trigger = typeof settings.trigger != "undefined" ? settings.trigger : defaultOptions.trigger;
|
||||
this.dbPath = typeof settings.dbPath != "undefined" ? settings.dbPath : defaultOptions.dbPath;
|
||||
this.container =
|
||||
typeof settings.container !== 'undefined' ? settings.container : defaultOptions.container;
|
||||
this.trigger =
|
||||
typeof settings.trigger !== 'undefined' ? settings.trigger : defaultOptions.trigger;
|
||||
this.dbPath = typeof settings.dbPath !== 'undefined' ? settings.dbPath : defaultOptions.dbPath;
|
||||
|
||||
this.lastSearch = {};
|
||||
|
||||
window.search = this;
|
||||
};
|
||||
searchEngine.prototype = {
|
||||
start: function () {
|
||||
}
|
||||
SearchEngine.prototype = {
|
||||
start() {
|
||||
const _this = this;
|
||||
|
||||
_this.fetchData(); // Prepare search data
|
||||
this.search = document.querySelector(this.container);
|
||||
this.box = document.querySelector("#mysearch-box");
|
||||
this.input = document.querySelector("#mysearch-input");
|
||||
this.result = document.querySelector("#mysearch-list");
|
||||
this.box = document.querySelector('#mysearch-box');
|
||||
this.input = document.querySelector('#mysearch-input');
|
||||
this.result = document.querySelector('#mysearch-list');
|
||||
this.lastSearch.query = this.input.value;
|
||||
|
||||
this.detectModal();
|
||||
|
||||
// Cancel button
|
||||
const cancel = document.querySelector(".cancel");
|
||||
cancel.addEventListener("click", function (e) {
|
||||
const cancel = document.querySelector('.cancel');
|
||||
cancel.addEventListener('click', () => {
|
||||
_this.closeModal(true);
|
||||
});
|
||||
|
||||
// Clear button
|
||||
const clear = document.querySelector("#mysearch-clear");
|
||||
clear.addEventListener("click", function (e) {
|
||||
_this.doSearch("", true).then();
|
||||
const clear = document.querySelector('#mysearch-clear');
|
||||
clear.addEventListener('click', () => {
|
||||
_this.doSearch('', true).then();
|
||||
});
|
||||
|
||||
// Search trigger
|
||||
const trigger = document.querySelector(_this.trigger);
|
||||
trigger.addEventListener("click", function (e) {
|
||||
trigger.addEventListener('click', () => {
|
||||
_this.openModal(true);
|
||||
});
|
||||
|
||||
document.body.addEventListener("click", function (e) {
|
||||
document.body.addEventListener('click', (e) => {
|
||||
if (_this.isOpened()) {
|
||||
if (!_this.box.contains(e.target) && !trigger.contains(e.target)) {
|
||||
_this.closeModal();
|
||||
@@ -171,41 +177,41 @@ window.addEventListener("load", () => {
|
||||
});
|
||||
|
||||
// Search input event
|
||||
this.input.addEventListener("keyup", function (e) {
|
||||
let value = _this.input.value;
|
||||
this.input.addEventListener('keyup', () => {
|
||||
const value = _this.input.value;
|
||||
if (value === _this.lastSearch.query) {
|
||||
return;
|
||||
}
|
||||
_this.doSearch(value, true).then();
|
||||
});
|
||||
|
||||
document.body.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowDown") {
|
||||
document.body.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (_this.isOpened()) {
|
||||
_this.moveItem(false);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
} else if (e.key === "ArrowUp") {
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
if (_this.isOpened()) {
|
||||
_this.moveItem(true);
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
} else if (e.key === "Enter") {
|
||||
} else if (e.key === 'Enter') {
|
||||
if (_this.isOpened()) {
|
||||
let active = _this.result.querySelector("li.active > a");
|
||||
if (active != null) {
|
||||
window.location.href = active.getAttribute("href");
|
||||
const active = _this.result.querySelector('li.active > a');
|
||||
if (active !== null) {
|
||||
window.location.href = active.getAttribute('href');
|
||||
}
|
||||
}
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
} else if (e.key === "Escape") {
|
||||
} else if (e.key === 'Escape') {
|
||||
_this.closeModal();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === "k") {
|
||||
} else if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
|
||||
_this.toggleModal();
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -213,64 +219,64 @@ window.addEventListener("load", () => {
|
||||
});
|
||||
},
|
||||
|
||||
moveItem: function (up) {
|
||||
let current = this.result.querySelector("li.active");
|
||||
let next = up ? current.previousElementSibling : current.nextElementSibling;
|
||||
moveItem(up) {
|
||||
const current = this.result.querySelector('li.active');
|
||||
const next = up ? current.previousElementSibling : current.nextElementSibling;
|
||||
if (next !== null) {
|
||||
current.classList.remove("active");
|
||||
current.classList.add("inactive");
|
||||
next.classList.remove("inactive");
|
||||
next.classList.add("active");
|
||||
current.classList.remove('active');
|
||||
current.classList.add('inactive');
|
||||
next.classList.remove('inactive');
|
||||
next.classList.add('active');
|
||||
this.renderPreview();
|
||||
}
|
||||
},
|
||||
detectModal: function () {
|
||||
detectModal() {
|
||||
const url_string = window.location.href;
|
||||
const url = new URL(url_string);
|
||||
const query = url.searchParams.get("q");
|
||||
if (query != null) {
|
||||
const query = url.searchParams.get('q');
|
||||
if (query !== null) {
|
||||
this.input.value = query;
|
||||
this.openModal(false);
|
||||
}
|
||||
},
|
||||
isOpened: function () {
|
||||
return this.search.classList.contains("block");
|
||||
isOpened() {
|
||||
return this.search.classList.contains('block');
|
||||
},
|
||||
toggleModal: function () {
|
||||
toggleModal() {
|
||||
if (this.isOpened()) {
|
||||
this.closeModal();
|
||||
} else {
|
||||
this.openModal();
|
||||
}
|
||||
},
|
||||
openModal: function (reset) {
|
||||
this.search.classList.remove("hidden");
|
||||
this.search.classList.add("block");
|
||||
openModal(reset) {
|
||||
this.search.classList.remove('hidden');
|
||||
this.search.classList.add('block');
|
||||
if (reset) {
|
||||
this.input.value = "";
|
||||
this.input.value = '';
|
||||
}
|
||||
document.body.classList.add("overflow-hidden");
|
||||
document.body.classList.add('overflow-hidden');
|
||||
this.doSearch(this.input.value, false);
|
||||
this.input.focus();
|
||||
},
|
||||
closeModal: function (reset) {
|
||||
this.search.classList.remove("block");
|
||||
this.search.classList.add("hidden");
|
||||
closeModal(reset) {
|
||||
this.search.classList.remove('block');
|
||||
this.search.classList.add('hidden');
|
||||
if (reset) {
|
||||
this.input.value = "";
|
||||
this.input.value = '';
|
||||
}
|
||||
document.body.classList.remove("overflow-hidden");
|
||||
document.body.classList.remove('overflow-hidden');
|
||||
this.input.blur();
|
||||
},
|
||||
changeUrl: function (params) {
|
||||
let baseURL = `${location.protocol}//${location.host}${location.pathname}`;
|
||||
changeUrl(params) {
|
||||
const baseURL = `${location.protocol}//${location.host}${location.pathname}`;
|
||||
let newURL = baseURL;
|
||||
if (params !== "" && params != null) {
|
||||
if (params !== '' && params !== null) {
|
||||
newURL = `${baseURL}?${params}`;
|
||||
}
|
||||
history.pushState({}, null, newURL);
|
||||
},
|
||||
fetchData: async function () {
|
||||
async fetchData() {
|
||||
const _this = this;
|
||||
if (_this.index !== undefined) {
|
||||
return;
|
||||
@@ -293,33 +299,33 @@ window.addEventListener("load", () => {
|
||||
// ignoreLocation: true,
|
||||
// ignoreFieldNorm: false,
|
||||
keys: [
|
||||
{ name: "title", weight: 12 },
|
||||
{ name: "tags", weight: 6 },
|
||||
{ name: "categories", weight: 6 },
|
||||
{ name: "sections.h3.title", weight: 5 },
|
||||
{ name: "sections.h2.title", weight: 1 },
|
||||
{ name: "intro", weight: 1 },
|
||||
],
|
||||
{ name: 'title', weight: 12 },
|
||||
{ name: 'tags', weight: 6 },
|
||||
{ name: 'categories', weight: 6 },
|
||||
{ name: 'sections.h3.title', weight: 5 },
|
||||
{ name: 'sections.h2.title', weight: 1 },
|
||||
{ name: 'intro', weight: 1 }
|
||||
]
|
||||
});
|
||||
// default return all
|
||||
_this.lastSearch.whole = _this.db.map((doc, idx) => ({
|
||||
item: doc,
|
||||
score: 1,
|
||||
refIndex: idx,
|
||||
refIndex: idx
|
||||
}));
|
||||
return resp;
|
||||
});
|
||||
},
|
||||
doSearch: async function (value, history) {
|
||||
async doSearch(value, history) {
|
||||
const _this = this;
|
||||
await _this.fetchData().then(() => {
|
||||
if (this.lastSearch.query === value && this.lastSearch.resp !== undefined) {
|
||||
this.renderResult(this.lastSearch.resp);
|
||||
this.renderPreview();
|
||||
} else {
|
||||
let results = value !== "" ? _this.index.search(`${value}`) : _this.lastSearch.whole;
|
||||
const results = value !== '' ? _this.index.search(`${value}`) : _this.lastSearch.whole;
|
||||
if (history) {
|
||||
this.changeUrl(value === "" ? null : `q=${value}`);
|
||||
this.changeUrl(value === '' ? null : `q=${value}`);
|
||||
}
|
||||
this.lastSearch.query = value;
|
||||
this.lastSearch.resp = results;
|
||||
@@ -328,40 +334,40 @@ window.addEventListener("load", () => {
|
||||
}
|
||||
});
|
||||
},
|
||||
addEventToResult: function () {
|
||||
addEventToResult() {
|
||||
const _this = this;
|
||||
this.result.querySelectorAll("li").forEach(function (li) {
|
||||
li.addEventListener("mouseover", function (e) {
|
||||
this.result.querySelectorAll('li').forEach((li) => {
|
||||
li.addEventListener('mouseover', function () {
|
||||
if (_this.isOpened()) {
|
||||
_this.result.querySelectorAll("li").forEach(function (e) {
|
||||
e.classList.remove("active");
|
||||
e.classList.add("inactive");
|
||||
_this.result.querySelectorAll('li').forEach((e) => {
|
||||
e.classList.remove('active');
|
||||
e.classList.add('inactive');
|
||||
});
|
||||
this.classList.remove("inactive");
|
||||
this.classList.add("active");
|
||||
this.classList.remove('inactive');
|
||||
this.classList.add('active');
|
||||
_this.renderPreview();
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
mark: function (text, matches) {
|
||||
let result = [];
|
||||
mark(text, matches) {
|
||||
const result = [];
|
||||
let pair = matches.shift();
|
||||
// Build the formatted string
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
let char = text.charAt(i);
|
||||
const char = text.charAt(i);
|
||||
if (pair && i === pair[0]) {
|
||||
result.push("<mark>");
|
||||
result.push('<mark>');
|
||||
}
|
||||
result.push(char);
|
||||
if (pair && i === pair[1]) {
|
||||
result.push("</mark>");
|
||||
result.push('</mark>');
|
||||
pair = matches.shift();
|
||||
}
|
||||
}
|
||||
return result.join("");
|
||||
return result.join('');
|
||||
},
|
||||
highlightMatches: function (result) {
|
||||
highlightMatches(result) {
|
||||
if (result.matches === undefined || result.item.length === 0) {
|
||||
return;
|
||||
}
|
||||
@@ -369,50 +375,54 @@ window.addEventListener("load", () => {
|
||||
result.item = JSON.parse(JSON.stringify(_this.db[result.refIndex]));
|
||||
result.matches.forEach((m) => {
|
||||
switch (m.key) {
|
||||
case "tags":
|
||||
case "categories":
|
||||
case 'tags':
|
||||
case 'categories':
|
||||
result.item[m.key][m.refIndex] = _this.mark(m.value, m.indices);
|
||||
break;
|
||||
case "sections.h2.title":
|
||||
result.item["sections"][m.refIndex]["h2"]["title"] = _this.mark(m.value, m.indices);
|
||||
case 'sections.h2.title':
|
||||
result.item.sections[m.refIndex].h2.title = _this.mark(m.value, m.indices);
|
||||
break;
|
||||
case "sections.h3.title":
|
||||
case 'sections.h3.title': {
|
||||
let currLength = 0;
|
||||
let lastLength = 0;
|
||||
for (let i = 0; i < result.item["sections"].length; i++) {
|
||||
let subArr = result.item["sections"][i]["h3"];
|
||||
for (let i = 0; i < result.item.sections.length; i++) {
|
||||
const subArr = result.item.sections[i].h3;
|
||||
currLength += subArr.length;
|
||||
if (m.refIndex >= lastLength && m.refIndex < currLength) {
|
||||
result.item["sections"][i]["h3"][m.refIndex - lastLength]["title"] = _this.mark(m.value, m.indices);
|
||||
result.item.sections[i].h3[m.refIndex - lastLength].title = _this.mark(
|
||||
m.value,
|
||||
m.indices
|
||||
);
|
||||
break;
|
||||
}
|
||||
lastLength += subArr.length;
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
result.item[m.key] = _this.mark(m.value, m.indices);
|
||||
break;
|
||||
}
|
||||
});
|
||||
},
|
||||
renderResult: function (results) {
|
||||
renderResult(results) {
|
||||
const _this = this;
|
||||
let liHtml = "";
|
||||
let liHtml = '';
|
||||
let index = 0;
|
||||
results.forEach(function (result, itemIndex) {
|
||||
let activeStr = "inactive";
|
||||
results.forEach((result, itemIndex) => {
|
||||
let activeStr = 'inactive';
|
||||
if (index === 0) {
|
||||
activeStr = "active";
|
||||
activeStr = 'active';
|
||||
}
|
||||
|
||||
_this.highlightMatches(result);
|
||||
|
||||
let hit = result.item;
|
||||
let tags = hit.tags || [];
|
||||
let categories = hit.categories || [];
|
||||
let tagStr = tags.join("<span class='text-slate-300 px-1'>•</span>");
|
||||
let tagsHTML = "";
|
||||
if (tagStr !== "") {
|
||||
const hit = result.item;
|
||||
const tags = hit.tags || [];
|
||||
const categories = hit.categories || [];
|
||||
const tagStr = tags.join("<span class='text-slate-300 px-1'>•</span>");
|
||||
let tagsHTML = '';
|
||||
if (tagStr !== '') {
|
||||
tagsHTML = `<div class="w-px h-3 bg-slate-300 mr-2"></div><span class="mr-2">${tagStr}</span>`;
|
||||
}
|
||||
liHtml += `<li class="group ${activeStr} m-3 fadeIn" data-index="${itemIndex}">
|
||||
@@ -439,41 +449,53 @@ window.addEventListener("load", () => {
|
||||
this.addEventToResult();
|
||||
},
|
||||
renderPreview() {
|
||||
const active = this.search.querySelector("li.active");
|
||||
if (active == null) {
|
||||
const active = this.search.querySelector('li.active');
|
||||
if (active === null) {
|
||||
return;
|
||||
}
|
||||
const _this = this;
|
||||
let itemIndex = active.getAttribute("data-index");
|
||||
let hit = _this.lastSearch.resp[parseInt(itemIndex)].item;
|
||||
const itemIndex = active.getAttribute('data-index');
|
||||
const hit = _this.lastSearch.resp[parseInt(itemIndex)].item;
|
||||
|
||||
let olInnerHtml = "";
|
||||
let olInnerHtml = '';
|
||||
|
||||
hit.sections.forEach(function (section, index, array) {
|
||||
let h3HTML = "";
|
||||
section.h3.forEach(function (h3) {
|
||||
let anchor = hit.path + h3.anchor;
|
||||
hit.sections.forEach((section) => {
|
||||
let h3HTML = '';
|
||||
section.h3.forEach((h3) => {
|
||||
const anchor = hit.path + h3.anchor;
|
||||
h3HTML += `<a href="${anchor}" class="inline-block mr-1 px-2 p-0.5 transition duration-200 ease-in-out rounded-full hover:bg-emerald-500 text-slate-500 dark:text-slate-300 hover:text-slate-50">${h3.title.toLowerCase()}</a>`;
|
||||
});
|
||||
let anchor = hit.path + section.h2.anchor;
|
||||
const anchor = hit.path + section.h2.anchor;
|
||||
olInnerHtml += `<li class="text-slate-700 dark:text-slate-300 hover:underline hover:text-slate-900 mt-3 mb-2">
|
||||
<a href="${anchor}"> ${section.h2.title}</a>
|
||||
</li>
|
||||
<span>${h3HTML}</span>`;
|
||||
});
|
||||
|
||||
document.querySelector(".preview-panel").innerHTML = `<section class="w-full py-3 px-5">
|
||||
document.querySelector('.preview-panel').innerHTML = `<section class="w-full py-3 px-5">
|
||||
<div class="flex justify-center pt-1 pb-4">
|
||||
<div class="flex justify-center items-center w-8 h-8 rounded ${hit.background === undefined ? "bg-emerald-500" : hit.background} shadow-lg">
|
||||
<div class="flex justify-center items-center w-8 h-8 rounded ${hit.background === undefined ? 'bg-emerald-500' : hit.background} shadow-lg">
|
||||
<i class="text-2xl text-slate-100">${hit.icon}</i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-center items-center font-medium flex-wrap dark:text-slate-200">${hit.title}</div>
|
||||
<ol class="list-inside mt-4 pt-2 text-sm list-decimal">${olInnerHtml}</ol>
|
||||
</section>`;
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
// Start search
|
||||
Utils.externalLibrary(Utils.LIBRARY.fuse).then(() => new searchEngine().start());
|
||||
Utils.externalLibrary(Utils.LIBRARY.fuse)
|
||||
.then((Fuse) => {
|
||||
if (typeof Fuse === 'undefined') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Fuse.js library failed to load');
|
||||
return;
|
||||
}
|
||||
new SearchEngine().start();
|
||||
})
|
||||
.catch((error) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('Failed to load search library:', error);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user