From b24f77d9d889d5e3c29f16f48e6a1d7253228634 Mon Sep 17 00:00:00 2001 From: Joem Bolinas Date: Thu, 24 Apr 2025 05:01:20 +0000 Subject: [PATCH 01/70] add Notion shortcuts guide --- package.json | 10 +- source/_posts/notion.md | 197 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+), 5 deletions(-) create mode 100644 source/_posts/notion.md diff --git a/package.json b/package.json index 3f00e09..db06ba8 100644 --- a/package.json +++ b/package.json @@ -19,15 +19,15 @@ }, "dependencies": { "eslint": "^8.27.0", - "gulp": "^4.0.2", - "gulp-cli": "^2.3.0", + "gulp": "^5.0.0", + "gulp-cli": "^3.0.0", "gulp-ext-replace": "^0.3.0", "gulp-htmlclean": "^2.7.22", "gulp-htmlmin": "^5.0.1", "gulp-minify-css": "^1.2.4", "gulp-postcss": "^9.0.1", "gulp-uglify-es": "^3.0.0", - "gulp-version-number": "^0.2.4", + "gulp-version-number": "^0.1.6", "hexo": "^5.4.0", "hexo-browsersync": "^0.3.0", "hexo-cli": "^4.3.0", @@ -39,7 +39,7 @@ "hexo-pagination": "^2.0.0", "hexo-related-popular-posts": "^5.0.1", "hexo-renderer-ejs": "^2.0.0", - "hexo-renderer-markdown-it": "^5.0.0", + "hexo-renderer-markdown-it": "^7.1.1", "hexo-renderer-stylus": "^2.0.1", "hexo-server": "^2.0.0", "markdown-it-abbr": "^1.0.4", @@ -60,7 +60,7 @@ "devDependencies": { "autoprefixer": "^10.4.0", "gulp-clean-css": "^4.3.0", - "gulp-filesize": "^0.0.6", + "gulp-filesize": "^0.0.1", "gulp-javascript-obfuscator": "^1.1.6", "gulp-replace": "^1.1.3", "gulp-rev": "^9.0.0", diff --git a/source/_posts/notion.md b/source/_posts/notion.md new file mode 100644 index 0000000..0cbe628 --- /dev/null +++ b/source/_posts/notion.md @@ -0,0 +1,197 @@ +--- +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)_ From 8675a6999fcef9ec3740526e88a2655ee11416b3 Mon Sep 17 00:00:00 2001 From: J Govind Yeswanth Date: Thu, 24 Apr 2025 10:41:49 +0530 Subject: [PATCH 02/70] Update javascript.md Updated comment for the callback function. --- source/_posts/javascript.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/_posts/javascript.md b/source/_posts/javascript.md index 758d3b2..7b88f50 100644 --- a/source/_posts/javascript.md +++ b/source/_posts/javascript.md @@ -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() From 2614b293aa9108f7e34c575d3a501c97ea28b8b8 Mon Sep 17 00:00:00 2001 From: Dreykp Date: Thu, 24 Apr 2025 23:13:51 +0300 Subject: [PATCH 03/70] Updated logos --- source/assets/icon/affinity-designer.svg | 3 +++ source/assets/icon/affinity-photo.svg | 4 +++ source/assets/icon/alpine-linux.svg | 4 +++ source/assets/icon/audacity.svg | 4 +++ source/assets/icon/brave.svg | 4 +++ source/assets/icon/curl.svg | 4 +++ source/assets/icon/framer-x.svg | 4 +++ source/assets/icon/gimp.svg | 4 +++ source/assets/icon/gnupg.svg | 4 +++ source/assets/icon/google-chrome.svg | 8 ++++++ source/assets/icon/homebrew.svg | 31 +++--------------------- source/assets/icon/ini.svg | 9 +++++++ source/assets/icon/missive.svg | 8 ++++++ source/assets/icon/monday.svg | 8 ++++++ source/assets/icon/obsidian.svg | 4 +++ source/assets/icon/openssl.svg | 4 +++ source/assets/icon/powershell.svg | 10 ++++++++ source/assets/icon/proto-io.svg | 4 +++ source/assets/icon/quip.svg | 4 +++ source/assets/icon/sketchup.svg | 10 +++----- source/assets/icon/ticktick.svg | 4 +++ source/assets/icon/unity-3d.svg | 4 +++ source/assets/icon/unity.svg | 3 --- source/assets/icon/unreal-engine.svg | 4 +++ source/assets/icon/vivaldi.svg | 4 +++ source/assets/icon/webflow.svg | 4 +++ 26 files changed, 121 insertions(+), 37 deletions(-) create mode 100644 source/assets/icon/affinity-designer.svg create mode 100644 source/assets/icon/affinity-photo.svg create mode 100644 source/assets/icon/alpine-linux.svg create mode 100644 source/assets/icon/audacity.svg create mode 100644 source/assets/icon/brave.svg create mode 100644 source/assets/icon/curl.svg create mode 100644 source/assets/icon/framer-x.svg create mode 100644 source/assets/icon/gimp.svg create mode 100644 source/assets/icon/gnupg.svg create mode 100644 source/assets/icon/google-chrome.svg create mode 100644 source/assets/icon/ini.svg create mode 100644 source/assets/icon/missive.svg create mode 100644 source/assets/icon/monday.svg create mode 100644 source/assets/icon/obsidian.svg create mode 100644 source/assets/icon/openssl.svg create mode 100644 source/assets/icon/powershell.svg create mode 100644 source/assets/icon/proto-io.svg create mode 100644 source/assets/icon/quip.svg create mode 100644 source/assets/icon/ticktick.svg create mode 100644 source/assets/icon/unity-3d.svg delete mode 100644 source/assets/icon/unity.svg create mode 100644 source/assets/icon/unreal-engine.svg create mode 100644 source/assets/icon/vivaldi.svg create mode 100644 source/assets/icon/webflow.svg diff --git a/source/assets/icon/affinity-designer.svg b/source/assets/icon/affinity-designer.svg new file mode 100644 index 0000000..77a5fd4 --- /dev/null +++ b/source/assets/icon/affinity-designer.svg @@ -0,0 +1,3 @@ + + + diff --git a/source/assets/icon/affinity-photo.svg b/source/assets/icon/affinity-photo.svg new file mode 100644 index 0000000..2ef53ec --- /dev/null +++ b/source/assets/icon/affinity-photo.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/alpine-linux.svg b/source/assets/icon/alpine-linux.svg new file mode 100644 index 0000000..1a1d2ae --- /dev/null +++ b/source/assets/icon/alpine-linux.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/audacity.svg b/source/assets/icon/audacity.svg new file mode 100644 index 0000000..446d0d7 --- /dev/null +++ b/source/assets/icon/audacity.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/brave.svg b/source/assets/icon/brave.svg new file mode 100644 index 0000000..92dc9fd --- /dev/null +++ b/source/assets/icon/brave.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/curl.svg b/source/assets/icon/curl.svg new file mode 100644 index 0000000..b96f1ea --- /dev/null +++ b/source/assets/icon/curl.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/framer-x.svg b/source/assets/icon/framer-x.svg new file mode 100644 index 0000000..a1466e5 --- /dev/null +++ b/source/assets/icon/framer-x.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/gimp.svg b/source/assets/icon/gimp.svg new file mode 100644 index 0000000..f31f8b3 --- /dev/null +++ b/source/assets/icon/gimp.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/gnupg.svg b/source/assets/icon/gnupg.svg new file mode 100644 index 0000000..cea8c83 --- /dev/null +++ b/source/assets/icon/gnupg.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/google-chrome.svg b/source/assets/icon/google-chrome.svg new file mode 100644 index 0000000..b25f7aa --- /dev/null +++ b/source/assets/icon/google-chrome.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/source/assets/icon/homebrew.svg b/source/assets/icon/homebrew.svg index 3e93075..e7681a9 100644 --- a/source/assets/icon/homebrew.svg +++ b/source/assets/icon/homebrew.svg @@ -1,27 +1,4 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + diff --git a/source/assets/icon/ini.svg b/source/assets/icon/ini.svg new file mode 100644 index 0000000..692956e --- /dev/null +++ b/source/assets/icon/ini.svg @@ -0,0 +1,9 @@ + + + + + + + + diff --git a/source/assets/icon/missive.svg b/source/assets/icon/missive.svg new file mode 100644 index 0000000..5b3a496 --- /dev/null +++ b/source/assets/icon/missive.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/source/assets/icon/monday.svg b/source/assets/icon/monday.svg new file mode 100644 index 0000000..4cb7d08 --- /dev/null +++ b/source/assets/icon/monday.svg @@ -0,0 +1,8 @@ + + + + + + + diff --git a/source/assets/icon/obsidian.svg b/source/assets/icon/obsidian.svg new file mode 100644 index 0000000..80b0e90 --- /dev/null +++ b/source/assets/icon/obsidian.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/openssl.svg b/source/assets/icon/openssl.svg new file mode 100644 index 0000000..542adc6 --- /dev/null +++ b/source/assets/icon/openssl.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/powershell.svg b/source/assets/icon/powershell.svg new file mode 100644 index 0000000..ddcbfa4 --- /dev/null +++ b/source/assets/icon/powershell.svg @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/source/assets/icon/proto-io.svg b/source/assets/icon/proto-io.svg new file mode 100644 index 0000000..3e158af --- /dev/null +++ b/source/assets/icon/proto-io.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/quip.svg b/source/assets/icon/quip.svg new file mode 100644 index 0000000..72aea16 --- /dev/null +++ b/source/assets/icon/quip.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/sketchup.svg b/source/assets/icon/sketchup.svg index a1458b3..d5a3757 100644 --- a/source/assets/icon/sketchup.svg +++ b/source/assets/icon/sketchup.svg @@ -1,8 +1,4 @@ - - - - + + diff --git a/source/assets/icon/ticktick.svg b/source/assets/icon/ticktick.svg new file mode 100644 index 0000000..432b7a4 --- /dev/null +++ b/source/assets/icon/ticktick.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/unity-3d.svg b/source/assets/icon/unity-3d.svg new file mode 100644 index 0000000..1f44482 --- /dev/null +++ b/source/assets/icon/unity-3d.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/unity.svg b/source/assets/icon/unity.svg deleted file mode 100644 index 1affcbd..0000000 --- a/source/assets/icon/unity.svg +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/source/assets/icon/unreal-engine.svg b/source/assets/icon/unreal-engine.svg new file mode 100644 index 0000000..b040c2f --- /dev/null +++ b/source/assets/icon/unreal-engine.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/vivaldi.svg b/source/assets/icon/vivaldi.svg new file mode 100644 index 0000000..45e535d --- /dev/null +++ b/source/assets/icon/vivaldi.svg @@ -0,0 +1,4 @@ + + + diff --git a/source/assets/icon/webflow.svg b/source/assets/icon/webflow.svg new file mode 100644 index 0000000..b6154db --- /dev/null +++ b/source/assets/icon/webflow.svg @@ -0,0 +1,4 @@ + + + From 75fe221ad169607a48a45bd5b5d6dcf96881d115 Mon Sep 17 00:00:00 2001 From: Fechin Date: Fri, 25 Apr 2025 08:50:22 +0800 Subject: [PATCH 04/70] chore(dependencies): update package versions --- package.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index db06ba8..a46a68c 100644 --- a/package.json +++ b/package.json @@ -19,15 +19,15 @@ }, "dependencies": { "eslint": "^8.27.0", - "gulp": "^5.0.0", - "gulp-cli": "^3.0.0", + "gulp": "^4.0.2", + "gulp-cli": "^2.3.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-uglify-es": "^3.0.0", - "gulp-version-number": "^0.1.6", + "gulp-version-number": "^0.2.4", "hexo": "^5.4.0", "hexo-browsersync": "^0.3.0", "hexo-cli": "^4.3.0", @@ -39,7 +39,7 @@ "hexo-pagination": "^2.0.0", "hexo-related-popular-posts": "^5.0.1", "hexo-renderer-ejs": "^2.0.0", - "hexo-renderer-markdown-it": "^7.1.1", + "hexo-renderer-markdown-it": "^5.0.0", "hexo-renderer-stylus": "^2.0.1", "hexo-server": "^2.0.0", "markdown-it-abbr": "^1.0.4", @@ -60,7 +60,7 @@ "devDependencies": { "autoprefixer": "^10.4.0", "gulp-clean-css": "^4.3.0", - "gulp-filesize": "^0.0.1", + "gulp-filesize": "^0.0.6", "gulp-javascript-obfuscator": "^1.1.6", "gulp-replace": "^1.1.3", "gulp-rev": "^9.0.0", @@ -77,4 +77,4 @@ "tailwindcss-animate": "^1.0.5", "tailwindcss-cli": "^0.1.2" } -} +} \ No newline at end of file From e59a26971d8b827657d21b28fe51e04cad441f2e Mon Sep 17 00:00:00 2001 From: andersonpablo Date: Wed, 30 Apr 2025 14:16:54 -0300 Subject: [PATCH 05/70] Update python.md --- source/_posts/python.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/source/_posts/python.md b/source/_posts/python.md index 6f04a7a..faba4bd 100644 --- a/source/_posts/python.md +++ b/source/_posts/python.md @@ -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 From 685c91a6ac5800c897aff2ae313074260a7f4833 Mon Sep 17 00:00:00 2001 From: Manjunath Prabhakar Date: Fri, 9 May 2025 22:23:54 -0400 Subject: [PATCH 06/70] Update xpath.md $X() method also supports in all of chromium based browser. hence changed chrome to chromium based --- source/_posts/xpath.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/source/_posts/xpath.md b/source/_posts/xpath.md index 7f5e74a..1341a3c 100644 --- a/source/_posts/xpath.md +++ b/source/_posts/xpath.md @@ -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') From bc08bb936d95d494b15fb5cea4cdc838409bc329 Mon Sep 17 00:00:00 2001 From: sai krishna Date: Fri, 6 Jun 2025 08:48:00 +0530 Subject: [PATCH 07/70] matplotlib.md by sai krishna --- source/_posts/matplotlib.md | 268 ++++++++++++++++++++++++++++++++++++ 1 file changed, 268 insertions(+) create mode 100644 source/_posts/matplotlib.md diff --git a/source/_posts/matplotlib.md b/source/_posts/matplotlib.md new file mode 100644 index 0000000..3b6f05d --- /dev/null +++ b/source/_posts/matplotlib.md @@ -0,0 +1,268 @@ +--- +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 | + +--- + From 1e77d2c6fd1a8c85fc54b290e64a834a664a686e Mon Sep 17 00:00:00 2001 From: Ganesh M Date: Sat, 7 Jun 2025 19:22:33 +0530 Subject: [PATCH 08/70] created cheatsheet for flask, fastapi and htmx --- source/_posts/fastapi.md | 251 +++++++++++++++++++++++++++++++++++++ source/_posts/flask.md | 262 +++++++++++++++++++++++++++++++++++++++ source/_posts/htmx.md | 212 +++++++++++++++++++++++++++++++ 3 files changed, 725 insertions(+) create mode 100644 source/_posts/fastapi.md create mode 100644 source/_posts/flask.md create mode 100644 source/_posts/htmx.md diff --git a/source/_posts/fastapi.md b/source/_posts/fastapi.md new file mode 100644 index 0000000..faca64f --- /dev/null +++ b/source/_posts/fastapi.md @@ -0,0 +1,251 @@ +--- +title: FastAPI +date: 2025-06-07 18:40:00 +background: bg-[#059669] +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"} +``` + diff --git a/source/_posts/flask.md b/source/_posts/flask.md new file mode 100644 index 0000000..c63797e --- /dev/null +++ b/source/_posts/flask.md @@ -0,0 +1,262 @@ +--- +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/") +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 +

Hello {{ name }}

+{% if name %}

Hi!

{% endif %} +``` + +### Static Files + +```html + +``` + + + +## 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 +``` diff --git a/source/_posts/htmx.md b/source/_posts/htmx.md new file mode 100644 index 0000000..08b452e --- /dev/null +++ b/source/_posts/htmx.md @@ -0,0 +1,212 @@ +--- +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 + +``` + +### Basic Usage + +```html + +
+``` + +### Server Response + +```html + +

Hello from server

+``` + + + +## Core Attributes {.cols-3} + +### `hx-get`, `hx-post`, etc. + +```html +Load Page +
+``` + +### `hx-target` + +```html + +
+``` + +### `hx-trigger` + +```html + +``` + + + +## Swap & Out of Band {.cols-3} + +### `hx-swap` + +```html +
+
+``` + +* `outerHTML` +* `innerHTML` +* `beforebegin`, `afterbegin`, etc. + +### `hx-swap-oob` + +```html +
+``` + +*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 +
+ + +
+
+``` + +### `hx-include` + +```html + + +``` + +### `hx-vals` + +```html + +``` + + + +## Advanced Features {.cols-3} + +### Loading Indicator + +```html + +
Loading...
+``` + +### `hx-push-url` + +```html +Go +``` + +### Polling + +```html +
+``` + + + +## 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 + +
+``` + + + +## Example Use Case {.cols-2} + +### Python Backend (Flask) + +```python +@app.route("/hello") +def hello(): + return "

Hello, HTMX!

" +``` + +### HTML Client + +```html + +
+``` + From ee3e163b2835d4ee21e17a48cb02dce14066aea6 Mon Sep 17 00:00:00 2001 From: Paul Gallagher Date: Sun, 8 Jun 2025 23:11:20 +0800 Subject: [PATCH 09/70] Clarify bash while examples and add example per #588 --- source/_posts/bash.md | 49 +++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/source/_posts/bash.md b/source/_posts/bash.md index e200e22..3f53f59 100644 --- a/source/_posts/bash.md +++ b/source/_posts/bash.md @@ -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 From 1870668b069a519a35b49edb7d870d6d13d677fa Mon Sep 17 00:00:00 2001 From: sumangal44 Date: Fri, 13 Jun 2025 08:36:13 +0530 Subject: [PATCH 10/70] =?UTF-8?q?=F0=9F=93=96=20DOC:=20Update=20dependenci?= =?UTF-8?q?es=20in=20package.json=20and=20add=20Vue=203=20cheat=20sheet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 38 ++--- source/_posts/vue.md | 325 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 344 insertions(+), 19 deletions(-) create mode 100644 source/_posts/vue.md diff --git a/package.json b/package.json index a46a68c..f6c2614 100644 --- a/package.json +++ b/package.json @@ -18,63 +18,63 @@ "version": "5.4.2" }, "dependencies": { - "eslint": "^8.27.0", + "eslint": "^8.57.1", "gulp": "^4.0.2", "gulp-cli": "^2.3.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": "^9.1.0", "gulp-uglify-es": "^3.0.0", "gulp-version-number": "^0.2.4", - "hexo": "^5.4.0", + "hexo": "^5.4.2", "hexo-browsersync": "^0.3.0", - "hexo-cli": "^4.3.0", - "hexo-excerpt": "^1.2.1", + "hexo-cli": "^4.3.2", + "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-log": "^3.2.0", "hexo-pagination": "^2.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-renderer-stylus": "^2.1.0", "hexo-server": "^2.0.0", "markdown-it-abbr": "^1.0.4", - "markdown-it-anchor": "^8.4.1", + "markdown-it-anchor": "^8.6.7", "markdown-it-attrs": "^4.3.1", "markdown-it-checkbox": "^1.1.0", - "markdown-it-emoji": "^2.0.0", + "markdown-it-emoji": "^2.0.2", "markdown-it-footnote": "^3.0.3", "markdown-it-highlight-lines": "^1.0.2", - "markdown-it-highlightjs": "^3.5.0", + "markdown-it-highlightjs": "^3.6.0", "markdown-it-ins": "^3.0.1", - "markdown-it-multimd-table": "^4.1.1", + "markdown-it-multimd-table": "^4.2.3", "markdown-it-shortcode-tag": "^1.1.0", "markdown-it-sub": "^1.0.0", "markdown-it-sup": "^1.0.0", "markdown-it-task-lists": "^2.1.1" }, "devDependencies": { - "autoprefixer": "^10.4.0", + "autoprefixer": "^10.4.21", "gulp-clean-css": "^4.3.0", "gulp-filesize": "^0.0.6", "gulp-javascript-obfuscator": "^1.1.6", - "gulp-replace": "^1.1.3", + "gulp-replace": "^1.1.4", "gulp-rev": "^9.0.0", "gulp-terser": "^2.1.0", "npm-run-all": "^4.1.5", - "postcss": "^8.4.4", + "postcss": "^8.5.5", "postcss-cli": "^9.1.0", - "postcss-import": "^14.0.2", - "postcss-minify": "^1.1.0", - "prettier": "^3.2.5", + "postcss-import": "^14.1.0", + "postcss-minify": "^1.2.0", + "prettier": "^3.5.3", "prettier-plugin-tailwindcss": "^0.5.14", "sync-request": "^6.1.0", - "tailwindcss": "^3.0.1", - "tailwindcss-animate": "^1.0.5", + "tailwindcss": "^3.4.17", + "tailwindcss-animate": "^1.0.7", "tailwindcss-cli": "^0.1.2" } } \ No newline at end of file diff --git a/source/_posts/vue.md b/source/_posts/vue.md new file mode 100644 index 0000000..44e3e78 --- /dev/null +++ b/source/_posts/vue.md @@ -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 + +
{{ message }}
+ +``` +### 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 +

{{ message }}

+ +``` + + +## 🧰 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 + +

Hi, {{ name }}!

+
    +
  • {{ item }}
  • +
+``` + + +## 🪝 5. Lifecycle Hooks + +```js +created() {}, +mounted() {}, +updated() {}, +unmounted() {} +``` + + +## 🎯 6. Events + +```html + + +``` + + +## 🔁 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: `

Hello, {{ name }}!

` +}); +``` + +```html + +``` + + +## 🔗 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 + +``` + + +## ⚒ 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 + + + + + + + + +``` + + +## 🧪 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 ` - - -``` - -### 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 + + + + Canvas Example + + + + + + +``` + +### 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) diff --git a/source/_posts/chatgpt.md b/source/_posts/chatgpt.md index 028816e..aa32c2d 100644 --- a/source/_posts/chatgpt.md +++ b/source/_posts/chatgpt.md @@ -15,82 +15,125 @@ plugins: --- ## Overview -### Glossary + +### Terminology + - Prompt: input text that guides an AI model’s response. - Tokens: the smallest units of text processed by an AI model. - Token Limit: the max number of tokens an AI model can process in one request. - Artificial intelligence (AI): machines that imitate human intelligence. - AI Model: a program trained on datasets to recognize patterns and make decisions without human intervention. -- Large language model (LLM): a transformer-based AI model trained on large text datasets to understand and generate human-like language. +- Large language model (LLM): a transformer-based AI model trained on large text datasets to understand and generate + human-like language. - Hallucination: when an AI model generates responses that are false or misleading but presented as fact. - Jailbreak: exploiting AI model vulnerabilities to bypass ethical guidelines and perform restricted actions. -### Prompt Tips -#### Efficiency +### Tips + +Prompt Efficiency + - Focus on achieving the desired output efficiently with minimal words in the prompt. -- Specify general instructions at the start of a conversation or when changing direction to avoid constantly restating them in each new prompt. +- Specify general instructions at the start of a conversation or when changing direction to avoid constantly restating + them in each new prompt. + ```{.wrap} Example: specify the role once at the start of a conversation. ``` + - Restructure text to eliminate filler words that don’t add meaning: + ```{.wrap} Example: “provide a breakdown" -> "provide sales breakdown”. ``` -- Do not explicitly refer to the item being processed unless addressing a specific part of it as what you provide will typically speak for itself: + +- Do not explicitly refer to the item being processed unless addressing a specific part of it as what you provide will + typically speak for itself: + ```{.wrap} Example: “Filter this piece of text" -> "Filter text” ``` + - Do not explicitly ask the AI for help: + ```{.wrap} Example: “can you help me x”. ``` + - Do not explicitly reference yourself unless clarifying multiple entities: + ```{.wrap} Example: "do X for me". Example: ”I want to x”. ``` + - Do not be polite to the AI: + ```{.wrap} Example: "please do X". Example: “thanks”. ``` -#### Clarity -- Consider breaking up complex ideas into granular bullet points to improve clarity, avoid searching for text, and eliminate comma lists and conjunctions (e.g., and). +Prompt Clarity + +- Consider breaking up complex ideas into granular bullet points to improve clarity, avoid searching for text, and + eliminate comma lists and conjunctions (e.g., and). - Avoid vague or close ended questions. + ```{.wrap} Example: “Do you think our site is good" -> "Explain flaws in the designs of each webpage” ``` + - Ensure prompts are specific + ```{.wrap} Example: “explain our sales" -> "explain a breakdown of our sales performance for the last quarter”. ``` -#### Response Refinement +Response Refinement + - If the AI model misunderstands your request then specify the intended action. - Provide sufficient context so the AI model can understand the scenario. -#### Security And Privacy -- Never share sensitive information with AI models as you can't be certain how it's stored, whether it will be shared, of if a data breach may occur. +Privacy And Security + +- Never share sensitive information with AI model's as you can't be certain how it's stored, whether it will be shared, + of if a data breach may occur. ## Prompt Engineering -### Prompt Frameworks -- Only use prompt components relevant to your needs -#### General Purpose -~~~ -[role] [task] [style] [output format] [constraint] -~~~ +### Prompt Frameworks + +Only use prompt components that are relevant for your needs. + +``` +General Purpose +[role] [task] [tone] [format] [restriction] +``` ### Role + Standard + - Act as [occupation] -- [List of roles](https://github.com/f/awesome-chatgpt-prompts) _(github.com)_ + +Common Standard Roles + +- Personal Coach +- Consultant +- Entrepreneur +- Proofreader +- Therapist + +Also See + +- [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) _(github.com)_ Roleplay + - Act as [figure] with [appearance] [personality] [behaviour examples] [lore] in [scenario] ### Task + [verb] [task] [specifics] #### 5W1H Questions @@ -218,40 +261,88 @@ Chat Memory #### Database CRUD Operations Create -- Generate [quantity] dummy entries following [fields] -- Create new entry with [data] + +- [Write content about X|suggest ideas about X|suggest titles about X] +- Write content about X in the style of [style] +- Write better +- Write email to [entity] about X +- [Continue|expand] +- [Explain how to do X|create roadmap for X] +- [Suggest best practices for X|suggest improvements|what am I doing right?|what am I doing wrong?] +- Show list of emojis about X +- [Create|generate|imagine] image about X Read -- Select records where [condition] -- Select the [top | last | random] [quantity] entries + +- [Summarise|write concise main points] +- [Explain|elaborate] +- Explain what [entity|text] meant by X +- Identify themes in X +- Write outline about X +- Extract keywords +- Get up-to-date [facts|news|data] on X +- Is this true? +- Suggest [media] [about|similar to] X +- Pick best from [options] Update -- Update entries where [condition] with [data] -- Replace X with Y + +- For all X do [action] +- For X do [action] if matching [criteria] +- Reformat everything as [format] Delete -- Delete entries where [condition] -- Delete duplicate items -- Delete items with missing or null values -### Style -Using [style] +- Delete [quantity] of X matching [criteria] +- Delete everything except X +- Delete [item] [number] +- Delete duplicate items from X -#### Imitate -- Using style of [person | brand | genre | character] +Compare + +- Identify [simlarities|diffirences] between X and Y +- Identify gaps in X +- Evaluate pros and cons of X +- X [comparison operator] Y. It could be abstractly expressed as "are apples bigger than walnuts?" + +Filter + +- Filter X by [criteria] +- Exclude X by [criteria]. Everything is excluded by default. + +Select + +- Select [quantity] of X based on [criteria|randomly] + +Simplify + +- Explain X like I’m 5 +- Explain in simple terms + +Sort + +- Sort X by [key] in [alphabetical|chronological|ascending|descending|lexicographical|custom] order + +Translate + +- Translate into [language]. For programming languages it's specifically called transpile + +### Tone + +Using [tone] tone + +Formality -#### Formality - Formal - Informal -#### Directness +Directness + - Direct - Indirect -#### Tones -- This is not an exhaustive list of tones +Positive Tones -Positive - Optimistic - Appreciative - Assertive @@ -262,7 +353,8 @@ Positive - Humorous - Inspirational -Negative +Negative Tones + - Pessimistic - Accusatory - Concerned @@ -271,12 +363,13 @@ Negative - Sarcastic - Urgent -### Output Format -In [output format] +### Format -#### Text +In [format] -List +Presentation + +- Plain text - Bullet point list - Numbered list - Check list @@ -285,13 +378,18 @@ Code - Code Process + - Step-by-step instructions Response + - Question and answer - Dialogue Creative + +- Poetry +- Music lyrics - Script - Comic strip dialogue - Poetry @@ -299,45 +397,34 @@ Creative - Riddle Game + - Quiz - RPG - Choose-Your-Own-Adventure -#### Visual +### Restriction -Data Visualization -- Table -- [Chart] chart ***(Chart type examples: gantt, bubble, error, contour, area, scatter, KDE, box, histogram, bar, line, 3D, joint, surface, polar, pie, cat, pair, strip, swarm, heatmap, hexbin)*** +But [restriction] -Creative -- Emojis -- Word cloud +Length Constraints -#### File Format -- Plain text -- Markdown -- CSV -- XML -- JSON -- PDF +- Concise +- In N words +- In N sentences -### Constraint -But [constraint] +Language Constraints -Length -- Be [extremely detailed | concise] -- In [quantity] [words | sentences] +- No jargon or technical terms -Language -- No jargon or technical terms +Structural Constraints -Structure -- Show [quantity] [examples | options] -- No headers -- No pretext titles +- Show N options +- No examples +- No headers +- No pretext titles + +Content Constraints -Content -- Use [first-person | second-person | third-person] narrative voice - Don't change the wording - Permit [minor | major] edits - Use pop culture references @@ -345,431 +432,555 @@ Content - Only show [changed | unchanged] content ## Examples + ### Job + Name Business + ```{.wrap} Suggest creative name for tech startup ``` + ```{.wrap} Suggest catchy names for bakery business ``` Interview Questions + ```{.wrap} Suggest common software engineer interview questions ``` Create Course Outline + ```{.wrap} Create course outline on web development for beginners ``` + ```{.wrap} Create training program outline for customer service workshop ``` ### Relationship + Gift Ideas + ```{.wrap} Suggest gift ideas for clients ``` + ```{.wrap} Suggest gift ideas for clients who work as flourists ``` + ```{.wrap} Suggest gift ideas for my wife who loves steampunk art and crafts, mystery sci-fi, journalling ``` + ```{.wrap} Suggest creative ideas for 10 year old’s birthday ``` ### Competition + Select Contest Winners + ```{.wrap} Randomly select 1 name from this list ``` + ```{.wrap} Randomly select 5 email addresses from this list ``` + ```{.wrap} Select top 3 records with the shortest lap times from this list ``` ### Programming + Create Code + ```{.wrap} Create program to calculate the factorial of given number in python ``` Create Regular Expressions + ```{.wrap} Create regex to match all email addresses in list ``` + ```{.wrap} Create regex to match all words that start with "ban" ``` + ```{.wrap} Create regex to match 8-digit password ``` Explain Code + ```{.wrap} Explain why code not working ``` + ```{.wrap} Explain what code does ``` + ```{.wrap} Explain how to make a HTTP request in javascript ``` Update Code + ```{.wrap} Add code comments ``` + ```{.wrap} Add class "header" to header tag ``` + ```{.wrap} Update CSS to change font color to blue ``` -Translate -- Specifically called transpile when addressing programming languages. +Transpile + ```{.wrap} Translate code to Python ``` ### Email + Create Emails + ```{.wrap} Write email inviting Jack to dinner on the weekend ``` + ```{.wrap} Write email sequence for our new customer onboarding process ``` + ```{.wrap} Write email to inform staff of elevator maintenance on 23 June 2025, elevators unavailable for 24 hours, apologise for inconvenience ``` + ```{.wrap} Suggest response to message asking about project status ``` Format Email + ```{.wrap} Proofread and format email ``` Email Marketing + ```{.wrap} Suggest tips to increase open and click-through rates for my email campaigns ``` + ```{.wrap} Suggest ways to make my email content more engaging and relevant to my subscribers ``` Extract Data + ```{.wrap} Extract all email addresses in text ``` ### Spreadsheet + Create Something + ```{.wrap} Create excel formula to calculate sum of cells A1 to A10 ``` + ```{.wrap} Generate spreadsheet dummy data as a placeholder ``` + ```{.wrap} Create macro to calculate average of cells B1 to B10 and insert result in cell C1 ``` Explain Something + ```{.wrap} Explain formula =SUM(A1:A10) in simple terms ``` + ```{.wrap} Suggest tips to improve spreadsheet efficiency ``` ### Social Media + Create Content + ```{.wrap} Suggest meme ideas for dogs ``` + ```{.wrap} Suggest climate change post ideas to engage my followers ``` + ```{.wrap} Generate hashtags and caption for a picture of scenic sunset ``` ### Reading + Text Analysis + ```{.wrap} Summarize article ``` + ```{.wrap} Write concise main points ``` Translate + ```{.wrap} Translate to spanish ``` Recommendations + ```{.wrap} Recommend books similar to Hunger Games ``` ### Design + Design Prompts + ```{.wrap} Create design prompt of logo for new sports brand ``` + ```{.wrap} Suggest eye-catching thumbnail designs for youtube video on healthy eating ``` Aesthetic Pairings + ```{.wrap} Suggest font pairing for travel blog header design ``` + ```{.wrap} Suggest color palette for wedding photography website ``` ### Data Analysis + Data Extraction + ```{.wrap} Extract all numbers from text ``` Data Filtering + ```{.wrap} Filter list based on [condition] ``` Data Presentation + ```{.wrap} Create table from data ``` ### Paid Ads + Create Ad + ```{.wrap} Suggest creative ideas for new product launch ``` + ```{.wrap} Suggest ad copy for travel company ``` + ```{.wrap} Create headlines, body text, and calls to action for new fitness program ad ``` Ad Targeting + ```{.wrap} Recommend target Facebook audience for clothing line ad campaign ``` Ad Technical Support + ```{.wrap} Review tag manager code for errors ``` ### Amazon FBA + Product Content + ```{.wrap} Write compelling product description for latest item ``` Communication + ```{.wrap} Rewrite appeal letter to make it more persuasive ``` + ```{.wrap} Write effective email to reach out to potential suppliers ``` Product Strategy + ```{.wrap} Suggest items that would make a good bundle for our customers ``` + ```{.wrap} Organize product and pricing information into a neat and manageable spreadsheet ``` ### Writing + Name Something + ```{.wrap} Suggest titles for short story ``` + ```{.wrap} Suggest titles for article 10 options ``` + ```{.wrap} Suggest domain name for gardening blog ``` Content Creation + ```{.wrap} Create outline for essay on exercise ``` + ```{.wrap} Suggest ideas for blog on sustainable fashion ``` + ```{.wrap} Create blog post on financial planning ``` + ```{.wrap} Expand jazz music sentence ``` Editing And Formatting + ```{.wrap} Change report tone to conversational ``` + ```{.wrap} Proofread article ``` + ```{.wrap} Format headings for blog post ``` Evaluation + ```{.wrap} Check for bias ``` + ```{.wrap} Check for plagiarism ``` ### Teacher + Teaching Support + ```{.wrap} Convert work history fact list into multiple-choice quiz ``` + ```{.wrap} Suggest ideas for history assignment on American Revolution ``` + ```{.wrap} Divide list of 30 students into groups of 6 ``` + ```{.wrap} Create grading curve for class based on their test scores ``` + ```{.wrap} Grade history essay and provide feedback on any areas for improvement ``` ### YouTube + Content Creation + ```{.wrap} Create timestamps for podcast episode transcript ``` + ```{.wrap} Convert youtube cooking video into blog post with headings and bullet points ``` + ```{.wrap} Create outline for a video about the benefits of meditation ``` + ```{.wrap} Suggest thumbnail ideas for video on "DIY home decor" ``` + ```{.wrap} Suggest fashion video ideas for individual episodes ``` Analyse + ```{.wrap} What is the script tone for environmental issues video ``` Communication + ```{.wrap} Create thoughtful and polite response to negative comment on youtube video ``` ### Research + History Research + ```{.wrap} Explain events leading up to American Civil War ``` + ```{.wrap} Provide key details about printing press invention ``` + ```{.wrap} Research olympic games history ``` + ```{.wrap} Provide key details about French Revolution ``` + ```{.wrap} Explain history of Byzantine Empire ``` Science Reseearch + ```{.wrap} Explain quantum computing in simple terms ``` + ```{.wrap} Explain rocket science like i'm five ``` ### SEO + Keywords + ```{.wrap} Find best keywords for [topic] with low competition ``` + ```{.wrap} Generate list of keywords targeting multiple geographic locations ``` + ```{.wrap} Generate list of keyword synonyms for [topic] ``` Content Optimization + ```{.wrap} Find opportunities for internal linking related to [topic] ``` + ```{.wrap} Research industry-specific terminology for use in [topic] content ``` + ```{.wrap} Find best time to publish content related to [topic] ``` + Link Building + ```{.wrap} Find authoritative websites to acquire backlinks for [topic] content ``` + ```{.wrap} Research best external linking strategies for [topic] ``` Tools + ```{.wrap} Find most popular tools used for [topic] seo ``` Tactics + ```{.wrap} Research best tactics for [topic] mobile optimization ``` + ```{.wrap} What are the best tactics for [topic] international seo? ``` Competitors + ```{.wrap} Research competitor strategies related to [topic] ``` + ```{.wrap} What are the best affiliate marketing websites for [topic]? ``` ### Roleplay + Simulate Character + ```{.wrap} Act as William Shakespeare @@ -797,14 +1008,12 @@ Scenario: - Lead actor is missing and staff are concerned about how to achieve the performance. ``` -## References (Used For Ideas) -- [General Purpose Framework](https://www.linkedin.com/posts/denis-panjuta_the-ultimate-chatgpt-40-guide-roles-activity-7231208824680976384-bdlY/) -- [General Info](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/2b88d101-e659-4adc-a63a-560b2b70179a/_FINAL__The_ChatGPT_Cheat_Sheet__1_.png) -- [Data Visualization](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/0a928290-8e99-414e-b847-5b2dff35ec55/ChatGPT_-_Code_Interpreter_In_a_Nutshell___1_.png) -- [Comprehensive Cheatsheet](https://github.com/bg-write/chatGPT-cheatsheet) +## Any Suggestions? + +- [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) \ No newline at end of file + diff --git a/source/_posts/cs.md b/source/_posts/cs.md index 1187f20..14d585f 100644 --- a/source/_posts/cs.md +++ b/source/_posts/cs.md @@ -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} diff --git a/source/_posts/css3.md b/source/_posts/css3.md index 51236ad..d0fa6cc 100644 --- a/source/_posts/css3.md +++ b/source/_posts/css3.md @@ -49,7 +49,7 @@ CSS is rich in capabilities and is more than simply laying out pages. ```html
-
+
``` 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, '.') ' '; } ``` diff --git a/source/_posts/dart.md b/source/_posts/dart.md index 2ddd7df..1c1a019 100644 --- a/source/_posts/dart.md +++ b/source/_posts/dart.md @@ -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 names = {}; // This works, too. // a map is an object that associates keys and values var person = Map(); // 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() { ``` - - diff --git a/source/_posts/django.md b/source/_posts/django.md index 6a52e70..b7e4a10 100644 --- a/source/_posts/django.md +++ b/source/_posts/django.md @@ -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 @@ -891,9 +893,8 @@ class ArticleForm(ModelForm): ```html
- {% csrf_token %} - {{ form.as_p }} - + {% csrf_token %} {{ form.as_p }} +
``` @@ -955,7 +956,8 @@ messages.error(request, 'Login error') ```html -{% 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')) Logout -{% 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 diff --git a/source/_posts/ejs.md b/source/_posts/ejs.md index 91dd1a9..22c7680 100644 --- a/source/_posts/ejs.md +++ b/source/_posts/ejs.md @@ -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 @@ -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: users }, { delimiter: "?" }); +ejs.render('', { 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;
``` diff --git a/source/_posts/es6.md b/source/_posts/es6.md index 3b39a1f..0af0215 100644 --- a/source/_posts/es6.md +++ b/source/_posts/es6.md @@ -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) { diff --git a/source/_posts/express.md b/source/_posts/express.md index 9116754..356868a 100644 --- a/source/_posts/express.md +++ b/source/_posts/express.md @@ -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!' }); }); ``` diff --git a/source/_posts/github-actions.md b/source/_posts/github-actions.md index 36bcbdd..bdc56e8 100644 --- a/source/_posts/github-actions.md +++ b/source/_posts/github-actions.md @@ -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" diff --git a/source/_posts/gnome-desktop.md b/source/_posts/gnome-desktop.md index f1ad2a5..f395f63 100644 --- a/source/_posts/gnome-desktop.md +++ b/source/_posts/gnome-desktop.md @@ -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)_ diff --git a/source/_posts/gnupg.md b/source/_posts/gnupg.md index fcd4c5c..6a86b24 100644 --- a/source/_posts/gnupg.md +++ b/source/_posts/gnupg.md @@ -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 ### 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 diff --git a/source/_posts/go.md b/source/_posts/go.md index 7ce3ce6..2f21399 100644 --- a/source/_posts/go.md +++ b/source/_posts/go.md @@ -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 diff --git a/source/_posts/google-search.md b/source/_posts/google-search.md index 4818ff5..b073a43 100644 --- a/source/_posts/google-search.md +++ b/source/_posts/google-search.md @@ -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 diff --git a/source/_posts/hook.md b/source/_posts/hook.md index dbd5b64..279a686 100644 --- a/source/_posts/hook.md +++ b/source/_posts/hook.md @@ -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 @@ -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 diff --git a/source/_posts/html.md b/source/_posts/html.md index 4a6fdd4..6626480 100644 --- a/source/_posts/html.md +++ b/source/_posts/html.md @@ -78,7 +78,13 @@ See: [The \ Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Ele ### Image Tag ```html {.wrap} -Describe image here +Describe image here ``` --- @@ -170,7 +176,7 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM ```html ``` @@ -277,7 +283,10 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM ```html {.wrap} ``` @@ -292,7 +301,10 @@ See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTM ### HTML5 Audio ```html {.wrap} - ### HTML5 Ruby ```html {.wrap} - 汉 (hàn) 字 (zì) + + 汉 (hàn) 字 (zì) + ``` #### ↓ Preview diff --git a/source/_posts/idea.md b/source/_posts/idea.md index d9a12d1..ca9961a 100644 --- a/source/_posts/idea.md +++ b/source/_posts/idea.md @@ -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 diff --git a/source/_posts/javascript.md b/source/_posts/javascript.md index 7b6e188..66920ab 100644 --- a/source/_posts/javascript.md +++ b/source/_posts/javascript.md @@ -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 + "
"; + text += 'The number is ' + i + '
'; } ``` @@ -732,7 +732,7 @@ for (let i = 0; i < 2; i += 1) { ### for...in loop ```javascript -const fruits = ["apple", "orange", "banana"]; +const fruits = ['apple', 'orange', 'banana']; for (let index in fruits) { console.log(index); @@ -745,7 +745,7 @@ for (let index in fruits) { ### for...of loop ```javascript -const fruits = ["apple", "orange", "banana"]; +const fruits = ['apple', 'orange', 'banana']; for (let fruit of fruits) { console.log(fruit); @@ -803,10 +803,10 @@ console.log(sum); // 10 ### Array.map() ```javascript -const members = ["Taylor", "Donald", "Don", "Natasha", "Bobby"]; +const members = ['Taylor', 'Donald', 'Don', 'Natasha', 'Bobby']; const announcements = members.map((member) => { - return member + " joined the contest."; + return member + ' joined the contest.'; }); console.log(announcements); @@ -837,8 +837,8 @@ const filteredArray = randomNumbers.filter((n) => { ```javascript const apple = { - color: "Green", - price: { bulk: "$3/kg", smallQty: "$4/kg" }, + color: 'Green', + price: { bulk: '$3/kg', smallQty: '$4/kg' } }; console.log(apple.color); // => Green console.log(apple.price.bulk); // => $3/kg @@ -862,7 +862,7 @@ const trainSchedule = { ```javascript const classElection = { - date: "January 12", + date: 'January 12' }; console.log(classElection.place); // undefined @@ -872,16 +872,16 @@ console.log(classElection.place); // undefined ```javascript const student = { - name: "Sheldon", + name: 'Sheldon', score: 100, - grade: "A", + grade: 'A' }; console.log(student); // { name: 'Sheldon', score: 100, grade: 'A' } delete student.score; -student.grade = "F"; +student.grade = 'F'; console.log(student); // { name: 'Sheldon', grade: 'F' } @@ -893,8 +893,8 @@ student = {}; ```javascript const person = { - name: "Tom", - age: "22", + name: 'Tom', + age: '22' }; const { name, age } = person; console.log(name); // 'Tom' @@ -905,10 +905,10 @@ console.log(age); // '22' ```javascript const person = { - firstName: "Matilda", + firstName: 'Matilda', age: 27, - hobby: "knitting", - goal: "learning JavaScript", + hobby: 'knitting', + goal: 'learning JavaScript' }; delete person.hobby; // or delete person[hobby]; @@ -927,11 +927,11 @@ console.log(person); ```javascript const origNum = 8; -const origObj = { color: "blue" }; +const origObj = { color: 'blue' }; const changeItUp = (num, obj) => { num = 7; - obj.color = "red"; + obj.color = 'red'; }; changeItUp(origNum, origObj); @@ -947,7 +947,7 @@ console.log(origObj.color); ### Shorthand object creation ```javascript -const activity = "Surfing"; +const activity = 'Surfing'; const beach = { activity }; console.log(beach); // { activity: 'Surfing' } ``` @@ -956,11 +956,11 @@ console.log(beach); // { activity: 'Surfing' } ```javascript const cat = { - name: "Pipey", + name: 'Pipey', age: 8, whatName() { return this.name; - }, + } }; console.log(cat.whatName()); // => Pipey ``` @@ -977,8 +977,8 @@ const dogFactory = (name, age, breed) => { age: age, breed: breed, bark() { - console.log("Woof!"); - }, + console.log('Woof!'); + } }; }; ``` @@ -993,11 +993,11 @@ const engine = { }, // anonymous arrow function expression with no arguments sputter: () => { - console.log("The engine sputters..."); - }, + console.log('The engine sputters...'); + } }; -engine.start("noisily"); +engine.start('noisily'); engine.sputter(); ``` @@ -1005,20 +1005,20 @@ engine.sputter(); ```javascript const myCat = { - _name: "Dottie", + _name: 'Dottie', get name() { return this._name; }, set name(newName) { this._name = newName; - }, + } }; // Reference invokes the getter console.log(myCat.name); // Assignment invokes the setter -myCat.name = "Yankee"; +myCat.name = 'Yankee'; ``` ## JavaScript Classes @@ -1032,16 +1032,16 @@ class Dog { } introduce() { - console.log("This is " + this._name + " !"); + console.log('This is ' + this._name + ' !'); } // A static method static bark() { - console.log("Woof!"); + console.log('Woof!'); } } -const myDog = new Dog("Buster"); +const myDog = new Dog('Buster'); myDog.introduce(); // Calling the static method @@ -1058,7 +1058,7 @@ class Song { } play() { - console.log("Song playing!"); + console.log('Song playing!'); } } @@ -1076,7 +1076,7 @@ class Song { } } -const mySong = new Song("Bohemian Rhapsody", "Queen"); +const mySong = new Song('Bohemian Rhapsody', 'Queen'); console.log(mySong.title); ``` @@ -1085,11 +1085,11 @@ console.log(mySong.title); ```javascript class Song { play() { - console.log("Playing!"); + console.log('Playing!'); } stop() { - console.log("Stopping!"); + console.log('Stopping!'); } } ``` @@ -1114,9 +1114,9 @@ class Song extends Media { } const mySong = new Song({ - artist: "Queen", - name: "Bohemian Rhapsody", - publishDate: 1975, + artist: 'Queen', + name: 'Bohemian Rhapsody', + publishDate: 1975 }); ``` @@ -1185,7 +1185,7 @@ module.exports = { add, subtract, multiply, - duplicate, + duplicate }; ``` @@ -1193,7 +1193,7 @@ module.exports = { ```javascript // main.js -const myMath = require("./myMath.js"); +const myMath = require('./myMath.js'); console.log(myMath.add(6, 2)); // 8 console.log(myMath.subtract(6, 2)); // 4 @@ -1210,15 +1210,15 @@ const promise = new Promise((resolve, reject) => { const res = true; // An asynchronous operation. if (res) { - resolve("Resolved!"); + resolve('Resolved!'); } else { - reject(Error("Error")); + reject(Error('Error')); } }); promise.then( (res) => console.log(res), - (err) => console.error(err), + (err) => console.error(err) ); ``` @@ -1226,7 +1226,7 @@ promise.then( ```javascript const executorFn = (resolve, reject) => { - resolve("Resolved!"); + resolve('Resolved!'); }; const promise = new Promise(executorFn); @@ -1236,7 +1236,7 @@ const promise = new Promise(executorFn); ```javascript const loginAlert = () => { - console.log("Login"); + console.log('Login'); }; setTimeout(loginAlert, 6000); @@ -1247,7 +1247,7 @@ setTimeout(loginAlert, 6000); ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { - resolve("Result"); + resolve('Result'); }, 200); }); @@ -1257,7 +1257,7 @@ promise.then( }, (err) => { console.error(err); - }, + } ); ``` @@ -1266,7 +1266,7 @@ promise.then( ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { - reject(Error("Promise Rejected Unconditionally.")); + reject(Error('Promise Rejected Unconditionally.')); }, 1000); }); @@ -1320,7 +1320,7 @@ Promise.allSettled([promise1, promise2]).then((res) => { ```javascript const promise = new Promise((resolve, reject) => { setTimeout(() => { - resolve("*"); + resolve('*'); }, 1000); }); @@ -1329,7 +1329,7 @@ const twoStars = (star) => { }; const oneDot = (star) => { - return star + "."; + return star + '.'; }; const print = (val) => { @@ -1344,7 +1344,7 @@ promise.then(twoStars).then(oneDot).then(print); ```javascript const executorFn = (resolve, reject) => { - console.log("The executor function of the promise!"); + console.log('The executor function of the promise!'); }; const promise = new Promise(executorFn); @@ -1353,11 +1353,15 @@ const promise = new Promise(executorFn); ### Chaining multiple .then() ```javascript -const promise = new Promise((resolve) => setTimeout(() => resolve("dAlan"), 100)); +const promise = new Promise((resolve) => + setTimeout(() => resolve('dAlan'), 100) +); promise .then((res) => { - return res === "Alan" ? Promise.resolve("Hey Alan!") : Promise.reject("Who are you?"); + return res === 'Alan' + ? Promise.resolve('Hey Alan!') + : Promise.reject('Who are you?'); }) .then( (res) => { @@ -1365,7 +1369,7 @@ promise }, (err) => { console.error(err); - }, + } ); ``` @@ -1378,7 +1382,7 @@ const mock = (success, timeout = 1000) => { if (success) { resolve({ status: 200, data: {} }); } else { - reject({ message: "Error" }); + reject({ message: 'Error' }); } }, timeout); }); @@ -1400,7 +1404,7 @@ const someEvent = async () => { function helloWorld() { return new Promise((resolve) => { setTimeout(() => { - resolve("Hello World!"); + resolve('Hello World!'); }, 2000); }); } @@ -1408,13 +1412,13 @@ function helloWorld() { const msg = async function () { //Async Function Expression const msg = await helloWorld(); - console.log("Message:", msg); + console.log('Message:', msg); }; const msg1 = async () => { //Async Arrow Function const msg = await helloWorld(); - console.log("Message:", msg); + console.log('Message:', msg); }; msg(); // Message: Hello World! <-- after 2 seconds @@ -1427,7 +1431,7 @@ msg1(); // Message: Hello World! <-- after 2 seconds let pro1 = Promise.resolve(5); let pro2 = 44; let pro3 = new Promise(function (resolve, reject) { - setTimeout(resolve, 100, "foo"); + setTimeout(resolve, 100, 'foo'); }); Promise.all([pro1, pro2, pro3]).then(function (values) { @@ -1442,14 +1446,14 @@ Promise.all([pro1, pro2, pro3]).then(function (values) { function helloWorld() { return new Promise((resolve) => { setTimeout(() => { - resolve("Hello World!"); + resolve('Hello World!'); }, 2000); }); } async function msg() { const msg = await helloWorld(); - console.log("Message:", msg); + console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds @@ -1464,7 +1468,7 @@ try { let user = JSON.parse(json); // <-- no errors console.log(user.name); // no name! } catch (e) { - console.error("Invalid JSON data!"); + console.error('Invalid JSON data!'); } ``` @@ -1474,14 +1478,14 @@ try { function helloWorld() { return new Promise((resolve) => { setTimeout(() => { - resolve("Hello World!"); + resolve('Hello World!'); }, 2000); }); } async function msg() { const msg = await helloWorld(); - console.log("Message:", msg); + console.log('Message:', msg); } msg(); // Message: Hello World! <-- after 2 seconds @@ -1505,7 +1509,7 @@ Also see: [JSON cheatsheet](/json) ```javascript const xhr = new XMLHttpRequest(); -xhr.open("GET", "mysite.com/getjson"); +xhr.open('GET', 'mysite.com/getjson'); ``` `XMLHttpRequest` is a browser-level API that enables the client to script data transfers via JavaScript, NOT part of the @@ -1515,8 +1519,8 @@ JavaScript language. ```javascript const req = new XMLHttpRequest(); -req.responseType = "json"; -req.open("GET", "/getdata?id=65"); +req.responseType = 'json'; +req.open('GET', '/getdata?id=65'); req.onload = () => { console.log(xhr.response); }; @@ -1528,13 +1532,13 @@ req.send(); ```javascript const data = { - fish: "Salmon", - weight: "1.5 KG", - units: 5, + fish: 'Salmon', + weight: '1.5 KG', + units: 5 }; const xhr = new XMLHttpRequest(); -xhr.open("POST", "/inventory/add"); -xhr.responseType = "json"; +xhr.open('POST', '/inventory/add'); +xhr.responseType = 'json'; xhr.send(JSON.stringify(data)); xhr.onload = () => { @@ -1566,7 +1570,7 @@ fetch(url, { ### JSON Formatted ```javascript -fetch("url-that-returns-JSON") +fetch('url-that-returns-JSON') .then((response) => response.json()) .then((jsonResponse) => { console.log(jsonResponse); @@ -1589,20 +1593,20 @@ fetch('url') ### Fetch API Function ```javascript -fetch("https://api-xxx.com/endpoint", { - method: "POST", - body: JSON.stringify({ id: "200" }), +fetch('https://api-xxx.com/endpoint', { + method: 'POST', + body: JSON.stringify({ id: '200' }) }) .then( (response) => { if (response.ok) { return response.json(); } - throw new Error("Request failed!"); + throw new Error('Request failed!'); }, (networkError) => { console.log(networkError.message); - }, + } ) .then((jsonResponse) => { console.log(jsonResponse); @@ -1616,7 +1620,7 @@ const getSuggestions = async () => { const wordQuery = inputField.value; const endpoint = `${url}${queryParams}${wordQuery}`; try { - const response = await fetch(endpoint, { cache: "no-cache" }); + const response = await fetch(endpoint, { cache: 'no-cache' }); if (response.ok) { const jsonResponse = await response.json(); } diff --git a/source/_posts/jquery.md b/source/_posts/jquery.md index 0b6b957..0355ad8 100644 --- a/source/_posts/jquery.md +++ b/source/_posts/jquery.md @@ -28,7 +28,10 @@ plugins: #### Official CDN ```html {.wrap} - + ``` ### 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").after("

Paragraph.

"); +$('span').after('

Paragraph.

'); /*Span.

Paragraph.

*/ /*Span.*/ -$("Span.").replaceAll("p"); +$('Span.').replaceAll('p'); /*

Span.

*/ /*This is span.*/ -$("span").wrap("

"); +$('span').wrap('

'); /*

This is span.

*/ ``` @@ -389,25 +392,25 @@ $("span").wrap("

"); ```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); }); ``` diff --git a/source/_posts/json.md b/source/_posts/json.md index d4e6247..250d774 100644 --- a/source/_posts/json.md +++ b/source/_posts/json.md @@ -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]; ``` --- diff --git a/source/_posts/latex.md b/source/_posts/latex.md index 71a703f..70e2f45 100644 --- a/source/_posts/latex.md +++ b/source/_posts/latex.md @@ -909,7 +909,6 @@ x = \begin{cases} \end{itemize} ``` - ### Ordered List diff --git a/source/_posts/markdown.md b/source/_posts/markdown.md index 4d5655d..100a724 100644 --- a/source/_posts/markdown.md +++ b/source/_posts/markdown.md @@ -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 diff --git a/source/_posts/mongodb.md b/source/_posts/mongodb.md index 66ecb4d..396e0f2 100644 --- a/source/_posts/mongodb.md +++ b/source/_posts/mongodb.md @@ -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} diff --git a/source/_posts/notion.md b/source/_posts/notion.md index 0cbe628..0165a55 100644 --- a/source/_posts/notion.md +++ b/source/_posts/notion.md @@ -12,7 +12,8 @@ categories: - Productivity - Software intro: - A comprehensive quick reference guide for Notion keyboard shortcuts on Desktop and Web, designed to boost your productivity. + A comprehensive quick reference guide for Notion keyboard shortcuts on Desktop and Web, designed to boost your + productivity. plugins: - copyCode --- @@ -22,26 +23,30 @@ plugins: ## Most Popular / Essential {.col-span-3} ### Create & Navigate -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :--------------------------- | :------------------------ | :----------------------- | -| Create a new page | `Cmd` `N` | `Ctrl` `N` | -| Open new Notion window | `Cmd` `Shift` `N` | `Ctrl` `Shift` `N` | -| Quick Find (Search) | `Cmd` `P` | `Ctrl` `P` | -| Go back in page history | `Cmd` `[` | `Ctrl` `[` | -| Go forward in page history | `Cmd` `]` | `Ctrl` `]` | -| Go to parent page | `Cmd` `Shift` `U` | `Ctrl` `Shift` `U` | -| Open Page Link in New Tab | `Cmd` `Click` | `Ctrl` `Click` | -| Open Page Link in New Window | `Option` `Shift` `Click` | `Alt` `Shift` `Click` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :--------------------------- | :----------------------- | :--------------------- | +| Create a new page | `Cmd` `N` | `Ctrl` `N` | +| Open new Notion window | `Cmd` `Shift` `N` | `Ctrl` `Shift` `N` | +| Quick Find (Search) | `Cmd` `P` | `Ctrl` `P` | +| Go back in page history | `Cmd` `[` | `Ctrl` `[` | +| Go forward in page history | `Cmd` `]` | `Ctrl` `]` | +| Go to parent page | `Cmd` `Shift` `U` | `Ctrl` `Shift` `U` | +| Open Page Link in New Tab | `Cmd` `Click` | `Ctrl` `Click` | +| Open Page Link in New Window | `Option` `Shift` `Click` | `Alt` `Shift` `Click` | + {.show-header .shortcuts} ### View & Mode -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :--------------------------- | :------------------------ | :----------------------- | -| Toggle Dark/Light Mode | `Cmd` `Shift` `L` | `Ctrl` `Shift` `L` | -| Lock/Unlock current page | `Cmd` `Shift` `L` (Hold) | `Ctrl` `Shift` `L` (Hold)| -| Zoom In | `Cmd` `+` | `Ctrl` `+` | -| Zoom Out | `Cmd` `-` | `Ctrl` `-` | -| Reset Zoom | `Cmd` `0` | `Ctrl` `0` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :----------------------- | :----------------------- | :------------------------ | +| Toggle Dark/Light Mode | `Cmd` `Shift` `L` | `Ctrl` `Shift` `L` | +| Lock/Unlock current page | `Cmd` `Shift` `L` (Hold) | `Ctrl` `Shift` `L` (Hold) | +| Zoom In | `Cmd` `+` | `Ctrl` `+` | +| Zoom Out | `Cmd` `-` | `Ctrl` `-` | +| Reset Zoom | `Cmd` `0` | `Ctrl` `0` | + {.show-header .shortcuts} --- @@ -49,64 +54,58 @@ plugins: # Markdown Style Formatting {.cols-1} ### On New Lines + Type the following at the beginning of an empty line, then press `Space`: -* `*`, `-`, or `+` : Bulleted list -* `[]` : To-do checkbox (Note: just the characters, no `Cmd`/`Ctrl`) -* `1.` : Numbered list -* `#` : H1 heading -* `##` : H2 heading -* `###` : H3 heading -* `>` : Toggle list -* `"` : Quote block -* `---` : Divider (three hyphens) -* ```` ```` : Code block (three backticks) +- `*`, `-`, or `+` : Bulleted list +- `[]` : To-do checkbox (Note: just the characters, no `Cmd`/`Ctrl`) +- `1.` : Numbered list +- `#` : H1 heading +- `##` : H2 heading +- `###` : H3 heading +- `>` : Toggle list +- `"` : Quote block +- `---` : Divider (three hyphens) +- ` ` : Code block (three backticks) ### Inline -* Wrap text with `**` or `__` for **Bold**. -* Wrap text with `*` or `_` for *Italics*. -* Wrap text with `~` for ~~Strikethrough~~. -* Wrap text with `` ` `` for `inline code`. + +- Wrap text with `**` or `__` for **Bold**. +- Wrap text with `*` or `_` for _Italics_. +- Wrap text with `~` for ~~Strikethrough~~. +- Wrap text with `` ` `` for `inline code`. --- # Text Formatting & Editing {.cols-2} ### Basic Formatting -Select text first, then use the shortcut: -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------- | :------------------------ | :----------------------- | -| Bold | `Cmd` `B` | `Ctrl` `B` | -| Italic | `Cmd` `I` | `Ctrl` `I` | -| Underline | `Cmd` `U` | `Ctrl` `U` | -| Strikethrough | `Cmd` `Shift` `S` | `Ctrl` `Shift` `S` | -| Inline Code | `Cmd` `E` | `Ctrl` `E` | -| Create Link | `Cmd` `K` | `Ctrl` `K` | -| Change Color / Highlight | `Cmd` `Shift` `H` | `Ctrl` `Shift` `H` | -| Clear Formatting | `Cmd` `\` | `Ctrl` `\` | -{.show-header .shortcuts} + +Select text first, then use the shortcut: | Action | Mac Shortcut | Windows/Linux Shortcut | | +:------------------------- | :------------------------ | :----------------------- | | Bold | `Cmd` `B` | `Ctrl` `B` | | +Italic | `Cmd` `I` | `Ctrl` `I` | | Underline | `Cmd` `U` | `Ctrl` `U` | | Strikethrough | `Cmd` `Shift` `S` | `Ctrl` +`Shift` `S` | | Inline Code | `Cmd` `E` | `Ctrl` `E` | | Create Link | `Cmd` `K` | `Ctrl` `K` | | Change Color / +Highlight | `Cmd` `Shift` `H` | `Ctrl` `Shift` `H` | | Clear Formatting | `Cmd` `\` | `Ctrl` `\` | {.show-header +.shortcuts} ### Block Type Conversion -Select the block(s) first, then use the shortcut: -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------- | :------------------------ | :----------------------- | -| Turn into Text block | `Cmd` `Option` `0` | `Ctrl` `Alt` `0` | -| Turn into H1 Heading | `Cmd` `Option` `1` | `Ctrl` `Alt` `1` | -| Turn into H2 Heading | `Cmd` `Option` `2` | `Ctrl` `Alt` `2` | -| Turn into H3 Heading | `Cmd` `Option` `3` | `Ctrl` `Alt` `3` | -| Turn into To-do list | `Cmd` `Option` `4` | `Ctrl` `Alt` `4` | -| Turn into Bulleted list | `Cmd` `Option` `5` | `Ctrl` `Alt` `5` | -| Turn into Numbered list | `Cmd` `Option` `6` | `Ctrl` `Alt` `6` | -| Turn into Toggle list | `Cmd` `Option` `7` | `Ctrl` `Alt` `7` | -| Turn into Code block | `Cmd` `Option` `8` | `Ctrl` `Alt` `8` | -| Turn into Page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` | -| Turn into Callout | `Cmd` `Option` `C` | `Ctrl` `Alt` `C` | -{.show-header .shortcuts} + +Select the block(s) first, then use the shortcut: | Action | Mac Shortcut | Windows/Linux Shortcut | | +:------------------------- | :------------------------ | :----------------------- | | Turn into Text block | `Cmd` +`Option` `0` | `Ctrl` `Alt` `0` | | Turn into H1 Heading | `Cmd` `Option` `1` | `Ctrl` `Alt` `1` | | Turn into H2 +Heading | `Cmd` `Option` `2` | `Ctrl` `Alt` `2` | | Turn into H3 Heading | `Cmd` `Option` `3` | `Ctrl` `Alt` `3` | | +Turn into To-do list | `Cmd` `Option` `4` | `Ctrl` `Alt` `4` | | Turn into Bulleted list | `Cmd` `Option` `5` | `Ctrl` +`Alt` `5` | | Turn into Numbered list | `Cmd` `Option` `6` | `Ctrl` `Alt` `6` | | Turn into Toggle list | `Cmd` `Option` +`7` | `Ctrl` `Alt` `7` | | Turn into Code block | `Cmd` `Option` `8` | `Ctrl` `Alt` `8` | | Turn into Page | `Cmd` +`Option` `9` | `Ctrl` `Alt` `9` | | Turn into Callout | `Cmd` `Option` `C` | `Ctrl` `Alt` `C` | {.show-header +.shortcuts} ### Editing -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------- | :------------------------ | :----------------------- | -| New Line within same block | `Shift` `Enter` | `Shift` `Enter` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :------------------------- | :-------------- | :--------------------- | +| New Line within same block | `Shift` `Enter` | `Shift` `Enter` | + {.show-header .shortcuts} --- @@ -114,32 +113,35 @@ Select the block(s) first, then use the shortcut: # Creating & Modifying Blocks {.cols-2} ### Creation & Selection -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------------------------ | :------------------------------- | :------------------------------ | -| Create new text block below | `Enter` | `Enter` | -| Open the `/` command menu | `/` | `/` | -| Select current block | `Esc` | `Esc` | -| Select parent block | `Shift` `Esc` | `Shift` `Esc` | -| Select block above/below | `Up` / `Down` | `Up` / `Down` | -| Select multiple blocks | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` | -| Select all blocks | `Cmd` `A` | `Ctrl` `A` | -| Edit selected block (or text within block) | `Enter` | `Enter` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :----------------------------------------- | :------------------ | :--------------------- | +| Create new text block below | `Enter` | `Enter` | +| Open the `/` command menu | `/` | `/` | +| Select current block | `Esc` | `Esc` | +| Select parent block | `Shift` `Esc` | `Shift` `Esc` | +| Select block above/below | `Up` / `Down` | `Up` / `Down` | +| Select multiple blocks | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` | +| Select all blocks | `Cmd` `A` | `Ctrl` `A` | +| Edit selected block (or text within block) | `Enter` | `Enter` | + {.show-header .shortcuts} - ### Moving & Structuring -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------------------------ | :------------------------------- | :------------------------------ | -| Duplicate selected block(s) | `Cmd` `D` | `Ctrl` `D` | -| Move selected block(s) up/down | `Cmd` `Shift` `Up`/`Down` | `Ctrl` `Shift` `Up`/`Down` | -| Indent block (nest) | `Tab` | `Tab` | -| Un-indent block | `Shift` `Tab` | `Shift` `Tab` | -| Expand/Collapse toggle list | `Cmd` `Option` `T` | `Ctrl` `Alt` `T` | -| Expand/Collapse all toggles | `Cmd` `Option` `Shift` `T` | `Ctrl` `Alt` `Shift` `T` | -| Open page from selected link/page block | `Cmd` `Enter` | `Ctrl` `Enter` | -| Delete selected block(s) | `Delete` or `Backspace` | `Delete` or `Backspace` | -| Turn block into a page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` | -| Move block(s) to another page | `Cmd` `Option` `Shift` `M` | `Ctrl` `Alt` `Shift` `M` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :-------------------------------------- | :------------------------- | :------------------------- | +| Duplicate selected block(s) | `Cmd` `D` | `Ctrl` `D` | +| Move selected block(s) up/down | `Cmd` `Shift` `Up`/`Down` | `Ctrl` `Shift` `Up`/`Down` | +| Indent block (nest) | `Tab` | `Tab` | +| Un-indent block | `Shift` `Tab` | `Shift` `Tab` | +| Expand/Collapse toggle list | `Cmd` `Option` `T` | `Ctrl` `Alt` `T` | +| Expand/Collapse all toggles | `Cmd` `Option` `Shift` `T` | `Ctrl` `Alt` `Shift` `T` | +| Open page from selected link/page block | `Cmd` `Enter` | `Ctrl` `Enter` | +| Delete selected block(s) | `Delete` or `Backspace` | `Delete` or `Backspace` | +| Turn block into a page | `Cmd` `Option` `9` | `Ctrl` `Alt` `9` | +| Move block(s) to another page | `Cmd` `Option` `Shift` `M` | `Ctrl` `Alt` `Shift` `M` | + {.show-header .shortcuts} --- @@ -147,24 +149,29 @@ Select the block(s) first, then use the shortcut: # Comments & Mentions {.cols-2} ### Comments -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------- | :------------------------ | :----------------------- | -| Add comment to selection | `Cmd` `Shift` `M` | `Ctrl` `Shift` `M` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :----------------------- | :---------------- | :--------------------- | +| Add comment to selection | `Cmd` `Shift` `M` | `Ctrl` `Shift` `M` | + {.show-header .shortcuts} ### Mentions & Links (Type in block) -* `@` + person's name: Mention a person -* `@` + page title: Mention/link a page -* `[[` + page title: Link another page -* `+` + page title: Link another page (alternative) -* `@` + date (e.g., `@today`, `@next tuesday`, `@1/15`): Add a date mention -* `@remind` + date + time (optional): Set a reminder + +- `@` + person's name: Mention a person +- `@` + page title: Mention/link a page +- `[[` + page title: Link another page +- `+` + page title: Link another page (alternative) +- `@` + date (e.g., `@today`, `@next tuesday`, `@1/15`): Add a date mention +- `@remind` + date + time (optional): Set a reminder ### Emoji -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :------------------------- | :------------------------ | :----------------------- | -| Emoji Picker (System) | `Cmd` `Ctrl` `Space` | `Win` `.` or `Win` `;` | -| Emoji Picker (Notion) | `:` + emoji name + `:` | `:` + emoji name + `:` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :-------------------- | :--------------------- | :--------------------- | +| Emoji Picker (System) | `Cmd` `Ctrl` `Space` | `Win` `.` or `Win` `;` | +| Emoji Picker (Notion) | `:` + emoji name + `:` | `:` + emoji name + `:` | + {.show-header .shortcuts} --- @@ -172,26 +179,29 @@ Select the block(s) first, then use the shortcut: # Database Shortcuts {.cols-2} ### Navigation & Selection -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :---------------------------------------- | :--------------------- | :---------------------- | -| Select row above/below | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` | -| Open selected page(s) | `Cmd` `Enter` | `Ctrl` `Enter` | -| Edit property | `Enter` | `Enter` | -| Move to cell above/below | `Shift` `Enter` | `Shift` `Enter` | -| Move to cell left/right | `Tab` / `Shift` `Tab` | `Tab` / `Shift` `Tab` | -| Select column | `Cmd` `Shift` `K` | `Ctrl` `Shift` `K` | -| Select multiple cards/rows | `Shift` `Click` | `Shift` `Click` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :------------------------- | :-------------------- | :--------------------- | +| Select row above/below | `Shift` `Up`/`Down` | `Shift` `Up`/`Down` | +| Open selected page(s) | `Cmd` `Enter` | `Ctrl` `Enter` | +| Edit property | `Enter` | `Enter` | +| Move to cell above/below | `Shift` `Enter` | `Shift` `Enter` | +| Move to cell left/right | `Tab` / `Shift` `Tab` | `Tab` / `Shift` `Tab` | +| Select column | `Cmd` `Shift` `K` | `Ctrl` `Shift` `K` | +| Select multiple cards/rows | `Shift` `Click` | `Shift` `Click` | + {.show-header .shortcuts} ### Other -| Action | Mac Shortcut | Windows/Linux Shortcut | -| :---------------------------------------- | :--------------------- | :---------------------- | -| Quick Find within Database | `Cmd` `Shift` `P` | `Ctrl` `Shift` `P` | + +| Action | Mac Shortcut | Windows/Linux Shortcut | +| :------------------------- | :---------------- | :--------------------- | +| Quick Find within Database | `Cmd` `Shift` `P` | `Ctrl` `Shift` `P` | + {.show-header .shortcuts} --- ## Also see -- [Official Notion Keyboard Shortcuts](https://www.notion.so/help/keyboard-shortcuts) - _(notion.so)_ +- [Official Notion Keyboard Shortcuts](https://www.notion.so/help/keyboard-shortcuts) _(notion.so)_ diff --git a/source/_posts/ocaml.md b/source/_posts/ocaml.md index 38884a1..1259116 100644 --- a/source/_posts/ocaml.md +++ b/source/_posts/ocaml.md @@ -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 ``` diff --git a/source/_posts/pandas.md b/source/_posts/pandas.md index 096f749..a3da0e2 100644 --- a/source/_posts/pandas.md +++ b/source/_posts/pandas.md @@ -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 | diff --git a/source/_posts/perl.md b/source/_posts/perl.md index 8484d92..a74686e 100644 --- a/source/_posts/perl.md +++ b/source/_posts/perl.md @@ -1,1122 +1,1122 @@ ---- -title: Perl -date: 2024-05-22 9:03:44 -background: bg-[#31719d] -tags: -categories: - - Programming -intro: | - The perl quick reference cheat sheet that aims at providing help on writing basic syntax and methods. -plugins: - - copyCode - - runCode ---- - -## Getting Started - -### Unix and Linux Installation - -- Open a Web browser and go to https://www.perl.org/get.html. - -- Follow the link to download zipped source code available for Unix/Linux. - -- Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. - -```shell -$tar -xzf perl-5.x.y.tar.gz -$cd perl-5.x.y -$./Configure -de -$make -$make test -$make install -``` - -### Windows Installation - -- Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com - -- Download either 32bit or 64bit version of installation. - -- Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard, which is - really easy to use. Just accept the default settings, wait until the installation is finished, and you're ready to - roll! - -### Macintosh Installation - -- Open a Web browser and go to https://www.perl.org/get.html. - -- Follow the link to download zipped source code available for Mac OS X. - -- Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt - -```shell -$tar -xzf perl-5.x.y.tar.gz -$cd perl-5.x.y -$./Configure -de -$make -$make test -$make install -``` - -### Running Perl - -```shell -# Unix/Linux -$perl -e -# Windows/DOS -C:>perl -e -``` - -### Available command line options - -| Option | Description | -| :-----------: | ----------------------------------: | -| -d[:debugger] | Runs program under debugger | -| -Idirectory | Specifies @INC/#include directory | -| -T | Enables tainting warnings | -| -U | Allows unsafe operations | -| -w | Enables many useful warnings | -| -W | Enables all warnings | -| -X | Disables all warnings | -| -e program | Runs Perl script sent in as program | -| file | Runs Perl script from a given file | - -### Script from the Command-line - -```shell -# Unix/Linux -$perl script.pl -# Windows/DOS -C:>perl script.pl -``` - -### First Perl Program - -```shell -$perl -e 'print "Hello World\n"' - -# #!/usr/bin/perl - -# This will print "Hello, World" -print "Hello, world\n"; -$chmod 0755 hello.pl -$./hello.pl - -``` - -### Comments in Perl - -```perl -# This is a comment in perl -=begin comment -This is all part of multiline comment. -You can use as many lines as you like -These comments will be ignored by the -compiler until the next =cut is encountered. -=cut - -``` - -### Whitespaces in Perl - -```perl -#!/usr/bin/perl - -# This would print with a line break in the middle -print "Hello - world\n"; -#output -#Hello -# world - -``` - -### Single and Double Quotes in Perl - -```perl -#!/usr/bin/perl - -print "Hello, world\n"; -print 'Hello, world\n'; - -#Hello, world -#Hello, world\n$ -``` - -## Datatypes - -### Creating Variables - -```perl -$age = 25; # An integer assignment -$name = "John Paul"; # A string -$salary = 1445.50; # A floating point -``` - -### Scalar Variables - -```perl -#!/usr/bin/perl - -$age = 25; # An integer assignment -$name = "John Paul"; # A string -$salary = 1445.50; # A floating point - -print "Age = $age\n"; -print "Name = $name\n"; -print "Salary = $salary\n"; -``` - -### Array Variables - -```perl -#!/usr/bin/perl - -@ages = (25, 30, 40); -@names = ("John Paul", "Lisa", "Kumar"); - -print "\$ages[0] = $ages[0]\n"; -print "\$ages[1] = $ages[1]\n"; -print "\$ages[2] = $ages[2]\n"; -print "\$names[0] = $names[0]\n"; -print "\$names[1] = $names[1]\n"; -print "\$names[2] = $names[2]\n"; -``` - -### Hash Variables - -```perl -#!/usr/bin/perl - -%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); - -print "\$data{'John Paul'} = $data{'John Paul'}\n"; -print "\$data{'Lisa'} = $data{'Lisa'}\n"; -print "\$data{'Kumar'} = $data{'Kumar'}\n"; -``` - -### Variable Context - -```perl -#!/usr/bin/perl - -@names = ('John Paul', 'Lisa', 'Kumar'); - -@copy = @names; -$size = @names; - -print "Given names are : @copy\n"; -print "Number of names are : $size\n"; -``` - -### Numeric Scalars - -```perl -#!/usr/bin/perl - -$integer = 200; -$negative = -300; -$floating = 200.340; -$bigfloat = -1.2E-23; - -# 377 octal, same as 255 decimal -$octal = 0377; - -# FF hex, also 255 decimal -$hexa = 0xff; - -print "integer = $integer\n"; -print "negative = $negative\n"; -print "floating = $floating\n"; -print "bigfloat = $bigfloat\n"; -print "octal = $octal\n"; -print "hexa = $hexa\n"; -``` - -### String Scalars - -```perl -#!/usr/bin/perl - -$var = "This is string scalar!"; -$quote = 'I m inside single quote - $var'; -$double = "This is inside single quote - $var"; - -$escape = "This example of escape -\tHello, World!"; - -print "var = $var\n"; -print "quote = $quote\n"; -print "double = $double\n"; -print "escape = $escape\n"; -``` - -### Scalar Operations - -```perl -#!/usr/bin/perl - -$str = "hello" . "world"; # Concatenates strings. -$num = 5 + 10; # adds two numbers. -$mul = 4 * 5; # multiplies two numbers. -$mix = $str . $num; # concatenates string and number. - -print "str = $str\n"; -print "num = $num\n"; -print "mul = $mul\n"; -print "mix = $mix\n"; -``` - -### Multiline Strings - -```perl -#!/usr/bin/perl - -$string = 'This is -a multiline -string'; - -print "$string\n"; - -########################## -print < 45, 'Lisa' => 30, 'Kumar' => 40); - -print "$data{'John Paul'}\n"; -print "$data{'Lisa'}\n"; -print "$data{'Kumar'}\n"; -``` - -### Extracting Slices - -```perl -#!/uer/bin/perl - - -%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); - -@array = @data{-JohnPaul, -Lisa}; - -print "Array : @array\n"; -``` - -### Extracting Keys and Values - -```perl -#!/usr/bin/perl - -%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); - -@names = keys %data; - -print "$names[0]\n"; -print "$names[1]\n"; -print "$names[2]\n"; -``` - -### Getting Hash Size - -```perl -#!/usr/bin/perl - -%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); - -@keys = keys %data; -$size = @keys; -print "1 - Hash size: is $size\n"; - -@values = values %data; -$size = @values; -print "2 - Hash size: is $size\n"; -``` - -### Add and Remove Elements in Hashes - -```perl -#!/usr/bin/perl - -%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); -@keys = keys %data; -$size = @keys; -print "1 - Hash size: is $size\n"; - -# adding an element to the hash; -$data{'Ali'} = 55; -@keys = keys %data; -$size = @keys; -print "2 - Hash size: is $size\n"; - -# delete the same element from the hash; -delete $data{'Ali'}; -@keys = keys %data; -$size = @keys; -print "3 - Hash size: is $size\n"; -``` - -## Control Flow - -### if-else - -```perl -#!/usr/bin/perl - -# Perl program to illustrate -# Decision-Making statements - -$a = 10; -$b = 15; - -# if condition to check -# for even number -if($a % 2 == 0 ) -{ - printf "Even Number"; -} - -# if-else condition to check -# for even number or odd number -if($b % 2 == 0 ) -{ - printf "\nEven Number"; -} -else -{ - printf "\nOdd Number"; -} -``` - -### The ? : Operator - -```perl -#!/usr/local/bin/perl - -$name = "Ali"; -$age = 10; - -$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen"; - -print "$name is - $status\n"; -``` - -### for loop - -```perl -#!/usr/bin/perl - -# Perl program to illustrate -# the use of for Loop - -# for loop -print("For Loop:\n"); -for ($count = 1 ; $count <= 3 ; $count++) -{ - print "GeeksForGeeks\n" -} -``` - -### foreach loop - -```perl -#!/usr/bin/perl - -# Perl program to illustrate -# the use of foreach Loop - -# Array -@data = ('GEEKS', 4, 'GEEKS'); - -# foreach loop -print("For-each Loop:\n"); -foreach $word (@data) -{ - print ("$word "); -} - -``` - -### while and do-while - -```perl -#!/usr/bin/perl - -# Perl program to illustrate -# the use of foreach Loop - -# while loop -$count = 3; - -print("While Loop:\n"); -while ($count >= 0) -{ - $count = $count - 1; - print "GeeksForGeeks\n"; -} - -print("\ndo...while Loop:\n"); -$a = 10; - -# do..While loop -do { - - print "$a "; - $a = $a - 1; -} while ($a > 0); - -``` - -## Object Oriented Programming - -### Class and object - -```perl -#!/usr/bin/perl - -# Perl Program for creation of a -# Class and its object -use strict; -use warnings; - -package student; - -# constructor -sub student_data -{ - - # shift will take package name 'student' - # and assign it to variable 'class' - my $class_name = shift; - my $self = { - 'StudentFirstName' => shift, - 'StudentLastName' => shift - }; - # Using bless function - bless $self, $class_name; - - # returning object from constructor - return $self; -} - -# Object creating and constructor calling -my $Data = student_data student("Geeks", "forGeeks"); - -# Printing the data -print "$Data->{'StudentFirstName'}\n"; -print "$Data->{'StudentLastName'}\n"; - -``` - -### Subroutines - -```perl -#!/usr/bin/perl - -# Perl Program to demonstrate the -# subroutine declaration and calling - -# defining subroutine -sub ask_user -{ - print "Hello Geeks!\n"; -} - -# calling subroutine -# you can also use -# &ask_user(); -ask_user(); -``` - -### Modules and Packages - -```perl -#!/usr/bin/perl - -# Using the Package 'Calculator' -use Calculator; - -print "Enter two numbers to multiply"; - -# Defining values to the variables -$a = 5; -$b = 10; - -# Subroutine call -Calculator::multiplication($a, $b); - -print "\nEnter two numbers to divide"; - -# Defining values to the variables -$a = 45; -$b = 5; - -# Subroutine call -Calculator::division($a, $b); -``` - -### References - -```perl -# Perl program to illustrate the -# Referencing and Dereferencing -# of an Array - -# defining an array -@array = ('1', '2', '3'); - -# making an reference to an array variable -$reference_array = \@array; - -# Dereferencing -# printing the value stored -# at $reference_array by prefixing -# @ as it is a array reference -print @$reference_array; -``` - -### Regular Expression - -```perl -# Perl program to demonstrate -# the m// and =~ operators - -# Actual String -$a = "GEEKSFORGEEKS"; - -# Prints match found if -# its found in $a -if ($a =~ m[GEEKS]) -{ - print "Match Found\n"; -} - -# Prints match not found -# if its not found in $a -else -{ - print "Match Not Found\n"; -} -``` - -### File Handling - -```perl -# Opening the file -open(fh, "GFG2.txt") or die "File '$filename' can't be opened"; - -# Reading First line from the file -$firstline = ; -print "$firstline\n"; -``` - -### File Test Operators - -```perl -#!/usr/bin/perl - -# Using predefined modules -use warnings; -use strict; - -# Providing path of file to a variable -my $filename = 'C:\Users\GeeksForGeeks\GFG.txt'; - -# Checking for the file existence -if(-e $filename) -{ - - # If File exists - print("File $filename exists\n"); -} - -else -{ - - # If File doesn't exists - print("File $filename does not exists\n"); -} -``` - -### Working with Excel Files - -```perl -#!/usr/bin/perl -use Excel::Writer::XLSX; - -my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' ); -my $Excelsheet = $Excelbook->add_worksheet(); - -$Excelsheet->write( "A1", "Hello!" ); -$Excelsheet->write( "A2", "GeeksForGeeks" ); -$Excelsheet->write( "B1", "Next_Column" ); - -$Excelbook->close; -``` - -### Reading from an Excel File: - -```perl -use 5.016; -use Spreadsheet::Read qw(ReadData); -my $book_data = ReadData (‘new_excel.xlsx'); -say 'A2: ' . $book_data->[1]{A2}; - -``` - -### Error Handling - -```perl -if(open(DATA, $file)) { - ... -} else { - die "Error: Couldn't open the file - $!" -} -#example -open(DATA, $file) || die "Error: Couldn't open the file $!"; -## example -unless(chdir("/etc")) { - die "Error: Can't change directory - $!"; -} -##example -print(exists($hash{value}) ? 'There' : 'Missing',"\n"); - -``` - -### The warn Function - -```perl -chdir('/etc') or warn "Can't change directory"; - - -``` - -### The die function - -```perl -chdir('/etc') or die "Can't change directory"; - -``` - -### Errors within Modules - -```perl -package T; - -require Exporter; -@ISA = qw/Exporter/; -@EXPORT = qw/function/; -use Carp; - -sub function { - warn "Error in module!"; -} -1; -#use T; -#function(); -# all below code call the funtion - -``` - -### The carp Function - -```perl -package T; - -require Exporter; -@ISA = qw/Exporter/; -@EXPORT = qw/function/; -use Carp; - -sub function { - carp "Error in module!"; -} -1; - -``` - -### The cluck Function - -```perl -package T; - -require Exporter; -@ISA = qw/Exporter/; -@EXPORT = qw/function/; -use Carp qw(cluck); - -sub function { - cluck "Error in module!"; -} -1; - -``` - -### The croak Function - -```perl -package T; - -require Exporter; -@ISA = qw/Exporter/; -@EXPORT = qw/function/; -use Carp; - -sub function { - croak "Error in module!"; -} -1; - -``` - -### The confess Function - -```perl -package T; - -require Exporter; -@ISA = qw/Exporter/; -@EXPORT = qw/function/; -use Carp; - -sub function { - confess "Error in module!"; -} -1; -``` - -## Date and Time - -### Current Date and Time - -```perl -#!/usr/local/bin/perl - -@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); -@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); - -($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); -print "$mday $months[$mon] $days[$wday]\n"; -#or -#!/usr/local/bin/perl - -$datestring = localtime(); -print "Local date and time $datestring\n"; -``` - -### GMT Time - -```perl -#!/usr/local/bin/perl - -$datestring = gmtime(); -print "GMT date and time $datestring\n"; -``` - -### Format Date and Time - -```perl -#!/usr/local/bin/perl - -($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); - -printf("Time Format - HH:MM:SS\n"); -printf("%02d:%02d:%02d", $hour, $min, $sec); -``` - -### Epoch time - -```perl -#!/usr/local/bin/perl - -$epoc = time(); - -print "Number of seconds since Jan 1, 1970 - $epoc\n"; -#or -#!/usr/local/bin/perl - -$datestring = localtime(); -print "Current date and time $datestring\n"; - -$epoc = time(); -$epoc = $epoc - 24 * 60 * 60; # one day before of current date. - -$datestring = localtime($epoc); -print "Yesterday's date and time $datestring\n"; -``` - -### POSIX Function strftime() - -| Specifier | Replaced by | Example | -| :-------- | :------------------------------------------------------------------------------------------------------------- | :----------------------: | -| %a | Abbreviated weekday name | Thu | -| %A | Full weekday name | Thursday | -| %b | Abbreviated month name | Aug | -| %B | Full month name | August | -| %c | Date and time representation | Thu Aug 23 14:55:02 2001 | -| %C | Year divided by 100 and truncated to integer (00-99) | 20 | -| %d | Day of the month, zero-padded (01-31) | 23 | -| %D | Short MM/DD/YY date, equivalent to %m/%d/%y | 08/23/01 | -| %e | Day of the month, space-padded ( 1-31) | 23 | -| %F | Short YYYY-MM-DD date, equivalent to %Y-%m-%d | 2001-08-23 | -| %g | Week-based year, last two digits (00-99) | 01 | -| %G | Week-based year | 2001 | -| %h | Abbreviated month name (same as %b) | Aug | -| %H | Hour in 24h format (00-23) | 14 | -| %I | Hour in 12h format (01-12) | 02 | -| %j | Day of the year (001-366) | 235 | -| %m | Month as a decimal number (01-12) | 08 | -| %M | Minute (00-59) | 55 | -| %n | New-line character ('\n') | -| %p | AM or PM designation | PM | -| %r | 12-hour clock time | 02:55:02 pm | -| %R | 24-hour HH:MM time, equivalent to %H:%M | 14:55 | -| %S | Second (00-61) | 02 | -| %t | Horizontal-tab character ('\t') | -| %T | ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S | 14:55 | -| %u | ISO 8601 weekday as number with Monday as 1 (1-7) | 4 | -| %U | Week number with the first Sunday as the first day of week one (00-53) | 33 | -| %V | ISO 8601 week number (00-53) | 34 | -| %w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 | -| %W | Week number with the first Monday as the first day of week one (00-53) | 34 | -| %x | Date representation | 08/23/01 | -| %X | Time representation | 14:55:02 | -| %y | Year, last two digits (00-99) | 01 | -| %Y | Year | 2001 | -| %z | ISO 8601 offset from UTC in timezone (1 minute = 1, 1 hour = 100)If timezone cannot be termined, no characters | +100 | -| %Z | Timezone name or abbreviation If timezone cannot be termined, no characters | CDT | -| %% | A % sign | % | - -```perl -#!/usr/local/bin/perl -use POSIX qw(strftime); - -$datestring = strftime "%a %b %e %H:%M:%S %Y", localtime; -printf("date and time - $datestring\n"); - -# or for GMT formatted appropriately for your locale: -$datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime; -printf("date and time - $datestring\n"); -``` +--- +title: Perl +date: 2024-05-22 9:03:44 +background: bg-[#31719d] +tags: +categories: + - Programming +intro: | + The perl quick reference cheat sheet that aims at providing help on writing basic syntax and methods. +plugins: + - copyCode + - runCode +--- + +## Getting Started + +### Unix and Linux Installation + +- Open a Web browser and go to https://www.perl.org/get.html. + +- Follow the link to download zipped source code available for Unix/Linux. + +- Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt. + +```shell +$tar -xzf perl-5.x.y.tar.gz +$cd perl-5.x.y +$./Configure -de +$make +$make test +$make install +``` + +### Windows Installation + +- Follow the link for the Strawberry Perl installation on Windows http://strawberryperl.com + +- Download either 32bit or 64bit version of installation. + +- Run the downloaded file by double-clicking it in Windows Explorer. This brings up the Perl install wizard, which is + really easy to use. Just accept the default settings, wait until the installation is finished, and you're ready to + roll! + +### Macintosh Installation + +- Open a Web browser and go to https://www.perl.org/get.html. + +- Follow the link to download zipped source code available for Mac OS X. + +- Download perl-5.x.y.tar.gz file and issue the following commands at $ prompt + +```shell +$tar -xzf perl-5.x.y.tar.gz +$cd perl-5.x.y +$./Configure -de +$make +$make test +$make install +``` + +### Running Perl + +```shell +# Unix/Linux +$perl -e +# Windows/DOS +C:>perl -e +``` + +### Available command line options + +| Option | Description | +| :-----------: | ----------------------------------: | +| -d[:debugger] | Runs program under debugger | +| -Idirectory | Specifies @INC/#include directory | +| -T | Enables tainting warnings | +| -U | Allows unsafe operations | +| -w | Enables many useful warnings | +| -W | Enables all warnings | +| -X | Disables all warnings | +| -e program | Runs Perl script sent in as program | +| file | Runs Perl script from a given file | + +### Script from the Command-line + +```shell +# Unix/Linux +$perl script.pl +# Windows/DOS +C:>perl script.pl +``` + +### First Perl Program + +```shell +$perl -e 'print "Hello World\n"' + +# #!/usr/bin/perl + +# This will print "Hello, World" +print "Hello, world\n"; +$chmod 0755 hello.pl +$./hello.pl + +``` + +### Comments in Perl + +```perl +# This is a comment in perl +=begin comment +This is all part of multiline comment. +You can use as many lines as you like +These comments will be ignored by the +compiler until the next =cut is encountered. +=cut + +``` + +### Whitespaces in Perl + +```perl +#!/usr/bin/perl + +# This would print with a line break in the middle +print "Hello + world\n"; +#output +#Hello +# world + +``` + +### Single and Double Quotes in Perl + +```perl +#!/usr/bin/perl + +print "Hello, world\n"; +print 'Hello, world\n'; + +#Hello, world +#Hello, world\n$ +``` + +## Datatypes + +### Creating Variables + +```perl +$age = 25; # An integer assignment +$name = "John Paul"; # A string +$salary = 1445.50; # A floating point +``` + +### Scalar Variables + +```perl +#!/usr/bin/perl + +$age = 25; # An integer assignment +$name = "John Paul"; # A string +$salary = 1445.50; # A floating point + +print "Age = $age\n"; +print "Name = $name\n"; +print "Salary = $salary\n"; +``` + +### Array Variables + +```perl +#!/usr/bin/perl + +@ages = (25, 30, 40); +@names = ("John Paul", "Lisa", "Kumar"); + +print "\$ages[0] = $ages[0]\n"; +print "\$ages[1] = $ages[1]\n"; +print "\$ages[2] = $ages[2]\n"; +print "\$names[0] = $names[0]\n"; +print "\$names[1] = $names[1]\n"; +print "\$names[2] = $names[2]\n"; +``` + +### Hash Variables + +```perl +#!/usr/bin/perl + +%data = ('John Paul', 45, 'Lisa', 30, 'Kumar', 40); + +print "\$data{'John Paul'} = $data{'John Paul'}\n"; +print "\$data{'Lisa'} = $data{'Lisa'}\n"; +print "\$data{'Kumar'} = $data{'Kumar'}\n"; +``` + +### Variable Context + +```perl +#!/usr/bin/perl + +@names = ('John Paul', 'Lisa', 'Kumar'); + +@copy = @names; +$size = @names; + +print "Given names are : @copy\n"; +print "Number of names are : $size\n"; +``` + +### Numeric Scalars + +```perl +#!/usr/bin/perl + +$integer = 200; +$negative = -300; +$floating = 200.340; +$bigfloat = -1.2E-23; + +# 377 octal, same as 255 decimal +$octal = 0377; + +# FF hex, also 255 decimal +$hexa = 0xff; + +print "integer = $integer\n"; +print "negative = $negative\n"; +print "floating = $floating\n"; +print "bigfloat = $bigfloat\n"; +print "octal = $octal\n"; +print "hexa = $hexa\n"; +``` + +### String Scalars + +```perl +#!/usr/bin/perl + +$var = "This is string scalar!"; +$quote = 'I m inside single quote - $var'; +$double = "This is inside single quote - $var"; + +$escape = "This example of escape -\tHello, World!"; + +print "var = $var\n"; +print "quote = $quote\n"; +print "double = $double\n"; +print "escape = $escape\n"; +``` + +### Scalar Operations + +```perl +#!/usr/bin/perl + +$str = "hello" . "world"; # Concatenates strings. +$num = 5 + 10; # adds two numbers. +$mul = 4 * 5; # multiplies two numbers. +$mix = $str . $num; # concatenates string and number. + +print "str = $str\n"; +print "num = $num\n"; +print "mul = $mul\n"; +print "mix = $mix\n"; +``` + +### Multiline Strings + +```perl +#!/usr/bin/perl + +$string = 'This is +a multiline +string'; + +print "$string\n"; + +########################## +print < 45, 'Lisa' => 30, 'Kumar' => 40); + +print "$data{'John Paul'}\n"; +print "$data{'Lisa'}\n"; +print "$data{'Kumar'}\n"; +``` + +### Extracting Slices + +```perl +#!/uer/bin/perl + + +%data = (-JohnPaul => 45, -Lisa => 30, -Kumar => 40); + +@array = @data{-JohnPaul, -Lisa}; + +print "Array : @array\n"; +``` + +### Extracting Keys and Values + +```perl +#!/usr/bin/perl + +%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); + +@names = keys %data; + +print "$names[0]\n"; +print "$names[1]\n"; +print "$names[2]\n"; +``` + +### Getting Hash Size + +```perl +#!/usr/bin/perl + +%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); + +@keys = keys %data; +$size = @keys; +print "1 - Hash size: is $size\n"; + +@values = values %data; +$size = @values; +print "2 - Hash size: is $size\n"; +``` + +### Add and Remove Elements in Hashes + +```perl +#!/usr/bin/perl + +%data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); +@keys = keys %data; +$size = @keys; +print "1 - Hash size: is $size\n"; + +# adding an element to the hash; +$data{'Ali'} = 55; +@keys = keys %data; +$size = @keys; +print "2 - Hash size: is $size\n"; + +# delete the same element from the hash; +delete $data{'Ali'}; +@keys = keys %data; +$size = @keys; +print "3 - Hash size: is $size\n"; +``` + +## Control Flow + +### if-else + +```perl +#!/usr/bin/perl + +# Perl program to illustrate +# Decision-Making statements + +$a = 10; +$b = 15; + +# if condition to check +# for even number +if($a % 2 == 0 ) +{ + printf "Even Number"; +} + +# if-else condition to check +# for even number or odd number +if($b % 2 == 0 ) +{ + printf "\nEven Number"; +} +else +{ + printf "\nOdd Number"; +} +``` + +### The ? : Operator + +```perl +#!/usr/local/bin/perl + +$name = "Ali"; +$age = 10; + +$status = ($age > 60 )? "A senior citizen" : "Not a senior citizen"; + +print "$name is - $status\n"; +``` + +### for loop + +```perl +#!/usr/bin/perl + +# Perl program to illustrate +# the use of for Loop + +# for loop +print("For Loop:\n"); +for ($count = 1 ; $count <= 3 ; $count++) +{ + print "GeeksForGeeks\n" +} +``` + +### foreach loop + +```perl +#!/usr/bin/perl + +# Perl program to illustrate +# the use of foreach Loop + +# Array +@data = ('GEEKS', 4, 'GEEKS'); + +# foreach loop +print("For-each Loop:\n"); +foreach $word (@data) +{ + print ("$word "); +} + +``` + +### while and do-while + +```perl +#!/usr/bin/perl + +# Perl program to illustrate +# the use of foreach Loop + +# while loop +$count = 3; + +print("While Loop:\n"); +while ($count >= 0) +{ + $count = $count - 1; + print "GeeksForGeeks\n"; +} + +print("\ndo...while Loop:\n"); +$a = 10; + +# do..While loop +do { + + print "$a "; + $a = $a - 1; +} while ($a > 0); + +``` + +## Object Oriented Programming + +### Class and object + +```perl +#!/usr/bin/perl + +# Perl Program for creation of a +# Class and its object +use strict; +use warnings; + +package student; + +# constructor +sub student_data +{ + + # shift will take package name 'student' + # and assign it to variable 'class' + my $class_name = shift; + my $self = { + 'StudentFirstName' => shift, + 'StudentLastName' => shift + }; + # Using bless function + bless $self, $class_name; + + # returning object from constructor + return $self; +} + +# Object creating and constructor calling +my $Data = student_data student("Geeks", "forGeeks"); + +# Printing the data +print "$Data->{'StudentFirstName'}\n"; +print "$Data->{'StudentLastName'}\n"; + +``` + +### Subroutines + +```perl +#!/usr/bin/perl + +# Perl Program to demonstrate the +# subroutine declaration and calling + +# defining subroutine +sub ask_user +{ + print "Hello Geeks!\n"; +} + +# calling subroutine +# you can also use +# &ask_user(); +ask_user(); +``` + +### Modules and Packages + +```perl +#!/usr/bin/perl + +# Using the Package 'Calculator' +use Calculator; + +print "Enter two numbers to multiply"; + +# Defining values to the variables +$a = 5; +$b = 10; + +# Subroutine call +Calculator::multiplication($a, $b); + +print "\nEnter two numbers to divide"; + +# Defining values to the variables +$a = 45; +$b = 5; + +# Subroutine call +Calculator::division($a, $b); +``` + +### References + +```perl +# Perl program to illustrate the +# Referencing and Dereferencing +# of an Array + +# defining an array +@array = ('1', '2', '3'); + +# making an reference to an array variable +$reference_array = \@array; + +# Dereferencing +# printing the value stored +# at $reference_array by prefixing +# @ as it is a array reference +print @$reference_array; +``` + +### Regular Expression + +```perl +# Perl program to demonstrate +# the m// and =~ operators + +# Actual String +$a = "GEEKSFORGEEKS"; + +# Prints match found if +# its found in $a +if ($a =~ m[GEEKS]) +{ + print "Match Found\n"; +} + +# Prints match not found +# if its not found in $a +else +{ + print "Match Not Found\n"; +} +``` + +### File Handling + +```perl +# Opening the file +open(fh, "GFG2.txt") or die "File '$filename' can't be opened"; + +# Reading First line from the file +$firstline = ; +print "$firstline\n"; +``` + +### File Test Operators + +```perl +#!/usr/bin/perl + +# Using predefined modules +use warnings; +use strict; + +# Providing path of file to a variable +my $filename = 'C:\Users\GeeksForGeeks\GFG.txt'; + +# Checking for the file existence +if(-e $filename) +{ + + # If File exists + print("File $filename exists\n"); +} + +else +{ + + # If File doesn't exists + print("File $filename does not exists\n"); +} +``` + +### Working with Excel Files + +```perl +#!/usr/bin/perl +use Excel::Writer::XLSX; + +my $Excelbook = Excel::Writer::XLSX->new( 'GFG_Sample.xlsx' ); +my $Excelsheet = $Excelbook->add_worksheet(); + +$Excelsheet->write( "A1", "Hello!" ); +$Excelsheet->write( "A2", "GeeksForGeeks" ); +$Excelsheet->write( "B1", "Next_Column" ); + +$Excelbook->close; +``` + +### Reading from an Excel File: + +```perl +use 5.016; +use Spreadsheet::Read qw(ReadData); +my $book_data = ReadData (‘new_excel.xlsx'); +say 'A2: ' . $book_data->[1]{A2}; + +``` + +### Error Handling + +```perl +if(open(DATA, $file)) { + ... +} else { + die "Error: Couldn't open the file - $!" +} +#example +open(DATA, $file) || die "Error: Couldn't open the file $!"; +## example +unless(chdir("/etc")) { + die "Error: Can't change directory - $!"; +} +##example +print(exists($hash{value}) ? 'There' : 'Missing',"\n"); + +``` + +### The warn Function + +```perl +chdir('/etc') or warn "Can't change directory"; + + +``` + +### The die function + +```perl +chdir('/etc') or die "Can't change directory"; + +``` + +### Errors within Modules + +```perl +package T; + +require Exporter; +@ISA = qw/Exporter/; +@EXPORT = qw/function/; +use Carp; + +sub function { + warn "Error in module!"; +} +1; +#use T; +#function(); +# all below code call the funtion + +``` + +### The carp Function + +```perl +package T; + +require Exporter; +@ISA = qw/Exporter/; +@EXPORT = qw/function/; +use Carp; + +sub function { + carp "Error in module!"; +} +1; + +``` + +### The cluck Function + +```perl +package T; + +require Exporter; +@ISA = qw/Exporter/; +@EXPORT = qw/function/; +use Carp qw(cluck); + +sub function { + cluck "Error in module!"; +} +1; + +``` + +### The croak Function + +```perl +package T; + +require Exporter; +@ISA = qw/Exporter/; +@EXPORT = qw/function/; +use Carp; + +sub function { + croak "Error in module!"; +} +1; + +``` + +### The confess Function + +```perl +package T; + +require Exporter; +@ISA = qw/Exporter/; +@EXPORT = qw/function/; +use Carp; + +sub function { + confess "Error in module!"; +} +1; +``` + +## Date and Time + +### Current Date and Time + +```perl +#!/usr/local/bin/perl + +@months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ); +@days = qw(Sun Mon Tue Wed Thu Fri Sat Sun); + +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); +print "$mday $months[$mon] $days[$wday]\n"; +#or +#!/usr/local/bin/perl + +$datestring = localtime(); +print "Local date and time $datestring\n"; +``` + +### GMT Time + +```perl +#!/usr/local/bin/perl + +$datestring = gmtime(); +print "GMT date and time $datestring\n"; +``` + +### Format Date and Time + +```perl +#!/usr/local/bin/perl + +($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(); + +printf("Time Format - HH:MM:SS\n"); +printf("%02d:%02d:%02d", $hour, $min, $sec); +``` + +### Epoch time + +```perl +#!/usr/local/bin/perl + +$epoc = time(); + +print "Number of seconds since Jan 1, 1970 - $epoc\n"; +#or +#!/usr/local/bin/perl + +$datestring = localtime(); +print "Current date and time $datestring\n"; + +$epoc = time(); +$epoc = $epoc - 24 * 60 * 60; # one day before of current date. + +$datestring = localtime($epoc); +print "Yesterday's date and time $datestring\n"; +``` + +### POSIX Function strftime() + +| Specifier | Replaced by | Example | +| :-------- | :------------------------------------------------------------------------------------------------------------- | :----------------------: | +| %a | Abbreviated weekday name | Thu | +| %A | Full weekday name | Thursday | +| %b | Abbreviated month name | Aug | +| %B | Full month name | August | +| %c | Date and time representation | Thu Aug 23 14:55:02 2001 | +| %C | Year divided by 100 and truncated to integer (00-99) | 20 | +| %d | Day of the month, zero-padded (01-31) | 23 | +| %D | Short MM/DD/YY date, equivalent to %m/%d/%y | 08/23/01 | +| %e | Day of the month, space-padded ( 1-31) | 23 | +| %F | Short YYYY-MM-DD date, equivalent to %Y-%m-%d | 2001-08-23 | +| %g | Week-based year, last two digits (00-99) | 01 | +| %G | Week-based year | 2001 | +| %h | Abbreviated month name (same as %b) | Aug | +| %H | Hour in 24h format (00-23) | 14 | +| %I | Hour in 12h format (01-12) | 02 | +| %j | Day of the year (001-366) | 235 | +| %m | Month as a decimal number (01-12) | 08 | +| %M | Minute (00-59) | 55 | +| %n | New-line character ('\n') | +| %p | AM or PM designation | PM | +| %r | 12-hour clock time | 02:55:02 pm | +| %R | 24-hour HH:MM time, equivalent to %H:%M | 14:55 | +| %S | Second (00-61) | 02 | +| %t | Horizontal-tab character ('\t') | +| %T | ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S | 14:55 | +| %u | ISO 8601 weekday as number with Monday as 1 (1-7) | 4 | +| %U | Week number with the first Sunday as the first day of week one (00-53) | 33 | +| %V | ISO 8601 week number (00-53) | 34 | +| %w | Weekday as a decimal number with Sunday as 0 (0-6) | 4 | +| %W | Week number with the first Monday as the first day of week one (00-53) | 34 | +| %x | Date representation | 08/23/01 | +| %X | Time representation | 14:55:02 | +| %y | Year, last two digits (00-99) | 01 | +| %Y | Year | 2001 | +| %z | ISO 8601 offset from UTC in timezone (1 minute = 1, 1 hour = 100)If timezone cannot be termined, no characters | +100 | +| %Z | Timezone name or abbreviation If timezone cannot be termined, no characters | CDT | +| %% | A % sign | % | + +```perl +#!/usr/local/bin/perl +use POSIX qw(strftime); + +$datestring = strftime "%a %b %e %H:%M:%S %Y", localtime; +printf("date and time - $datestring\n"); + +# or for GMT formatted appropriately for your locale: +$datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime; +printf("date and time - $datestring\n"); +``` diff --git a/source/_posts/quickref.md b/source/_posts/quickref.md index 531d546..3bc559b 100644 --- a/source/_posts/quickref.md +++ b/source/_posts/quickref.md @@ -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 --- diff --git a/source/_posts/react.md b/source/_posts/react.md index de2acb1..17cdb8b 100644 --- a/source/_posts/react.md +++ b/source/_posts/react.md @@ -29,13 +29,13 @@ let emptyHeading =

; ### JSX Expressions ```javascript -let name = "Josh Perez"; +let name = 'Josh Perez'; let element =

Hello, {name}

; function fullName(firstName, lastName) { - return firstName + " " + lastName; + return firstName + ' ' + lastName; } -let element =

Hello, {fullName("Julie", "Johnson")}

; +let element =

Hello, {fullName('Julie', 'Johnson')}

; ``` ### 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 () => ; ### 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 (
    @@ -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 (
      @@ -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
      Julie Johnson
      ; @@ -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() {

      Count: {count}

      - + @@ -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 (
      - + - + -