Merge branch 'main' into chatgpt

This commit is contained in:
S-JZR authored and GitHub committed 2025-08-30 00:34:56 +10:00
commit 17f4796d55
212 files changed
+25368 -3817

No files matched your search

+50
View File
@@ -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']
}
};
-7
View File
@@ -1,7 +0,0 @@
root = true
[*.md]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
+1 -1
View File
@@ -9,4 +9,4 @@ community_bridge: # Replace with a single Community Bridge project-name e.g., cl
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: ["https://buymeacoffee.com/cheatsheets.zip"]
custom: ["https://coff.ee/cheatsheets.zip"]
+1 -1
View File
@@ -1,7 +1,7 @@
---
name: Cheatsheet request
about: For request cheatsheet and reference.
title: "Cheatsheet request: "
title: 'Cheatsheet request: '
labels: request
assignees: Fechin
---
+63 -13
View File
@@ -8,32 +8,82 @@
ehthumbs.db
Thumbs.db
nohup.out
*.tmp
*.temp
# Python files #
# Environment files #
######################
.python-version
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
.python-version
.venv
.ipynb_checkpoints
# Logs #
######################
*.log
# Editor files #
######################
.idea
.vscode
# Node files #
######################
node_modules/
dist/
logs/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Editor files #
######################
.idea/
.vscode/
*.swp
*.swo
*~
.vim/
.emacs.d/
.sublime-*
# Node.js #
######################
node_modules/
dist/
build/
coverage/
.nyc_output/
.cache/
.parcel-cache/
.next/
.nuxt/
.vuepress/dist/
.serverless/
.fusebox/
.dynamodb/
.tern-port
package-lock.json
# Testing #
######################
.jest/
.coverage/
junit.xml
test-results/
# Other files #
# Build artifacts #
######################
themes/coo/source/css/style.css
public/
db.json
*.tgz
*.tar.gz
# Security #
######################
.npmrc
.yarnrc
.pnpm-store/
# Misc #
######################
.eslintcache
.stylelintcache
.prettierignore
+36
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
npx commitlint --edit $1
+1
View File
@@ -0,0 +1 @@
npx lint-staged
+10
View File
@@ -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']
};
-12
View File
@@ -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
View File
@@ -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
-5
View File
@@ -1,5 +0,0 @@
{
"printWidth": 120,
"proseWrap": "always",
"plugins": ["prettier-plugin-tailwindcss"]
}
+42
View File
@@ -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
}
}
]
};
+45
View File
@@ -0,0 +1,45 @@
module.exports = {
extends: ['stylelint-config-standard'],
rules: {
// Tailwind CSS compatibility
'at-rule-no-unknown': [
true,
{
ignoreAtRules: ['tailwind', 'apply', 'variants', 'responsive', 'screen', 'layer']
}
],
// Disable @apply deprecation warning, as this is a Tailwind CSS feature
'at-rule-no-deprecated': null,
// Allow duplicate selectors, as this is common in generated CSS
'no-descending-specificity': null,
'no-duplicate-selectors': null,
// Allow camelCase class names
'selector-class-pattern': null,
// Allow camelCase ID selectors
'selector-id-pattern': null,
// Allow unknown properties (Tailwind generated CSS variables)
'property-no-unknown': null,
// Allow unknown type selectors (custom elements)
'selector-type-no-unknown': null,
// Allow unknown declaration values
'declaration-property-value-no-unknown': null,
// Allow duplicate custom properties
'declaration-block-no-duplicate-custom-properties': null,
// Allow multiple declarations on single line
'declaration-block-single-line-max-declarations': null,
// Allow decimal precision
'number-max-precision': null,
// Allow unknown media feature values
'media-feature-name-value-no-unknown': null,
// Allow non-kebab-case keyframe names
'keyframes-name-pattern': null,
// Allow empty source files
'no-empty-source': null
},
ignoreFiles: [
'node_modules/**/*',
'public/**/*',
'themes/coo/source/css/highlightjs/**/*',
'**/*.min.css'
]
};
+96 -53
View File
@@ -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/).
[![Quick reference](https://cheatsheets.zip/assets/image/preview.png?9nd3)](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
@@ -338,7 +383,7 @@ file should include a front matter section with the following format:
title: CheatSheets
date: 2020-11-25 18:28:43
icon: icon-style
background: bg-emerald-600
background: bg-indigo-600
tags:
categories:
- Other
@@ -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
[![Follow us on Twitter](https://img.shields.io/twitter/follow/FechinLi?color=%234a99e9&style=for-the-badge)](https://twitter.com/FechinLi)
@@ -361,9 +404,9 @@ Only the `title` and `intro` fields are required, and the other options can be l
Stay up-to-date with our project by following us on Twitter! Get all the latest news and updates right in your feed.
It's the perfect way to stay in the loop.
<a href="https://www.buymeacoffee.com/randy8080"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=randy8080&button_colour=40DCA5&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00" /></a>
<a href="https://buymeacoffee.com/cheatsheets.zip"><img src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=cheatsheets.zip&button_colour=40DCA5&font_colour=ffffff&font_family=Cookie&outline_colour=000000&coffee_colour=FFDD00" /></a>
## 📃 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).
+35 -8
View File
@@ -7,9 +7,9 @@ title: CheatSheets.zip
subtitle: "Ultimate Cheat for Developers"
description: "Share quick reference and cheat sheet for developers"
keywords: cheat,sheet,cheatsheets,reference,programming,code table,snippets,linux,command,shortcuts,developers
author: CheatSheets.zip
author: Fechin
language: en
timezone: ""
timezone: "UTC"
# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
@@ -45,6 +45,7 @@ render_drafts: false
post_asset_folder: false
relative_link: false
future: true
syntax_highlighter: # empty to disable built-in syntax highlighting
highlight:
enable: false
@@ -59,13 +60,29 @@ index_generator:
# Category & Tag
default_category: uncategorized
category_map:
tag_map:
category_map: {}
tag_map: {}
# Metadata elements
## https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta
meta_generator: false
# SEO configuration
seo:
# Default image for social sharing
default_image: "/assets/image/preview.png"
# Author information
author_name: "Fechin"
author_url: "https://cheatsheets.zip"
# Social media configuration
social:
twitter: "Fechin"
github: "Fechin/reference"
# Site type
site_type: "Educational Technology Platform"
# Target audience
target_audience: "Developers, Programmers, System Administrators"
# Date / Time format
## Hexo uses Moment.js to parse and display date
## You can customize the date format as defined in
@@ -82,10 +99,10 @@ pagination_dir: page
# Include / Exclude file(s)
## include:/exclude: options only apply to the 'source/' folder
include:
include: []
exclude:
- ".github"
ignore:
ignore: []
# Extensions
## Plugins: https://hexo.io/plugins/
@@ -96,7 +113,11 @@ nofollow:
enable: true
field: site
exclude:
- "exclude1.com"
- "tableconvert.com"
- "dorefer.com"
- "fionaai.com"
- "github.com"
- "x.com"
excerpt:
depth: 2
@@ -107,7 +128,6 @@ excerpt:
# Deployment
## Docs: https://hexo.io/docs/deployment.html
deploy:
# - type: cjh_google_url_submitter
- type: cjh_bing_url_submitter
- type: cjh_baidu_url_submitter
@@ -132,6 +152,7 @@ markdown:
linkify: false
typographer: false
quotes: "“”‘’"
langPrefix: "hljs language-"
anchors:
level: 2
collisionSuffix: ""
@@ -140,3 +161,9 @@ markdown:
permalinkSymbol: "#"
case: 1
separator: "-"
# Browsersync configuration
browsersync:
ui: false # disable ui
notify: false # disable notification
logLevel: silent # set log level to silent
+65
View File
@@ -0,0 +1,65 @@
const js = require('@eslint/js');
const globals = require('globals');
module.exports = [
js.configs.recommended,
{
languageOptions: {
ecmaVersion: 2022,
sourceType: 'module',
globals: {
...globals.browser,
...globals.node
}
},
rules: {
'no-unused-vars': 'warn',
'no-console': 'off'
}
},
{
files: ['**/*.js'],
languageOptions: {
sourceType: 'script',
globals: {
...globals.node,
...globals.browser
}
}
},
{
files: ['source/sw.js'],
languageOptions: {
globals: {
...globals.serviceworker
}
}
},
{
files: ['themes/coo/scripts/**/*.js'],
languageOptions: {
globals: {
...globals.node,
hexo: 'readonly'
}
}
},
{
files: ['themes/coo/source/js/main.js'],
languageOptions: {
globals: {
...globals.browser,
Fuse: 'readonly'
}
}
},
{
ignores: [
'node_modules/**',
'public/**',
'db.json',
'.deploy_git/**',
'themes/coo/source/js/fuse_*.js'
]
}
];
+20 -20
View File
@@ -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'));
+63 -38
View File
@@ -12,69 +12,94 @@
"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",
"audit": "pnpm audit --audit-level moderate",
"audit:fix": "pnpm audit --fix",
"security:check": "pnpm audit && pnpm outdated",
"deps:check": "npx npm-check-updates",
"deps:update": "npx npm-check-updates -u && pnpm install",
"prepare": "husky",
"commit": "cz"
},
"hexo": {
"version": "5.4.2"
"version": "7.3.0"
},
"dependencies": {
"eslint": "^8.27.0",
"gulp": "^4.0.2",
"gulp-cli": "^2.3.0",
"gulp": "^5.0.1",
"gulp-cli": "^3.1.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",
"hexo": "^7.3.0",
"hexo-browsersync": "^0.3.0",
"hexo-cli": "^4.3.0",
"hexo-excerpt": "^1.2.1",
"hexo-excerpt": "^1.3.1",
"hexo-filter-nofollow": "^2.0.2",
"hexo-generator-index": "^2.0.0",
"hexo-generator-sitemap": "^2.2.0",
"hexo-log": "^3.0.0",
"hexo-pagination": "^2.0.0",
"hexo-fs": "^5.0.0",
"hexo-generator-index": "^4.0.0",
"hexo-generator-sitemap": "^3.0.1",
"hexo-log": "^4.1.0",
"hexo-pagination": "^4.0.0",
"hexo-related-popular-posts": "^5.0.1",
"hexo-renderer-ejs": "^2.0.0",
"hexo-renderer-markdown-it": "^5.0.0",
"hexo-renderer-stylus": "^2.0.1",
"hexo-server": "^2.0.0",
"markdown-it-abbr": "^1.0.4",
"markdown-it-anchor": "^8.4.1",
"hexo-renderer-stylus": "^3.0.1",
"hexo-server": "^3.0.0",
"hexo-util": "^3.3.0",
"highlight.js": "^11.11.1",
"markdown-it-abbr": "^2.0.0",
"markdown-it-anchor": "^9.2.0",
"markdown-it-attrs": "^4.3.1",
"markdown-it-checkbox": "^1.1.0",
"markdown-it-emoji": "^2.0.0",
"markdown-it-footnote": "^3.0.3",
"markdown-it-emoji": "^3.0.0",
"markdown-it-footnote": "^4.0.0",
"markdown-it-highlight-lines": "^1.0.2",
"markdown-it-highlightjs": "^3.5.0",
"markdown-it-ins": "^3.0.1",
"markdown-it-multimd-table": "^4.1.1",
"markdown-it-highlightjs": "^4.2.0",
"markdown-it-ins": "^4.0.0",
"markdown-it-shortcode-tag": "^1.1.0",
"markdown-it-sub": "^1.0.0",
"markdown-it-sup": "^1.0.0",
"markdown-it-sub": "^2.0.0",
"markdown-it-sup": "^2.0.0",
"markdown-it-task-lists": "^2.1.1"
},
"devDependencies": {
"autoprefixer": "^10.4.0",
"@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1",
"autoprefixer": "^10.4.21",
"commitizen": "^4.3.1",
"cssnano": "^7.0.7",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^9.29.0",
"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": "^11.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.7",
"lint-staged": "^16.1.2",
"npm-run-all2": "^8.0.4",
"postcss": "^8.5.6",
"postcss-cli": "^11.0.1",
"postcss-import": "^16.1.1",
"prettier": "^3.5.3",
"prettier-plugin-tailwindcss": "^0.6.12",
"stylelint": "^16.20.0",
"stylelint-config-standard": "^38.0.0",
"tailwindcss": "^3.4.14",
"tailwindcss-animate": "^1.0.7"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}
+10592
View File
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -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: {} } : {})
}
};
+24 -6
View File
@@ -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 -3
View File
@@ -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
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: Aspect Ratio
date: 2022-09-21 10:28:43
background: bg-emerald-600
background: bg-indigo-600
tags:
- photo
- image
+31 -22
View File
@@ -515,26 +515,6 @@ for i in {5..50..5}; do
done
```
### Auto increment
```bash
i=1
while [[ $i -lt 4 ]]; do
echo "Number: $i"
((i++))
done
```
### Auto decrement
```bash
i=3
while [[ $i -gt 0 ]]; do
echo "Number: $i"
((i--))
done
```
### Continue
```bash {data=3,5}
@@ -569,6 +549,35 @@ until [ $count -gt 10 ]; do
done
```
### While with increment
```bash
i=1
while [[ $i -lt 4 ]]; do
echo "Number: $i"
((i++))
done
```
### While with decrement
```bash
i=3
while [[ $i -gt 0 ]]; do
echo "Number: $i"
((i--))
done
```
#### Combined with test
```bash
i=3
while ((i--)); do
echo "Number: $i"
done
```
### Forever
```bash
@@ -588,9 +597,9 @@ done
### Reading lines
```bash
cat file.txt | while read line; do
while read line; do
echo $line
done
done < file.txt
```
## Bash Functions
+243 -238
View File
@@ -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)
+1 -1
View File
@@ -1014,4 +1014,4 @@ Scenario:
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>
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: Chmod
date: 2021-07-01 10:51:44
background: bg-emerald-600
background: bg-indigo-600
tags:
- permission
categories:
+61
View File
@@ -0,0 +1,61 @@
---
title: Color Picker
date: 2025-07-01 18:28:43
background: bg-[#2a6387]
tags:
- html
- color
categories:
- Toolkit
intro: The Color Picker cheat sheet provides you basic color info and choices
plugins:
- copyCode
---
## Getting Started
### Color Basics {.col-span-3}
| **Category** | **Description** |
|:---------------------------------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **Color Models** | **RGB**: Red, Green, Blue – additive model used in screens. <br> **HEX**: Hexadecimal color codes, e.g., #FFFFFF. <br> **HSL**: Hue, Saturation, Lightness – intuitive for color adjustments. <br> **HSV**: Hue, Saturation, Value – similar to HSL but with different brightness handling. |
| **Color Terminology** | **Saturation**: Intensity or purity of a color. <br> **Hue**: The color type (e.g., red, blue). <br> **Lightness**: Brightness or darkness of a color. <br> **Opacity**: Transparency level of a color, often defined as alpha in RGBA. |
| **Color Representation Formats** | **HEX**: `#RRGGBB` or `#RRGGBBAA` (with alpha). <br> **RGB**: `rgb(255, 255, 255)` <br> **RGBA**: `rgba(255, 255, 255, 0.5)` <br> **HSL**: `hsl(120, 100%, 50%)` <br> **HSLA**: `hsla(120, 100%, 50%, 0.5)` |
### Main Frameworks {.col-span-3}
| **Framework** | **Color Notation / Syntax** | **Description** | **Documentation Link** |
|:-----------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------------------------------|:-------------------------------------------------------------------------------------------|
| **CSS** | `color: red;` <br> `color: #ff0000;` <br> `color: rgb(255, 0, 0);` <br> `color: rgba(255, 0, 0, 0.5);` <br> `color: hsl(0, 100%, 50%);` <br> `color: hsla(0, 100%, 50%, 0.5);` | Standard CSS color properties and formats. | [CSS Color Documentation](https://developer.mozilla.org/en-US/docs/Web/CSS/color) |
| **SASS/SCSS** | `$color: #ff0000;` <br> `color: $color;` | Variables for colors, can use same formats as CSS. | [SASS Color Documentation](https://sass-lang.com/documentation/values/colors) |
| **Tailwind CSS** | `class="bg-red-500"` <br> `class="text-green-300"` | Utility classes with predefined color shades. | [Tailwind CSS Colors](https://tailwindcss.com/docs/customizing-colors) |
| **Bootstrap** | `class="text-primary"` <br> `class="bg-success"` | Named color classes for quick styling. | [Bootstrap Colors](https://getbootstrap.com/docs/5.0/getting-started/introduction/#colors) |
| **Material UI** | `style={{ color: 'primary' }}` or theme palette | Uses theme palette, can override with specific color codes. | [Material UI Color](https://mui.com/customization/color/) |
## Color Palette
### Tailwind Palette {.col-span-3}
<widget name="color-palette-tailwind"/>
## Gradient CSS
### Gradient Maker {.col-span-3}
<widget name="gradient-maker"/>
| Parameter | Description | Example |
|:--------------|:----------------------------------|:-----------------------------------------------|
| **to right** | Gradient goes from left to right | `linear-gradient(to right, #ff7e5f, #feb47b)` |
| **to left** | Gradient goes from right to left | `linear-gradient(to left, #ff7e5f, #feb47b)` |
| **to bottom** | Gradient goes from top to bottom | `linear-gradient(to bottom, #ff7e5f, #feb47b)` |
| **to top** | Gradient goes from bottom to top | `linear-gradient(to top, #ff7e5f, #feb47b)` |
| **deg** | Specify an angle in degrees | `linear-gradient(45deg, ...)` |
+20 -14
View File
@@ -51,20 +51,26 @@ Min Hour Day Mon Weekday
### Examples
| Example | Description |
| -------------- | ------------------------------------------------ |
| `*/15 * * * *` | Every 15 mins |
| `0 * * * *` | Every hour |
| `0 */2 * * *` | Every 2 hours |
| `15 2 * * *` | At 2:15AM of every day |
| `15 2 * * ?` | At 2:15AM of every day |
| `10 9 * * 5` | At 9:10AM of every Friday |
| `0 0 * * 0` | At midnight of every Sunday |
| `15 2 * * 1L` | At 2:15am on the last monday of every month |
| `15 0 * * 4#2` | At 00:15am on the second thursday of every month |
| `0 0 1 * *` | Every 1st of month (monthly) |
| `0 0 1 1 *` | Every 1st of january (yearly) |
| `@reboot` | Every reboot <br>_(non-standard)_ |
| Example | Description |
| -------------- |--------------------------------------------------------------------|
| `*/15 * * * *` | Every 15 mins |
| `0 * * * *` | Every hour |
| `0 */2 * * *` | Every 2 hours |
| `15 2 * * *` | At 2:15AM (of every day) |
| `15 2 * * ?` | At 2:15AM (of every day) |
| `10 9 * * 5` | At 9:10AM (of every Friday) |
| `0 0 * * 0` | At 12:00 AM, only on Sunday |
| `15 2 * * 1L` | At 2:15am on the last monday of every month |
| `15 0 * * 4#2` | At 00:15am on the second thursday of every month |
| `0 0 1 * *` | At 12:00 AM, on day 1 of the month (1st of month / monthly) |
| `0 0 1 1 *` | At 12:00 AM, on day 1 of the month, only in January (1st of month) |
| `@reboot` | Every reboot <br>_(non-standard)_ |
### Cron Generator {.col-span-3}
<widget name="cron"/>
### Special strings
+5 -5
View File
@@ -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
View File
@@ -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, '.') ' ';
}
```
+4 -6
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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!'
});
});
```
+234
View File
@@ -0,0 +1,234 @@
---
title: FastAPI
date: 2025-06-07 18:40:00
background: bg-[#3730a3]
tags:
- web
- python
- backend
categories:
- Programming
intro: |
A concise cheatsheet for FastAPI, a fast and modern web framework for building APIs with Python 3.7+.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### Install & Run
```bash
pip install fastapi uvicorn
uvicorn main:app --reload
```
### Hello World
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello FastAPI"}
```
### CLI Run Hint
```bash
uvicorn main:app --reload
```
## Routing & Parameters {.cols-3}
### Path Parameter
```python
@app.get("/items/{id}")
def read(id: int):
return {"id": id}
```
### Query Parameter
```python
@app.get("/search")
def find(q: str = "default"):
return {"q": q}
```
### Optional Query
```python
@app.get("/filter")
def filter_data(limit: int = 10, active: bool = True):
return {"limit": limit, "active": active}
```
## Request Body & Validation {.cols-3}
### Using Pydantic
```python
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
```
### JSON Body
```python
@app.post("/items/")
def create(item: Item):
return item
```
### Response Model
```python
@app.post("/items/", response_model=Item)
def create(item: Item):
return item
```
## Forms, Files, Headers {.cols-3}
### Form Input
```python
from fastapi import Form
@app.post("/login")
def login(user: str = Form(...)):
return {"user": user}
```
### File Upload
```python
from fastapi import UploadFile, File
@app.post("/upload")
def upload(f: UploadFile = File(...)):
return {"filename": f.filename}
```
### Headers / Cookies
```python
from fastapi import Header, Cookie
@app.get("/info")
def info(ua: str = Header(None)):
return {"UA": ua}
```
## Middleware & Dependency {.cols-2}
### Middleware
```python
@app.middleware("http")
async def log_req(req, call_next):
res = await call_next(req)
return res
```
### Dependency
```python
from fastapi import Depends
def auth(token: str = ""):
if token != "xyz": raise HTTPException(401)
return True
@app.get("/secure")
def secure(_: bool = Depends(auth)):
return {"secure": True}
```
## Errors & JSON API {.cols-2}
### HTTP Error
```python
from fastapi import HTTPException
@app.get("/err")
def error():
raise HTTPException(404, "Not Found")
```
### JSON API
```python
from fastapi import FastAPI
@app.get("/json")
def get_data():
return {"status": "ok"}
```
## Templates & Static {.cols-2}
### Mount Static
```python
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")
```
### Jinja2 Support
```python
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates("templates")
```
## Routers & Structure {.cols-2}
### Routers (Blueprints)
```python
from fastapi import APIRouter
router = APIRouter()
@router.get("/")
def admin():
return {"admin": True}
app.include_router(router, prefix="/admin")
```
### Folder Layout
```bash
project/
├── main.py
├── static/
├── templates/
├── routers/
│ └── admin.py
└── models/
```
## Docs & Status {.cols-2}
### Built-in Docs
- Swagger: `/docs`
- ReDoc: `/redoc`
### Custom Status Code
```python
from fastapi import status
@app.post("/create", status_code=status.HTTP_201_CREATED)
def create():
return {"msg": "Created"}
```
+248
View File
@@ -0,0 +1,248 @@
---
title: Flask
date: 2025-06-07 19:05:00
background: bg-[#3598db]
tags:
- web
- python
- backend
categories:
- Programming
intro: |
A concise cheatsheet for Flask, a lightweight WSGI web application framework for Python.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### Install Flask
```bash
pip install flask
```
### Hello World
```python
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, World!"
app.run(debug=True)
```
### Flask CLI
```bash
export FLASK_APP=app.py
flask run
```
## App Config & Environment {.cols-3}
### App Object
```python
from flask import Flask
app = Flask(__name__)
```
### Configuration
```python
app.config["DEBUG"] = True
app.config.from_pyfile("config.py")
```
### Common Config Keys
| Key | Description |
| | -- |
| `DEBUG` | Enable debug mode |
| `SECRET_KEY` | For sessions/cookies |
| `ENV` | Set to 'development' |
## Routing & Methods {.cols-3}
### Basic Route
```python
@app.route("/")
def home():
return "Home"
```
### Methods
```python
@app.route("/login", methods=["GET", "POST"])
def login():
return "Login"
```
### Dynamic Routes
```python
@app.route("/user/<name>")
def user(name):
return f"User: {name}"
```
## Request & Response {.cols-3}
### Request Object
```python
from flask import request
@app.route("/data", methods=["POST"])
def data():
return request.json
```
### Request Attributes
- `request.args`: Query params
- `request.form`: Form data
- `request.json`: JSON body
### Custom Response
```python
from flask import make_response
@app.route("/custom")
def custom():
res = make_response("Custom", 200)
res.headers["X-Test"] = "True"
return res
```
## Templates & Static {.cols-3}
### Render Template
```python
from flask import render_template
@app.route("/")
def page():
return render_template("index.html", name="Flask")
```
### Jinja Syntax
```html
<h1>Hello {{ name }}</h1>
{% if name %}
<p>Hi!</p>
{% endif %}
```
### Static Files
```html
<link href="{{ url_for('static', filename='style.css') }}" />
```
## Sessions & Cookies {.cols-2}
### Using Sessions
```python
from flask import session
app.secret_key = "secret"
@app.route("/login")
def login():
session["user"] = "admin"
return "Logged in"
```
### Access Cookies
```python
from flask import request, make_response
@app.route("/cookie")
def cookie():
resp = make_response("Set cookie")
resp.set_cookie("site", "Flask")
return resp
```
## JSON API & Middleware {.cols-2}
### JSON Response
```python
from flask import jsonify
@app.route("/api")
def api():
return jsonify(message="Hello")
```
### Middleware
```python
@app.before_request
def before():
print("Before")
@app.after_request
def after(res):
print("After")
return res
```
## Error Handling & Blueprints {.cols-2}
### Error Handling
```python
@app.errorhandler(404)
def not_found(e):
return "Page not found", 404
```
### Blueprint
```python
from flask import Blueprint
admin = Blueprint("admin", __name__, url_prefix="/admin")
@admin.route("/")
def dash():
return "Admin"
app.register_blueprint(admin)
```
## Project Structure {.cols-2}
### File Structure
```bash
project/
├── app.py
├── templates/
│ └── index.html
├── static/
│ └── style.css
└── config.py
```
### Run Server
```bash
python app.py
# or using CLI
export FLASK_APP=app.py
flask run
```
+3 -3
View File
@@ -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"
+61 -63
View File
@@ -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)_
+9 -8
View File
@@ -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
View File
@@ -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
+43 -43
View File
@@ -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
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: Grep
date: 2020-11-25 18:28:43
background: bg-emerald-400
background: bg-indigo-400
tags:
- egrep
- search
+4 -4
View File
@@ -143,7 +143,7 @@ brew tap homebrew/cask
List all the installed casks .
```bash
brew cask list
brew list --cask
```
Search all known casks based on the substring text.
@@ -155,19 +155,19 @@ brew search <text>
Install the given cask.
```bash
brew cask install <cask>
brew install --cask <cask>
```
Reinstalls the given Cask
```bash
brew cask reinstall <cask>
brew reinstall --cask <cask>
```
Uninstall the given cask.
```bash
brew cask uninstall <cask>
brew uninstall --cask <cask>
```
### Search, Install, Remove
+20 -20
View File
@@ -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
View File
@@ -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
+175
View File
@@ -0,0 +1,175 @@
---
title: HTMX
date: 2025-06-07 19:30:00
background: bg-[#ff5f4d]
tags:
- frontend
- javascript
- htmx
categories:
- Programming
intro: |
A modern, minimal JavaScript library that allows you to create dynamic web interfaces using HTML attributes.
plugins:
- copyCode
---
## Getting Started {.cols-3}
### CDN Import
```html
<script src="https://unpkg.com/htmx.org@1.9.2"></script>
```
### Basic Usage
```html
<button hx-get="/hello" hx-target="#result">Say Hi</button>
<div id="result"></div>
```
### Server Response
```html
<!-- /hello response -->
<p>Hello from server</p>
```
## Core Attributes {.cols-3}
### `hx-get`, `hx-post`, etc.
```html
<a hx-get="/page">Load Page</a>
<form hx-post="/submit"></form>
```
### `hx-target`
```html
<button hx-get="/data" hx-target="#box"></button>
<div id="box"></div>
```
### `hx-trigger`
```html
<input
hx-get="/search"
hx-trigger="keyup changed delay:300ms"
hx-target="#results"
/>
```
## Swap & Out of Band {.cols-3}
### `hx-swap`
```html
<div hx-get="/frag" hx-swap="innerHTML"></div>
```
- `outerHTML`
- `innerHTML`
- `beforebegin`, `afterbegin`, etc.
### `hx-swap-oob`
```html
<div hx-swap-oob="true" id="msg"></div>
```
_Useful for global updates from partials._
### Swap Modifiers
```html
hx-swap="outerHTML transition:true swap:1s"
```
## Forms & Events {.cols-3}
### Auto POST on Submit
```html
<form hx-post="/submit" hx-target="#status">
<input name="name" />
<button type="submit">Send</button>
</form>
<div id="status"></div>
```
### `hx-include`
```html
<input id="user-id" name="id" />
<button hx-post="/update" hx-include="#user-id">Update</button>
```
### `hx-vals`
```html
<button hx-post="/save" hx-vals='{"id": 42, "active": true}'>Save</button>
```
## Advanced Features {.cols-3}
### Loading Indicator
```html
<button hx-get="/load" hx-indicator="#spinner">Load</button>
<div id="spinner" class="htmx-indicator">Loading...</div>
```
### `hx-push-url`
```html
<a hx-get="/page" hx-push-url="true">Go</a>
```
### Polling
```html
<div hx-get="/time" hx-trigger="every 5s"></div>
```
## Events & Extensions {.cols-3}
### Listen to Events
```js
document.body.addEventListener('htmx:afterSwap', (e) => {
console.log('Swap complete');
});
```
### Event Hooks
- `htmx:beforeRequest`
- `htmx:afterSwap`
- `htmx:responseError`
### Extensions
```html
<script src="https://unpkg.com/htmx.org/dist/ext/json-enc.js"></script>
<form hx-post="/api" hx-ext="json-enc"></form>
```
## Example Use Case {.cols-2}
### Python Backend (Flask)
```python
@app.route("/hello")
def hello():
return "<p>Hello, HTMX!</p>"
```
### HTML Client
```html
<button hx-get="/hello" hx-target="#msg">Click</button>
<div id="msg"></div>
```
+1 -2
View File
@@ -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
+156 -136
View File
@@ -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);
@@ -785,7 +785,7 @@ let printMsg = (evenFunc, num) => {
// Pass in isEven as the callback function
printMsg(isEven, 4);
// => The number 4 is an even number: True.
// => 4 is an even number: True.
```
### Array.reduce()
@@ -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);
});
@@ -1299,12 +1299,28 @@ Promise.all([promise1, promise2]).then((res) => {
});
```
### Promise.allSettled()
```javascript
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject(2);
}, 100);
});
Promise.allSettled([promise1, promise2]).then((res) => {
console.log(res[0].status);
console.log(res[1].status);
});
```
### Avoiding nested Promise and .then()
```javascript
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("*");
resolve('*');
}, 1000);
});
@@ -1313,7 +1329,7 @@ const twoStars = (star) => {
};
const oneDot = (star) => {
return star + ".";
return star + '.';
};
const print = (val) => {
@@ -1328,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);
@@ -1337,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) => {
@@ -1349,7 +1369,7 @@ promise
},
(err) => {
console.error(err);
},
}
);
```
@@ -1362,7 +1382,7 @@ const mock = (success, timeout = 1000) => {
if (success) {
resolve({ status: 200, data: {} });
} else {
reject({ message: "Error" });
reject({ message: 'Error' });
}
}, timeout);
});
@@ -1384,7 +1404,7 @@ const someEvent = async () => {
function helloWorld() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Hello World!");
resolve('Hello World!');
}, 2000);
});
}
@@ -1392,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
@@ -1411,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) {
@@ -1426,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
@@ -1448,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!');
}
```
@@ -1458,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
@@ -1489,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
@@ -1499,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);
};
@@ -1512,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 = () => {
@@ -1550,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);
@@ -1573,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);
@@ -1600,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();
}
+314
View File
@@ -0,0 +1,314 @@
---
title: Jest Cheat Sheet
date: 2022-09-09 00:00:00
background: bg-blue-500
description: A complete cheat sheet on Jest for testing React applications effectively.
tags: React
Testing
Jest
categories:
- Testing
intro:
Jest is a JavaScript testing framework designed by Facebook. It works out of the box with modern
JavaScript apps especially those built with React or Node.js. Its main goal is to simplify testing by providing all required features in one package test runner, assertion library, mocking, spies, coverage reports, and snapshot testing.
---
---
## A Quick Overview to Jest
Jest is a delightful JavaScript testing framework maintained by Facebook. It is widely used for **unit testing**, **integration testing**, and even **end-to-end testing** in modern JavaScript and Node.js applications. Jest comes with a powerful set of features, including a built-in test runner, assertion library, mocking utilities, snapshot testing, and test coverage reporting.
This guide targets **Jest v20** and gives a concise yet practical overview of how to use it effectively.
### Key Concepts Explained
- **`describe()`**: Used to group related test cases into a test suite.
- **`test()` / `it()`**: Define a single test case. `it()` is just a BDD-style alias for `test()`.
- **`expect()`**: Assertion library that checks whether a value meets expectations.
- **`beforeEach()` / `afterEach()`**: Runs code before or after every test in a suite.
- **`beforeAll()` / `afterAll()`**: Runs setup/teardown code once before or after all tests.
- **`.only` / `.skip`**: Focus or ignore specific tests/suites.
- **Snapshot testing**: Captures the rendered output and compares it across test runs.
- **Mock functions**: Simulate function behavior or monitor how functions are called.
- **Timer mocks**: Test time-based behavior like `setTimeout()` and `setInterval()`.
- **Async testing**: Write tests that handle Promises or `async/await`.
---
### 🚀 Quick Start
```bash
npm install --save-dev jest babel-jest
```
Add this to your `package.json`:
```json
"scripts": {
"test": "jest"
}
```
Run your tests:
```bash
npm test -- --watch
```
📖 See: [Getting Started](https://jestjs.io/docs/getting-started)
---
## ✍️ Writing Tests
```js
describe('My work', () => {
test('works', () => {
expect(2).toEqual(2);
});
});
```
- **describe**: Group related tests.
- **test** or **it**: Define individual test cases.
- **expect**: Make assertions.
🔄 `it()` is an alias for `test()`.
---
## 🔧 Setup Hooks
Use these for setup/teardown routines:
```js
beforeEach(() => { ... });
afterEach(() => { ... });
beforeAll(() => { ... });
afterAll(() => { ... });
```
---
## 🎯 Focusing or Skipping Tests
**Focusing tests:**
```js
describe.only(...);
it.only(...); // or fit()
```
**Skipping tests:**
```js
describe.skip(...);
it.skip(...); // or xit()
```
---
## 🏁 Optional CLI Flags
| Flag | Description |
| --------------------- | --------------------------------------- |
| `--coverage` | Show test coverage summary |
| `--detectOpenHandles` | Detect unclosed handles (e.g., sockets) |
| `--runInBand` | Run tests serially (useful for CI) |
---
## ✅ Expectations (Matchers)
### Basic
```js
expect(value).not.toBe(value);
expect(value).toEqual(value);
expect(value).toBeTruthy();
```
> Note: `toEqual` performs deep equality.
### Snapshots
```js
expect(value).toMatchSnapshot();
expect(value).toMatchInlineSnapshot();
```
> Inline snapshots require Prettier.
### Errors
```js
expect(fn).toThrow(error);
expect(fn).toThrowErrorMatchingSnapshot();
```
### Booleans
```js
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeTruthy();
expect(value).toBeUndefined();
expect(value).toBeDefined();
```
### Numbers
```js
expect(value).toBeCloseTo(number, digits);
expect(value).toBeGreaterThan(number);
expect(value).toBeLessThanOrEqual(number);
```
### Objects
```js
expect(value).toBeInstanceOf(Class);
expect(value).toMatchObject(obj);
expect(value).toHaveProperty('key', value);
```
### Arrays/Strings
```js
expect(value).toContain(item);
expect(value).toHaveLength(number);
expect(value).toMatch(/pattern/);
```
### Custom Matchers
```js
expect.extend(customMatchers);
expect.any(Constructor);
expect.assertions(1);
```
---
## ⏱️ Async Tests
### Promises
```js
test('resolves correctly', () => {
return somePromise().then(data => {
expect(data).toEqual(...);
});
});
```
### Async/Await
```js
test('awaits correctly', async () => {
const result = await asyncFunc();
expect(result).toBe(...);
});
```
📖 See: [Jest Async Testing](https://jestjs.io/docs/asynchronous)
---
## 📸 Snapshot Testing
```js
it('renders correctly', () => {
const output = something();
expect(output).toMatchSnapshot();
});
```
For React components:
```js
import renderer from 'react-test-renderer';
it('matches snapshot', () => {
const tree = renderer.create(<Component />).toJSON();
expect(tree).toMatchSnapshot();
});
```
---
## ⏲️ Timers
```js
jest.useFakeTimers();
it('delays call', () => {
jest.runOnlyPendingTimers();
jest.runAllTimers();
});
```
📖 See: [Timer Mocks](https://jestjs.io/docs/timer-mocks)
---
## 🧪 Mock Functions
### Creating Mocks
```js
const fn = jest.fn();
const squared = jest.fn((n) => n * n);
```
### Assertions
```js
expect(fn).toHaveBeenCalled();
expect(fn).toHaveBeenCalledTimes(2);
expect(fn).toHaveBeenCalledWith(arg1, arg2);
```
### Flexible Matchers
```js
expect(fn).toHaveBeenCalledWith(expect.any(String));
expect(fn).toHaveBeenCalledWith(expect.arrayContaining([1, 2]));
```
### Instances
```js
const MyClass = jest.fn();
const a = new MyClass();
const b = new MyClass();
MyClass.mock.instances; // [a, b]
```
### Call Data
```js
fn.mock.calls.length;
fn.mock.calls[0][0];
```
### Return Values
```js
jest.fn().mockReturnValue('hello');
jest.fn().mockReturnValueOnce('hi');
```
### Mock Implementations
```js
const fn = jest
.fn()
.mockImplementationOnce(() => 1)
.mockImplementationOnce(() => 2);
```
---
This comprehensive guide helps you get started with Jest testing or use it like a pro. It pairs perfectly with the React Testing Library for a user-centric testing workflow.
+42 -39
View File
@@ -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
View File
@@ -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];
```
---
+1 -1
View File
@@ -550,7 +550,7 @@ fun main() {
### Default Parameters
```kotlin {.wrap}
fun favoriteLanguage(name, language = "Kotlin") {
fun favoriteLanguage(name: String, language: String = "Kotlin") {
println("Hello, $name. Your favorite programming language is $language")
}
+2 -3
View File
@@ -200,7 +200,7 @@ Example based on KaTeX showing on one line: `KaTeX:\int_0^\infty x^2 dx`
### `KaTeX:\LaTeX` math constructs {.col-span-3}
| 预览 | 方法 | 预览 | 方法 | 预览 | 方法 |
| Preview | Method | Preview | Method | Preview | Method |
| :---------------------- | :--------------------------- | :---------------------- | :--------------------------- | :--------------------------- | :-------------------------------- |
| `KaTeX:\frac{abc}{xyz}` | <pur>`\frac{abc}{xyz}`</pur> | `KaTeX:\overline{abc}` | <pur>`\overline{abc}`</pur> | `KaTeX:\overrightarrow{abc}` | <pur>`\overrightarrow{abc}`</pur> |
| `KaTeX:f'` | <pur>`f'`</pur> | `KaTeX:\underline{abc}` | <pur>`\underline{abc}`</pur> | `KaTeX:\overleftarrow{abc}` | <pur>`\overleftarrow{abc}`</pur> |
@@ -481,7 +481,7 @@ The pair of expressions `\left` `KaTeX:s_1` and `\right` `KaTeX:s_2` can be used
{.left-align}
### 可扩展箭头 {.col-span-3}
### Extensible arrows {.col-span-3}
| :- | :- | :- | :- |
| :------------------------------- | :------------------------------------ | :-------------------------------- | :------------------------------------- |
@@ -909,7 +909,6 @@ x = \begin{cases}
\end{itemize}
```
### Ordered List
<!--rehype:style=flex:1;-->
+2 -2
View File
@@ -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
+266
View File
@@ -0,0 +1,266 @@
---
title: 'Matplotlib'
date: 06-06-2025
background: bg-[#1a073e]
tags:
- 'data visualization'
- 'matplotlib'
- 'plotting'
categories:
- 'Python'
intro: |
[Matplotlib](https://matplotlib.org/) is a comprehensive library for creating static, animated, and interactive plots in Python.
This cheat sheet provides a quick reference from basic to advanced usage, covering essential features for data science, machine learning, and scientific computing.
plugins:
- copyCode
---
---
## Getting Started {.cols-2}
### Importing
```python
import matplotlib.pyplot as plt # Core plotting library
import numpy as np # For numerical operations
```
### Basic Plot
```python
x = np.linspace(0, 10, 100) # 100 points between 0 and 10
y = np.sin(x) # Sine function values
plt.plot(x, y) # Create a line plot
plt.show() # Display the plot
```
---
## Plot Types {.cols-2}
### Line Plot
```python
plt.plot(x, y) # Line plot of y vs x
plt.title("Sine Wave") # Set title
plt.xlabel("x-axis") # Label x-axis
plt.ylabel("y-axis") # Label y-axis
plt.grid(True) # Show gridlines
plt.show()
```
### Scatter Plot
```python
plt.scatter(x, y) # Scatter plot
plt.title("Scatter Plot")
plt.show()
```
### Bar Plot
```python
categories = ['A', 'B', 'C']
values = [10, 20, 15]
plt.bar(categories, values) # Vertical bar chart
plt.title("Bar Chart")
plt.show()
```
### Horizontal Bar Plot
```python
plt.barh(categories, values) # Horizontal bar chart
plt.title("Horizontal Bar Chart")
plt.show()
```
### Histogram
```python
data = np.random.randn(1000) # Random normal distribution
plt.hist(data, bins=30) # Histogram with 30 bins
plt.title("Histogram")
plt.show()
```
### Pie Chart
```python
sizes = [25, 35, 20, 20]
labels = ['A', 'B', 'C', 'D']
plt.pie(sizes, labels=labels, autopct='%1.1f%%') # Pie chart with % labels
plt.title("Pie Chart")
plt.show()
```
---
## Customization {.row-span-2}
| Feature | Code Example | Description |
| --------------- | ------------------------------------------------------------------------------------ | ------------------------------------------- |
| Title | `plt.title("Title")` | Set the title of the plot |
| X/Y Labels | `plt.xlabel("X")`, `plt.ylabel("Y")` | Label the axes |
| Grid | `plt.grid(True)` | Show grid |
| Legend | `plt.legend(["line1"])` | Add legend |
| Line Style | `plt.plot(x, y, linestyle='--')` | Dashed line |
| Color | `plt.plot(x, y, color='green')` | Set line color |
| Marker | `plt.plot(x, y, marker='o')` | Show markers on points |
| Axis Limits | `plt.xlim(0, 10)`, `plt.ylim(-1, 1)` | Set axis range |
| Tick Labels | `plt.xticks([...])`, `plt.yticks([...])` | Customize tick positions |
| Text Annotation | `plt.text(5, 0, "Midpoint")` | Add text at a specific coordinate |
| Arrow | `plt.annotate("Peak", xy=(7, 1), xytext=(6, 1.5), arrowprops=dict(arrowstyle="->"))` | Add annotation arrow |
| Style Sheets | `plt.style.use('ggplot')` | Use predefined styles like `seaborn`, `bmh` |
---
## Subplots & Layouts
### Multiple Subplots
```python
fig, axs = plt.subplots(2, 2) # Create 2x2 grid of subplots
axs[0, 0].plot(x, y) # Top-left subplot
axs[0, 1].scatter(x, y) # Top-right subplot
axs[1, 0].bar(categories, values) # Bottom-left subplot
axs[1, 1].hist(data) # Bottom-right subplot
plt.tight_layout() # Adjust spacing to prevent overlap
plt.show()
```
### Figure Size
```python
plt.figure(figsize=(10, 5)) # Set figure size (width, height in inches)
```
---
## Advanced Visualizations {.cols-2}
### Heatmap
```python
data = np.random.rand(10, 10) # Random 10x10 matrix
plt.imshow(data, cmap='hot', interpolation='nearest') # Display as image
plt.colorbar() # Show color scale
plt.title("Heatmap")
plt.show()
```
### Contour Plot
```python
X, Y = np.meshgrid(x, x)
Z = np.sin(X) * np.cos(Y)
plt.contour(X, Y, Z) # Contour lines
plt.title("Contour Plot")
plt.show()
```
### 3D Plot
```python
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d') # 3D subplot
ax.plot3D(x, y, np.cos(x)) # 3D line
plt.title("3D Plot")
plt.show()
```
---
## Working with Images
```python
import matplotlib.image as mpimg
img = mpimg.imread('image.jpg') # Load image
plt.imshow(img) # Display image
plt.axis('off') # Hide axes
plt.title("Image Display")
plt.show()
```
---
## For Machine Learning
### Plotting Loss vs Epoch
```python
epochs = range(1, 11)
loss = [0.9, 0.7, 0.5, 0.4, 0.3, 0.25, 0.2, 0.18, 0.15, 0.13]
plt.plot(epochs, loss)
plt.title("Training Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.show()
```
### Confusion Matrix (Heatmap)
```python
from sklearn.metrics import confusion_matrix
import seaborn as sns
y_true = [0, 1, 2, 2, 0]
y_pred = [0, 0, 2, 2, 1]
cm = confusion_matrix(y_true, y_pred) # Create confusion matrix
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues') # Heatmap visualization
plt.title("Confusion Matrix")
plt.show()
```
### ROC Curve
```python
from sklearn.metrics import roc_curve, auc
fpr, tpr, _ = roc_curve([0, 0, 1, 1], [0.1, 0.4, 0.35, 0.8]) # Compute ROC
roc_auc = auc(fpr, tpr) # Area under curve
plt.plot(fpr, tpr, label=f'AUC = {roc_auc:.2f}')
plt.plot([0, 1], [0, 1], 'k--') # Diagonal line
plt.xlabel("False Positive Rate")
plt.ylabel("True Positive Rate")
plt.title("ROC Curve")
plt.legend()
plt.show()
```
---
## Saving Plots
```python
plt.savefig("figure.png", dpi=300, bbox_inches='tight') # Save plot to file
```
---
## Show & Clear
```python
plt.show() # Show plot window
plt.clf() # Clear current figure (useful when plotting in loops)
plt.close() # Close figure window (useful in scripts or GUI apps)
```
---
## More Useful Functions
| Function | Use Case |
| ------------------------------ | ------------------------------- |
| `plt.fill_between(x, y1, y2)` | Fill area between curves |
| `plt.axhline(y=value)` | Draw horizontal line at y |
| `plt.axvline(x=value)` | Draw vertical line at x |
| `plt.errorbar(x, y, yerr=...)` | Plot with error bars |
| `plt.twinx()` | Create secondary y-axis |
| `plt.subplots_adjust(...)` | Manually adjust subplot spacing |
| `plt.gca()` | Get current axes |
| `plt.gcf()` | Get current figure |
---
+8 -9
View File
@@ -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}
+227
View File
@@ -0,0 +1,227 @@
---
title: NetworkPorts
date: 2025-06-19 15:00:00
background: bg-[#71d1f9]
tags:
- Network
categories:
- Other
intro: |
A network ports cheat sheet with non-exhaustive list of ports used according to their field of application.
plugins:
---
## Networking and Infrastructure
### Web Ports
| **Port** | **Nom** | **Description** |
|:-------------| :--------------- |:----------------------------|
| `80` | HTTP | HyperText Transfer Protocol |
| `443` | HTTPS | HTTP Secure |
| `8080` | HTTP-Alt | Alternative HTTP Port |
| `8443` | HTTPS-Alt | Alternative HTTPS Port |
| `8000` | HTTP-Proxy | For proxy server HTTP |
| `8008` | HTTP-Backup | Backup port for HTTP |
| `8888` | HTTP-Alternative | Alternative port for HTTP |
### Network and Infrastructure Service Ports
| **Port** | **Nom** | **Description** |
|:---------| :-------- |:------------------------------------|
| `53` | DNS | Domain Name System |
| `67`/`68`| DHCP | Dynamic Host Configuration Protocol |
| `123` | NTP | Network Time Protocol |
| `161` | SNMP | Simple Network Management Protocol |
| `162` | SNMP-Trap | SNMP Trap Messages |
| `514` | Syslog | Logging system |
| `69` | TFTP | Trivial File Transfer Protocol |
### Virtualization and Containerization Service Ports
| **Port** | **Nom** | **Description** |
|:----------| :------------ |:--------------------------------|
| `2375` | Docker | Docker without TLS |
| `2376` | Docker | Docker with TLS |
| `6443` | Kubernetes | Kubernetes API Server |
| `8443` | Kubernetes | Alternative Kubernetes API port |
| `9100` | Node Exporter | Prometheus Node Exporter |
| `9090` | Prometheus | Prometheus Monitoring |
| `5672` | RabbitMQ | Message Broker RabbitMQ |
### Monitoring and Management Service Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:---------| :--------- |:------------------------------------------|
| `631` | IPP | Internet Printing Protocol |
| `873` | rsync | Remote Sync |
| `8086` | InfluxDB | Time Series Database InfluxDB |
| `9093` | Prometheus | Prometheus Alertmanager Alert Management |
## Data Management
### Data Base Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:----------| :------------------- |:--------------------------------------|
| `1433` | Microsoft SQL Server | Microsoft SQL Database Server |
| `3306` | MySQL | MySQL Database Management System |
| `5432` | PostgreSQL | PostgreSQL Database Management System |
| `1521` | Oracle | Oracle Database Management System |
| `27017` | MongoDB | MongoDB NoSQL Database |
| `11211` | Memcached | Memcached Memory Caching System |
| `6379` | Redis | Redis In-Memory Database |
## Communication Services
### Remote Ports
| **Port** | **Nom** | **Description** |
|:---------| :------ |:-----------------------------------|
| `22` | SSH | Secure Shell |
| `23` | Telnet | Unsecure remote terminal protocol |
| `3389` | RDP | Remote Desktop Protocol |
| `5900` | VNC | Virtual Network Computing |
| `69` | TFTP | Trivial File Transfer Protocol |
| `179` | BGP | Border Gateway Protocol |
| `113` | Ident | Ident Protocol |
### Messagerie Service Ports
| **Port** | **Nom** | **Description** |
|:---------| :-------------- |:---------------------------------|
| `25` | SMTP | Simple Mail Transfer Protocol |
| `465` | SMTPS | SMTP Secure |
| `587` | SMTP-Submission | Port for email submission |
| `110` | POP3 | Post Office Protocol v3 |
| `995` | POP3S | POP3 Secure |
| `143` | IMAP | Internet Message Access Protocol |
| `993` | IMAPS | IMAP Secure |
### Instant Messaging and VoIP Service Ports
| **Port** | **Nom** | **Description** |
|:---------| :---------- |:-------------------------------------------|
| `5060` | SIP | Session Initiation Protocol |
| `5061` | SIP-Secure | SIP over TLS |
| `1720` | H.323 | Communication protocol for VoIP |
| `3478` | STUN | Session Traversal Utilities for NAT |
| `1234` | Skype | Communication VoIP via Skype |
| `5222` | XMPP | Extensible Messaging and Presence Protocol |
| `5223` | XMPP-Secure | XMPP over SSL |
### Voice and Video Service Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:----------------| :--------- |:--------------------------------------------------------|
| `5060` | SIP | Session Initiation Protocol pour VoIP |
| `5061` | SIP Secure | SIP sur TLS |
| `16384`-`32767` | RTP | Real-time Transport Protocol pour streaming audio/vidéo |
| `3478` | STUN | Session Traversal Utilities for NAT |
| `5004` | RTP | Real-time Transport Protocol for media |
| `5222` | XMPP | Extensible messaging protocol for instant messaging |
| `9000` | WebRTC | Protocols for real-time communication via browser |
### P2P Download and Sharing Service Ports
| **Port** | **Nom** | **Description** |
|:--------------| :--------- |:---------------------------------------|
| `6881`-`6889` | BitTorrent | Ports used by BitTorrent clients |
| `51413` | BitTorrent | Default port for BitTorrent |
| `6969` | BitTorrent | Default port for BitTorrent trackers |
| `1194` | OpenVPN | Also used for VPNs and some P2P |
| `4661` | uTorrent | Port used by uTorrent client |
| `37152` | Steam | Used by Steam platform for downloads |
## Security Services
### Security Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:---------| :---------- | :----------------------------------------- |
| `1194` | OpenVPN | Virtual Private Network |
| `1701` | L2TP | Layer 2 Tunneling Protocol |
| `1723` | PPTP | Point-to-Point Tunneling Protocol |
| `4500` | IPsec-NAT-T | IPsec NAT Traversal |
| `500` | IKE | Internet Key Exchange |
| `1812` | RADIUS | Remote Authentication Dial-In User Service |
| `3306` | MySQL SSL | MySQL avec chiffrement SSL |
### Cryptography and Security Service Ports
| **Port** | **Nom** | **Description** |
|:---------| :-------- |:---------------------------------------|
| `443` | HTTPS | HTTP Secure avec SSL/TLS |
| `993` | IMAPS | IMAP sécurisé avec SSL/TLS |
| `995` | POP3S | POP3 sécurisé avec SSL/TLS |
| `636` | LDAPS | LDAP sécurisé avec SSL/TLS |
| `8443` | HTTPS-Alt | Alternative port for HTTPS |
| `8888` | SSL Proxy | Secure proxy using SSL/TLS |
| `563` | SNEWS | Secure Network News Transfer Protocol |
## System and Application Services
### File Service Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:---------| :---------- |:----------------------------------------|
| `20` | FTP-DATA | FTP data transfer |
| `21` | FTP | File Transfer Protocol |
| `22` | SFTP | Secure File Transfer Protocol (via SSH) |
| `445` | SMB | Server Message Block (Windows Shares) |
| `139` | NetBIOS-SSN | NetBIOS Session Service |
| `2049` | NFS | Network File System |
| `548` | AFP | Apple Filing Protocol |
### Miscellaneous System and App Ports
| **Port** | **Nom** | **Description** |
|:------------| :------ |:----------------------------------------------|
| `137`-`139` | NetBIOS | NetBIOS services for naming and file sharing |
| `1900` | UPnP | Universal Plug and Play |
| `24800` | Vuze | Client BitTorrent Vuze |
| `32400` | Plex | Serveur multimédia Plex |
## Miscellaneous Services
### Gaming Service Ports {.col-span-2}
| **Port** | **Nom** | **Description** |
|:----------| :------------ |:---------------------------------|
| `27015` | Steam | Steam gaming platform |
| `7777` | Unreal Engine | Game servers using Unreal Engine |
| `27020` | Source Engine | Game servers using Source Engine |
| `28910` | Various Games | Various multiplayer games |
| `27000` | Various Games | Additional multiplayer games |
### Miscellaneous Service Ports
| **Port** | **Nom** | **Description** |
|:----------| :------ | :-------------------------------------------------------- |
| `500` | ISAKMP | Internet Security Association and Key Management Protocol |
| `520` | RIP | Routing Information Protocol |
| `1900` | UPnP | Universal Plug and Play |
| `3659` | RADIUS | Remote Authentication Dial-In User Service |
+314
View File
@@ -0,0 +1,314 @@
---
title: Nix
date: 2025-08-24 23:33:40
background: bg-[#304673]
tags:
categories:
- Programming
intro: |
The Nix quick reference cheat sheet that aims at providing help on writing basic nix code.
plugins:
- copyCode
---
## Types & Syntax
### String
```nix
let
x = "single-line string";
y = ''
multi-line string
'';
in
```
### Integer
```nix
let
x = -123;
y - 123;
in
```
### Float
```nix
let
x = -0.32;
y = 0.45;
in
```
### Boolean
```nix
let
x = true;
y = false;
in
```
### Null
```nix
let
x = null;
in
```
### Path
```nix
let
x = /absolute/path;
y = ./relative/path;
in
```
### Attribute Set
```nix
let
x = {
a = 1;
b = 2;
};
y = { c = 3; };
in
```
see [Attribute Sets](#attribute-sets)
### List
```nix
let
x = [ 1 2.0 ];
y = [
1
"this is a string"
23.0
null
];
in
```
### Comment
#### ↓ single-line comment
```nix
# your comment
```
#### ↓ multi-line comment
```nix
/*
your comment
*/
```
## Scoping
### Define Local Variable
```nix
let
x = 1;
y = 2;
in
x + y # -> returns 3
```
### Add Variables Into Scope
```nix
let
x = 1;
in
{ inherit x; }
```
#### ↓ desugars to
```nix
let
x = 1;
in
{ x = x; }
```
### Add Attributes Into Scope
```nix
let
x = { y = 1; };
in
{ inherit (x) y; }
```
#### ↓ desugars to
```nix
let
x = { y = 1; };
in
{ y = x.y; }
```
### Add All Attributes Into Scope
```nix
let
x = { y = 1; z = 2; };
in
with x;
y + z # -> returns 3
```
## Conditionals
### Define Conditionals
```nix
if x > 0
then 1
else -1
```
## Attribute Sets
### Define Attribute Sets
```nix
let
x = {
a = 1;
b = 2;
};
y = { c = 3; };
in
```
### Update Attribute Sets
```nix
{ x = 1; } // { y = 2; } # -> returns { x = 1; y = 2; }
{ x = 1; } // { x = 2; } # -> returns { x = 2; }
```
### Check For Attribute
```nix
let
x = { y = 1; };
in
x ? y # -> returns true
```
### Reference Attirbute Keys
```nix
let
x = { y = 1; };
in
x.y # -> returns 1
```
#### ↓ optional
```nix
let
x = { y = 1; };
in
x.z or 2 # -> returns 2
```
## Concatenation & Interpolation
### Concatenate Lists
```nix
[ 1 2 ] ++ [ 3 4 ] # -> returns [ 1 2 3 4 ]
```
### Concatenate Paths & Strings
```nix
/bin + /sh # -> returns /bin/sh
/bin + "/sh" # -> returns /bin/sh
"/bin" + "/sh" # -> returns "/bin/sh"
```
### Interpolate Strings
```nix
let
x = "bar";
in
"foo ${x} baz" # -> returns "foo bar baz"
```
## Functions
### Simple Function
```nix
let
f = x: x + 1;
in
f 1 # -> returns 2
```
### Multiple Arguments
```nix
let
f = x: y: [ x y ];
in
f 1 2 # -> returns [ 1 2 ]
```
### Named Arguments
```nix
let
f = {x, y}: x + y;
in
f { x=1; y=2; } # -> returns 3
```
#### ↓ ignoring arguments
```nix
let
f = {x, y, ... }: x + y;
in
f { x=1; y=2; z=3; } # -> returns 3
```
#### ↓ default values
```nix
let
f = {x, y ? 2 }: x + y;
in
f { x=1; } # -> returns 3
```
#### ↓ bind to variable
```nix
let
f = {x, y}@args: args.x + args.y;
in
f { x=1; y=2; } # -> returns 3
```
## Sources
- [NixOS/marketing](https://github.com/nixos/marketing) _(github.com)_
+138
View File
@@ -0,0 +1,138 @@
---
title: Nmap
date: 2025-06-17 08:30:00
background: bg-[#2a0d45]
tags:
- network
- scan
- port
categories:
- Linux Command
intro:
The [Nmap](https://nmap.org/) cheat sheet is a one-page reference sheet for the famous Network Mapper tool.
plugins:
- copyCode
---
## Getting Started
### Basic Usage :
```bash
# set your target in etc/hosts
# fast scan of all port of your target
nmap -p- -T5 target
# fast scan on port 80 with os detection
namp -p, 80 -T5 -O target
```
### Basic Options : {.col-span-2}
| Options | Purpose |
|:-------------------------|:------------------------------------------|
| `-p-` | all ports |
| `-p1-1023` | scan ports 1 to 1023 |
| `-F` | 100 most common ports |
| `-r` | scan ports in consecutive order |
| `-T<0-5>` | -T0 being the slowest and T5 the fastest |
| `--max-rate 50` | rate <= 50 packets/sec |
| `--min-rate 15` | rate >= 15 packets/sec |
| `--min-parallelism 100` | at least 100 probes in parallel |
## Nmap Intermediate Options
### Service Detections : {.col-span-2}
| Option | Meaning |
|:-----------------------------|:-----------------------------------------|
| `--traceroute` | run traceroute to target |
| `--script=SCRIPTS` | Nmap scripts to run |
| `-sC` or `--script=default` | run default scripts |
| `-O` | OS detection |
| `-sV` | Service version detection |
| `-A` | equivalent to `-sV -O -sC --traceroute` |
### Timing {.col-span-3}
| Option | Meaning |
|:--------------------------------------------------------------------|:---------------------------------------------------------------------------------------------------|
| `-T<0-5>` | Timing template – paranoid (0), sneaky (1), polite (2), normal (3), aggressive (4), and insane (5) |
| `--min-parallelism <numprobes>` and `--max-parallelism <numprobes>` | Minimum and maximum number of parallel probes |
| `--min-rate <number>` and `--max-rate <number>` | Minimum and maximum rate (packets/second) |
| `--host-timeout` | Maximum amount of time to wait for a target host |
## Formating answers
### Details & Report {.col-span-2}
| Option | Purpose |
|:------------------|:---------------------------------------|
| `--reason` | explains how Nmap made its conclusion |
| `-v` | verbose |
| `-vv` | very verbose |
| `-d` | debugging |
| `-dd` | more details for debugging |
| `-oN <filename>` | Normal output |
| `-oX <filename>` | XML output |
| `-oG <filename>` | `grep`-able output |
| `-oA <basename>` | Output in all major formats |
## Advanced Technic
### Advanced Scan {.col-span-3}
| Options | Protocol | Main Function | Typical Use Case |
|------------|:---------|:------------------|:-----------------------------------------------|
| `-PR -sn` | **ARP** | Scan | Discovering devices on the local network (LAN) |
| `-PE -sn` | **ICMP** | Echo Scan | Checking if hosts are reachable (pinging) |
| `-PP -sn` | **ICMP** | Timestamp Scan | Gathering device time info (less common) |
| `-PM -sn` | **ICMP** | Address Mask Scan | Determining subnet mask info from hosts |
| `-PS -sn` | **TCP** | SYN Ping Scan | Detecting open TCP ports and live hosts |
| `-PA -sn ` | **TCP** | ACK Ping Scan | Identifying firewall rules and open ports |
| `-PU -sn` | **ICMP** | Ping Scan | Finding hosts with open UDP services |
## Investigation Exemple
### Verbose Os Quick port scan {.col-span-3}
```bash
nmap -sV -O -p- -T5 target
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-11-02 15:17 CET
Nmap scan report for target (10.10.158.161)
Host is up (0.021s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.8 (Ubuntu Linux; protocol 2.0)
8009/tcp open ajp13 Apache Jserv (Protocol v1.3)
8080/tcp open http Apache Tomcat 8.5.5
Aggressive OS guesses: Linux 3.10 - 3.13 (95%), Linux 5.4 (95%), ASUS RT-N56U WAP (Linux 3.4) (95%),
Linux 3.16 (95%), Linux 3.1 (93%), Linux 3.2 (93%), AXIS 210A or 211 Network Camera (Linux 2.6.17) (93%),
Sony Android TV (Android 5.0) (93%), Android 5.0 - 6.0.1 (Linux 3.4) (93%), Android 5.1 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 39.94 seconds
# you can then use `nmap -A -p 22, 8009, 8080 target` on discovered ports
```
Do not use this tool without consent. For educational purposes, this example is coming from a Try Hack Me [machine](https://tryhackme.com/room/bsidesgtthompson).
## Also See
- [Nmap](https://nmap.org/)
+207
View File
@@ -0,0 +1,207 @@
---
title: Notion Shortcuts
date: 2025-04-24 12:51:00 # You might want to adjust this date
background: bg-gradient-to-l from-gray-400 to-gray-600 hover:from-blue-500 hover:to-purple-500 # Notion-like gradient, adjust as desired
tags:
- notion
- keyboard
- shortcuts
- productivity
- reference
categories:
- Productivity
- Software
intro:
A comprehensive quick reference guide for Notion keyboard shortcuts on Desktop and Web, designed to boost your
productivity.
plugins:
- copyCode
---
# Notion Keyboard Shortcuts {.cols-3}
## 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` |
{.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` |
{.show-header .shortcuts}
---
# 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)
### Inline
- 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}
### 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}
### Editing
| Action | Mac Shortcut | Windows/Linux Shortcut |
| :------------------------- | :-------------- | :--------------------- |
| New Line within same block | `Shift` `Enter` | `Shift` `Enter` |
{.show-header .shortcuts}
---
# 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` |
{.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` |
{.show-header .shortcuts}
---
# Comments & Mentions {.cols-2}
### Comments
| 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
### Emoji
| 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}
---
# 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` |
{.show-header .shortcuts}
### Other
| 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)_
+26 -27
View File
@@ -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
```
+1 -1
View File
@@ -2,7 +2,7 @@
title: OpenSSL
date: 2020-11-25 18:28:43
icon: icon-style
background: bg-emerald-600
background: bg-indigo-600
tags:
categories:
- Linux Command
+82 -84
View File
@@ -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
View File
File diff suppressed because it is too large. Load diff
+179
View File
@@ -913,6 +913,166 @@ class Cls implements Foo, Bar
}
```
## PHP Trait
### Trait declaration & Use case {.col-span-3}
```php
// Declare Trait allows reuse of code
// across multiple classes for common characteristics or use cases
<?php
trait Logger {
public function log($message) {
$date = new DateTime();
echo "| ". $date->format('Y-m-d H:i:s') . " | " . $message;
}
}
// Use case :
// Call trait with "use <trait name> in Class"
class User {
use Logger;
public function createUser() {
// User creation logic
$this->log("User created.");
}
}
class Product {
use Logger;
public function createProduct() {
// Product creation logic
$this->log("Product created.");
}
}
$user = new User();
$user->createUser(); // Output ex: | 2025-06-18 14:06:09 | User created.
$product = new Product();
$product->createProduct(); // Output ex: | 2025-06-18 14:06:09 | Product created.
```
## PHP Enums (PHP 8.1)
### Enum Declaration & Use case {.col-span-3}
```php
<?php
// enum is a data type that allows you to define a set of named constants,
// representing a fixed group of related values
enum Status {
case Pending;
case Approved;
case Rejected;
}
// Use case
function getStatusMessage(Status $status): string {
return match($status) {
Status::Pending => "Waiting for approval.",
Status::Approved => "Your request has been approved.",
Status::Rejected => "Your request has been rejected.",
};
}
$currentStatus = Status::Approved;
echo getStatusMessage($currentStatus); // Output : Your request has been approved.
```
## PHP Date & Time Handling
### Current date and time
```php
// DateTime in PHP handles both date and time
<?php
$now = new DateTime();
echo $now->format('Y-m-d H:i:s.u');
// Output ex: 2024-04-27 14:35:22.123456
```
### Creating specific date/time objects
```php
<?php
// Create a date object
$d = new DateTime('2024-04-27');
echo $d->format('Y-m-d');
// Output : 2024-04-27
// Create a time object
$t = new DateTime('15:30:45');
echo $t->format('H:i:s');
// Output : 15:30:45
// Create a datetime object
$dt = new DateTime('2024-04-27 15:30:45');
echo $dt->format('Y-m-d H:i:s');
// Output : 2024-04-27 15:30:45
```
### Converting between date formats
```php
<?php
// Convert a string to a DateTime object
$date_str = "2024-04-27 14:00";
$dt_obj = new DateTime($date_str);
echo $dt_obj->format('Y-m-d H:i:s');
// Output : 2024-04-27 14:00:0027
// Convert a DateTime object to a string
$formatted_str = $dt_obj->format('d/m/Y H:i');
echo $formatted_str;
// Output : 27/04/2024 14:00
```
### Timestamps and Unix time {.col-span-2}
```php
<?php
// Get current timestamp
$timestamp = time();
echo $timestamp;
// Output ex: 1750253583
// Convert timestamp back to DateTime
$dt_from_timestamp = (new DateTime())->setTimestamp($timestamp);
echo $dt_from_timestamp->format('Y-m-d H:i:s');
// Output ex : 2025-06-18 13:33:03
```
### Date difference and timedelta {.col-span-1}
```php
<?php
$date1 = new DateTime('2024-04-27');
$date2 = new DateTime('2024-05-01');
$interval = $date1->diff($date2);
echo $interval->days;
// Output : 4
// Using DateInterval for date arithmetic
$new_date = clone $date1;
$new_date->add(new DateInterval('P10D'));
echo $new_date->format('Y-m-d');
// Output : 2024-05-07
```
## Miscellaneous
### Basic error handling
@@ -1002,6 +1162,25 @@ See: [Regex in PHP](/regex#regex-in-php)
| `a` | Write, append |
| `a+` | Read and write, append |
### Super Global Variables {.col-span-2}
| Variable | Description |
|--------------|:-------------------------------------------------------------|
| `$_SERVER` | Holds information about headers, paths, and script locations |
| `$_GET` | Contains data sent via URL parameters (query string) |
| `$_POST` | Contains data sent via HTTP POST method |
| `$_FILES` | Contains information about uploaded files |
| `$_COOKIE` | Contains cookie data |
| `$_SESSION` | Stores session variables |
| `$_REQUEST` | Contains data from `$_GET`, `$_POST`, and `$_COOKIE` |
| `$_ENV` | Contains environment variables |
| `$GLOBALS` | References all global variables available in the script |
{.left-text}
Super Global Variables are built-in variables always available in all scopes.
### Runtime defined Constants
```php
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: PhpStorm
date: 2022-11-23 16:23:31.703719
background: bg-gradient-to-r from-[#be4fe9] to-[#715bef] hover:from-emerald-400 hover:to-blue-500
background: bg-gradient-to-r from-[#be4fe9] to-[#715bef] hover:from-indigo-400 hover:to-blue-500
label:
tags:
- jetbrains
+256
View File
@@ -219,6 +219,30 @@ See: [Lists](#python-lists)
```python
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
tupla = (1, 2, 3, 'python')
print(tupla[0]) # Output: 1
print(tupla.count(1)) # Count occurrences
print(tupla.index(2)) # Find index
tupla1 = (1, 2, 3)
tupla2 = ('a', 'b')
len(tuple) → Returns the number of elements.
in → Checks if an element exists in the tuple.
Concatenation (+) → Combines two tuples.
Repetition (*) → Repeats a tuple.
Slicing (tuple[start:end]) → Extracts a subtuple.
print(len(tupla1)) # Output: 3
print(2 in tupla1) # Output: True
print(tupla1 + tupla2) # Output: (1, 2, 3, 'a', 'b')
print(tupla1[1:]) # Output: (2, 3)
# unpacking
a, b, c, d = tupla # Each value goes into a variable
```
Similar to List but immutable
@@ -933,6 +957,80 @@ else:
Also see: [Python Tips](https://book.pythontips.com/en/latest/for_-_else.html)
### Over Dictionary
```python
johndict = {
"firstname": "John",
"lastname": "Doe",
"age": 30
}
x = johndict.items()
print(x)
# Output: dict_items([('firstname', 'John'),
# ('lastname', 'Doe'),
# ('age', 30)])
for key, value in johndict.items():
print(f"{key} : : {value}")
# Output: firstname : : John
# Output: lastname : : Doe
# Output: age : : 30
```
## Python Comprehensions
### Comprehension List {.col-span-2}
```python
languages = ["html", "go", "rust", "javascript", "python"]
newlist = [x for x in languages if "l" not in x]
# add language for language in languages if "l" not in language
print(newlist) #Output : [ 'go', 'rust', 'javascript', 'python']
# List comprehension avoid this :
oldlist = []
for x in languages:
if "l" not in x:
oldlist.append(x)
print(oldlist) #Output : [ 'go', 'rust', 'javascript', 'python']
```
### Comprehension Dictionary {.col-span-2}
```python
languages = ["html", "go", "rust", "javascript", "python"]
language_dict = {lang: ('l' not in lang) for lang in languages}
# Key is the language & bool is Value (no offense for html..)
print(language_dict)
# Output: {'html': False, 'go': True, 'rust': True,
# 'javascript': True, 'python': True}
# Dictionary comprehension avoid this :
language_dict2 = {}
for e in languages:
if "l" not in e:
language_dict2[e] = True
else:
language_dict2[e] = False
print(language_dict2)
# Output: {'html': False, 'go': True, 'rust': True,
# 'javascript': True, 'python': True}
```
## Python Functions
### Basic
@@ -1006,6 +1104,29 @@ add(5, 20) # => 25
(lambda x, y: x ** 2 + y ** 2)(2, 1)
```
### @decorator {.col-span-2}
```python
# Modify or extend behavior of function or class method,
# without changing their actual code.
# Define decorator that will wrap function or method
def handle_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return print(f"Error : {e}")
return wrapper
# Decorate function or method
@handle_errors
def divide(a, b):
return a / b
divide(10, 0) # Output : Error : division by zero
```
## Python Modules
### Import modules
@@ -1274,6 +1395,24 @@ print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
```
### @staticmethod {.col-span-2}
```python
class MyClass:
@staticmethod
def greet(name):
return f"Hello, {name}!"
# No instantiation nedded
# Call via class
print(MyClass.greet("Alice")) # => Hello, Alice!
# Can still call via instance
obj = MyClass()
print(obj.greet("Bob")) # => Hello, Bob!
```
## Python Type Hints (Since Python 3.5)
### Variable & Parameter
@@ -1501,6 +1640,80 @@ while (data := values[i]):
# Expected result: 1, "text", True
```
## Date & Time Handling
### Current date and time
```python
import datetime
now = datetime.datetime.now()
print(now) # e.g., 2024-04-27 14:35:22.123456
```
### Creating specific date/time objects
```python
import datetime
# Create a date object
d = datetime.date(2024, 4, 27)
print(d) # 2024-04-27
# Create a time object
t = datetime.time(15, 30, 45)
print(t) # 15:30:45
# Create a datetime object
dt = datetime.datetime(2024, 4, 27, 15, 30, 45)
print(dt) # 2024-04-27 15:30:45
```
### Converting between date formats
```python
import datetime
# Convert a string to a datetime object
date_str = "2024-04-27 14:00"
dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt_obj) # 2024-04-27 14:00:00
# Convert a datetime object to a string
formatted_str = dt_obj.strftime("%d/%m/%Y %H:%M")
print(formatted_str) # 27/04/2024 14:00
```
### Timestamps and Unix time
```python
import datetime
# Get current timestamp
timestamp = datetime.datetime.now().timestamp()
print(timestamp) # e.g., 1714188922.123456
# Convert timestamp back to datetime
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp)
```
### Date difference and timedelta {.col-span-2}
```python
import datetime
date1 = datetime.date(2024, 4, 27)
date2 = datetime.date(2024, 5, 1)
delta = date2 - date1
print(delta.days) # 4
# Using timedelta for date arithmetic
new_date = date1 + datetime.timedelta(days=10)
print(new_date) # 2024-05-07
```
## Miscellaneous
### Comments
@@ -1558,3 +1771,46 @@ else: # Optional clause to the try/except block. Must follow
finally: # Execute under all circumstances
print("We can clean up resources here")
```
### Dispatcher Pattern {.col-span-3}
```python
# Dispatcher allows dynamic selection and execution of functions based on user input or other runtime conditions
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return 'Error: Division by zero'
return x / y
# Dispatcher dictionary: maps operation names to their corresponding functions
operations = {
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# Function to dispatch operation based on operation name
# Common use cases include executing different functions dynamically, such as in calculators, command interpreters, or event handling
def dispatcher(operation_name, x, y):
func = operations.get(operation_name)
if func:
return func(x, y)
else:
return f"Unknown operation: {operation_name}"
# Usage examples
print(dispatcher('add', 5, 3)) # Output: 8
print(dispatcher('multiply', 4, 2)) # Output: 8
print(dispatcher('divide', 10, 0)) # Output: Error: Division by zero
print(dispatcher('mod', 10, 3)) # Output: Unknown operation: mod
```
+1 -2
View File
@@ -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
---
+310
View File
@@ -0,0 +1,310 @@
---
title: 'React Testing Library Cheat Sheet'
date: 2022-09-09 00:00:00
background: bg-blue-500
tags:
- react
- testing
- javascript
- cheatsheet
categories:
- Testing
intro: |
When it comes to testing React apps manually, we can either choose to render individual component trees in a simplified test environment or run the complete app in a realistic browser environment (end-to-end testing). But for automated tests, React Testing Library (RTL) is recommended for its user-centric approach and maintainability.
plugins:
- copyCode
---
## Introduction
React Testing Library is built on top of DOM Testing Library to test React components by querying and interacting with real DOM nodes, avoiding reliance on implementation details.
## Basic level
### 1. Purpose & Solution
RTL addresses maintainability by focusing on user-visible behavior:
- Tests run in actual DOM nodes.
- Queries mirror user interactions.
- `data-testid` as an escape hatch when needed.
- Encourages accessibility.
### 2. A basic component render test
**Component (App.js):**
```js
const title = 'Hello, World!';
function App() {
return <div>{title}</div>;
}
export default App;
```
**Test (App.test.js):**
```js
import { render } from '@testing-library/react';
import App from './App';
describe('App', () => {
test('renders App component', () => {
render(<App />);
});
});
```
Add debug to inspect output:
```js
import { render, screen } from '@testing-library/react';
import App from './App';
describe('App', () => {
test('renders App component', () => {
render(<App />);
screen.debug();
});
});
```
Output in console:
```html
<body>
<div>
<div>Hello, World!</div>
</div>
</body>
```
### 3. Why use RTL vs Enzyme?
1. Tests based on user interactions, not internal APIs.
2. Improves maintainability after refactors.
3. Intuitive syntax (`getByText`, `getByAltText`, etc.).
### 4. Queries in RTL
```js
import { render, screen } from '@testing-library/react';
test('should show login form', () => {
render(<Login />);
const input = screen.getByLabelText('Username');
// events & assertions
});
```
**Single element queries:**
- `getBy*`: throws if none found
- `queryBy*`: returns null if none
- `findBy*`: async Promise
**Multiple elements queries:**
- `getAllBy*`: throws if none
- `queryAllBy*`: returns \[] if none
- `findAllBy*`: async Promise array
### 5. Component tree testing level
- Test at user interaction level, not per individual child component unless needed.
## Intermediate level
### 1. Jest vs RTL
- **Jest**: Test runner & assertion library (`describe`, `test`, `expect`).
- **RTL**: DOM utilities for React; works within Jest (or other runners).
### 2. Mocking with MSW
```js
// fetch.test.jsx
import React from 'react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { render, fireEvent, waitFor, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import Fetch from '../fetch';
const server = setupServer(
rest.get('/greeting', (req, res, ctx) =>
res(ctx.json({ greeting: 'hello there' }))
)
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('loads and displays greeting', async () => {
render(<Fetch url="/greeting" />);
fireEvent.click(screen.getByText('Load Greeting'));
await waitFor(() => screen.getByRole('heading'));
expect(screen.getByRole('heading')).toHaveTextContent('hello there');
expect(screen.getByRole('button')).toBeDisabled();
});
test('handles server error', async () => {
server.use(rest.get('/greeting', (req, res, ctx) => res(ctx.status(500))));
render(<Fetch url="/greeting" />);
fireEvent.click(screen.getByText('Load Greeting'));
await waitFor(() => screen.getByRole('alert'));
expect(screen.getByRole('alert')).toHaveTextContent('Oops, failed to fetch!');
expect(screen.getByRole('button')).not.toBeDisabled();
});
```
### 3. `render` options
```js
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
test('renders a message', () => {
const table = document.createElement('table');
const { container } = render(<TableBody {...props} />, {
container: document.body.appendChild(table),
baseElement: document.body,
hydrate: true,
legacyRoot: true,
queries: {
/* custom queries */
}
});
expect(container).toBeInTheDocument();
});
```
### 4. `renderHook` usage
```js
import { renderHook } from '@testing-library/react';
test('returns logged in user', () => {
const { result, rerender } = renderHook(
({ name } = {}) => useLoggedInUser(name),
{ initialProps: { name: 'Alice' } }
);
expect(result.current).toEqual({ name: 'Alice' });
rerender({ name: 'Bob' });
expect(result.current).toEqual({ name: 'Bob' });
});
```
## Advanced Level
### 1. Adding custom queries
```js
const dom = require('@testing-library/dom');
const { queryHelpers, buildQueries } = require('@testing-library/react');
// Override testId attribute
export const queryByTestId = queryHelpers.queryByAttribute.bind(
null,
'data-test-id'
);
export const queryAllByTestId = queryHelpers.queryAllByAttribute.bind(
null,
'data-test-id'
);
export function getAllByTestId(container, id, ...rest) {
const els = queryAllByTestId(container, id, ...rest);
if (!els.length)
throw queryHelpers.getElementError(
`No element with [data-test-id="${id}"]`,
container
);
return els;
}
export function getByTestId(container, id, ...rest) {
const els = getAllByTestId(container, id, ...rest);
if (els.length > 1)
throw queryHelpers.getElementError(
`Multiple elements with [data-test-id="${id}"]`,
container
);
return els[0];
}
```
Or using `buildQueries`:
```js
const queryAllByDataCy = (...args) =>
queryHelpers.queryAllByAttribute('data-cy', ...args);
const [
queryByDataCy,
getAllByDataCy,
getByDataCy,
findAllByDataCy,
findByDataCy
] = buildQueries(
queryAllByDataCy,
(c, v) => `Found multiple elements with data-cy="${v}"`,
(c, v) => `Unable to find element with data-cy="${v}"`
);
```
### 2. Skipping auto cleanup
- Via CLI: `cross-env RTL_SKIP_AUTO_CLEANUP=true jest`
- Or add to Jest `setupFiles`: `import '@testing-library/react/dont-cleanup-after-each';`
### 3. Migrating from Enzyme
1. Install RTL & jest-dom.
2. Replace `shallow`/`mount` with `render` + `screen`.
3. Migrate tests incrementally.
### 4. Querying within elements
```js
import { render, within } from '@testing-library/react';
const { getByText } = render(<MyComponent />);
const section = getByText('messages');
const hello = within(section).getByText('hello');
```
### 5. Integration testing
```js
import { render, cleanup, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import nock from 'nock';
import App from '../App';
const REPOS = [{ name: 'repo1', description: '...' }];
beforeAll(() =>
nock('https://api.github.com')
.persist()
.get('/users/alice/repos')
.reply(200, REPOS)
);
afterEach(cleanup);
test('user sees public repos', async () => {
render(<App />);
userEvent.type(screen.getByPlaceholderText('Enter username'), 'alice');
userEvent.click(screen.getByRole('button', { name: /submit/i }));
await waitFor(() =>
REPOS.forEach((r) => expect(screen.getByText(r.name)).toBeInTheDocument())
);
expect(screen.queryByText('Loading...')).toBeNull();
});
```
## Conclusion
This comprehensive cheat sheet covers basic to advanced RTL usage—rendering, querying, mocking, custom queries, and integration tests—to help you write robust, maintainable tests.
+90 -55
View File
@@ -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
View File
@@ -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);
```
+1 -1
View File
@@ -449,7 +449,7 @@ case input
# Check for an integer, 19
when 19
puts "It's 19"
# 检查一个确切的字符串,“Zaman”
# Check for an exact string,“Zaman”
when "Zaman"
puts "Hi Zaman"
when 7..11
+7 -7
View File
@@ -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 {
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: Screen
date: 2021-01-02 20:03:55
background: bg-emerald-500
background: bg-indigo-500
tags:
- terminal
- session
+620
View File
@@ -0,0 +1,620 @@
---
title: Socket io
date: 27-06-2025
icon: icon-style
background: bg-[#1289D8]
tags:
- socket io
- web
categories:
- Programming
intro: |
Socket.IO is a JavaScript library for real-time web applications. It enables bi-directional, event-based communication between clients (typically browsers or native apps) and servers.
plugins:
- copyCode
---
# Socket.IO Multi-Language Cheat Sheet (v4)
## Introduction
### Introduction
- [Socket.IO Official Website](https://socket.io/) _(socket.io)_
- [Socket.IO Documentation (v4.1)](https://socket.io/docs/v4/) _(socket.io)_
- [Socket.IO GitHub Repository](https://github.com/socketio/socket.io) _(github.com)_
- [Getting Started with Socket.IO (Chat App Tutorial)](https://socket.io/get-started/chat/) _(socket.io)_
- [FreeCodeCamp Socket.IO Tutorial](https://www.freecodecamp.org/news/socket-io-tutorial/) _(freecodecamp.org)_
## Installation / Setup
### Installation / Setup
**JavaScript (Node.js)**
```bash
npm install socket.io socket.io-client
```
**Python**
```bash
pip install python-socketio eventlet
# or
pip install python-socketio aiohttp
```
**Java**
```groovy
implementation 'io.socket:socket.io-client:2.0.1'
```
### Installation / Setup
**Swift (iOS)**
```ruby
pod 'Socket.IO-Client-Swift', '~> 16.0.1'
```
**C# (.NET)**
```powershell
Install-Package SocketIoClientDotNet
```
**React Native**
```bash
npm install socket.io-client
```
### Installation / Setup
**Go**
```bash
go get github.com/googollee/go-socket.io
```
**Rust**
```bash
cargo add socketio-client
```
---
## Connecting / Setup
### JavaScript (Browser Client then Node.js Server)
**Client**
```js
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
```
**Server**
```js
const io = require('socket.io')(3000, {
cors: { origin: '*' }
});
io.on('connection', (socket) => {
console.log('Client connected:', socket.id);
});
```
### Python (Client then Server)
**Client**
```python
import socketio
sio = socketio.Client()
sio.connect('http://localhost:3000')
```
**Server**
```python
import socketio, eventlet, flask
app = flask.Flask(__name__)
sio = socketio.Server(cors_allowed_origins='*')
app = socketio.WSGIApp(sio, app)
@sio.event
def connect(sid, environ):
print('Client connected:', sid)
if __name__ == '__main__':
eventlet.wsgi.server(eventlet.listen(('', 3000)), app)
```
### Java (Client then Server)
**Client**
```java
IO.Options opts = new IO.Options();
Socket socket = IO.socket("http://localhost:3000", opts);
socket.connect();
```
**Server**
```java
import io.socket.engineio.server.EngineIoServer;
import io.socket.server.SocketIoServer;
EngineIoServer engineIo = new EngineIoServer();
SocketIoServer io = new SocketIoServer(engineIo);
io.listen(3000);
io.on("connection", args -> {
var client = args[0];
System.out.println("Client connected: " + client.id());
});
```
### Swift (iOS Client then Server)
**Client**
```swift
let manager = SocketManager(
socketURL: URL(string: "http://localhost:3000")!,
config: [.log(true), .compress]
)
let socket = manager.defaultSocket
socket.connect()
```
**Server**
_Server setups in Swift are uncommon; usually Node.js or Python is used._
### C# (.NET Client then Server)
**Client**
```csharp
var socket = IO.Socket("http://localhost:3000");
socket.Connect();
```
**Server**
```csharp
using Fleck;
var server = new WebSocketServer("ws://0.0.0.0:3000");
server.Start(socket =>
{
socket.OnOpen = () => Console.WriteLine("Client connected");
});
```
### React Native (Client)
**Client**
```js
import io from 'socket.io-client';
const socket = io('http://localhost:3000');
```
_(Server side same as JavaScript above.)_
### Go (Client then Server)
**Client**
```go
import "github.com/googollee/go-socket.io-client"
socket, err := gosocketio.Dial(
gosocketio.GetUrl("localhost", 3000, false),
transport.GetDefaultWebsocketTransport(),
)
```
**Server**
```go
import (
"github.com/googollee/go-socket.io"
"net/http"
)
server, _ := socketio.NewServer(nil)
server.OnConnect("/", func(s socketio.Conn) error {
fmt.Println("Client connected:", s.ID())
return nil
})
http.Handle("/socket.io/", server)
go http.ListenAndServe(":3000", nil)
```
### Rust (Client then Server)
**Client**
```rust
use socketio_client::ClientBuilder;
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let socket = ClientBuilder::new("http://localhost:3000")
.transport("websocket")
.connect()
.await?;
Ok(())
}
```
**Server**
_Rust server support is experimental; commonly use Node.js/Python servers._
---
## Emitting & Listening to Events
### JavaScript (Client then Server)
**Client**
```js
socket.emit('msg', 'Hi');
socket.on('reply', (data) => console.log('Reply:', data));
```
**Server**
```js
io.on('connection', (socket) => {
socket.on('msg', (msg) => {
console.log('Received:', msg);
socket.emit('reply', 'Hello from server');
});
});
```
### Python (Client then Server)
**Client**
```python
sio.emit('msg', 'Hi')
@sio.on('reply')
def on_reply(data):
print('Reply:', data)
```
**Server**
```python
@sio.event
def msg(sid, data):
print('Received:', data)
sio.emit('reply', 'Hello from server', to=sid)
```
### Java (Client then Server)
**Client**
```java
socket.emit("msg", "Hi");
socket.on("reply", args -> System.out.println("Reply: " + args[0]));
```
**Server**
```java
io.on("connection", args -> {
var client = args[0];
client.on("msg", msgArgs -> {
System.out.println("Received: " + msgArgs[0]);
client.emit("reply", "Hello from server");
});
});
```
### Swift (Client then Server)
**Client**
```swift
socket.emit("msg", "Hi")
socket.on("reply") { data, _ in
print("Reply:", data[0])
}
```
**Server**
_Server side in Swift is rare; use Node.js/Python._
### C# (Client then Server)
**Client**
```csharp
socket.Emit("msg", "Hi");
socket.On("reply", data => Console.WriteLine("Reply: " + data));
```
**Server**
```csharp
socket.OnMessage = message =>
{
Console.WriteLine("Received: " + message);
socket.Send("reply", "Hello from server");
};
```
### Go (Client then Server)
**Client**
```go
socket.Emit("msg", "Hi")
socket.On("reply", func(msg string) {
fmt.Println("Reply:", msg)
})
```
**Server**
```go
server.OnEvent("/", "msg", func(s socketio.Conn, msg string) {
fmt.Println("Received:", msg)
s.Emit("reply", "Hello from server")
})
```
### Rust (Client then Server)
**Client**
```rust
socket.emit("msg", Payload::String("Hi"));
socket.on("reply", |payload| println!("Reply: {:?}", payload));
```
**Server**
_Experimental; typically use Node.js/Python._
---
## Broadcasting & Rooms
### Client (All Languages)
- **Join a room:**
```js
// JavaScript/Python/C#/etc.
socket.emit('join', 'room1');
socket.on('msg', (data) => console.log('Room message:', data));
```
### Server (All Languages)
- **Node.js**
```js
io.on('connection', (socket) => {
socket.on('join', (room) => {
socket.join(room);
io.to(room).emit('msg', 'Hello Room');
});
});
```
- **Python**
```python
@sio.event
def join(sid, room):
sio.enter_room(sid, room)
sio.emit('msg', 'Hello Room', room=room)
```
- **Go**
```go
server.OnEvent("/", "join", func(s socketio.Conn, room string) {
s.Join(room)
server.BroadcastToRoom("/", room, "msg", "Welcome")
})
```
---
## Disconnects & Errors
### Client (All Languages)
```js
socket.on('disconnect', (reason) => console.log('Disconnected:', reason));
socket.on('connect_error', (err) => console.error('Connection error:', err));
```
```python
@sio.event
def disconnect():
print('Disconnected')
@sio.event
def connect_error(data):
print('Connection error:', data)
```
```go
// Go client library varies; similar patterns apply.
```
### Server (All Languages)
```js
io.on('connection', (socket) => {
socket.on('disconnect', (reason) =>
console.log('Client disconnected:', reason)
);
});
```
```go
server.OnDisconnect("/", func(s socketio.Conn, reason string) {
fmt.Println("Client disconnected:", reason)
})
```
---
## Namespaces
### Client (All Languages)
```js
const adminSocket = io('/admin');
```
```python
sio.connect('http://localhost:3000/admin', namespaces=['/admin'])
```
### Server (All Languages)
```js
io.of('/admin').on('connection', (socket) => {
console.log('Admin connected:', socket.id);
});
```
```go
server.Of("/admin").OnConnect(func(s socketio.Conn) {
fmt.Println("Admin connected:", s.ID())
})
```
---
## Authentication (Basic Token)
### Client (All Languages)
```js
const socket = io('http://localhost:3000', {
auth: { token: 'abc' }
});
```
```python
sio.connect('http://localhost:3000', auth={'token': 'abc'})
```
### Server (All Languages)
```js
io.use((socket, next) => {
const token = socket.handshake.auth.token;
token === 'abc' ? next() : next(new Error('Auth error'));
});
```
---
## Tips for Debugging & Logging
### Client
- Log events:
```js
socket.onAny((event, ...args) => console.log(event, args));
```
- Inspect network in browser devtools.
### Server
- **JavaScript**
```bash
DEBUG=socket.io* node server.js
```
- **Python**
```python
import logging
logging.getLogger('socketio').setLevel(logging.DEBUG)
```
- **Go**
Print handler errors and use middleware for structured logs.
---
## Advanced Features
### Middleware
**Client**
_(Rarely needed)_
**Server**
```js
io.use((socket, next) => {
console.log('Middleware:', socket.id);
next();
});
```
```go
server.Use(func(s socketio.Conn, next func()) {
fmt.Println("Middleware triggered:", s.ID())
next()
})
```
### Binary Streaming
**Client**
```js
fetch('/file')
.then((res) => res.arrayBuffer())
.then((buf) => socket.emit('file', buf));
```
**Server**
```go
server.OnEvent("/", "file", func(s socketio.Conn, data []byte) {
ioutil.WriteFile("upload", data, 0644)
})
```
---
## Best Practices
# Implement reconnection with exponential backoff on the client.
# Sanitize and validate all data on both sides.
# Use TLS in production and rotate authentication tokens frequently.
# Separate concerns with namespaces and rooms.
# Throttle high-frequency events and enable compression where possible.
> Official docs: [https://socket.io/docs/v4/](https://socket.io/docs/v4/)
+59
View File
@@ -249,7 +249,66 @@ $ ssh-keygen -R <ip/hostname>
- PEM
- PKCS8
## SSH Tunneling
### SSH Tunnel Options {.row-span-2}
| Option | Description |
| ------ | :----------------------------------------------------- |
| `-L` | Local port forwarding |
| `-R` | Remote port forwarding |
| `-D` | Dynamic port forwarding |
| `-f` | Run in background |
| `-N` | Do not execute a remote command |
| `-g` | Allow remote hosts to connect to local forwarded ports |
{.left-text}
more details on flag above with `man ssh`
### Local Port Forwarding {.col-span-2}
```bash
# Forward a local port to a remote server
ssh -L local_port:remote_host:remote_port user@ssh_server
# Example: Forward local port 8080 to remote port 80 on example.com
ssh -L 8080:example.com:80 user@ssh_server
```
### Dynamic Port Forwarding {.col-span-2}
```bash
# Create a SOCKS proxy on a local port
ssh -D local_port user@ssh_server
# Create a SOCKS proxy on local port 1080 in the background
ssh -f -N -D 1080 user@ssh_server
```
### Background Tunnel {.col-span-3}
```bash
# Create a local port forwarding tunnel in the background
ssh -f -N -L local_port:remote_host:remote_port user@ssh_server
```
### Multiple Tunnels {.col-span-3}
```bash
# Create multiple tunnels in a single SSH command
ssh -L 8080:example.com:80 -L 3306:db.example.com:3306 user@ssh_server
```
### Combining Options {.col-span-3}
```bash
# In background, no command, allow remote host, local port forward, identity_file
ssh -f -N -g -L 8080:example.com:80 -i ~/.ssh/custom_key user@ssh_server
```
## Also see
- [OpenSSH Config File Examples](https://www.cyberciti.biz/faq/create-ssh-config-file-on-linux-unix/) _(cyberciti.biz)_
- [ssh_config](https://linux.die.net/man/5/ssh_config) _(linux.die.net)_
- [man-ssh](https://man7.org/linux/man-pages/man1/ssh.1.html)
+27 -32
View File
@@ -1,6 +1,6 @@
---
title: Svelte
date: 2025-04-08 19:45:00
date: 2025-08-16 10:30:00
background: bg-[#FF3E00]
tags:
- svelte
@@ -87,7 +87,7 @@ Note: Svelte components must always return a root element or content.
```js
<script>
export let name = "User";
let { name = "User" } = $props();
</script>
<div class="UserProfile">
@@ -127,8 +127,7 @@ Note: External components should be installed via npm first.
```js
<script>
export let firstName;
export let lastName;
let { firstName, lastName } = $props();
function fullName() {
return `${firstName} ${lastName}`;
@@ -143,21 +142,14 @@ 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
```js
<script>
export let firstName;
export let lastName;
export let age;
let { firstName, lastName, age } = $props();
</script>
<h1>{firstName} {lastName} is {age}.</h1>
@@ -169,7 +161,7 @@ Note: External components should be installed via npm first.
```js
<script>
let name = "Zehan";
let name = $state("Zehan");
function updateName() {
name = prompt("What is your name?") || name;
@@ -177,7 +169,7 @@ Note: External components should be installed via npm first.
</script>
<h1>{name}</h1>
<button on:click={updateName}>Update name</button>
<button onclick={updateName}>Update name</button>
```
## Events {.cols-1}
@@ -192,12 +184,12 @@ Note: External components should be installed via npm first.
}
</script>
<a href="#" on:click|preventDefault={handleClick}>
<a href="#" onclick|preventDefault={handleClick}>
Say Hi
</a>
```
Note: The most common event listeners are `on:click` and `on:submit`.
Note: The most common event listeners are `onclick` and `onsubmit`.
## Loops {.cols-2}
@@ -241,8 +233,8 @@ Note: The most common event listeners are `on:click` and `on:submit`.
```js
<script>
let username = "";
let password = "";
let username = $state("");
let password = $state("");
function handleSubmit(event) {
event.preventDefault();
@@ -250,7 +242,7 @@ Note: The most common event listeners are `on:click` and `on:submit`.
}
</script>
<form on:submit={handleSubmit}>
<form onsubmit={handleSubmit}>
<input type="text" placeholder="Username" bind:value={username} />
<input type="password" placeholder="Password" bind:value={password} />
<input type="submit" value="Login" />
@@ -279,7 +271,7 @@ Note: The most common event listeners are `on:click` and `on:submit`.
<script>
import { onMount } from 'svelte';
let notifications = [];
let loading = true;
let loading = $state(true);
onMount(async () => {
const res = await fetch("https://notifications.com");
@@ -304,6 +296,7 @@ Note: Use `onMount` for side effects like API calls.
## Lifecycle Hooks {.cols-1}
### onMount
```js
<script>
import { onMount } from 'svelte';
@@ -315,6 +308,7 @@ Note: Use `onMount` for side effects like API calls.
```
### beforeUpdate
```js
<script>
import { beforeUpdate } from 'svelte';
@@ -326,6 +320,7 @@ Note: Use `onMount` for side effects like API calls.
```
### afterUpdate
```js
<script>
import { afterUpdate } from 'svelte';
@@ -337,6 +332,7 @@ Note: Use `onMount` for side effects like API calls.
```
### onDestroy
```js
<script>
import { onDestroy } from 'svelte';
@@ -346,8 +342,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 +355,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
@@ -391,9 +388,9 @@ export const time = readable(new Date(), function start(set) {
```js
<script>
let a = 2;
let b = 3;
$: sum = a + b;
let a = $state(2);
let b = $state(3);
let sum = $derived(a + b);
</script>
<p>{sum}</p>
@@ -404,8 +401,7 @@ export const time = readable(new Date(), function start(set) {
```js
<script>
let name = 'Zehan';
$: console.log('Name changed to', name);
$effect(() => console.log('Name changed to', name));
</script>
```
@@ -413,7 +409,7 @@ export const time = readable(new Date(), function start(set) {
```js
<script>
let text = '';
let text = $state('');
</script>
<textarea bind:value={text} />
@@ -424,7 +420,7 @@ export const time = readable(new Date(), function start(set) {
```js
<script>
let selected = 'apple';
let selected = $state('apple');
</script>
<label><input type="radio" bind:group={selected} value="apple" /> Apple</label>
@@ -481,11 +477,10 @@ export async function load({ fetch }) {
```js
// +page.svelte
<script>
export let data;
let { data } = $props();
</script>
<h1>{data.title}</h1>
```
Note: Requires SvelteKit setup for SSR routes.
+17 -8
View File
@@ -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}
+452
View File
@@ -0,0 +1,452 @@
---
title: Symfony
date: 2025-07-23 18:28:43
background: bg-[#67526d]
label: php
tags:
- php
- web
categories:
- Programming
intro: |
This Symfony Cheat Sheet is a non exhaustive list of main symfony basics that you can use or need.
plugins:
- copyCode
---
## Getting Started
### Installation
```bash
curl -sS https://get.symfony.com/cli/installer | bash
```
- [Doc Symfony Download](https://symfony.com/download)
{.marker-round}
### Symfony CLI: Basic Commands {.col-span-2}
| Command | Description |
|:--------------------------------|:----------------------------------------------|
| `symfony check:requirements` | Check system requirements for running Symfony |
| `symfony version` | Display the Symfony CLI version |
| `symfony help` | Display all available commands |
| `symfony help <cmd>` | Display help for a specific command |
| `symfony server:start` | Start server |
| `symfony server:stop` | Stop server |
| `symfony serve -d` | Run Symfony server in background |
### Creating a New Symfony Project {.col-span-3}
| Command | Description |
|:--------------------------------------------------------------|:---------------------------------------------------|
| `symfony new <dir>` | Create a new Symfony project in `<dir>` |
| `symfony new my_project_directory --version="7.3.x" --webapp` | Create a new web application |
| `symfony new my_project_directory --version="7.3.x"` | Create a new API application |
| `composer create-project symfony/skeleton <dir>` | Create a new Symfony project using Composer |
----
[Doc Symfony creating app](https://symfony.com/doc/current/setup.html#creating-symfony-applications) {.link-arrow}
### Symfony Console Basic Usage
| CMD | Description |
|:--------------------------|:----------------------------------------------------------|
| `bin/console` | List all available commands |
| `bin/console <namespace>` | List all commands in a specific namespace or bundle |
| `bin/console <cmd>` | Run a specific command |
| `bin/console help <cmd>` | Show help for a specific command |
| `bin/console --env=<env>` | Run console in environment: dev, test, or prod |
| `bin/console cache:clear` | Clear the cache |
### Linting Commands {.col-span-2}
| CMD | Description |
|:-------------------------------|:-------------------------------------------------------|
| `bin/console lint:container` | Check service arguments for type mismatches |
| `bin/console lint:twig <dir>` | Lint Twig templates for syntax errors |
| `bin/console lint:yaml <dir>` | Lint YAML files for syntax errors |
| `bin/console lint:xliff <dir>` | Lint XLIFF translation files |
### Debugging Commands {.col-span-3}
| CMD | Description |
|:---------------------------------------------|:----------------------------------------|
| `bin/console debug:asset-map` | Show all mapped assets |
| `bin/console debug:autowiring` | List all autowireable services |
| `bin/console debug:config <bundle>` | Dump configuration of a bundle |
| `bin/console debug:container` | List all public services |
| `bin/console debug:container <service>` | Get info about a specific service |
| `bin/console debug:container --env-vars` | Show environment variables in container |
| `bin/console debug:container --tags` | List tagged public services |
| `bin/console debug:container --tag=<t>` | List services with a specific tag |
| `bin/console debug:dotenv` | Display parsed dotenv values |
| `bin/console debug:dotenv <search>` | Show dotenv values matching a search |
| `bin/console debug:event-dispatcher` | List all event listeners |
| `bin/console debug:firewall <name>` | Show details of a firewall |
| `bin/console debug:form` | Show form type information |
| `bin/console debug:messenger` | List dispatchable messages |
| `bin/console debug:router` | List all registered routes |
| `bin/console debug:router <name>` | Get info about a specific route |
| `bin/console debug:translation <loc>` | Show messages for a locale |
### AssetMap Commands {.col-span-2}
| CMD | Description |
|:--------------------------------------|:---------------------------------------------------|
| `bin/console asset-map:compile` | Compile assets for production |
| `bin/console importmap:require <pkg>` | Add an NPM package to the import map |
| `bin/console importmap:install` | Download all importmap packages |
| `bin/console importmap:update` | Update all importmap packages |
| `bin/console importmap:remove <pkg>` | Remove a package from import map |
| `bin/console importmap:outdated` | List outdated importmap packages |
| `bin/console importmap:audit` | Check dependencies for vulnerabilities |
## ORM & Migration
### Database Connection {.col-span-2}
```bash
# MySQL
DATABASE_URL="mysql://username:password@127.0.0.1:3306/db_name?serverVersion=X.Y.Z&charset=utf8mb4"
# MariaDB
DATABASE_URL="mysql://username:password@127.0.0.1:3307/db_name?serverVersion=X.Y.Z-MariaDB&charset=utf8mb4"
# PostgreSQL
DATABASE_URL="postgresql://username:password@127.0.0.1:5432/db_name?serverVersion=X.Y.Z&charset=utf8"
```
----
`username` : user of DBMS <br>
`password` : password of DBMS <br>
`127.0.0.1`: `3306` MySQL `3307` MariaDB `5432` PostgreSQL <br>
`db_name` : name of data base <br>
`serverVersion` : to know server version <code>SHOW GLOBAL VARIABLE LIKE</code> `%version%` in your DBMS
### Doctrine Commands {.col-span-3}
| CMD | Description |
|:--------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------|
| `bin/console doctrine:database:create`or `php bin/console d:d:c` | Create the configured database |
| `bin/console doctrine:database:drop` or `php bin/console d:d:d` | Drop the configured database |
| `bin/console doctrine:mapping:info` | List mapped entities |
| `bin/console doctrine:schema:update --dump-sql` | Generate SQL to sync DB schema |
| `bin/console doctrine:schema:update --force` | Sync DB schema with mapping info |
| `bin/console doctrine:schema:validate` | Validate the mapping files |
| `bin/console doctrine:query:sql <sql cmd>` | Run a raw SQL query |
| `bin/console doctrine:query:dql <dql cmd>` | Run a DQL query |
| `bin/console doctrine:fixtures:load` | Load data fixtures into the database |
---
You can run <code>php bin/console doctrine:schema:drop --force && php bin/console doctrine:schema:update --force && php bin/console doctrine:fixtures:load -n</code> to Load data fixtures & reset sequence to 0
----
[Doc Symfony Database](https://symfony.com/doc/current/doctrine.html#configuring-the-database) {.link-arrow}
### Migration Commands {.col-span-3}
| CMD | Description |
|:--------------------------------------------------------------------|:--------------------------------------------------------------------|
| `bin/console make:migration` | Generate a new migration based on schema changes |
| `bin/console doctrine:migration:generate` | Generate a new migration based on schema changes |
| `bin/console doctrine:migration:migrate` or `php bin/console d:m:m` | Execute pending migrations to update the database |
| `bin/console doctrine:migration:status` | Show status of migrations (pending, executed) |
| `bin/console doctrine:migration:diff` | Compare current schema with the database and generate migration SQL |
## Symfony Maker
### Maker-Bundle List {.col-span-2}
| Command | Description |
|:-----------------------------|:-----------------------------------------------------------------------------------------------------|
| `bin/console list make ` | List all make commands available |
| `make:auth` | Create a Guard authenticator of different flavors |
| `make:command` | Create a new console command class |
| `make:controller` | Create a new controller class |
| `make:crud` | Create CRUD for Doctrine entity class |
| `make:docker:database` | Add a database container to your compose.yaml file |
| `make:entity` | Create or update a Doctrine entity class, and optionally an API Platform resource |
| `make:fixtures` | Create a new class to load Doctrine fixtures |
| `make:form` | Create a new form class |
| `make:functional-test` | Create a new test class |
| `make:listener` | [make:subscriber] Creates a new event subscriber class or a new event listener class |
| `make:message` | Create a new message and handler |
| `make:messenger-middleware` | Create a new messenger middleware |
| `make:migration` | Create a new migration based on database changes |
| `make:registration-form` | Create a new registration form system |
| `make:reset-password` | Create controller, entity, and repositories for use with symfonycasts/reset-password-bundle |
| `make:schedule` | Create a scheduler component |
| `make:security:custom` | Create a custom security authenticator |
| `make:security:form-login` | Generate the code needed for the form_login authenticator |
| `make:serializer:encoder` | Create a new serializer encoder class |
| `make:serializer:normalizer` | Create a new serializer normalizer class |
| `make:stimulus-controller` | Create a new Stimulus controller |
| `make:subscriber` | Creates a new event subscriber class or a new event listener class |
| `make:test` | [make:unit-test make:functional-test] Create a new test class |
| `make:twig-component` | Create a Twig (or Live) component |
| `make:twig-extension` | Create a new Twig extension with its runtime class |
| `make:unit-test` | Create a new test class |
| `make:user` | Create a new security user class |
| `make:validator` | Create a new validator and constraint class |
| `make:voter` | Create a new security voter class |
| `make:webhook` | Create a new Webhook |
[Doc Symfony Maker Bundle](https://symfony.com/bundles/SymfonyMakerBundle/current/index.html) {.link-arrow}
## Controller Basics
### Route Attributes and Descriptions {.col-span-3}
`use Symfony\Component\Routing\Attribute\Route;`
| Attribute | Description |
|:----------------------------------------------------------------------------|:-------------------------------------------|
| `#[Route('/path')]` | Define a route for a controller method |
| `#[Route('/path', name: 'name')]` | Define a named route for a method |
| `#[Route('/path', methods: ['GET'])]` | Define allowed HTTP methods |
| `#[Route('/blog/{slug}')]` | Define a route with a parameter |
| `#[Route('/page/{page}', requirements: ['page' => '\d+'])]` | Define a route with a parameter constraint |
| `#[Route(path: ['en' => '/about-us', 'nl' => '/over-ons'], name: 'about')]` | Define localized routes |
[Doc Symfony Route Parameters](https://symfony.com/doc/current/routing.html#route-parameters) {.link-arrow}
### AbstractController Methods {.col-span-3}
| Method | Description |
|:-------------------------------------------------------|:----------------------------------------------|
| `$this->render('template.html')` | Returns a Response with the rendered template |
| `$this->redirectToRoute('homepage')` | Returns a RedirectResponse to a named route |
| `$this->redirectToRoute('name', ['param' => 'value'])` | Returns a redirect to a route with parameters |
| `$this->redirectToRoute('name', [], 301)` | Returns a RedirectResponse with status code |
| `$this->redirect('http://example.com')` | Returns a RedirectResponse to an external URL |
| `$this->createNotFoundException($msg)` | Returns a NotFoundHttpException |
| `$this->createForm(FormType::class, $data)` | Creates a new Form instance based on the type |
### Form Methods {.col-span-2}
| Method | Description |
|:---------------------------------|:--------------------------------|
| `$form->handleRequest($request)` | Handle a form submission |
| `$form->isSubmitted()` | Check if the form was submitted |
| `$form->isValid()` | Check if the form is valid |
## Form Type : [Doc Symfony Form types](https://symfony.com/doc/current/reference/forms/types.html)
### Form Fields: Text Fields
| Type | Description |
|:---------------|:----------------------------------------|
| `TextType` | A basic text input field |
| `TextareaType` | A multi-line textarea field |
| `EmailType` | An email field (`<input type="email">`) |
| `PasswordType` | A password field |
| `SearchType` | A search field |
| `UrlType` | A URL field (`<input type="url">`) |
| `TelType` | A tel (phone number) input field |
| `UuidType` | A UUID field |
### Form Fields: Numeric Fields
| Type | Description |
|:---------------|:-------------------------------------------|
| `IntegerType` | A number field for integers |
| `MoneyType` | A money field, with a specifiable currency |
| `NumberType` | A number field |
| `PercentType` | A number field for percentages |
| `RangeType` | A range input field (slider) |
### Form Fields: Choice Fields
| Type | Description |
|:---------------|:----------------------------------------|
| `ChoiceType` | Field for selecting one or more options |
| `EnumType` | Choose from PHP enum cases |
| `EntityType` | Choose from a Doctrine entity |
| `CountryType` | Choose a country |
| `LanguageType` | Choose a language |
| `LocaleType` | Choose a locale |
| `TimezoneType` | Choose a timezone |
| `CurrencyType` | Choose a currency |
### Form Fields: Symfony UX Fields
| Type | Description |
|:----------------|:-----------------------------------|
| `CropperType` | A Cropper.js image cropper field |
| `DropzoneType` | A Dropzone file upload field |
### Form Fields: Date and Time Fields
| Type | Description |
|:-------------------|:----------------------------|
| `DateType` | A date field |
| `DateIntervalType` | A date interval field |
| `DateTimeType` | A date and time field |
| `TimeType` | A time field |
| `BirthdayType` | A date field for birthdays |
| `WeekType` | Select a year and week |
### Form Fields: Other Fields
| Type | Description |
|:---------------|:------------------------------------|
| `CheckboxType` | A single checkbox field |
| `FileType` | A file upload field |
| `RadioType` | A radio button field |
| `HiddenType` | A hidden field |
### Form Fields: Field Groups
| Type | Description |
|:------------------|:-----------------------------------------------------------|
| `CollectionType` | A group of fields that can be added or removed |
| `RepeatedType` | A field that is repeated (e.g., password confirmation) |
## Validation Attributes and Descriptions : [Doc Symfony Validation](https://symfony.com/doc/current/validation.html)
### General Constraints
| Attribute | Description |
|:---------------------------|:--------------------------------------------------|
| `#[Assert\NotBlank]` | Value is not an empty string/array, false or null |
| `#[Assert\Blank]` | Value is an empty string or null |
| `#[Assert\NotNull]` | Value is not strictly equal to null |
| `#[Assert\IsNull]` | Value is exactly equal to null |
| `#[Assert\Type('string')]` | Value is of a specific type |
### Validation: Comparison Constraints {.col-span-2}
| Attribute | Description |
|:------------------------------------|:--------------------------------------------------|
| `#[Assert\<Not>EqualTo('Foo')]` | Value is (not) equal to another value |
| `#[Assert\<Not>IdenticalTo('Foo')]` | Value is (not) identical to another value |
| `#[Assert\LessThan<OrEqual>(5)]` | Value is less than (or equal to) another value |
| `#[Assert\GreaterThan<OrEqual>(5)]` | Value is greater than (or equal to) another value |
| `#[Assert\Range(min: 2, max: 10)]` | Number or DateTime object is within a range |
### Validation: String Constraints {.col-span-2}
| Attribute | Description |
|:-----------------------------------|:------------------------------------------------------|
| `#[Assert\Length(2, 10)]` | String is between `<min>` and `<max>` characters long |
| `#[Assert\Email]` | String is a valid email address |
| `#[Assert\Url]` | String is a valid URL |
| `#[Assert\Hostname]` | String is a valid hostname |
| `#[Assert\Ip]` | String is a valid IP address |
| `#[Assert\NoSuspiciousCharacters]` | String does not contain spoofing characters |
| `#[Assert\Uuid]` | String is a valid UUID |
| `#[Assert\CssColor]` | String is a valid CSS color |
### Validation: Date and Time Constraints
| Attribute | Description |
|:---------------------|:--------------------------------------------------|
| `#[Assert\Date]` | Value is a valid date string in `Y-m-d` format |
| `#[Assert\DateTime]` | Value is a valid datetime in the specified format |
| `#[Assert\Time]` | Value is a valid time string in `H:i:s` format |
| `#[Assert\Timezone]` | Value is a valid timezone identifier |
### Validation: Password Constraints {.col-span-2}
| Attribute | Description |
|:-----------------------------------|:--------------------------------------------|
| `#[Assert\UserPassword]` | String is the authenticated user's password |
| `#[Assert\NotCompromisedPassword]` | Password is not found in any data breaches |
| `#[Assert\PasswordStrength]` | Password has sufficient entropy |
### Validation: Financial and Other Number Constraints
| Attribute | Description |
|:-----------------------|:-------------------------------------------------|
| `#[Assert\Bic]` | Value is a valid Business Identifier Code (BIC) |
| `#[Assert\CardScheme]` | Value is a valid credit card number |
| `#[Assert\Currency]` | Value is a valid 3-letter ISO 4217 currency code |
| `#[Assert\Luhn]` | Value passes the Luhn algorithm |
| `#[Assert\Iban]` | Value is a valid IBAN |
| `#[Assert\Isbn]` | Value is a valid ISBN |
### Validation: File Constraints
| Attribute | Description |
|:------------------|:------------------------------------------------|
| `#[Assert\File]` | Value is a valid file path or File object |
| `#[Assert\Image]` | Same as File, but only accepts image MIME types |
### Validation: Number Constraints {.col-span-2}
| Attribute | Description |
|:-----------------------------|:----------------------------|
| `#[Assert\Positive<OrZero>]` | Value is positive (or zero) |
| `#[Assert\Negative<OrZero>]` | Value is negative (or zero) |
### Validation: Choice Constraints {.col-span-2}
| Attribute | Description |
|:-------------------------------------|:------------------------------------------|
| `#[Assert\Choice(['A', 'B', 'C'])]` | Value is one of the specified choices |
| `#[Assert\Country]` | Value is a valid ISO 3166-1 country code |
| `#[Assert\Language]` | Value is a valid two-letter language code |
| `#[Assert\Locale]` | Value is a valid locale identifier |
+242
View File
@@ -0,0 +1,242 @@
---
title: Systemd
date: 02-07-2025
icon: icon-systemd
background: bg-[#00ADEF]
tags:
- systemd
- linux
categories:
- Linux Command
intro: |
systemd is the init system and service manager used by most modern Linux distributions.
plugins:
- copyCode
---
## systemd Core Utilities{.cols-4}
### systemd utility List {.col-span-4}
| Utility | Description |
| ------------------------------------- | -------------------------------------------------------------- |
| [`systemctl`](#systemctl) | Manages services (start, stop, restart, enable, disable, etc.) |
| [`journalctl`](#journalctl) | Views and filters logs collected by the systemd journal |
| [`loginctl`](#loginctl) | Manages user logins and sessions |
| [`hostnamectl`](#hostnamectl) | Sets or queries the hostname and related machine metadata |
| [`timedatectl`](#timedatectl) | Sets or queries the system date, time, and NTP settings |
| [`systemd-analyze`](#systemd-analyze) | Analyzes system boot-up performance |
| [`systemd-cgtop`](#systemd-cgtop) | Monitors control group resource usage in real time |
| [`systemd-run`](#systemd-run) | Runs a command as a transient service or scope |
| [`resolvectl`](#resolvectl) | Resolves domain names using the systemd-resolved service |
| [`busctl`](#busctl) | Interacts with the D-Bus message bus system |
{.left-text}
---
## Utility Commands {.cols-4}
### systemctl {#systemctl .col-span-2 .row-span-2}
#### systemctl - System Commands
- Manage systemd units and control system services (start, stop, enable, etc.).
| Command | Description |
| --------------------- | ------------------------------------------------------------------ |
| `systemctl halt` | Stop all running software, leave the hardware powered on. |
| `systemctl hibernate` | Save contents of system memory to disk and power off the hardware. |
| `systemctl poweroff` | Halt and power off the system. |
| `systemctl reboot` | Reboot the system. |
{.left-text}
#### systemctl - Service Commands
| Command | Description |
| ----------------------------- | -------------------------------------------- |
| `systemctl start <service>` | Start a service immediately |
| `systemctl stop <service>` | Stop a running service |
| `systemctl restart <service>` | Restart a service |
| `systemctl reload <service>` | Reload service configuration without restart |
| `systemctl enable <service>` | Enable service to start at boot |
| `systemctl disable <service>` | Disable boot-time start |
| `systemctl status <service>` | Show current status and recent logs |
| `systemctl mask <service>` | Prevent service from being started |
| `systemctl unmask <service>` | Remove mask so it can start again |
| `systemctl list-units` | List active units |
| `systemctl list-unit-files` | List all unit files and their enabled state |
{.left-text}
### journalctl {#journalctl .col-span-2}
- Query and filter logs from the systemd journal.
| Command | Description |
| -------------------------- | ----------------------------------------- |
| `journalctl` | Show entire journal |
| `journalctl -b` | Show logs from current boot |
| `journalctl --list-boots` | List all boot sessions |
| `journalctl -b -1` | Logs from previous boot |
| `journalctl -u <service>` | Show logs for a specific unit/service |
| `journalctl -n 100` | Show the last 100 log entries |
| `journalctl -f` | Follow new log entries (tail -f style) |
| `journalctl -p err..emerg` | Show only error (and above) priority logs |
| `journalctl --disk-usage` | Show disk usage of journal |
| `journalctl --since today` | Show logs since today |
{.left-text}
### busctl {#busctl .col-span-2}
- Inspect and monitor D-Bus (Desktop Bus) for debugging or introspection.
| Command | Description |
| ------------------------------ | -------------------------------------------------- |
| `busctl list` | List all services/peers on the bus |
| `busctl status [SERVICE\|PID]` | Show process info & credentials for service or PID |
| `busctl monitor [SERVICE...]` | Dump live message traffic, Ctrl+C to stop |
| `busctl capture [SERVICE...]` | Capture bus traffic to a pcap file |
| `busctl tree [SERVICE...]` | Show object tree exported by service(s) |
{.left-text}
### loginctl{#loginctl .col-span-2 .row-span-2}
- Manages user sessions and login-related settings.
| Command | Description |
| --------------------------------- | ---------------------------------------------- |
| `loginctl list-sessions` | List all active sessions |
| `loginctl list-users` | List logged-in users |
| `loginctl user-status <UID>` | Show all sessions & processes for user `<UID>` |
| `loginctl session-status <ID>` | Show detailed info and logs for session `<ID>` |
| `loginctl show-session <ID>` | Show machine-parsable properties of a session |
| `loginctl terminate-session <ID>` | End all processes in session `<ID>` |
| `loginctl lock-session <ID>` | Lock the specified session |
| `loginctl unlock-session <ID>` | Unlock the specified session |
{.left-text}
### systemd-analyze{#systemd-analyze .col-span-2}
- Analyze system boot performance and unit dependencies.
| Command | Description |
| --------------------------------- | ------------------------------------- |
| `systemd-analyze` | Show total boot time breakdown |
| `systemd-analyze blame` | List services ordered by startup time |
| `systemd-analyze plot > boot.svg` | Generate SVG visual of boot sequence |
{.left-text}
### systemd-cgtop{#systemd-cgtop .col-span-2}
- Real-time monitoring of resource usage by cgroups (CPU, memory, I/O).
| Command | Description |
| -------------------------- | ---------------------------------- |
| `systemd-cgtop` | Monitor top cgroups resource usage |
| `systemd-cgtop -c` | Sort cgroups by CPU usage |
| `systemd-cgtop -d <delay>` | Change refresh delay interval |
{.left-text}
### timedatectl{#timedatectl .col-span-2}
- Manage system date, time, timezone, and NTP synchronization.
| Command | Description |
| ----------------------------------- | ------------------------------- |
| `timedatectl status` | Show current date/time settings |
| `timedatectl list-timezones` | List all available timezones |
| `timedatectl set-timezone <Zone>` | Set system timezone |
| `timedatectl set-time "YYYY-MM-DD"` | Manually set date |
| `timedatectl set-time "HH:MM:SS"` | Manually set time |
| `timedatectl set-ntp true` | Enable NTP sync |
| `timedatectl set-ntp false` | Disable NTP sync |
{.left-text}
### resolvectl{#resolvectl .col-span-2}
- Interact with systemd-resolved DNS resolver service.
| Command | Description |
| -------------------------------------- | ----------------------------------------------- |
| `resolvectl status` | Show DNS configuration and link info |
| `resolvectl query <hostname>` | Resolve hostname via systemd-resolved |
| `resolvectl dns <interface> <IP>` | Set DNS server(s) for a specific interface |
| `resolvectl domain <interface> <name>` | Set search domain(s) for an interface |
| `resolvectl flush-caches` | Clear the DNS cache managed by systemd-resolved |
| `resolvectl reset-statistics` | Reset all DNS resolution statistics |
{.left-text}
### hostnamectl{#hostnamectl .col-span-4}
- Query and set the system hostname (static, transient, pretty) and related metadata.
#### ↓ Commands
| Command | Description |
| --------------------------------------------- | ------------------------------------------------ |
| `hostnamectl status` | Show current hostname & system info |
| `hostnamectl hostname <NAME>` | Set the static/transient/pretty hostname |
| `hostnamectl set-hostname <NAME> --static` | Set only the static hostname |
| `hostnamectl set-hostname <NAME> --transient` | Set only the transient hostname |
| `hostnamectl set-hostname <NAME> --pretty` | Set the pretty (user-friendly) hostname |
| `hostnamectl set-chassis <TYPE>` | Set chassis type (e.g., desktop, laptop, server) |
{.left-text}
#### ↓ Description
```markdown
- Static - The permanent hostname stored in `/etc/hostname`. Used at boot time.
- Transient - Temporary hostname set at runtime (often by DHCP or manually). Lost on reboot.
- Pretty - A user-friendly, display name (can include spaces and special characters).
```
{.left-text}
### systemd-run{#systemd-run .col-span-4}
- Run a command as a transient systemd unit (service, scope, timer, etc.).
| Command | Description |
| -------------------------------------------------------- | -------------------------------------------------- |
| `systemd-run <command>` | Run command as a transient `.service` unit |
| `systemd-run -p BlockIOWeight=10 updatedb` | Run with a specific resource limit property |
| `systemd-run -p MemoryMax=100M script.sh` | Run a memory-hungry task with a memory usage limit |
| `systemd-run --on-calendar='YYYY-MM-DD HH:MM' script.sh` | Schedule script to run at a specific date and time |
| `systemd-run -E VAR=value script.sh` | Run a script with environment variables set |
{.left-text}
#### Types of systemd limits{.col-span-3}
```markdown
There are different kinds of limit that can be imposed:
- CPU Limits
- Memory Limits
- I/O Limits
- Task/Thread Limits
- Security/Isolation
- Execution/Environment
```
Example
```bash
systemd-run -p MemoryMax=100M -p CPUQuota=50% scriptFile.sh
```
## Also See
- [linux training academy](https://www.linuxtrainingacademy.com/systemd-cheat-sheet/)
- [linux Audit Cheat Sheet](https://linux-audit.com/cheat-sheets/systemd/)
- [RedHat Reference](https://www.redhat.com/en/blog/systemd-commands)
+52
View File
@@ -0,0 +1,52 @@
---
title: Telnet
date: 2025-08-10 18:28:43
background: bg-indigo-400
tags:
- network
- scan
- port
categories:
- Linux Command
intro:
This cheat sheet is intended to be a quick reminder for the main concepts involved in using the command line program
telnet and assumes you already understand its usage.
plugins:
- copyCode
---
## Getting Started
### Usage
Standard usage (i.e. a host to connect can be by ip or by domain)
```shell script
$ telnet [options] target [port]
```
communicate over http protocol
```shell script
$ telnet example.com 80
```
create traceroute file
```shell script
$ telnet example.com 80
```
### Option examples
| Option | Example | Operation |
| ------ | ----------------------------------------- | ---------------------------------------------------- |
| `-E` | telnet -E target port | To treat all characters as data and prevent dropping to command
| `-e` | telnet -e '^C' host | Set a custom escape character instead of default ^] |
| `-l` | telnet -l alice host | Pass a username to the remote host |
| `-d` | telnet -d host | Enable debug mode |
| `-l` | telnet -n host | Creates a trace file |
## Also see
- [Telnet manpage](https://www.commandlinux.com/man-page/man1/telnet.1.html)
+112 -1
View File
@@ -12,7 +12,118 @@ intro: |
A visual cheat-sheet for the 25 keyboard shortcuts found in the TickTick desktop app
---
## Keyboard Shortcuts {.cols-2}
## Keyboard Shortcuts (Mac) {.cols-3}
### General
| Shortcut | Action |
| ----------------- | ----------------- |
| `Cmd` `S` | Sync task |
| `Esc` | Cancel |
| `Cmd` `Z` | Undo |
| `Cmd` `Shift` `Z` | Redo |
| `Cmd` `P` | Print |
| `Cmd` `K` | Open command menu |
| `?` | Shortcuts |
{.shortcuts}
### Global Action
| Shortcut | Action |
| -------------------------- | ------------------------ |
| `Ctrl` `Shift` `A` | Quick add |
| `Cmd` `Shift` `O` | Show or hide mini window |
| `Cmd` `Option` `Shift` `P` | Start or abandon pomo |
{.shortcuts}
### Navigation
| Shortcut | Action |
| ------------------------- | ------------------ |
| `G` then `S` or `Cmd` `,` | Go to Settings |
| `G` then `A` | Go to All |
| `G` then `T` | Go to Today |
| `G` then `R` | Go to Tomorrow |
| `G` then `N` | Go to Next 7 days |
| `G` then `M` | Go to Assign to me |
| `G` then `I` | Go to Inbox |
| `G` then `C` | Go to Completed |
| `G` then `W` | Go to Won't do |
| `G` then `B` | Go to Summary |
| `G` then `G` | Go to Trash |
{.shortcuts}
### Task
| Shortcut | Action |
| ---------------- | -------------- |
| `Cmd` `N` | Add task |
| `Return` | Add task below |
| `Shift` `Return` | Add subtask |
{.shortcuts}
### Quick Add
| Shortcut | Action |
| -------- | -------------------------- |
| `*` | Set due date for the task |
| `!` | Set priority for the task. |
| `#` | Set tag for the task. |
| `~/^` | Add/move task to list. |
| `@` | Assigned task to a member |
{.shortcuts}
### Edit Tasks
| Shortcut | Action |
| ----------------- | ------------------- |
| `Cmd` `Shift` `M` | Complete tasks |
| `Cmd` `Delete` | Delete tasks |
| `Cmd` `D` | Set date |
| `Cmd` `0` | Clear date |
| `Cmd` `1` | Set today |
| `Cmd` `2` | Set tomorrow |
| `Cmd` `3` | Set next week |
| `Ctrl` `0` | Set no priority |
| `Ctrl` `1` | Set low priority |
| `Ctrl` `2` | Set medium priority |
| `Ctrl` `3` | Set high priority |
{.shortcuts}
### Switch Views
| Shortcut | Action |
| ------------ | ------------- |
| `V` then `L` | List View |
| `V` then `K` | Kanban View |
| `G` then `T` | Timeline View |
| `D` / `1` | Day View |
| `W` / `2` | Week View |
| `M` / `3` | Month View |
| `T` | Back to Today |
{.shortcuts}
### Sticky Note
| Shortcut | Action |
| ----------------- | ------------------- |
| `F12` | Pin |
| `Cmd` `Shift` `C` | Color |
| `Cmd` `E` | Expand/Collapse All |
| `Cmd` `Opt` `↑` | Arrange by Top |
| `Cmd` `Opt` `←` | Arrange by Left |
| `Cmd` `Opt` `→` | Arrange by Right |
{.shortcuts}
## Keyboard Shortcuts (Windows) {.cols-2}
### General I
+7 -9
View File
@@ -1,7 +1,7 @@
---
title: Tmux
date: 2021-02-20 14:31:24
background: bg-emerald-600
background: bg-indigo-600
tags:
- utility
- terminal
@@ -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}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+98 -99
View File
@@ -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)_
+1 -1
View File
@@ -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 |
+325
View File
@@ -0,0 +1,325 @@
---
title: Vue
date: 2025-06-13 14:45:00
background: bg-[#43CF96]
tags:
- vue
- web
categories:
- Programming
intro: |
A Vue 3 cheat sheet with the most important concepts, reactivity, component system, routing, and more. Updated for the latest version and perfect for both beginners and advanced users.
plugins:
- copyCode
- runCode
---
## 📘 Vue.js 3 Cheatsheet – Beginner to Advanced
> The ultimate reference for mastering Vue 3.
## ⚙️ 1. Setup
### CDN (Quick Start)
```html
<script src="https://unpkg.com/vue@3"></script>
<div id="app">{{ message }}</div>
<script>
Vue.createApp({
data() {
return { message: "Hello Vue!" };
}
}).mount("#app");
</script>
```
### Vite + Vue
```bash
npm create vite@latest my-vue-app --template vue
cd my-vue-app
npm install
npm run dev
```
## 🧠 2. App Structure
```
src/
├─ components/
├─ views/
├─ App.vue
├─ main.js
```
## 📦 3. Data, Methods, Template
```js
data() {
return {
count: 0,
message: "Welcome!"
};
},
methods: {
increment() {
this.count++;
}
}
```
```html
<h1>{{ message }}</h1>
<button @click="increment">+</button>
```
## 🧰 4. Directives
| Directive | Purpose |
| --------------- | ----------------------- |
| `v-bind` / `:` | Bind attributes |
| `v-model` | Two-way binding |
| `v-if / v-else` | Conditional rendering |
| `v-show` | Toggle visibility |
| `v-for` | List rendering |
| `v-on` / `@` | Event handling |
| `v-slot` | Named/Scoped slot usage |
### Example
```html
<input v-model="name" />
<p v-if="name">Hi, {{ name }}!</p>
<ul>
<li v-for="item in list" :key="item.id">{{ item }}</li>
</ul>
```
## 🪝 5. Lifecycle Hooks
```js
created() {},
mounted() {},
updated() {},
unmounted() {}
```
## 🎯 6. Events
```html
<button @click="sayHi">Click</button>
<input @keyup.enter="submit" />
```
## 🔁 7. Computed & Watch
```js
computed: {
reversed() {
return this.message.split('').reverse().join('');
}
},
watch: {
count(newVal, oldVal) {
console.log(`Count changed from ${oldVal} to ${newVal}`);
}
}
```
## 🧱 8. Components
### Register + Use
```js
app.component("Greeting", {
props: ["name"],
template: `<h1>Hello, {{ name }}!</h1>`
});
```
```html
<Greeting name="Sumangal" />
```
## 🔗 9. Props & Emits
### Props
```js
props: {
title: String,
age: {
type: Number,
default: 18
}
}
```
### Emit
```js
this.$emit("custom-event", payload);
```
## 🔄 10. v-model with Components
```js
props: ['modelValue'],
emits: ['update:modelValue']
```
```html
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
```
## ⚒ 11. Composition API
```js
import { ref, computed } from "vue";
export default {
setup() {
const count = ref(0);
const double = computed(() => count.value * 2);
const increment = () => count.value++;
return { count, double, increment };
}
};
```
## 🌐 12. Vue Router
```bash
npm install vue-router
```
### router.js
```js
import { createRouter, createWebHistory } from "vue-router";
import Home from "./views/Home.vue";
import About from "./views/About.vue";
const routes = [
{ path: "/", component: Home },
{ path: "/about", component: About }
];
export default createRouter({
history: createWebHistory(),
routes
});
```
### main.js
```js
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
const app = createApp(App);
app.use(router).mount("#app");
```
## 📦 13. Pinia (Vuex Alternative)
```bash
npm install pinia
```
### store/counter.js
```js
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => ({ count: 0 }),
actions: {
increment() {
this.count++;
}
}
});
```
```js
const counter = useCounterStore();
counter.increment();
```
## 🎨 14. Slots
```html
<!-- Default -->
<slot></slot>
<!-- Named -->
<slot name="header"></slot>
<!-- Scoped -->
<slot :user="user"></slot>
```
## 🧪 15. Testing
### Vitest + Vue Test Utils
```bash
npm install vitest @vue/test-utils
```
```js
import { mount } from "@vue/test-utils";
import MyComponent from "@/components/MyComponent.vue";
test("renders", () => {
const wrapper = mount(MyComponent);
expect(wrapper.text()).toContain("Hello");
});
```
## 🧼 16. Best Practices
* Use `ref()` for primitives, `reactive()` for objects
* Use `<script setup>` syntax in SFCs
* Break UI into small, reusable components
* Always define `key` in `v-for`
* Use slots for flexible composition
## 🛠 17. Dev Tools
* 🧩 [Vue DevTools](https://devtools.vuejs.org/)
* 🧠 [Volar](https://github.com/vuejs/language-tools) for VSCode
* ⚡ [Vite](https://vitejs.dev) for fast dev environment
## 📚 18. Official Resources
* 📘 [Vue Docs](https://vuejs.org)
* 🧭 [Router Docs](https://router.vuejs.org)
* 📦 [Pinia Docs](https://pinia.vuejs.org)
* 🧪 [Composition API FAQ](https://vuejs.org/guide/extras/composition-api-faq.html)
+1 -1
View File
@@ -1,7 +1,7 @@
---
title: WebStorm
date: 2020-12-17 21:51:44
background: bg-gradient-to-r from-emerald-300 to-blue-400 hover:from-emerald-400 hover:to-blue-500
background: bg-gradient-to-r from-indigo-300 to-blue-400 hover:from-indigo-400 hover:to-blue-500
tags:
- jetbrains
- web
+200
View File
@@ -0,0 +1,200 @@
---
title: Windows Cmd
date: 2025-06-30 18:28:43
background: bg-red-500
tags:
- command
categories:
- Programming
intro: |
This windows command Cheat Sheet is a non exhaustive list of main windows command that you can use.
plugins:
- copyCode
---
## Getting Started
### Basic {.col-span-3}
| CMD | Description |
|:-----------|:------------------------------------------------------------|
| `cls` | Clears the content of the screen. |
| `echo` | Displays messages or enables/disables command echoing. |
| `help` | Provides help information for Windows commands. |
| `exit` | Exits the CMD.EXE program (command interpreter). |
| `date` | Displays or sets the date. |
| `time` | Displays or sets the system time. |
| `ver` | Displays the Windows version. |
| `dir` | Displays a list of files and subdir in a directory. |
| `cd` | Displays the name of or changes the current directory. |
| `copy` | Copies one or more files to another location. |
| `move` | Moves files and renames files and directories. |
| `del` | Deletes one or more files. |
| `mkdir` | Creates a directory. |
| `rmdir` | Removes a directory. |
| `type` | Displays the contents of a text file. |
| `ren` | Renames a file or files. |
| `start` | Starts a separate window to run a specified program or cmd. |
| `shutdown` | Allows you to shut down or restart the computer. |
| `tasklist` | Displays all currently running tasks including services. |
| `taskkill` | Ends one or more tasks or processes. |
## Manage file :
### File {.col-span-3}
| CMD | Description |
|:-----------|:------------------------------------------------------------------|
| `attrib` | Displays or changes file attributes. |
| `fc` | Compares two files and displays the differences between them. |
| `find` | Searches for a text string in a file or files. |
| `findstr` | Searches for strings in files. |
| `xcopy` | Copies files and directory trees. |
| `robocopy` | Robust File Copy for Windows, a more advanced version of `xcopy`. |
| `compact` | Displays or alters the compression of files on NTFS partitions. |
| `expand` | Expands one or more compressed files. |
| `replace` | Replaces files. |
| `tree` | Graphically displays the folder structure of a drive or path. |
| `sort` | Sorts input. |
| `more` | Displays output one screen at a time. |
| `print` | Prints a text file. |
| `cipher` | Displays or alters the encryption of dir [files] on NTFS parts. |
| `diskcomp` | Compares the contents of two floppy disks. |
| `diskcopy` | Copies the contents of one floppy disk to another. |
| `format` | Formats a disk for use with Windows. |
| `chkdsk` | Checks a disk and displays a status report. |
| `label` | Creates, changes, or deletes the volume label of a disk. |
| `recover` | Recovers readable information from a bad or defective disk. |
## System & Network
### System {.col-span-3}
| CMD | Description |
|:--------------|:------------------------------------------------------------------------------------------|
| `systeminfo` | Displays detailed configuration information about a computer and its operating system. |
| `driverquery` | Displays current device driver status and properties. |
| `msinfo32` | Starts the System Information tool. |
| `reg` | Registry Console Tool, used to manage the Windows Registry. |
| `sc` | Displays or configures services (background processes). |
| `taskmgr` | Starts the Task Manager. |
| `wmic` | Windows Management Instrumentation , used for managing Windows systems. |
| `sfc` | System File Checker, scans and verifies the versions of all protected system files. |
| `gpupdate` | Refreshes local and Active Directory-based Group Policy settings. |
| `gpresult` | Displays Group Policy settings and Resultant Set of Policy (RSoP) for a user or computer. |
| `powercfg` | Configures power settings. |
| `dxdiag` | Starts the DirectX Diagnostic Tool. |
| `msinfo32` | Starts the Microsoft System Information tool. |
| `perfmon` | Starts the Performance Monitor. |
| `rsop` | Resultant Set of Policy, used to view Group Policy settings. |
| `sigverif` | Starts the File Signature Verification tool. |
| `sysedit` | Starts the System Configuration Editor. |
| `syskey` | Secures the Windows XP account database. |
| `chgport` | Displays or changes Com port mappings. |
| `chgusr` | Changes the installed user mode. |
### Network {.col-span-3}
| CMD | Description |
|:-----------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------|
| `ipconfig` | Displays all current TCP/IP network configuration values. |
| `ping` | Tests network connectivity to a specified host. |
| `tracert` | Traces the route taken by packets to a specified destination. |
| `netstat` | Displays active TCP connections, ports on which the computer is listening. |
| `nslookup` | Displays information that you can use to diagnose Domain Name System (DNS) infrastructure. |
| `net` | Manages network resources, services, and user accounts. |
| `netsh` | Network Shell, used to configure and monitor network devices. |
| `arp` | Displays and modifies the IP-to-Physical address translation tables used by the Address Resolution Protocol (ARP). |
| `route` | Displays and modifies the entries in the local IP routing table. |
| `ftp` | Starts the File Transfer Protocol (FTP) client. |
| `telnet` | Starts the Telnet client. |
| `nbtstat` | Displays protocol statistics and current TCP/IP connections using NBT (NetBIOS over TCP/IP). |
| `netuse` | Displays information about network connections. |
| `net session` | Manages server computer connections. |
| `net start` | Starts a network service. |
| `net stop` | Stops a network service. |
| `net view` | Displays a list of resources being shared on a specified computer. |
| `net user` | Manages user accounts. |
| `net localgroup` | Manages local groups. |
| `net share` | Manages shared resources. |
| `net statistics` | Displays network statistics. |
## Miscellaneouss
### Process Management {.col-span-1}
| CMD | Description |
|:---------------|:-------------------------------------------------------------|
| `wmic process` | Manages processes using Windows Management Instrumentation . |
| `timeout` | Waits for specified number of seconds / until a key pressed. |
### Disk Management {.col-span-1}
| CMD Command | Description |
|:-------------|:------------------------------------|
| `diskpart` | Manages disk partitions. |
| `defrag` | Defragments a disk. |
| `convert` | Converts a FAT volume to NTFS. |
| `diskperf` | Manages disk performance counters. |
### System Configuration {.col-span-1}
| CMD Command | Description |
|:-------------|:--------------------------------------------------------|
| `bcdedit` | Manages the Boot Configuration Data (BCD) store. |
| `bootcfg` | Configures, queries, or changes Boot.ini file settings. |
| `msconfig` | Starts the System Configuration utility. |
| `regedit` | Starts the Registry Editor. |
## Tips & Tricks
### Miscellaneouss Tips & Tricks {.col-span-3}
| Tip or Trick | Description |
|:----------------------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------|
| `wmic path SoftwareLicensingService get OA3xOriginalProductKey` | Get your Windows Product key |
| `cmd /k` | Opens the command prompt and executes a specified command, keeping the window open. |
| `cmd /c` | Opens the command prompt, executes a specified command, and then closes the window. |
| `&&` | Allows you to run multiple commands in sequence. For example, `command1 && command2`. |
| `\|\|` | Allows you to run a second command only if the first command fails. For example, `command1 `\|\|` command2`. |
| `>` | Redirects the output of a command to a file, overwriting the file if it already exists. For example, `command > output.txt`. |
| `>>` | Redirects the output of a command to a file, appending the output if the file already exists. For example, `command >> output.txt`. |
| `\|` | Pipes the output of one command to another command. For example, `command1 `\|` command2`. |
| `clip` | Redirects the output of a command to the Windows clipboard. For example, `dir `\|` clip`. |
| `for %i in (*.txt) do echo %i` | Loops through all `.txt` files in the current directory and echoes their names. |
| `pushd` and `popd` | `pushd` saves the current directory and then changes to a new directory. `popd` returns to the saved directory. |
| `set` | Displays, sets, or removes environment variables. For example, `set PATH=C:\newpath`. |
| `start "" "C:\Path\To\Program\program.exe"` | Starts a program without waiting for it to finish. |
| `taskkill /IM "process.exe" /F` | Forcefully kills a process by its image name. |
| `wmic product get name` | Lists all installed software on the system. |
| `wmic logicaldisk get size,freespace,caption` | Displays the size, free space, and caption of all logical disks. |
| `systeminfo` `\|` `findstr /B /C:"OS Name" /C:"OS Version"` | Displays the OS name and version. |
| `schtasks /query /fo LIST /v` | Lists all scheduled tasks in detail. |
| `netsh wlan show profiles` | Displays a list of all saved Wi-Fi profiles. |
| `netsh wlan show profiles name="ProfileName" key=clear` | Displays the password for a specific Wi-Fi profile. |
| `assoc` | Displays or modifies file extension associations. |
| `ftype` | Displays or modifies file types used in file extension associations. |
| `driverquery /v` | Lists all installed drivers with detailed information. |
| `powercfg /energy` | Generates a detailed energy report for the system. |
| `powercfg /batteryreport` | Generates a battery life report for laptops. |
| `robocopy C:\Source D:\Destination /MIR` | Mirrors a directory from one location to another, including subdirectories and files. |
| `mklink /D "C:\Path\To\Link" "C:\Path\To\Target"` | Creates a symbolic link to a directory. |
| `mklink /H "C:\Path\To\Link" "C:\Path\To\Target"` | Creates a hard link to a file. |
| `mklink /J "C:\Path\To\Link" "C:\Path\To\Target"` | Creates a directory junction. |
| `diskpart /s script.txt` | Runs a DiskPart script to automate disk partitioning tasks. |
| `shutdown /a` | Aborts a system shutdown. |
| `chkdsk /f /r` | Checks a disk and fixes errors, also recovers readable information from bad sectors. |
| `sfc /scannow` | Scans and repairs protected system files. |
| `DISM /Online /Cleanup-Image /RestoreHealth` | Repairs the Windows image using DISM. |
| `bcdboot C:\Windows` | Repairs the boot environment by copying boot files from the Windows directory. |
| `bootrec /fixmbr` | Repairs the Master Boot Record (MBR). |
| `bootrec /fixboot` | Writes a new boot sector to the system partition. |
| `bootrec /scanos` | Scans for installations compatible with Windows and displays the entries that are currently not in the Boot Configuration Data store. |
| `bootrec /rebuildbcd` | Scans for installations compatible with Windows and allows you to select the installations you want to add to the Boot Configuration Data store. |
## Other
- Also see : [Windows Official Documentation](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands)
+1 -1
View File
@@ -20,7 +20,7 @@ plugins:
- [Xpath test bed](http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm) _(whitebeam.org)_
Test in Firefox or Chrome console:
Test in Firefox or Chromium based browser console:
```console
$x('/html/body')
+2 -2
View File
@@ -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
View File
@@ -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)
+4 -5
View File
@@ -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.
+3
View File
@@ -0,0 +1,3 @@
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" fill="currentColor" height="1em" width="1em">
<path d="M 452.759 56.3 L 56.3 743.002 L 56.3 940.358 C 56.3 955.358 68.452 967.548 83.262 967.7 L 464.152 967.7 L 272.758 636.444 L 607.697 56.3 L 452.759 56.3 Z M 648.71 56.3 L 464.152 375.974 L 605.418 620.495 L 967.7 620.495 L 967.7 83.566 C 967.7 68.49 955.548 56.3 940.358 56.3 L 648.71 56.3 Z M 443.645 411.48 L 365.417 547.241 C 356.682 562.393 356.682 581.001 365.417 596.153 C 374.151 611.343 390.1 620.457 407.569 620.457 L 564.405 620.457 L 443.645 411.48 Z M 325.163 656.039 L 505.164 967.7 L 940.738 967.7 C 955.548 967.548 967.7 955.396 967.7 940.434 L 967.7 656.001 L 325.163 656.039 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 738 B

+4
View File
@@ -0,0 +1,4 @@
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
fill="currentColor" height="1em" width="1em">
<path d="M 445.44 0 L 424.96 35.456 L 675.84 470.016 L 947.2 0 L 445.44 0 Z M 993.28 0 L 627.328 633.856 L 1024 633.856 L 1024 30.336 C 1023.79 13.52 1010.1 -0.001 993.28 0 Z M 401.92 75.392 L 245.76 345.856 L 558.08 345.856 L 401.92 75.392 Z M 468.608 385.024 L 467.84 385.024 C 452.48 385.237 437.973 394.24 430.336 407.339 L 384.128 487.552 L 383.787 488.149 C 376.284 501.686 376.284 518.133 383.787 531.669 C 399.33 558.607 414.875 585.544 430.421 612.48 C 438.272 625.707 453.035 633.813 468.181 633.856 C 468.267 633.856 527.061 633.941 556.373 633.813 C 571.733 633.6 586.197 625.067 593.835 611.968 C 609.365 585.045 625.024 558.165 640.469 531.157 C 647.979 517.76 647.723 501.163 640.171 488.021 L 639.744 487.381 L 593.749 407.595 L 593.493 407.211 C 585.655 393.842 571.48 385.456 555.989 385.024 L 555.477 385.024 L 468.608 385.024 Z M 222.72 385.707 L 0 771.499 L 0 788.139 L 0.128 995.968 C 1.44 1010.94 13.39 1022.76 28.373 1023.91 L 396.8 385.707 L 222.72 385.707 Z M 348.16 549.76 L 74.069 1024 L 621.909 1024 L 348.16 549.76 Z M 465.792 673.749 L 668.032 1024 L 993.28 1024 C 1010.25 1024 1024 1010.25 1024 993.28 L 1024 673.792 L 465.792 673.749 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
fill="currentColor" height="1em" width="1em">
<path d="M 255.915 68.565 L 0 512 L 255.915 955.434 L 768.085 955.434 L 1024 512 L 768.085 68.565 L 255.915 68.565 Z M 425.173 303.786 L 540.16 422.4 L 608.341 490.453 L 608.427 490.368 L 711.253 591.189 C 702.72 597.162 694.784 601.941 687.232 605.866 C 680.41 609.458 673.337 612.552 666.069 615.125 C 660.163 617.193 654.099 618.777 647.936 619.861 C 642.347 620.842 637.269 621.312 632.661 621.312 C 627.115 621.312 622.336 620.714 618.24 619.861 C 614.737 619.165 611.308 618.136 608 616.789 C 604.971 615.533 602.106 613.914 599.467 611.968 L 554.155 565.376 L 424.491 435.626 L 377.557 480.554 L 246.571 611.626 C 243.922 613.535 241.058 615.124 238.037 616.362 C 234.776 617.727 231.389 618.77 227.925 619.477 C 223.179 620.438 218.347 620.91 213.504 620.885 C 208.896 620.885 203.819 620.501 198.229 619.562 C 192.063 618.437 185.998 616.81 180.096 614.698 C 172.828 612.126 165.755 609.032 158.933 605.44 C 150.626 601.072 142.603 596.184 134.912 590.805 L 425.173 303.786 Z M 626.56 337.28 L 821.931 533.461 L 880.896 591.189 C 873.191 596.583 865.154 601.485 856.832 605.866 C 850.039 609.457 842.995 612.552 835.755 615.125 C 829.835 617.196 823.756 618.78 817.579 619.861 C 812.032 620.842 806.869 621.312 802.219 621.312 C 796.715 621.312 791.936 620.714 787.84 619.861 C 782.065 618.681 776.518 616.578 771.413 613.632 C 770.584 613.171 769.823 612.596 769.152 611.925 L 716.587 559.957 L 626.517 469.888 L 612.267 484.138 L 545.707 418.133 L 626.603 337.194 L 626.56 337.28 Z M 372.011 513.066 L 372.011 620.97 C 366.915 620.9 361.834 620.4 356.821 619.477 C 350.698 618.306 344.678 616.651 338.816 614.528 C 331.666 611.987 324.707 608.936 317.995 605.397 C 309.807 601.059 301.898 596.214 294.315 590.89 L 371.968 513.024 L 372.011 513.066 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

Loaded 100 of 212 files, more files were not shown because too many files have changed in this diff. Show more