From 7b487ced37f22d2f56a7167e8b8f757728bbca3b Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 19:01:47 +0000 Subject: [PATCH 01/19] Update consolidated snippets --- public/consolidated/c.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 1588cd69..a9258611 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] } From be204bba5211dd9721cc5bbe213e279345e41f67 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 00:35:41 -0500 Subject: [PATCH 02/19] Add frontend view to show frameworks --- public/consolidated/_index.json | 7 +- public/consolidated/cpp.json | 18 +++- public/consolidated/css.json | 63 ++++++++++++ public/consolidated/java.json | 18 ++++ public/consolidated/javascript--react.json | 18 ++++ public/icons/javascript--react.svg | 9 ++ .../javascript/[react]/basics/hello-world.md | 21 ++++ snippets/javascript/[react]/icon.svg | 9 ++ src/components/LanguageSelector.tsx | 59 ++++++++---- src/components/SublanguageSelector.tsx | 95 +++++++++++++++++++ src/contexts/AppContext.tsx | 2 +- src/hooks/useCategories.ts | 2 +- src/hooks/useKeyboardNavigation.ts | 7 +- src/hooks/useSnippets.ts | 2 +- src/styles/main.css | 27 ++++++ src/types/index.ts | 3 +- 16 files changed, 335 insertions(+), 25 deletions(-) create mode 100644 public/consolidated/javascript--react.json create mode 100644 public/icons/javascript--react.svg create mode 100644 snippets/javascript/[react]/basics/hello-world.md create mode 100644 snippets/javascript/[react]/icon.svg create mode 100644 src/components/SublanguageSelector.tsx diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json index c5640dd3..7b5c17c9 100644 --- a/public/consolidated/_index.json +++ b/public/consolidated/_index.json @@ -37,7 +37,12 @@ { "name": "JAVASCRIPT", "icon": "/icons/javascript.svg", - "subLanguages": [] + "subLanguages": [ + { + "name": "REACT", + "icon": "/icons/javascript--react.svg" + } + ] }, { "name": "PYTHON", diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index fd38de1b..c121a725 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -33,7 +33,6 @@ ] }, { - "categoryName": "Debuging", "name": "Debugging", "snippets": [ { @@ -50,6 +49,23 @@ } ] }, + { + "name": "Debuging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "name": "Math And Numbers", "snippets": [ diff --git a/public/consolidated/css.json b/public/consolidated/css.json index 359088c9..0f19249e 100644 --- a/public/consolidated/css.json +++ b/public/consolidated/css.json @@ -1,4 +1,67 @@ [ + { + "name": "Animations", + "snippets": [ + { + "title": "Blink Animation", + "description": "Adds an infinite blinking animation to an element", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "blink", + "infinite" + ], + "contributors": [], + "code": ".blink {\n animation: blink 1s linear infinite;\n}\n\n@keyframes blink{\n 0%{\n opacity: 0;\n }\n 50%{\n opacity: 1;\n }\n 100%{\n opacity: 0;\n }\n}\n" + }, + { + "title": "Pulse Animation", + "description": "Adds a smooth pulsing animation with opacity and scale effects", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "pulse", + "pulse-scale" + ], + "contributors": [], + "code": ".pulse {\n animation: pulse 2s ease-in-out infinite;\n}\n\n@keyframes pulse {\n 0% {\n opacity: 0.5;\n transform: scale(1);\n }\n 50% {\n opacity: 1;\n transform: scale(1.05);\n }\n 100% {\n opacity: 0.5;\n transform: scale(1);\n }\n}\n" + }, + { + "title": "Shake Animation", + "description": "Adds a shake animation ( commonly used to mark invalid fields )", + "author": "AlsoKnownAs-Ax", + "tags": [ + "shake", + "shake-horizontal" + ], + "contributors": [], + "code": ".shake {\n animation: shake .5s ease-in-out;\n}\n\n@keyframes shake {\n 0%, 100% {\n transform: translateX(0);\n }\n 25% {\n transform: translateX(-10px);\n }\n 50% {\n transform: translateX(10px);\n }\n 75% {\n transform: translateX(-10px);\n }\n}\n" + }, + { + "title": "Slide-in Animation", + "description": "Adds a slide-in from the right side of the screen", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "slide-in", + "slide-right" + ], + "contributors": [], + "code": ".slide-in {\n animation: slide-in 1s ease-in-out;\n}\n\n@keyframes slide-in {\n from {\n scale: 300% 1;\n translate: 150vw 0;\n }\n\n to {\n scale: 100% 1;\n translate: 0 0;\n }\n}\n" + }, + { + "title": "Typewriter Animation", + "description": "Adds a typewriter animation + blinking cursor", + "author": "AlsoKnownAs-Ax", + "tags": [ + "blinking", + "typewriter" + ], + "contributors": [], + "code": "
\n
\n

Typerwriter Animation

\n
\n
\n```\n\n```css\n .typewriter{\n display: flex;\n justify-content: center;\n }\n\n .typewriter p {\n overflow: hidden;\n font-size: 1.5rem;\n font-family: monospace;\n border-right: 1px solid;\n margin-inline: auto;\n white-space: nowrap;\n /* The cursor will inherit the text's color by default */\n /* border-color: red */ \n /* Steps: number of chars (better to set directly in js)*/\n animation: typing 3s steps(21) forwards,\n blink 1s step-end infinite;\n }\n\n @keyframes typing{\n from{\n width: 0%\n }\n to{\n width: 100%\n }\n }\n\n @keyframes blink{\n 50%{\n border-color: transparent;\n }\n }\n" + } + ] + }, { "name": "Buttons", "snippets": [ diff --git a/public/consolidated/java.json b/public/consolidated/java.json index 3a36e17d..f972f5e0 100644 --- a/public/consolidated/java.json +++ b/public/consolidated/java.json @@ -1,4 +1,22 @@ [ + { + "name": "Array Manipulation", + "snippets": [ + { + "title": "Zip Two Lists", + "description": "Zips two lists into a list of paired elements, combining corresponding elements from both lists.", + "author": "davidanukam", + "tags": [ + "lists", + "zip", + "stream-api", + "collections" + ], + "contributors": [], + "code": "import java.util.*; // Importing utility classes for List and Arrays\nimport java.util.stream.IntStream; // Importing IntStream for range and mapping\nimport java.util.stream.Collectors; // Importing Collectors for collecting stream results\n\npublic List> zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList arr1 = Arrays.asList(\"a\", \"b\", \"c\");\nList arr2 = Arrays.asList(1, 2, 3);\nList> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n" + } + ] + }, { "name": "Basics", "snippets": [ diff --git a/public/consolidated/javascript--react.json b/public/consolidated/javascript--react.json new file mode 100644 index 00000000..2530b7b6 --- /dev/null +++ b/public/consolidated/javascript--react.json @@ -0,0 +1,18 @@ +[ + { + "name": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Show Hello World on the page.", + "author": "ACR1209", + "tags": [ + "printing", + "hello-world" + ], + "contributors": [], + "code": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => {\n return (\n
\n

Hello, World!

\n
\n );\n};\n\nReactDOM.render(, document.getElementById('root'));\n" + } + ] + } +] \ No newline at end of file diff --git a/public/icons/javascript--react.svg b/public/icons/javascript--react.svg new file mode 100644 index 00000000..b9025712 --- /dev/null +++ b/public/icons/javascript--react.svg @@ -0,0 +1,9 @@ + + React Logo + + + + + + + \ No newline at end of file diff --git a/snippets/javascript/[react]/basics/hello-world.md b/snippets/javascript/[react]/basics/hello-world.md new file mode 100644 index 00000000..5cdaba09 --- /dev/null +++ b/snippets/javascript/[react]/basics/hello-world.md @@ -0,0 +1,21 @@ +--- +title: Hello, World! +description: Show Hello World on the page. +author: ACR1209 +tags: printing,hello-world +--- + +```tsx +import React from 'react'; +import ReactDOM from 'react-dom'; + +const App = () => { + return ( +
+

Hello, World!

+
+ ); +}; + +ReactDOM.render(, document.getElementById('root')); +``` diff --git a/snippets/javascript/[react]/icon.svg b/snippets/javascript/[react]/icon.svg new file mode 100644 index 00000000..b9025712 --- /dev/null +++ b/snippets/javascript/[react]/icon.svg @@ -0,0 +1,9 @@ + + React Logo + + + + + + + \ No newline at end of file diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index d8e208fe..4b7ccdcf 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -1,18 +1,28 @@ -import { useRef, useEffect, useState } from "react"; +import { useRef, useEffect, useState, useMemo } from "react"; import { useAppContext } from "@contexts/AppContext"; import { useKeyboardNavigation } from "@hooks/useKeyboardNavigation"; import { useLanguages } from "@hooks/useLanguages"; import { LanguageType } from "@types"; +import SubLanguageSelector from "./SublanguageSelector"; // Inspired by https://blog.logrocket.com/creating-custom-select-dropdown-css/ const LanguageSelector = () => { const { language, setLanguage } = useAppContext(); const { fetchedLanguages, loading, error } = useLanguages(); + const allLanguages = useMemo(() => + fetchedLanguages.flatMap((lang) => + lang.subLanguages.length > 0 + ? [lang, ...lang.subLanguages.map((subLang) => ({ ...subLang, mainLanguage: lang, subLanguages: [] }))] + : [lang] + ), + [fetchedLanguages] + ); const dropdownRef = useRef(null); const [isOpen, setIsOpen] = useState(false); + const [openedLanguages, setOpenedLanguages] = useState([]); const handleSelect = (selected: LanguageType) => { setLanguage(selected); @@ -21,8 +31,9 @@ const LanguageSelector = () => { const { focusedIndex, handleKeyDown, resetFocus, focusFirst } = useKeyboardNavigation({ - items: fetchedLanguages, - isOpen, + items: allLanguages, + isOpen, + openedLanguages, onSelect: handleSelect, onClose: () => setIsOpen(false), }); @@ -38,6 +49,14 @@ const LanguageSelector = () => { }, 0); }; + const handleOpenedSublanguage = (open: boolean, openedLang: LanguageType) => { + if (open) { + setOpenedLanguages((prev) => [...prev, openedLang]); + } else { + setOpenedLanguages((prev) => prev.filter((lang) => lang.name !== openedLang.name)); + } + }; + const toggleDropdown = () => { setIsOpen((prev) => { if (!prev) setTimeout(focusFirst, 0); @@ -91,21 +110,25 @@ const LanguageSelector = () => { tabIndex={-1} > {fetchedLanguages.map((lang, index) => ( -
  • handleSelect(lang)} - className={`selector__item ${ - language.name === lang.name ? "selected" : "" - } ${focusedIndex === index ? "focused" : ""}`} - aria-selected={language.name === lang.name} - > - -
  • + lang.subLanguages.length > 0 ? ( + { setIsOpen(false)}} onDropdownChange={handleOpenedSublanguage}/> + ) : ( +
  • handleSelect(lang)} + className={`selector__item ${ + language.name === lang.name ? "selected" : "" + } ${focusedIndex === index ? "focused" : ""}`} + aria-selected={language.name === lang.name} + > + +
  • + ) ))} )} diff --git a/src/components/SublanguageSelector.tsx b/src/components/SublanguageSelector.tsx new file mode 100644 index 00000000..e1d43f4e --- /dev/null +++ b/src/components/SublanguageSelector.tsx @@ -0,0 +1,95 @@ +import { useAppContext } from "@contexts/AppContext"; +import { LanguageType } from "@types"; +import { useEffect, useState } from "react"; + +type SubLanguageSelectorProps = { + mainLanguage: LanguageType; + afterSelect: () => void; + onDropdownChange: (open: boolean, openedLang: LanguageType) => void; +}; + +const SubLanguageSelector = ({ + mainLanguage, + afterSelect, + onDropdownChange +}: SubLanguageSelectorProps) => { + const { language, setLanguage } = useAppContext(); + const [isOpen, setIsOpen] = useState( + mainLanguage.subLanguages.some( + (subLanguage) => language.name === subLanguage.name + ) + ); + + const handleSelect = (selected: LanguageType) => { + setLanguage(selected); + setIsOpen(false); + afterSelect(); + }; + + useEffect(() => { + onDropdownChange(isOpen, mainLanguage); + }, [isOpen]); + + return ( + <> +
  • setLanguage(mainLanguage)} + > + +
  • + + {isOpen && ( + <> + {mainLanguage.subLanguages.map((subLanguage) => ( +
  • { + handleSelect({ + ...subLanguage, + mainLanguage: mainLanguage, + subLanguages: [], + }); + setIsOpen(false); + }} + > + +
  • + ))} + + )} + + ); +}; + +export default SubLanguageSelector; diff --git a/src/contexts/AppContext.tsx b/src/contexts/AppContext.tsx index 30dd366e..ac7b51ce 100644 --- a/src/contexts/AppContext.tsx +++ b/src/contexts/AppContext.tsx @@ -6,7 +6,7 @@ import { AppState, LanguageType, SnippetType } from "@types"; const defaultLanguage: LanguageType = { name: "JAVASCRIPT", icon: "/icons/javascript.svg", - subIndexes: [], + subLanguages: [], }; // TODO: add custom loading and error handling diff --git a/src/hooks/useCategories.ts b/src/hooks/useCategories.ts index 4bd00685..d1d4a631 100644 --- a/src/hooks/useCategories.ts +++ b/src/hooks/useCategories.ts @@ -9,7 +9,7 @@ import { useFetch } from "./useFetch"; export const useCategories = () => { const { language } = useAppContext(); const { data, loading, error } = useFetch( - `/consolidated/${slugify(language.name)}.json` + `/consolidated/${language.mainLanguage ? `${slugify(language.mainLanguage.name)}--${slugify(language.name)}` : slugify(language.name)}.json` ); const fetchedCategories = useMemo(() => { diff --git a/src/hooks/useKeyboardNavigation.ts b/src/hooks/useKeyboardNavigation.ts index 46bda82c..a445af25 100644 --- a/src/hooks/useKeyboardNavigation.ts +++ b/src/hooks/useKeyboardNavigation.ts @@ -7,11 +7,13 @@ interface UseKeyboardNavigationProps { isOpen: boolean; onSelect: (item: LanguageType) => void; onClose: () => void; + openedLanguages: LanguageType[]; } const keyboardEventKeys = { arrowDown: "ArrowDown", arrowUp: "ArrowUp", + arrowRight: "ArrowRight", enter: "Enter", escape: "Escape", } as const; @@ -22,6 +24,7 @@ type KeyboardEventKeys = export const useKeyboardNavigation = ({ items, isOpen, + openedLanguages, onSelect, onClose, }: UseKeyboardNavigationProps) => { @@ -42,9 +45,11 @@ export const useKeyboardNavigation = ({ case "ArrowUp": setFocusedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1)); break; + case "ArrowRight": + break; case "Enter": if (focusedIndex >= 0) { - onSelect(items[focusedIndex]); + onSelect(items.filter((item) => !item.mainLanguage || openedLanguages.includes(item.mainLanguage))[focusedIndex]); } break; case "Escape": diff --git a/src/hooks/useSnippets.ts b/src/hooks/useSnippets.ts index a9d85499..f0d30800 100644 --- a/src/hooks/useSnippets.ts +++ b/src/hooks/useSnippets.ts @@ -7,7 +7,7 @@ import { useFetch } from "./useFetch"; export const useSnippets = () => { const { language, category } = useAppContext(); const { data, loading, error } = useFetch( - `/consolidated/${slugify(language.name)}.json` + `/consolidated/${language.mainLanguage ? `${slugify(language.mainLanguage.name)}--${slugify(language.name)}` : slugify(language.name)}.json` ); const fetchedSnippets = data diff --git a/src/styles/main.css b/src/styles/main.css index cd4ea727..80328239 100644 --- a/src/styles/main.css +++ b/src/styles/main.css @@ -403,6 +403,33 @@ abbr { border-radius: var(--br-md); } +.sublanguage__item { + margin-left: 1.5rem; +} + +.sublanguage__button{ + margin-left: auto; + display: flex; + align-items: center; + justify-content: center; + padding: 1rem 0.5rem; + border: 0; + background-color: transparent; +} + +.sublanguage__arrow { + border-left: 7px solid transparent; + border-right: 7px solid transparent; + border-top: 7px solid var(--clr-text-primary); /* [1] */ + transition: transform 100ms ease; + cursor: pointer; +} + +[aria-expanded="true"] .sublanguage__arrow { + transform: rotate(180deg); +} + + .selector__item label { width: 100%; padding: 0.25em 0.75em; diff --git a/src/types/index.ts b/src/types/index.ts index 9f6c4fb2..14f8885f 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,7 +1,8 @@ export type LanguageType = { name: string; icon: string; - subIndexes: { + mainLanguage?: LanguageType; + subLanguages: { name: string; icon: string; }[]; From f934e321e9e9774bfa4b9012b954c264aa8012b5 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 00:36:15 -0500 Subject: [PATCH 03/19] Changes to code style --- cspell-dict.txt | 1 + src/components/LanguageSelector.tsx | 40 +++++++++++++++++++------- src/components/SublanguageSelector.tsx | 7 +++-- src/hooks/useKeyboardNavigation.ts | 8 +++++- 4 files changed, 41 insertions(+), 15 deletions(-) diff --git a/cspell-dict.txt b/cspell-dict.txt index 4d39d3eb..c39e06a8 100644 --- a/cspell-dict.txt +++ b/cspell-dict.txt @@ -1,2 +1,3 @@ quicksnip slugifyed +sublanguage \ No newline at end of file diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index 4b7ccdcf..fd039099 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -4,6 +4,7 @@ import { useAppContext } from "@contexts/AppContext"; import { useKeyboardNavigation } from "@hooks/useKeyboardNavigation"; import { useLanguages } from "@hooks/useLanguages"; import { LanguageType } from "@types"; + import SubLanguageSelector from "./SublanguageSelector"; // Inspired by https://blog.logrocket.com/creating-custom-select-dropdown-css/ @@ -11,12 +12,20 @@ import SubLanguageSelector from "./SublanguageSelector"; const LanguageSelector = () => { const { language, setLanguage } = useAppContext(); const { fetchedLanguages, loading, error } = useLanguages(); - const allLanguages = useMemo(() => - fetchedLanguages.flatMap((lang) => - lang.subLanguages.length > 0 - ? [lang, ...lang.subLanguages.map((subLang) => ({ ...subLang, mainLanguage: lang, subLanguages: [] }))] - : [lang] - ), + const allLanguages = useMemo( + () => + fetchedLanguages.flatMap((lang) => + lang.subLanguages.length > 0 + ? [ + lang, + ...lang.subLanguages.map((subLang) => ({ + ...subLang, + mainLanguage: lang, + subLanguages: [], + })), + ] + : [lang] + ), [fetchedLanguages] ); @@ -32,7 +41,7 @@ const LanguageSelector = () => { const { focusedIndex, handleKeyDown, resetFocus, focusFirst } = useKeyboardNavigation({ items: allLanguages, - isOpen, + isOpen, openedLanguages, onSelect: handleSelect, onClose: () => setIsOpen(false), @@ -53,7 +62,9 @@ const LanguageSelector = () => { if (open) { setOpenedLanguages((prev) => [...prev, openedLang]); } else { - setOpenedLanguages((prev) => prev.filter((lang) => lang.name !== openedLang.name)); + setOpenedLanguages((prev) => + prev.filter((lang) => lang.name !== openedLang.name) + ); } }; @@ -109,9 +120,16 @@ const LanguageSelector = () => { onKeyDown={handleKeyDown} tabIndex={-1} > - {fetchedLanguages.map((lang, index) => ( + {fetchedLanguages.map((lang, index) => lang.subLanguages.length > 0 ? ( - { setIsOpen(false)}} onDropdownChange={handleOpenedSublanguage}/> + { + setIsOpen(false); + }} + onDropdownChange={handleOpenedSublanguage} + /> ) : (
  • {
  • ) - ))} + )} )} diff --git a/src/components/SublanguageSelector.tsx b/src/components/SublanguageSelector.tsx index e1d43f4e..a5aa7db4 100644 --- a/src/components/SublanguageSelector.tsx +++ b/src/components/SublanguageSelector.tsx @@ -1,6 +1,7 @@ +import { useEffect, useState } from "react"; + import { useAppContext } from "@contexts/AppContext"; import { LanguageType } from "@types"; -import { useEffect, useState } from "react"; type SubLanguageSelectorProps = { mainLanguage: LanguageType; @@ -11,7 +12,7 @@ type SubLanguageSelectorProps = { const SubLanguageSelector = ({ mainLanguage, afterSelect, - onDropdownChange + onDropdownChange, }: SubLanguageSelectorProps) => { const { language, setLanguage } = useAppContext(); const [isOpen, setIsOpen] = useState( @@ -28,7 +29,7 @@ const SubLanguageSelector = ({ useEffect(() => { onDropdownChange(isOpen, mainLanguage); - }, [isOpen]); + }, [mainLanguage, onDropdownChange, isOpen]); return ( <> diff --git a/src/hooks/useKeyboardNavigation.ts b/src/hooks/useKeyboardNavigation.ts index a445af25..c793dcf6 100644 --- a/src/hooks/useKeyboardNavigation.ts +++ b/src/hooks/useKeyboardNavigation.ts @@ -49,7 +49,13 @@ export const useKeyboardNavigation = ({ break; case "Enter": if (focusedIndex >= 0) { - onSelect(items.filter((item) => !item.mainLanguage || openedLanguages.includes(item.mainLanguage))[focusedIndex]); + onSelect( + items.filter( + (item) => + !item.mainLanguage || + openedLanguages.includes(item.mainLanguage) + )[focusedIndex] + ); } break; case "Escape": From 4d6028f7d0afae3dc5447a7452bd59a0f92b95c2 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 01:07:46 -0500 Subject: [PATCH 04/19] Allow to open sublanguages with keyboard --- src/components/LanguageSelector.tsx | 13 ++++++++++--- src/components/SublanguageSelector.tsx | 13 ++++++------- src/hooks/useKeyboardNavigation.ts | 13 +++++++++++++ 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index fd039099..e988c3b2 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -36,6 +36,7 @@ const LanguageSelector = () => { const handleSelect = (selected: LanguageType) => { setLanguage(selected); setIsOpen(false); + setOpenedLanguages([]); }; const { focusedIndex, handleKeyDown, resetFocus, focusFirst } = @@ -43,6 +44,7 @@ const LanguageSelector = () => { items: allLanguages, isOpen, openedLanguages, + toggleDropdown: (openedLang) => handleToggleSublanguage(openedLang), onSelect: handleSelect, onClose: () => setIsOpen(false), }); @@ -58,8 +60,12 @@ const LanguageSelector = () => { }, 0); }; - const handleOpenedSublanguage = (open: boolean, openedLang: LanguageType) => { - if (open) { + const handleToggleSublanguage = (openedLang: LanguageType) => { + const isAlreadyOpened = openedLanguages.some( + (lang) => lang.name === openedLang.name + ); + + if (!isAlreadyOpened) { setOpenedLanguages((prev) => [...prev, openedLang]); } else { setOpenedLanguages((prev) => @@ -128,7 +134,8 @@ const LanguageSelector = () => { afterSelect={() => { setIsOpen(false); }} - onDropdownChange={handleOpenedSublanguage} + opened={openedLanguages.includes(lang)} + onDropdownToggle={handleToggleSublanguage} /> ) : (
  • void; - onDropdownChange: (open: boolean, openedLang: LanguageType) => void; + onDropdownToggle: (openedLang: LanguageType) => void; + opened: boolean; }; const SubLanguageSelector = ({ mainLanguage, afterSelect, - onDropdownChange, + onDropdownToggle, + opened, }: SubLanguageSelectorProps) => { const { language, setLanguage } = useAppContext(); const [isOpen, setIsOpen] = useState( @@ -24,13 +26,10 @@ const SubLanguageSelector = ({ const handleSelect = (selected: LanguageType) => { setLanguage(selected); setIsOpen(false); + onDropdownToggle(mainLanguage); afterSelect(); }; - useEffect(() => { - onDropdownChange(isOpen, mainLanguage); - }, [mainLanguage, onDropdownChange, isOpen]); - return ( <>
  • - {isOpen && ( + {(opened || isOpen) && ( <> {mainLanguage.subLanguages.map((subLanguage) => (
    - {(opened || isOpen) && ( + {opened && ( <> {mainLanguage.subLanguages.map((subLanguage) => (
  • void; onClose: () => void; + toggleDropdown: (openedLang: LanguageType) => void; openedLanguages: LanguageType[]; } @@ -27,6 +28,7 @@ export const useKeyboardNavigation = ({ openedLanguages, onSelect, onClose, + toggleDropdown, }: UseKeyboardNavigationProps) => { const [focusedIndex, setFocusedIndex] = useState(-1); @@ -46,6 +48,17 @@ export const useKeyboardNavigation = ({ setFocusedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1)); break; case "ArrowRight": + if (focusedIndex >= 0) { + const selectedItem = items.filter( + (item) => + !item.mainLanguage || + openedLanguages.includes(item.mainLanguage) + )[focusedIndex]; + + if (selectedItem.subLanguages.length > 0) { + toggleDropdown(selectedItem); + } + } break; case "Enter": if (focusedIndex >= 0) { From 75f586a9f00724430f56473d875eecc5f0b7cf0e Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 01:08:08 -0500 Subject: [PATCH 05/19] Changes to code styles --- src/components/LanguageSelector.tsx | 2 +- .../{SublanguageSelector.tsx => SubLanguageSelector.tsx} | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename src/components/{SublanguageSelector.tsx => SubLanguageSelector.tsx} (98%) diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index e988c3b2..57145ccb 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -5,7 +5,7 @@ import { useKeyboardNavigation } from "@hooks/useKeyboardNavigation"; import { useLanguages } from "@hooks/useLanguages"; import { LanguageType } from "@types"; -import SubLanguageSelector from "./SublanguageSelector"; +import SubLanguageSelector from "./SubLanguageSelector"; // Inspired by https://blog.logrocket.com/creating-custom-select-dropdown-css/ diff --git a/src/components/SublanguageSelector.tsx b/src/components/SubLanguageSelector.tsx similarity index 98% rename from src/components/SublanguageSelector.tsx rename to src/components/SubLanguageSelector.tsx index 049f8e93..0f18a835 100644 --- a/src/components/SublanguageSelector.tsx +++ b/src/components/SubLanguageSelector.tsx @@ -1,4 +1,4 @@ -import { useEffect, useState } from "react"; +import { useState } from "react"; import { useAppContext } from "@contexts/AppContext"; import { LanguageType } from "@types"; From 3e7bb65cd93fd090d33fae152e27dd5607cd8c45 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 01:18:09 -0500 Subject: [PATCH 06/19] Add FastAPI framework with basics section --- .../python/[fastapi]/basics/hello-world.md | 21 +++++++++++++++++++ snippets/python/[fastapi]/icon.svg | 1 + 2 files changed, 22 insertions(+) create mode 100644 snippets/python/[fastapi]/basics/hello-world.md create mode 100644 snippets/python/[fastapi]/icon.svg diff --git a/snippets/python/[fastapi]/basics/hello-world.md b/snippets/python/[fastapi]/basics/hello-world.md new file mode 100644 index 00000000..69afb9cf --- /dev/null +++ b/snippets/python/[fastapi]/basics/hello-world.md @@ -0,0 +1,21 @@ +--- +title: Hello, World! +description: Returns Hello, World! when it recives a GET request made to the root endpoint. +author: ACR1209 +tags: printing,hello-world,web,api +--- + +```py +from typing import Union +from fastapi import FastAPI + +app = FastAPI() + + +@app.get("/") +def read_root(): + return {"msg": "Hello, World!"} + +# Usage: +# -> Go to http://127.0.0.1:8000/ and you'll see {"msg", "Hello, World!"} +``` diff --git a/snippets/python/[fastapi]/icon.svg b/snippets/python/[fastapi]/icon.svg new file mode 100644 index 00000000..a7be660d --- /dev/null +++ b/snippets/python/[fastapi]/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file From 9805157e2eeb245846153208e0e5c4cd101a3653 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Mon, 6 Jan 2025 06:18:47 +0000 Subject: [PATCH 07/19] Update consolidated snippets --- public/consolidated/_index.json | 7 ++++++- public/consolidated/python--fastapi.json | 20 ++++++++++++++++++++ public/icons/python--fastapi.svg | 1 + 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 public/consolidated/python--fastapi.json create mode 100644 public/icons/python--fastapi.svg diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json index 7b5c17c9..e57286a1 100644 --- a/public/consolidated/_index.json +++ b/public/consolidated/_index.json @@ -47,7 +47,12 @@ { "name": "PYTHON", "icon": "/icons/python.svg", - "subLanguages": [] + "subLanguages": [ + { + "name": "FASTAPI", + "icon": "/icons/python--fastapi.svg" + } + ] }, { "name": "REGEX", diff --git a/public/consolidated/python--fastapi.json b/public/consolidated/python--fastapi.json new file mode 100644 index 00000000..2614a56e --- /dev/null +++ b/public/consolidated/python--fastapi.json @@ -0,0 +1,20 @@ +[ + { + "name": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Returns Hello, World! when it recives a GET request made to the root endpoint.", + "author": "ACR1209", + "tags": [ + "printing", + "hello-world", + "web", + "api" + ], + "contributors": [], + "code": "from typing import Union\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"msg\": \"Hello, World!\"}\n\n# Usage: \n# -> Go to http://127.0.0.1:8000/ and you'll see {\"msg\", \"Hello, World!\"}\n" + } + ] + } +] \ No newline at end of file diff --git a/public/icons/python--fastapi.svg b/public/icons/python--fastapi.svg new file mode 100644 index 00000000..a7be660d --- /dev/null +++ b/public/icons/python--fastapi.svg @@ -0,0 +1 @@ + \ No newline at end of file From b5a2e941dd016cdff80231eb0f9894322b592f9d Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Mon, 6 Jan 2025 01:30:00 -0500 Subject: [PATCH 08/19] Bugfix where the initial opened state is not considered --- src/components/LanguageSelector.tsx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index 57145ccb..f39a192a 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -88,6 +88,12 @@ const LanguageSelector = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [isOpen]); + useEffect(() => { + if (language.mainLanguage) { + handleToggleSublanguage(language.mainLanguage); + } + }, [language]); + useEffect(() => { if (isOpen && focusedIndex >= 0) { const element = document.querySelector( From 4aa4a469ff45586cc45e73285fbcfdbf27487484 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 19:29:40 +0100 Subject: [PATCH 09/19] Merge of main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix cuz description was messed up Consolidate for the Prime Number Description Updated combinations.md Removing end of line prettier config as it's not needed anymore snippets: hex to rgb color snippets: rgb to hsl color snippets: hsl to rgb color refactor: optimized rgb to hsl color fix: hex to rgb color Added Sorting and Search Algorithms to C (#199) Update consolidated snippets Updating to use vite HMR to consolidate snippets Changing status check in plugin Snippets c++ (#103) * [C++] added snippet * [C++] added 3 snippets for string. * Added missing chrono header * fixed tags * fixed exemple needing std=c++20 * Fixed Usage to accommodate to new guidelines * Fixed all tags + type * Revert "Fixed all tags + type" This reverts commit aebefdeb709bcf2cb4efea5062b266548d9fd0b1. * Fixed type and all tags * fixed gh check failing * Update consolidated snippets * Update consolidated snippets * Update consolidated snippets * Revert "Merge remote-tracking branch 'origin/main' into snippets-c++" This reverts commit 4708bd931837bef88af62d7d7414ed304a4317ab, reversing changes made to a959e9503bef55728a97282c68aefb0fa0f3681b. * Update consolidated snippets --------- Co-authored-by: GitHub Action java date-time formatting snippets added duration formatting removed language from tags enforced formatting requirements Renamed and improved python truncate snippet Renamed from `truncate-string.py` to `truncate.py` Replaced "..." with ellipses("…") to only use one character Implemented toggle for the `suffix` "…" on string with default of `True` Update reverse-string.md Added type hints Renamed `remove-specific-characters.md` to `remove-characters.md` Improved accuracy of Description for `convert-string-to-ascii` for better functional representation Renamed `convert-string-to-ascii.md` to `convert-string-to-unicode.md` Replaced ASCII with Unicode Kept `ascii` tag as it is a subset of unicode and to minimize search errors Fixed issue https://github.com/dostonnabotov/quicksnip/issues/192 Update CONTRIBUTING.md Added a `not` on line 68 in "Does that snippet have a real, and practical use case ?" to prevent useless snippets from being acceptable and useful snippets from being denied. Rectified loss of attribution recovered old attribution in the python snippet`truncate` to axorax and added the contributors tag. truncate.md reconformed to PEP 8 removed Tab Update truncate.md Replaced "…" with "..." Updated Description to match Update reverse-string.md followed change request Miner miner mods refactor 1 (#2) 2nd integration feat: update snippet button and modal increased the size of the snippet modal, added a bit more responsitivity too removed the gray filter on the snippet button feat: add minimum width to modal Added bash as a new language, also added a category and a snippet (#204) * Added a bash as a new language, also added a category and a snippet * Fixed the snippet to make it more like a snippet * Deleted public/consolidated/ and put code into a function * Deleted public/consolidated/ Update calculate-compound-interest.md Create Calculate-factorial.md Rename Calculate-factorial.md to calculate-factorial.md Update calculate-factorial.md Delete snippets/python/math-and-numbers/calculate-factorial.md refacto(css/pulse-animation): add 'alternate' and edit keyframes Added Rust category and a snippet [Snippet] [Fix] Added a bash snippet (#219) * removed bash icon * fix comments of a script * added kill_prev snippet * followed guidelines Remove language tag in guidelines math - remap function math - remap function to most languages remap to linearMapping, args renamed fix all mistakes,typos added array manipulation snippets removed unnecessary snippets --- .github/workflows/consolidate-snippets.yml | 39 - .gitignore | 4 + .prettierrc | 1 - CONTRIBUTING.md | 10 +- README.md | 2 +- package-lock.json | 16 + package.json | 1 + public/consolidated/_index.json | 82 -- public/consolidated/c.json | 45 - public/consolidated/cpp.json | 112 --- public/consolidated/csharp.json | 115 --- public/consolidated/css.json | 239 ----- public/consolidated/haskell.json | 224 ----- public/consolidated/html.json | 35 - public/consolidated/java.json | 37 - public/consolidated/javascript.json | 872 ------------------ public/consolidated/python.json | 713 -------------- public/consolidated/regex.json | 74 -- public/consolidated/ruby.json | 222 ----- public/consolidated/rust.json | 61 -- public/consolidated/scss.json | 228 ----- public/consolidated/typescript.json | 19 - public/icons/c.svg | 15 - public/icons/cpp.svg | 10 - public/icons/csharp.svg | 10 - public/icons/css.svg | 6 - public/icons/haskell.svg | 6 - public/icons/html.svg | 8 - public/icons/java.svg | 12 - public/icons/javascript.svg | 6 - public/icons/python.svg | 21 - public/icons/regex.svg | 6 - public/icons/ruby.svg | 139 --- public/icons/rust.svg | 9 - public/icons/scss.svg | 5 - public/icons/typescript.svg | 8 - snippets/bash/icon.svg | 1 + .../bash/system/kill-previous-instances.md | 20 + .../bash/system/system-resource-monitor.md | 22 + .../mathematical-functions/linear-mapping.md | 18 + snippets/c/search/binary-search.md | 36 + snippets/c/search/linear-search.md | 25 + snippets/c/sorting/bubble-sort.md | 27 + snippets/c/sorting/insertion-sort.md | 30 + snippets/c/sorting/merge-sort.md | 71 ++ snippets/c/sorting/quick-sort.md | 47 + snippets/c/sorting/selection-sort.md | 33 + .../cpp/array-manipulation/filter-vector.md | 25 + .../array-manipulation/transform-vector.md | 26 + .../file-handling/find-files-recursively.md | 57 ++ snippets/cpp/file-handling/find-files.md | 57 ++ .../cpp/file-handling/list-directories.md | 37 + snippets/cpp/string-manipulation/filter.md | 25 + .../cpp/string-manipulation/palindrome.md | 26 + .../cpp/string-manipulation/reverse-string.md | 2 +- snippets/cpp/string-manipulation/transform.md | 25 + snippets/css/animations/pulse-animation.md | 11 +- .../array-manipulation/remove-duplicates.md | 22 + .../date-time-formatting-american.md | 32 + .../date-time-formatting-european.md | 32 + ...ration-formatting-hours-minutes-seconds.md | 33 + .../duration-formatting-minutes-seconds.md | 28 + .../color-manipulation/hex-to-rgb-color.md | 28 + .../color-manipulation/hsl-to-rgb-color.md | 34 + .../color-manipulation/rgb-to-hsl-color.md | 37 + .../mathematical-functions/combinations.md | 31 + .../mathematical-functions/cross-product.md | 23 + .../mathematical-functions/dot-product.md | 19 + .../mathematical-functions/error-function.md | 21 + .../greatest-common-divisor.md | 2 +- .../least-common-multiple.md | 25 + .../mathematical-functions/linear-mapping.md | 17 + .../matrix-multiplication.md | 34 + .../mathematical-functions/modular-inverse.md | 33 + .../mathematical-functions/prime-number.md | 24 + .../calculate-compound-interest.md | 2 +- .../python/math-and-numbers/linear-mapping.md | 16 + .../convert-string-to-ascii.md | 14 - .../convert-string-to-unicode.md | 14 + ...fic-characters.md => remove-characters.md} | 2 +- .../string-manipulation/reverse-string.md | 2 +- .../string-manipulation/truncate-string.md | 14 - .../python/string-manipulation/truncate.md | 16 + snippets/rust/linux/get-desktop-enviroment.md | 44 + src/components/CodePreview.tsx | 2 +- src/components/SnippetModal.tsx | 48 +- src/styles/main.css | 29 +- utils/consolidateSnippets.js | 5 +- vite.config.ts | 29 +- 89 files changed, 1285 insertions(+), 3460 deletions(-) delete mode 100644 .github/workflows/consolidate-snippets.yml delete mode 100644 public/consolidated/_index.json delete mode 100644 public/consolidated/c.json delete mode 100644 public/consolidated/cpp.json delete mode 100644 public/consolidated/csharp.json delete mode 100644 public/consolidated/css.json delete mode 100644 public/consolidated/haskell.json delete mode 100644 public/consolidated/html.json delete mode 100644 public/consolidated/java.json delete mode 100644 public/consolidated/javascript.json delete mode 100644 public/consolidated/python.json delete mode 100644 public/consolidated/regex.json delete mode 100644 public/consolidated/ruby.json delete mode 100644 public/consolidated/rust.json delete mode 100644 public/consolidated/scss.json delete mode 100644 public/consolidated/typescript.json delete mode 100644 public/icons/c.svg delete mode 100644 public/icons/cpp.svg delete mode 100644 public/icons/csharp.svg delete mode 100644 public/icons/css.svg delete mode 100644 public/icons/haskell.svg delete mode 100644 public/icons/html.svg delete mode 100644 public/icons/java.svg delete mode 100644 public/icons/javascript.svg delete mode 100644 public/icons/python.svg delete mode 100644 public/icons/regex.svg delete mode 100644 public/icons/ruby.svg delete mode 100644 public/icons/rust.svg delete mode 100644 public/icons/scss.svg delete mode 100644 public/icons/typescript.svg create mode 100644 snippets/bash/icon.svg create mode 100644 snippets/bash/system/kill-previous-instances.md create mode 100644 snippets/bash/system/system-resource-monitor.md create mode 100644 snippets/c/mathematical-functions/linear-mapping.md create mode 100644 snippets/c/search/binary-search.md create mode 100644 snippets/c/search/linear-search.md create mode 100644 snippets/c/sorting/bubble-sort.md create mode 100644 snippets/c/sorting/insertion-sort.md create mode 100644 snippets/c/sorting/merge-sort.md create mode 100644 snippets/c/sorting/quick-sort.md create mode 100644 snippets/c/sorting/selection-sort.md create mode 100644 snippets/cpp/array-manipulation/filter-vector.md create mode 100644 snippets/cpp/array-manipulation/transform-vector.md create mode 100644 snippets/cpp/file-handling/find-files-recursively.md create mode 100644 snippets/cpp/file-handling/find-files.md create mode 100644 snippets/cpp/file-handling/list-directories.md create mode 100644 snippets/cpp/string-manipulation/filter.md create mode 100644 snippets/cpp/string-manipulation/palindrome.md create mode 100644 snippets/cpp/string-manipulation/transform.md create mode 100644 snippets/java/array-manipulation/remove-duplicates.md create mode 100644 snippets/java/date-time/date-time-formatting-american.md create mode 100644 snippets/java/date-time/date-time-formatting-european.md create mode 100644 snippets/java/date-time/duration-formatting-hours-minutes-seconds.md create mode 100644 snippets/java/date-time/duration-formatting-minutes-seconds.md create mode 100644 snippets/javascript/color-manipulation/hex-to-rgb-color.md create mode 100644 snippets/javascript/color-manipulation/hsl-to-rgb-color.md create mode 100644 snippets/javascript/color-manipulation/rgb-to-hsl-color.md create mode 100644 snippets/javascript/mathematical-functions/combinations.md create mode 100644 snippets/javascript/mathematical-functions/cross-product.md create mode 100644 snippets/javascript/mathematical-functions/dot-product.md create mode 100644 snippets/javascript/mathematical-functions/error-function.md create mode 100644 snippets/javascript/mathematical-functions/least-common-multiple.md create mode 100644 snippets/javascript/mathematical-functions/linear-mapping.md create mode 100644 snippets/javascript/mathematical-functions/matrix-multiplication.md create mode 100644 snippets/javascript/mathematical-functions/modular-inverse.md create mode 100644 snippets/javascript/mathematical-functions/prime-number.md create mode 100644 snippets/python/math-and-numbers/linear-mapping.md delete mode 100644 snippets/python/string-manipulation/convert-string-to-ascii.md create mode 100644 snippets/python/string-manipulation/convert-string-to-unicode.md rename snippets/python/string-manipulation/{remove-specific-characters.md => remove-characters.md} (88%) delete mode 100644 snippets/python/string-manipulation/truncate-string.md create mode 100644 snippets/python/string-manipulation/truncate.md create mode 100644 snippets/rust/linux/get-desktop-enviroment.md diff --git a/.github/workflows/consolidate-snippets.yml b/.github/workflows/consolidate-snippets.yml deleted file mode 100644 index a252a721..00000000 --- a/.github/workflows/consolidate-snippets.yml +++ /dev/null @@ -1,39 +0,0 @@ -name: Consolidate JSON Files - -on: - push: - paths: - - "snippets/**" - -permissions: - contents: write - -jobs: - consolidate: - runs-on: ubuntu-latest - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up Node.js - uses: actions/setup-node@v4 - with: - node-version: 22 - - - name: Install dependencies - run: | - npm install - - - name: Consolidate Snippets - run: | - node utils/consolidateSnippets.js # Run the script located in the utils/ folder - - - name: Commit and push changes - run: | - git config --global user.name "GitHub Action" - git config --global user.email "action@github.com" - git add public/consolidated/* - git add public/icons/* - git diff-index --quiet HEAD || git commit -m "Update consolidated snippets" - git push diff --git a/.gitignore b/.gitignore index b6cdf575..eab7cdd9 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,7 @@ dist-ssr *.njsproj *.sln *.sw? + +# Consolidated snippets +public/consolidated +public/icons diff --git a/.prettierrc b/.prettierrc index 453861ee..f70b340c 100644 --- a/.prettierrc +++ b/.prettierrc @@ -7,6 +7,5 @@ "bracketSpacing": true, "bracketSameLine": false, "arrowParens": "always", - "endOfLine": "lf", "jsxSingleQuote": false } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2ad95510..78743edf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -65,7 +65,7 @@ If your function doesn't return anything just show how to use it. If the result To ensure your snippet isn’t refused, consider these questions: - **Does the standard library of my language provide an easy way of doing this ?** -- **Does that snippet have a real, and practical use case ?** +- **Does that snippet not have a real, and practical use case ?** - **Could it be split into separate parts to be better understood ?** If any answer is yes, then your snippet will most likely get rejected. @@ -117,7 +117,7 @@ Here’s an example for JavaScript: title: Format Date description: Formats a date in 'YYYY-MM-DD' format. author: dostonnabotov -tags: javascript,date,format +tags: date,format --- ```js @@ -141,11 +141,11 @@ console.log(formatDate(new Date())); // Output: '2024-12-10' It will return nothing if they are well formatted, otherwise it will tell you what the error is. --- - To preview the snippets, you need to consolidate them, use the `snippets:consolidate` script: + To preview the snippets, start the vite server using: ``` - $ npm run snippets:consolidate + $ npm run dev ``` - It will update the snippets in the `/public` folder, making them available to the frontend. + It will use HMR to update the snippets in the `/public` folder, making them available to the frontend. Expected file structure: diff --git a/README.md b/README.md index 90b3effb..f778fce9 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ Here's an example for JavaScript: title: Format Date description: Formats a date in 'YYYY-MM-DD' format. author: dostonnabotov -tags: javascript,date,format +tags: date,format --- ```js diff --git a/package-lock.json b/package-lock.json index 66d58886..9f98d54f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "quicksnip", "version": "0.0.0", "dependencies": { + "@types/node": "^22.10.5", "motion": "^11.15.0", "prismjs": "^1.29.0", "react": "^18.3.1", @@ -1706,6 +1707,15 @@ "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", "dev": true }, + "node_modules/@types/node": { + "version": "22.10.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.10.5.tgz", + "integrity": "sha512-F8Q+SeGimwOo86fiovQh8qiXfFEh2/ocYv7tU5pJ3EXMSSxk1Joj5wefpFK2fHTf/N6HKGSxIDBT9f3gCxXPkQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.20.0" + } + }, "node_modules/@types/prop-types": { "version": "15.7.14", "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.14.tgz", @@ -5999,6 +6009,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/undici-types": { + "version": "6.20.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", + "integrity": "sha512-Ny6QZ2Nju20vw1SRHe3d9jVu6gJ+4e3+MMpqu7pqE5HT6WsTSlce++GQmK5UXS8mzV8DSYHrQH+Xrf2jVcuKNg==", + "license": "MIT" + }, "node_modules/uri-js": { "version": "4.4.1", "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", diff --git a/package.json b/package.json index ff3e622e..290c1ea6 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "snippets:consolidate": "node ./utils/consolidateSnippets.js" }, "dependencies": { + "@types/node": "^22.10.5", "motion": "^11.15.0", "prismjs": "^1.29.0", "react": "^18.3.1", diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json deleted file mode 100644 index e57286a1..00000000 --- a/public/consolidated/_index.json +++ /dev/null @@ -1,82 +0,0 @@ -[ - { - "name": "C", - "icon": "/icons/c.svg", - "subLanguages": [] - }, - { - "name": "CPP", - "icon": "/icons/cpp.svg", - "subLanguages": [] - }, - { - "name": "CSHARP", - "icon": "/icons/csharp.svg", - "subLanguages": [] - }, - { - "name": "CSS", - "icon": "/icons/css.svg", - "subLanguages": [] - }, - { - "name": "HASKELL", - "icon": "/icons/haskell.svg", - "subLanguages": [] - }, - { - "name": "HTML", - "icon": "/icons/html.svg", - "subLanguages": [] - }, - { - "name": "JAVA", - "icon": "/icons/java.svg", - "subLanguages": [] - }, - { - "name": "JAVASCRIPT", - "icon": "/icons/javascript.svg", - "subLanguages": [ - { - "name": "REACT", - "icon": "/icons/javascript--react.svg" - } - ] - }, - { - "name": "PYTHON", - "icon": "/icons/python.svg", - "subLanguages": [ - { - "name": "FASTAPI", - "icon": "/icons/python--fastapi.svg" - } - ] - }, - { - "name": "REGEX", - "icon": "/icons/regex.svg", - "subLanguages": [] - }, - { - "name": "RUBY", - "icon": "/icons/ruby.svg", - "subLanguages": [] - }, - { - "name": "RUST", - "icon": "/icons/rust.svg", - "subLanguages": [] - }, - { - "name": "SCSS", - "icon": "/icons/scss.svg", - "subLanguages": [] - }, - { - "name": "TYPESCRIPT", - "icon": "/icons/typescript.svg", - "subLanguages": [] - } -] \ No newline at end of file diff --git a/public/consolidated/c.json b/public/consolidated/c.json deleted file mode 100644 index 2343c989..00000000 --- a/public/consolidated/c.json +++ /dev/null @@ -1,45 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "0xHouss", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "#include // Includes the input/output library\n\nint main() { // Defines the main function\n printf(\"Hello, World!\\n\") // Outputs Hello, World! and a newline\n\n return 0; // indicate the program executed successfully\n}\n" - } - ] - }, - { - "name": "Mathematical Functions", - "snippets": [ - { - "title": "Factorial Function", - "description": "Calculates the factorial of a number.", - "author": "0xHouss", - "tags": [ - "math", - "factorial" - ], - "contributors": [], - "code": "int factorial(int x) {\n int y = 1;\n\n for (int i = 2; i <= x; i++)\n y *= i;\n\n return y;\n}\n\n// Usage:\nfactorial(4); // Returns: 24\n" - }, - { - "title": "Swap numbers", - "description": "Swaps two numbers without using third variable", - "author": "Emosans", - "tags": [ - "swap", - "numbers" - ], - "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json deleted file mode 100644 index c121a725..00000000 --- a/public/consolidated/cpp.json +++ /dev/null @@ -1,112 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "James-Beans", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "#include // Includes the input/output stream library\n\nint main() { // Defines the main function\n std::cout << \"Hello, World!\" << std::endl; // Outputs Hello, World! and a newline\n return 0; // indicate the program executed successfully\n}\n" - } - ] - }, - { - "name": "Data Structure Conversion", - "snippets": [ - { - "title": "Vector to Queue", - "description": "Convert vector into queue quickly", - "author": "mrityunjay2003", - "tags": [ - "data structures", - "queue", - "vector" - ], - "contributors": [], - "code": "#include\n#include\n#include\n\nstd::queue vectorToQueue(const std::vector& v) {\n return std::queue(std::deque(v.begin(), v.end()));\n}\n\nstd::vector vec = { 1, 2, 3, 4, 5 };\nvectorToQueue(&vec); // Returns: std::queue { 1, 2, 3, 4, 5 }\n" - } - ] - }, - { - "name": "Debugging", - "snippets": [ - { - "title": "Vector Print", - "description": "Overloads the << operator to print the contents of a vector just like in python.", - "author": "Mohamed-faaris", - "tags": [ - "printing", - "debuging", - "vector" - ], - "contributors": [], - "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" - } - ] - }, - { - "name": "Debuging", - "snippets": [ - { - "title": "Vector Print", - "description": "Overloads the << operator to print the contents of a vector just like in python.", - "author": "Mohamed-faaris", - "tags": [ - "printing", - "debuging", - "vector" - ], - "contributors": [], - "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" - } - ] - }, - { - "name": "Math And Numbers", - "snippets": [ - { - "title": "Check Prime Number", - "description": "Check if an integer is a prime number", - "author": "MihneaMoso", - "tags": [ - "number", - "prime" - ], - "contributors": [], - "code": "bool is_prime(int n) {\n if (n < 2) return false;\n if (n == 2 || n == 3) return true;\n if (n % 2 == 0) return false;\n for (int i = 3; i * i <= n; i += 2) {\n if (n % i == 0) return false;\n }\n return true;\n}\n\n// Usage:\nis_prime(29); // Returns: true\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "author": "Vaibhav-kesarwani", - "tags": [ - "array", - "reverse" - ], - "contributors": [], - "code": "#include \n#include \n\nstd::string reverseString(const std::string& input) {\n std::string reversed = input;\n std::reverse(reversed.begin(), reversed.end());\n return reversed;\n}\n\nreverseString(\"quicksnip\"); // Returns: \"pinskciuq\"\n" - }, - { - "title": "Split String", - "description": "Splits a string by a delimiter", - "author": "saminjay", - "tags": [ - "string", - "split" - ], - "contributors": [], - "code": "#include \n#include \n\nstd::vector split_string(std::string str, std::string delim) {\n std::vector splits;\n int i = 0, j;\n int inc = delim.length();\n while (j != std::string::npos) {\n j = str.find(delim, i);\n splits.push_back(str.substr(i, j - i));\n i = j + inc;\n }\n return splits;\n}\n\n// Usage:\nsplit_string(\"quick_-snip\", \"_-\"); // Returns: std::vector { \"quick\", \"snip\" }\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/csharp.json b/public/consolidated/csharp.json deleted file mode 100644 index fbd87ed4..00000000 --- a/public/consolidated/csharp.json +++ /dev/null @@ -1,115 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "chaitanya-jvnm", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "public class Program {\n public static void Main(string[] args) {\n System.Console.WriteLine(\"Hello, World!\");\n }\n}\n" - } - ] - }, - { - "name": "Guid Utilities", - "snippets": [ - { - "title": "Generate GUID", - "description": "Generates a new GUID", - "author": "chaitanya-jvnm", - "tags": [ - "guid", - "generate" - ], - "contributors": [], - "code": "public static string GenerateGuid() {\n return Guid.NewGuid().ToString();\n}\n\n// Usage:\nGenerateGuid(); // Returns: 1c4c38d8-64e4-431b-884a-c6eec2ab02cd (Uuid is random)\n" - }, - { - "title": "Validate GUID", - "description": "Checks if a string is a valid GUID.", - "author": "chaitanya-jvnm", - "tags": [ - "guid", - "validate" - ], - "contributors": [], - "code": "public static bool IsGuid(string str) {\n return Guid.TryParse(str, out _);\n}\n\n// Usage:\nIsGuid(\"1c4c38d8-64e4-431b-884a-c6eec2ab02cd\"); // Returns: true\nIsGuid(\"quicksnip\"); // Returns: false\n" - } - ] - }, - { - "name": "Jwt Utilities", - "snippets": [ - { - "title": "Decode JWT", - "description": "Decodes a JWT.", - "author": "chaitanya-jvnm", - "tags": [ - "jwt", - "decode" - ], - "contributors": [], - "code": "public static string DecodeJwt(string token) {\n return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString();\n}\n\n// Usage:\nstring token = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nDecodeJwt(token); // Returns: \"{\\\"alg\\\":\\\"HS256\\\",\\\"typ\\\":\\\"JWT\\\"}.{\\\"sub\\\":\\\"1234567890\\\",\\\"name\\\":\\\"John Doe\\\",\\\"iat\\\":1516239022}\"\n" - }, - { - "title": "Validate JWT", - "description": "Validates a JWT.", - "author": "chaitanya-jvnm", - "tags": [ - "jwt", - "validate" - ], - "contributors": [], - "code": "public static bool ValidateJwt(string token, string secret) {\n var tokenHandler = new JwtSecurityTokenHandler();\n var validationParameters = new TokenValidationParameters {\n ValidateIssuerSigningKey = true,\n IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret)),\n ValidateIssuer = false,\n ValidateAudience = false\n };\n try {\n tokenHandler.ValidateToken(token, validationParameters, out _);\n return true;\n }\n catch {\n return false\n }\n}\n\n// Usage:\nstring JWT = \"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\";\nstring correctSecret = \"your-256-bit-secret\";\nstring wrongSecret = \"this-is-not-the-right-secret\";\n\nValidateJwt(JWT, correctSecret); // Returns: true\nValidateJwt(JWT, wrongSecret); // Returns: false\n" - } - ] - }, - { - "name": "List Utilities", - "snippets": [ - { - "title": "Swap items at index", - "description": "Swaps two items at determined indexes", - "author": "omegaleo", - "tags": [ - "list", - "swapping" - ], - "contributors": [], - "code": "public static IList Swap(this IList list, int indexA, int indexB)\n{\n (list[indexA], list[indexB]) = (list[indexB], list[indexA]);\n return list;\n}\n\nvar list = new List() {\"Test\", \"Test2\"};\n\nlist.Swap(0, 1); // Swaps \"Test\" and \"Test2\" in place\n" - } - ] - }, - { - "name": "String Utilities", - "snippets": [ - { - "title": "Capitalize first letter", - "description": "Makes the first letter of a string uppercase.", - "author": "chaitanya-jvnm", - "tags": [ - "string", - "capitalize" - ], - "contributors": [], - "code": "public static string Capitalize(this string str) {\n return str.Substring(0, 1).ToUpper() + str.Substring(1);\n}\n\n// Usage:\n\"quicksnip\".Capitalize(); // Returns: \"Quicksnip\"\n" - }, - { - "title": "Truncate String", - "description": "Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string", - "author": "omegaleo", - "tags": [ - "string", - "truncate" - ], - "contributors": [], - "code": "public static string Truncate(this string value, int maxChars)\n{\n return value.Length <= maxChars ? value : value.Substring(0, maxChars) + \"...\";\n}\n\n// Usage:\n\"Quicksnip\".Truncate(5); // Returns: \"Quick...\"\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/css.json b/public/consolidated/css.json deleted file mode 100644 index 0f19249e..00000000 --- a/public/consolidated/css.json +++ /dev/null @@ -1,239 +0,0 @@ -[ - { - "name": "Animations", - "snippets": [ - { - "title": "Blink Animation", - "description": "Adds an infinite blinking animation to an element", - "author": "AlsoKnownAs-Ax", - "tags": [ - "animation", - "blink", - "infinite" - ], - "contributors": [], - "code": ".blink {\n animation: blink 1s linear infinite;\n}\n\n@keyframes blink{\n 0%{\n opacity: 0;\n }\n 50%{\n opacity: 1;\n }\n 100%{\n opacity: 0;\n }\n}\n" - }, - { - "title": "Pulse Animation", - "description": "Adds a smooth pulsing animation with opacity and scale effects", - "author": "AlsoKnownAs-Ax", - "tags": [ - "animation", - "pulse", - "pulse-scale" - ], - "contributors": [], - "code": ".pulse {\n animation: pulse 2s ease-in-out infinite;\n}\n\n@keyframes pulse {\n 0% {\n opacity: 0.5;\n transform: scale(1);\n }\n 50% {\n opacity: 1;\n transform: scale(1.05);\n }\n 100% {\n opacity: 0.5;\n transform: scale(1);\n }\n}\n" - }, - { - "title": "Shake Animation", - "description": "Adds a shake animation ( commonly used to mark invalid fields )", - "author": "AlsoKnownAs-Ax", - "tags": [ - "shake", - "shake-horizontal" - ], - "contributors": [], - "code": ".shake {\n animation: shake .5s ease-in-out;\n}\n\n@keyframes shake {\n 0%, 100% {\n transform: translateX(0);\n }\n 25% {\n transform: translateX(-10px);\n }\n 50% {\n transform: translateX(10px);\n }\n 75% {\n transform: translateX(-10px);\n }\n}\n" - }, - { - "title": "Slide-in Animation", - "description": "Adds a slide-in from the right side of the screen", - "author": "AlsoKnownAs-Ax", - "tags": [ - "animation", - "slide-in", - "slide-right" - ], - "contributors": [], - "code": ".slide-in {\n animation: slide-in 1s ease-in-out;\n}\n\n@keyframes slide-in {\n from {\n scale: 300% 1;\n translate: 150vw 0;\n }\n\n to {\n scale: 100% 1;\n translate: 0 0;\n }\n}\n" - }, - { - "title": "Typewriter Animation", - "description": "Adds a typewriter animation + blinking cursor", - "author": "AlsoKnownAs-Ax", - "tags": [ - "blinking", - "typewriter" - ], - "contributors": [], - "code": "
    \n
    \n

    Typerwriter Animation

    \n
    \n
    \n```\n\n```css\n .typewriter{\n display: flex;\n justify-content: center;\n }\n\n .typewriter p {\n overflow: hidden;\n font-size: 1.5rem;\n font-family: monospace;\n border-right: 1px solid;\n margin-inline: auto;\n white-space: nowrap;\n /* The cursor will inherit the text's color by default */\n /* border-color: red */ \n /* Steps: number of chars (better to set directly in js)*/\n animation: typing 3s steps(21) forwards,\n blink 1s step-end infinite;\n }\n\n @keyframes typing{\n from{\n width: 0%\n }\n to{\n width: 100%\n }\n }\n\n @keyframes blink{\n 50%{\n border-color: transparent;\n }\n }\n" - } - ] - }, - { - "name": "Buttons", - "snippets": [ - { - "title": "3D Button Effect", - "description": "Adds a 3D effect to a button when clicked.", - "author": "dostonnabotov", - "tags": [ - "button", - "3D", - "effect" - ], - "contributors": [], - "code": ".button {\n background-color: #28a745;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);\n transition: transform 0.1s;\n}\n\n.button:active {\n transform: translateY(2px);\n box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);\n}\n" - }, - { - "title": "Button Hover Effect", - "description": "Creates a hover effect with a color transition.", - "author": "dostonnabotov", - "tags": [ - "button", - "hover", - "transition" - ], - "contributors": [], - "code": ".button {\n background-color: #007bff;\n color: white;\n padding: 10px 20px;\n border: none;\n border-radius: 5px;\n cursor: pointer;\n transition: background-color 0.3s ease;\n}\n\n.button:hover {\n background-color: #0056b3;\n}\n" - }, - { - "title": "MacOS Button", - "description": "A macOS-like button style, with hover and shading effects.", - "author": "e3nviction", - "tags": [ - "button", - "macos", - "hover", - "transition" - ], - "contributors": [], - "code": ".button {\n font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,;\n background: #0a85ff;\n color: #fff;\n padding: 8px 12px;\n border: none;\n margin: 4px;\n border-radius: 10px;\n cursor: pointer;\n box-shadow: inset 0 1px 1px #fff2, 0px 2px 3px -2px rgba(0, 0, 0, 0.3) !important; /*This is really performance heavy*/\n font-size: 14px;\n display: flex;\n align-items: center;\n justify-content: center;\n text-decoration: none;\n transition: all 150ms cubic-bezier(0.175, 0.885, 0.32, 1.275);\n}\n.button:hover {\n background: #0974ee;\n color: #fff\n}\n" - } - ] - }, - { - "name": "Effects", - "snippets": [ - { - "title": "Blur Background", - "description": "Applies a blur effect to the background of an element.", - "author": "dostonnabotov", - "tags": [ - "blur", - "background", - "effects" - ], - "contributors": [], - "code": ".blur-background {\n backdrop-filter: blur(10px);\n background: rgba(255, 255, 255, 0.5);\n}\n" - }, - { - "title": "Hover Glow Effect", - "description": "Adds a glowing effect on hover.", - "author": "dostonnabotov", - "tags": [ - "hover", - "glow", - "effects" - ], - "contributors": [], - "code": ".glow {\n background-color: #f39c12;\n padding: 10px 20px;\n border-radius: 5px;\n transition: box-shadow 0.3s ease;\n}\n\n.glow:hover {\n box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);\n}\n" - }, - { - "title": "Hover to Reveal Color", - "description": "A card with an image that transitions from grayscale to full color on hover.", - "author": "Haider-Mukhtar", - "tags": [ - "hover", - "image", - "effects" - ], - "contributors": [], - "code": ".card {\n height: 300px;\n width: 200px;\n border-radius: 5px;\n overflow: hidden;\n}\n\n.card img{\n height: 100%;\n width: 100%;\n object-fit: cover;\n filter: grayscale(100%);\n transition: all 0.3s;\n transition-duration: 200ms;\n cursor: pointer;\n}\n\n.card:hover img {\n filter: grayscale(0%);\n scale: 1.05;\n}\n" - } - ] - }, - { - "name": "Layouts", - "snippets": [ - { - "title": "CSS Reset", - "description": "Resets some default browser styles, ensuring consistency across browsers.", - "author": "AmeerMoustafa", - "tags": [ - "reset", - "browser", - "layout" - ], - "contributors": [], - "code": "* {\n margin: 0;\n padding: 0;\n box-sizing: border-box\n}\n" - }, - { - "title": "Equal-Width Columns", - "description": "Creates columns with equal widths using flexbox.", - "author": "dostonnabotov", - "tags": [ - "flexbox", - "columns", - "layout" - ], - "contributors": [], - "code": ".columns {\n display: flex;\n justify-content: space-between;\n}\n\n.column {\n flex: 1;\n margin: 0 10px;\n}\n" - }, - { - "title": "Grid layout", - "description": "Equal sized items in a responsive grid", - "author": "xshubhamg", - "tags": [ - "layout", - "grid" - ], - "contributors": [], - "code": ".grid-container {\n display: grid\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n/* Explanation:\n- `auto-fit`: Automatically fits as many columns as possible within the container.\n- `minmax(250px, 1fr)`: Defines a minimum column size of 250px and a maximum size of 1fr (fraction of available space).\n*/\n}\n" - }, - { - "title": "Responsive Design", - "description": "The different responsive breakpoints.", - "author": "kruimol", - "tags": [ - "responsive", - "media queries" - ], - "contributors": [], - "code": "/* Phone */\n.element {\n margin: 0 10%\n}\n\n/* Tablet */\n@media (min-width: 640px) {\n .element {\n margin: 0 20%\n }\n}\n\n/* Desktop base */\n@media (min-width: 768px) {\n .element {\n margin: 0 30%\n }\n}\n\n/* Desktop large */\n@media (min-width: 1024px) {\n .element {\n margin: 0 40%\n }\n}\n\n/* Desktop extra large */\n@media (min-width: 1280px) {\n .element {\n margin: 0 60%\n }\n}\n\n/* Desktop bige */\n@media (min-width: 1536px) {\n .element {\n margin: 0 80%\n }\n}\n" - }, - { - "title": "Sticky Footer", - "description": "Ensures the footer always stays at the bottom of the page.", - "author": "dostonnabotov", - "tags": [ - "layout", - "footer", - "sticky" - ], - "contributors": [], - "code": "body {\n display: flex;\n flex-direction: column;\n min-height: 100vh;\n}\n\nfooter {\n margin-top: auto;\n}\n" - } - ] - }, - { - "name": "Typography", - "snippets": [ - { - "title": "Letter Spacing", - "description": "Adds space between letters for better readability.", - "author": "dostonnabotov", - "tags": [ - "typography", - "spacing" - ], - "contributors": [], - "code": "p {\n letter-spacing: 0.05em;\n}\n" - }, - { - "title": "Responsive Font Sizing", - "description": "Adjusts font size based on viewport width.", - "author": "dostonnabotov", - "tags": [ - "font", - "responsive", - "typography" - ], - "contributors": [], - "code": "h1 {\n font-size: calc(1.5rem + 2vw);\n}\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/haskell.json b/public/consolidated/haskell.json deleted file mode 100644 index d199bba5..00000000 --- a/public/consolidated/haskell.json +++ /dev/null @@ -1,224 +0,0 @@ -[ - { - "name": "Array Manipulation", - "snippets": [ - { - "title": "Binary Search", - "description": "Searches for an element in a sorted array using binary search.", - "author": "ACR1209", - "tags": [ - "array", - "binary-search", - "search" - ], - "contributors": [], - "code": "binarySearch :: Ord a => a -> [a] -> Maybe Int\nbinarySearch _ [] = Nothing\nbinarySearch target xs = go 0 (length xs - 1)\n where\n go low high\n | low > high = Nothing\n | midElem < target = go (mid + 1) high\n | midElem > target = go low (mid - 1)\n | otherwise = Just mid\n where\n mid = (low + high) `div` 2\n midElem = xs !! mid\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5]\n print $ binarySearch 3 array -- Output: Just 2\n print $ binarySearch 6 array -- Output: Nothing\n" - }, - { - "title": "Chunk Array", - "description": "Splits an array into chunks of a specified size.", - "author": "ACR1209", - "tags": [ - "array", - "chunk", - "utility" - ], - "contributors": [], - "code": "chunkArray :: Int -> [a] -> [[a]]\nchunkArray _ [] = []\nchunkArray n xs = take n xs : chunkArray n (drop n xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let array = [1, 2, 3, 4, 5, 6]\n print $ chunkArray 2 array -- Output: [[1, 2], [3, 4], [5, 6]]\n" - }, - { - "title": "Matrix Transpose", - "description": "Transposes a 2D matrix.", - "author": "ACR1209", - "tags": [ - "array", - "matrix", - "transpose" - ], - "contributors": [], - "code": "transposeMatrix :: [[a]] -> [[a]]\ntransposeMatrix [] = []\ntransposeMatrix ([]:_) = []\ntransposeMatrix xs = map head xs : transposeMatrix (map tail xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n print $ transposeMatrix matrix -- Output: [[1,4,7],[2,5,8],[3,6,9]]\n" - } - ] - }, - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "ACR1209", - "tags": [ - "printing", - "hello-world", - "utility" - ], - "contributors": [], - "code": "putStrLn \"Hello, World!\"\n" - } - ] - }, - { - "name": "File Handling", - "snippets": [ - { - "title": "Find Files in Directory by Type", - "description": "Finds all files in a directory with a specific extension.", - "author": "ACR1209", - "tags": [ - "file", - "search", - "extension", - "filesystem" - ], - "contributors": [], - "code": "import System.Directory (listDirectory)\nimport System.FilePath (takeExtension)\n\nfindFilesByExtension :: FilePath -> String -> IO [FilePath]\nfindFilesByExtension dir ext = do\n files <- listDirectory dir\n return $ filter (\\f -> takeExtension f == ext) files\n\n-- Usage:\nmain :: IO ()\nmain = do\n let directory = \".\"\n let ext = \".txt\"\n files <- findFilesByExtension directory ext\n mapM_ putStrLn files -- Output: list of txt files on the current directory\n" - }, - { - "title": "Read File in Chunks", - "description": "Reads a file in chunks grouped by lines.", - "author": "ACR1209", - "tags": [ - "file", - "read", - "chunks", - "utility" - ], - "contributors": [], - "code": "import System.IO (openFile, IOMode(ReadMode), hGetContents)\nimport Data.List (unfoldr)\n\nreadFileInChunks :: FilePath -> Int -> IO [[String]]\nreadFileInChunks filePath chunkSize = do\n handle <- openFile filePath ReadMode\n contents <- hGetContents handle\n let linesList = lines contents\n return $ go linesList\n where\n go [] = []\n go xs = take chunkSize xs : go (drop chunkSize xs)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let file = \"example.txt\"\n let chunkSize = 3 -- Number of lines per chunk\n chunks <- readFileInChunks file chunkSize\n mapM_ (putStrLn . unlines) chunks\n\n" - } - ] - }, - { - "name": "Monads", - "snippets": [ - { - "title": "Either Monad for Error Handling", - "description": "Using the Either monad to handle errors in a computation.", - "author": "ACR1209", - "tags": [ - "monads", - "either", - "error handling" - ], - "contributors": [], - "code": "safeDiv :: Int -> Int -> Either String Int\nsafeDiv _ 0 = Left \"Division by zero error\"\nsafeDiv x y = Right (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 0 -- This will trigger an error\n return b\n print result -- Output: Left \"Division by zero error\"\n" - }, - { - "title": "Maybe Monad", - "description": "Using the Maybe monad to handle computations that might fail.", - "author": "ACR1209", - "tags": [ - "monads", - "maybe" - ], - "contributors": [], - "code": "safeDiv :: Int -> Int -> Maybe Int\nsafeDiv _ 0 = Nothing\nsafeDiv x y = Just (x `div` y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let result = do\n a <- safeDiv 10 2\n b <- safeDiv a 2\n return b\n print result -- Output: Just 2\n" - }, - { - "title": "State Monad", - "description": "Managing mutable state using the State monad.", - "author": "ACR1209", - "tags": [ - "monads", - "state", - "state-management" - ], - "contributors": [], - "code": "import Control.Monad.State\n\nincrement :: State Int Int\nincrement = do\n count <- get\n put (count + 1)\n return count\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (res1, intermediateState) = runState increment 0\n print res1 -- Output: 0\n let (result, finalState) = runState increment intermediateState\n print result -- Output: 1\n print finalState -- Output: 2\n\n" - }, - { - "title": "Writer Monad", - "description": "Using the Writer monad to accumulate logs or other outputs alongside a computation.", - "author": "ACR1209", - "tags": [ - "monads", - "writer", - "logs" - ], - "contributors": [], - "code": "import Control.Monad.Writer\n\naddAndLog :: Int -> Int -> Writer [String] Int\naddAndLog x y = do\n tell [\"Adding \" ++ show x ++ \" and \" ++ show y]\n return (x + y)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let (result, logs) = runWriter $ do\n res1 <- addAndLog 3 5\n addAndLog res1 1\n print result -- Output: 9\n print logs -- Output: [\"Adding 3 and 5\", \"Adding 8 and 1\"]\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "CamelCase to snake_case", - "description": "Converts a Camel Case string to Snake case.", - "author": "ACR1209", - "tags": [ - "string", - "convert", - "camel-case", - "snake-case", - "utility" - ], - "contributors": [], - "code": "import Data.Char (isUpper, toLower)\n\ncamelToSnake :: String -> String\ncamelToSnake [] = []\ncamelToSnake (x:xs)\n | isUpper x = '_' : toLower x : camelToSnake xs\n | otherwise = x : camelToSnake xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let camelCase = \"camelCaseToSnakeCase\"\n print $ camelToSnake camelCase -- Output: \"camel_case_to_snake_case\"\n" - }, - { - "title": "Capitalize Words", - "description": "Capitalizes the first letter of each word in a string.", - "author": "ACR1209", - "tags": [ - "string", - "capitalize", - "words" - ], - "contributors": [], - "code": "import Data.Char (toUpper)\n\ncapitalizeWords :: String -> String\ncapitalizeWords = unwords . map capitalize . words\n where\n capitalize [] = []\n capitalize (x:xs) = toUpper x : xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let sentence = \"haskell is awesome\"\n print $ capitalizeWords sentence -- Output: \"Haskell Is Awesome\"\n" - }, - { - "title": "Count Word Occurrences in String", - "description": "Counts the occurrences of each word in a given string.", - "author": "ACR1209", - "tags": [ - "string", - "occurrences", - "word-count" - ], - "contributors": [], - "code": "import Data.List (group, sort)\n\ncountWordOccurrences :: String -> [(String, Int)]\ncountWordOccurrences = map (\\(w:ws) -> (w, length (w:ws))) . group . sort . words\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"haskell is awesome and haskell is fun\"\n print $ countWordOccurrences text -- Output: [(\"and\",1),(\"awesome\",1),(\"fun\",1),(\"haskell\",2),(\"is\",2)]\n" - }, - { - "title": "Remove Punctuation", - "description": "Removes all punctuation from a given string.", - "author": "ACR1209", - "tags": [ - "string", - "punctuation", - "remove" - ], - "contributors": [], - "code": "import Data.Char (isPunctuation)\n\nremovePunctuation :: String -> String\nremovePunctuation = filter (not . isPunctuation)\n\n-- Usage:\nmain :: IO ()\nmain = do\n let text = \"Hello, Haskell! How's it going?\"\n print $ removePunctuation text -- Output: \"Hello Haskell Hows it going\"\n" - }, - { - "title": "Snake_Case to CamelCase", - "description": "Converts a Snake Case string to Camel Case.", - "author": "ACR1209", - "tags": [ - "string", - "convert", - "snake-case", - "camel-case", - "utilty" - ], - "contributors": [], - "code": "import Data.Char (toUpper)\n\nsnakeToCamel :: String -> String\nsnakeToCamel [] = []\nsnakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs\nsnakeToCamel (x:xs) = x : snakeToCamel xs\n\n-- Usage:\nmain :: IO ()\nmain = do\n let snakeCase = \"snake_case_to_camel_case\"\n print $ snakeToCamel snakeCase -- Output: \"snakeCaseToCamelCase\"\n" - }, - { - "title": "Truncate String", - "description": "Truncates a string to a specified length, optionally adding an ellipsis.", - "author": "ACR1209", - "tags": [ - "string", - "truncate", - "utility" - ], - "contributors": [], - "code": "truncateString :: Int -> String -> String\ntruncateString maxLength str\n | length str <= maxLength = str\n | otherwise = take (maxLength - 3) str ++ \"...\"\n\n-- Usage:\nmain :: IO ()\nmain = do\n let longString = \"Haskell is a powerful functional programming language.\"\n print $ truncateString 20 longString -- Output: \"Haskell is a powe...\"\n print $ truncateString 54 longString -- Output: \"Haskell is a powerful functional programming language.\"\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/html.json b/public/consolidated/html.json deleted file mode 100644 index 1509d6d5..00000000 --- a/public/consolidated/html.json +++ /dev/null @@ -1,35 +0,0 @@ -[ - { - "name": "Basic Layouts", - "snippets": [ - { - "title": "Grid Layout with Navigation", - "description": "Full-height grid layout with header navigation using nesting syntax.", - "author": "GreenMan36", - "tags": [ - "css", - "layout", - "sticky", - "grid", - "full-height" - ], - "contributors": [], - "code": "\n\n \n \n \n \n
    \n
    Main Content
    \n
    Footer
    \n \n\n" - }, - { - "title": "Sticky Header-Footer Layout", - "description": "Full-height layout with sticky header and footer, using modern viewport units and flexbox.", - "author": "GreenMan36", - "tags": [ - "css", - "layout", - "sticky", - "flexbox", - "viewport" - ], - "contributors": [], - "code": "\n\n \n \n \n \n
    header
    \n
    body/content
    \n
    footer
    \n \n\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/java.json b/public/consolidated/java.json deleted file mode 100644 index f972f5e0..00000000 --- a/public/consolidated/java.json +++ /dev/null @@ -1,37 +0,0 @@ -[ - { - "name": "Array Manipulation", - "snippets": [ - { - "title": "Zip Two Lists", - "description": "Zips two lists into a list of paired elements, combining corresponding elements from both lists.", - "author": "davidanukam", - "tags": [ - "lists", - "zip", - "stream-api", - "collections" - ], - "contributors": [], - "code": "import java.util.*; // Importing utility classes for List and Arrays\nimport java.util.stream.IntStream; // Importing IntStream for range and mapping\nimport java.util.stream.Collectors; // Importing Collectors for collecting stream results\n\npublic List> zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList arr1 = Arrays.asList(\"a\", \"b\", \"c\");\nList arr2 = Arrays.asList(1, 2, 3);\nList> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n" - } - ] - }, - { - "name": "Basics", - "snippets": [ - { - "title": "Hello-World", - "description": "Prints Hello world in the console", - "author": "SarvariHarshitha", - "tags": [ - "java", - "console", - "printing" - ], - "contributors": [], - "code": "// This is the main class of the Java program\npublic class Main {\n // The main method is the entry point of the program\n public static void main(String args[]) {\n // This statement prints \"Hello, World!\" to the console\n System.out.println(\"Hello, World!\");\n }\n}\n\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json deleted file mode 100644 index 1b49645a..00000000 --- a/public/consolidated/javascript.json +++ /dev/null @@ -1,872 +0,0 @@ -[ - { - "name": "Array Manipulation", - "snippets": [ - { - "title": "Partition Array", - "description": "Splits an array into two arrays based on a callback function.", - "author": "Swaraj-Singh-30", - "tags": [ - "array", - "partition", - "reduce" - ], - "contributors": [], - "code": "const partition = (arr, callback) =>\n arr.reduce(\n ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),\n [[], []]\n );\n\n// Usage:\nconst numbers = [1, 2, 3, 4, 5, 6];\nconst isEven = (n) => n % 2 === 0;\npartition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]\n" - }, - { - "title": "Remove Duplicates", - "description": "Removes duplicate values from an array.", - "author": "dostonnabotov", - "tags": [ - "array", - "deduplicate" - ], - "contributors": [], - "code": "const removeDuplicates = (arr) => [...new Set(arr)];\n\n// Usage:\nconst numbers = [1, 2, 2, 3, 4, 4, 5];\nremoveDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]\n" - }, - { - "title": "Remove Falsy Values", - "description": "Removes falsy values from an array.", - "author": "mubasshir", - "tags": [ - "array", - "falsy", - "filter" - ], - "contributors": [], - "code": "const removeFalsy = (arr) => arr.filter(Boolean);\n\n// Usage:\nconst array = [0, 1, false, 2, \"\", 3, null];\nremoveFalsy(array); // Returns: [1, 2, 3]\n" - }, - { - "title": "Shuffle Array", - "description": "Shuffles an Array.", - "author": "loxt-nixo", - "tags": [ - "array", - "shuffle" - ], - "contributors": [], - "code": "function shuffleArray(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}\n\n// Usage:\nconst array = [1, 2, 3, 4, 5];\nshuffleArray(array); // Shuffles `array` in place\n" - }, - { - "title": "Zip Arrays", - "description": "Combines two arrays by pairing corresponding elements from each array.", - "author": "Swaraj-Singh-30", - "tags": [ - "array", - "map" - ], - "contributors": [], - "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n" - } - ] - }, - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "James-Beans", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n" - } - ] - }, - { - "name": "Color Manipulation", - "snippets": [ - { - "title": "RGB to Hex Color", - "description": "Converts RGB color values to hexadecimal color code.", - "author": "jjcantu", - "tags": [ - "color", - "conversion" - ], - "contributors": [], - "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" - } - ] - }, - { - "name": "Date And Time", - "snippets": [ - { - "title": "Check Leap Year", - "description": "Determines if a given year is a leap year.", - "author": "axorax", - "tags": [ - "date", - "leap-year" - ], - "contributors": [], - "code": "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Usage:\nisLeapYear(2024); // Returns: true\nisLeapYear(2023); // Returns: false\n" - }, - { - "title": "Convert to Unix Timestamp", - "description": "Converts a date to a Unix timestamp in seconds.", - "author": "Yugveer06", - "tags": [ - "date", - "unix", - "timestamp" - ], - "contributors": [], - "code": "function convertToUnixSeconds(input) {\n if (typeof input === 'string') {\n if (!input.trim()) {\n throw new Error('Date string cannot be empty or whitespace');\n }\n } else if (!input) {\n throw new Error('Input is required');\n }\n\n let date;\n\n if (typeof input === 'string') {\n date = new Date(input);\n } else if (input instanceof Date) {\n date = input;\n } else {\n throw new Error('Input must be a valid date string or Date object');\n }\n\n if (isNaN(date.getTime())) {\n throw new Error('Invalid date provided');\n }\n\n return Math.floor(date.getTime() / 1000);\n}\n\n// Usage:\nconvertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800\nconvertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800\nconvertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds\n" - }, - { - "title": "Format Date", - "description": "Formats a date in 'YYYY-MM-DD' format.", - "author": "dostonnabotov", - "tags": [ - "date", - "format" - ], - "contributors": [], - "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n" - }, - { - "title": "Get Day of the Year", - "description": "Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.", - "author": "axorax", - "tags": [ - "date", - "day-of-year" - ], - "contributors": [], - "code": "const getDayOfYear = (date) => {\n const startOfYear = new Date(date.getFullYear(), 0, 0);\n const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;\n return Math.floor(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\ngetDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)\n" - }, - { - "title": "Get Days in Month", - "description": "Calculates the number of days in a specific month of a given year.", - "author": "axorax", - "tags": [ - "date", - "days-in-month" - ], - "contributors": [], - "code": "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();\n\n// Usage:\ngetDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)\ngetDaysInMonth(2023, 1); // Returns: 28\n" - }, - { - "title": "Get Time Difference", - "description": "Calculates the time difference in days between two dates.", - "author": "dostonnabotov", - "tags": [ - "date", - "time-difference" - ], - "contributors": [], - "code": "const getTimeDifference = (date1, date2) => {\n const diff = Math.abs(date2 - date1);\n return Math.ceil(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst date1 = new Date('2024-01-01');\nconst date2 = new Date('2024-12-31');\ngetTimeDifference(date1, date2); // Returns: 365\n" - }, - { - "title": "Relative Time Formatter", - "description": "Displays how long ago a date occurred or how far in the future a date is.", - "author": "Yugveer06", - "tags": [ - "date", - "time", - "relative", - "future", - "past" - ], - "contributors": [], - "code": "const getRelativeTime = (date) => {\n const now = Date.now();\n const diff = date.getTime() - now;\n const seconds = Math.abs(Math.floor(diff / 1000));\n const minutes = Math.abs(Math.floor(seconds / 60));\n const hours = Math.abs(Math.floor(minutes / 60));\n const days = Math.abs(Math.floor(hours / 24));\n const years = Math.abs(Math.floor(days / 365));\n\n if (Math.abs(diff) < 1000) return 'just now';\n\n const isFuture = diff > 0;\n\n if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;\n if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;\n if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;\n if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;\n\n return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;\n}\n\n// Usage:\nconst pastDate = new Date('2021-12-29 13:00:00');\nconst futureDate = new Date('2099-12-29 13:00:00');\ngetRelativeTime(pastDate); // x years ago\ngetRelativeTime(new Date()); // just now\ngetRelativeTime(futureDate); // in x years\n" - }, - { - "title": "Start of the Day", - "description": "Returns the start of the day (midnight) for a given date.", - "author": "axorax", - "tags": [ - "date", - "start-of-day" - ], - "contributors": [], - "code": "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));\n\n// Usage:\nconst today = new Date();\nstartOfDay(today); // Returns: Date object for midnight\n" - } - ] - }, - { - "name": "Dom Manipulation", - "snippets": [ - { - "title": "Change Element Style", - "description": "Changes the inline style of an element.", - "author": "axorax", - "tags": [ - "dom", - "style" - ], - "contributors": [], - "code": "const changeElementStyle = (element, styleObj) => {\n Object.entries(styleObj).forEach(([property, value]) => {\n element.style[property] = value;\n });\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nchangeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });\n" - }, - { - "title": "Remove Element", - "description": "Removes a specified element from the DOM.", - "author": "axorax", - "tags": [ - "dom", - "remove" - ], - "contributors": [], - "code": "const removeElement = (element) => {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nremoveElement(element);\n" - } - ] - }, - { - "name": "Function Utilities", - "snippets": [ - { - "title": "Compose Functions", - "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.", - "author": "axorax", - "tags": [ - "function", - "compose" - ], - "contributors": [], - "code": "const compose = (...funcs) => (initialValue) => {\n return funcs.reduce((acc, func) => func(acc), initialValue);\n};\n\n// Usage:\nconst add2 = (x) => x + 2;\nconst multiply3 = (x) => x * 3;\nconst composed = compose(multiply3, add2);\ncomposed(5); // Returns: 17 ((5 * 3) + 2)\n" - }, - { - "title": "Curry Function", - "description": "Transforms a function into its curried form.", - "author": "axorax", - "tags": [ - "curry", - "function" - ], - "contributors": [], - "code": "const curry = (func) => {\n const curried = (...args) => {\n if (args.length >= func.length) {\n return func(...args);\n }\n return (...nextArgs) => curried(...args, ...nextArgs);\n };\n return curried;\n};\n\n// Usage:\nconst add = (a, b, c) => a + b + c;\nconst curriedAdd = curry(add);\ncurriedAdd(1)(2)(3); // Returns: 6\ncurriedAdd(1, 2)(3); // Returns: 6\n" - }, - { - "title": "Debounce Function", - "description": "Delays a function execution until after a specified time.", - "author": "dostonnabotov", - "tags": [ - "debounce", - "performance" - ], - "contributors": [], - "code": "const debounce = (func, delay) => {\n let timeout;\n\n return (...args) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => func(...args), delay);\n };\n};\n\n// Usage:\nwindow.addEventListener(\n 'resize',\n debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms\n);\n" - }, - { - "title": "Get Contrast Color", - "description": "Returns either black or white text color based on the brightness of the provided hex color.", - "author": "yaya12085", - "tags": [ - "color", - "hex", - "contrast", - "brightness" - ], - "contributors": [], - "code": "const getContrastColor = (hexColor) => {\n // Expand short hex color to full format\n if (hexColor.length === 4) {\n hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;\n }\n const r = parseInt(hexColor.slice(1, 3), 16);\n const g = parseInt(hexColor.slice(3, 5), 16);\n const b = parseInt(hexColor.slice(5, 7), 16);\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";\n};\n\n// Usage:\ngetContrastColor('#fff'); // Returns: #000000 (black)\ngetContrastColor('#123456'); // Returns: #FFFFFF (white)\ngetContrastColor('#ff6347'); // Returns: #000000 (black)\ngetContrastColor('#f4f'); // Returns: #000000 (black)\n" - }, - { - "title": "Memoize Function", - "description": "Caches the result of a function based on its arguments to improve performance.", - "author": "axorax", - "tags": [ - "memoization", - "optimization" - ], - "contributors": [], - "code": "const memoize = (func) => {\n const cache = new Map();\n return (...args) => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = func(...args);\n cache.set(key, result);\n return result;\n };\n};\n\n// Usage:\nconst factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));\nfactorial(5); // Returns: 120\nfactorial(5); // Returns: 120 (retrieved from cache)\n" - }, - { - "title": "Once Function", - "description": "Ensures a function is only called once.", - "author": "axorax", - "tags": [ - "function", - "once" - ], - "contributors": [], - "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n" - }, - { - "title": "Rate Limit Function", - "description": "Limits how often a function can be executed within a given time window.", - "author": "axorax", - "tags": [ - "function", - "rate-limiting" - ], - "contributors": [], - "code": "const rateLimit = (func, limit, timeWindow) => {\n let queue = [];\n setInterval(() => {\n if (queue.length) {\n const next = queue.shift();\n func(...next.args);\n }\n }, timeWindow);\n return (...args) => {\n if (queue.length < limit) {\n queue.push({ args });\n }\n };\n};\n\n// Usage:\nconst fetchData = () => console.log('Fetching data...');\nconst rateLimitedFetch = rateLimit(fetchData, 2, 1000);\nsetInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds\n" - }, - { - "title": "Repeat Function Invocation", - "description": "Invokes a function a specified number of times.", - "author": "dostonnabotov", - "tags": [ - "function", - "repeat" - ], - "contributors": [], - "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n" - }, - { - "title": "Sleep Function", - "description": "Waits for a specified amount of milliseconds before resolving.", - "author": "0xHouss", - "tags": [ - "javascript", - "sleep", - "delay", - "utility", - "promises" - ], - "contributors": [], - "code": "const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n// Usage:\nconsole.log('Hello');\nawait sleep(2000); // Waits for 2 seconds\nconsole.log('World!');\n" - } - ] - }, - { - "name": "Local Storage", - "snippets": [ - { - "title": "Add Item to localStorage", - "description": "Stores a value in localStorage under the given key.", - "author": "dostonnabotov", - "tags": [ - "localStorage", - "storage" - ], - "contributors": [], - "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n" - }, - { - "title": "Check if Item Exists in localStorage", - "description": "Checks if a specific item exists in localStorage.", - "author": "axorax", - "tags": [ - "localStorage", - "storage" - ], - "contributors": [], - "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n" - }, - { - "title": "Retrieve Item from localStorage", - "description": "Retrieves a value from localStorage by key and parses it.", - "author": "dostonnabotov", - "tags": [ - "localStorage", - "storage" - ], - "contributors": [], - "code": "const getFromLocalStorage = (key) => {\n const item = localStorage.getItem(key);\n return item ? JSON.parse(item) : null;\n};\n\n// Usage:\ngetFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }\n" - } - ] - }, - { - "name": "Mathematical Functions", - "snippets": [ - { - "title": "Greatest Common Divisor", - "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.", - "author": "JanluOfficial", - "tags": [ - "math", - "division" - ], - "contributors": [], - "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n" - } - ] - }, - { - "name": "Number Formatting", - "snippets": [ - { - "title": "Convert Number to Currency", - "description": "Converts a number to a currency format with a specific locale.", - "author": "axorax", - "tags": [ - "number", - "currency" - ], - "contributors": [], - "code": "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currency\n }).format(num);\n};\n\n// Usage:\nconvertToCurrency(1234567.89); // Returns: '$1,234,567.89'\nconvertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'\n" - }, - { - "title": "Convert Number to Roman Numerals", - "description": "Converts a number to Roman numeral representation.", - "author": "axorax", - "tags": [ - "number", - "roman" - ], - "contributors": [], - "code": "const numberToRoman = (num) => {\n const romanNumerals = {\n 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',\n 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'\n };\n let result = '';\n Object.keys(romanNumerals).reverse().forEach(value => {\n while (num >= value) {\n result += romanNumerals[value];\n num -= value;\n }\n });\n return result;\n};\n\n// Usage:\nnumberToRoman(1994); // Returns: 'MCMXCIV'\nnumberToRoman(58); // Returns: 'LVIII'\n" - }, - { - "title": "Convert to Scientific Notation", - "description": "Converts a number to scientific notation.", - "author": "axorax", - "tags": [ - "number", - "scientific" - ], - "contributors": [], - "code": "const toScientificNotation = (num) => {\n if (isNaN(num)) {\n throw new Error('Input must be a number');\n }\n if (num === 0) {\n return '0e+0';\n }\n const exponent = Math.floor(Math.log10(Math.abs(num)));\n const mantissa = num / Math.pow(10, exponent);\n return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;\n};\n\n// Usage:\ntoScientificNotation(12345); // Returns: '1.23e+4'\ntoScientificNotation(0.0005678); // Returns: '5.68e-4'\ntoScientificNotation(1000); // Returns: '1.00e+3'\ntoScientificNotation(0); // Returns: '0e+0'\ntoScientificNotation(-54321); // Returns: '-5.43e+4'\n" - }, - { - "title": "Format File Size", - "description": "Converts bytes into human-readable file size format.", - "author": "jjcantu", - "tags": [ - "format", - "size" - ], - "contributors": [], - "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n" - }, - { - "title": "Format Number with Commas", - "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).", - "author": "axorax", - "tags": [ - "number", - "format" - ], - "contributors": [], - "code": "const formatNumberWithCommas = (num) => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n};\n\n// Usage:\nformatNumberWithCommas(1000); // Returns: '1,000'\nformatNumberWithCommas(1234567); // Returns: '1,234,567'\nformatNumberWithCommas(987654321); // Returns: '987,654,321'\n" - }, - { - "title": "Number Formatter", - "description": "Formats a number with suffixes (K, M, B, etc.).", - "author": "realvishalrana", - "tags": [ - "number", - "format" - ], - "contributors": [], - "code": "const nFormatter = (num) => {\n if (!num) return;\n num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));\n const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];\n let index = 0;\n while (num >= 1000 && index < suffixes.length - 1) {\n num /= 1000;\n index++;\n }\n return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];\n};\n\n// Usage:\nnFormatter(1234567); // Returns: '1.23M'\n" - }, - { - "title": "Number to Words Converter", - "description": "Converts a number to its word representation in English.", - "author": "axorax", - "tags": [ - "number", - "words" - ], - "contributors": [], - "code": "const numberToWords = (num) => {\n const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];\n const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];\n const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];\n if (num < 20) return below20[num];\n let words = '';\n for (let i = 0; num > 0; i++) {\n if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;\n if (num % 100 >= 20) {\n words = tens[Math.floor(num / 10)] + ' ' + words;\n num %= 10;\n }\n if (num < 20) words = below20[num] + ' ' + words;\n num = Math.floor(num / 100);\n }\n return words.trim();\n};\n\n// Usage:\nnumberToWords(123); // Returns: 'One Hundred Twenty Three'\nnumberToWords(2045); // Returns: 'Two Thousand Forty Five'\n" - } - ] - }, - { - "name": "Object Manipulation", - "snippets": [ - { - "title": "Check if Object is Empty", - "description": "Checks whether an object has no own enumerable properties.", - "author": "axorax", - "tags": [ - "object", - "check", - "empty" - ], - "contributors": [], - "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nisEmptyObject({}); // Returns: true\nisEmptyObject({ a: 1 }); // Returns: false\n" - }, - { - "title": "Compare Two Objects Shallowly", - "description": "Compares two objects shallowly and returns whether they are equal.", - "author": "axorax", - "tags": [ - "object", - "compare", - "shallow" - ], - "contributors": [], - "code": "function shallowEqual(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n return keys1.every(key => obj1[key] === obj2[key]);\n}\n\n// Usage:\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nconst obj3 = { a: 1, b: 3 };\nshallowEqual(obj1, obj2); // Returns: true\nshallowEqual(obj1, obj3); // Returns: false\n" - }, - { - "title": "Convert Object to Query String", - "description": "Converts an object to a query string for use in URLs.", - "author": "axorax", - "tags": [ - "object", - "query string", - "url" - ], - "contributors": [], - "code": "function toQueryString(obj) {\n return Object.entries(obj)\n .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))\n .join('&');\n}\n\n// Usage:\nconst params = { search: 'test', page: 1 };\ntoQueryString(params); // Returns: 'search=test&page=1'\n" - }, - { - "title": "Count Properties in Object", - "description": "Counts the number of own properties in an object.", - "author": "axorax", - "tags": [ - "object", - "count", - "properties" - ], - "contributors": [], - "code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ncountProperties(obj); // Returns: 3\n" - }, - { - "title": "Deep Clone Object", - "description": "Creates a deep copy of an object or array without reference.", - "author": "jjcantu", - "tags": [ - "object", - "clone" - ], - "contributors": [], - "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n" - }, - { - "title": "Filter Object", - "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.", - "author": "realvishalrana", - "tags": [ - "object", - "filter" - ], - "contributors": [], - "code": "export const filterObject = (object = {}) =>\n Object.fromEntries(\n Object.entries(object)\n .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))\n );\n\n// Usage:\nconst obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };\nfilterObject(obj1); // Returns: { a: 1, d: 4 }\n\nconst obj2 = { x: 0, y: false, z: 'Hello', w: [] };\nfilterObject(obj2); // Returns: { z: 'Hello' }\n\nconst obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };\nfilterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } }\n\nconst obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };\nfilterObject(obj4); // Returns: { e: 'Valid' }\n" - }, - { - "title": "Flatten Nested Object", - "description": "Flattens a nested object into a single-level object with dot notation for keys.", - "author": "axorax", - "tags": [ - "object", - "flatten" - ], - "contributors": [], - "code": "function flattenObject(obj, prefix = '') {\n return Object.keys(obj).reduce((acc, key) => {\n const fullPath = prefix ? `${prefix}.${key}` : key;\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n Object.assign(acc, flattenObject(obj[key], fullPath));\n } else {\n acc[fullPath] = obj[key];\n }\n return acc;\n }, {});\n}\n\n// Usage:\nconst nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };\nflattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }\n" - }, - { - "title": "Freeze Object", - "description": "Freezes an object to make it immutable.", - "author": "axorax", - "tags": [ - "object", - "freeze", - "immutable" - ], - "contributors": [], - "code": "function freezeObject(obj) {\n return Object.freeze(obj);\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst frozenObj = freezeObject(obj);\nfrozenObj.a = 42; // This will fail silently in strict mode.\nfrozenObj.a; // Returns: 1\n" - }, - { - "title": "Get Nested Value", - "description": "Retrieves the value at a given path in a nested object.", - "author": "realvishalrana", - "tags": [ - "object", - "nested" - ], - "contributors": [], - "code": "const getNestedValue = (obj, path) => {\n const keys = path.split('.');\n return keys.reduce((currentObject, key) => {\n return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;\n }, obj);\n};\n\n// Usage:\nconst obj = { a: { b: { c: 42 } } };\ngetNestedValue(obj, 'a.b.c'); // Returns: 42\n" - }, - { - "title": "Invert Object Keys and Values", - "description": "Creates a new object by swapping keys and values of the given object.", - "author": "axorax", - "tags": [ - "object", - "invert" - ], - "contributors": [], - "code": "function invertObject(obj) {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [value, key])\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ninvertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }\n" - }, - { - "title": "Merge Objects Deeply", - "description": "Deeply merges two or more objects, including nested properties.", - "author": "axorax", - "tags": [ - "object", - "merge", - "deep" - ], - "contributors": [], - "code": "function deepMerge(...objects) {\n return objects.reduce((acc, obj) => {\n Object.keys(obj).forEach(key => {\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n acc[key] = deepMerge(acc[key] || {}, obj[key]);\n } else {\n acc[key] = obj[key];\n }\n });\n return acc;\n }, {});\n}\n\n// Usage:\nconst obj1 = { a: 1, b: { c: 2 } };\nconst obj2 = { b: { d: 3 }, e: 4 };\ndeepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }\n" - }, - { - "title": "Omit Keys from Object", - "description": "Creates a new object with specific keys omitted.", - "author": "axorax", - "tags": [ - "object", - "omit" - ], - "contributors": [], - "code": "function omitKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nomitKeys(obj, ['b', 'c']); // Returns: { a: 1 }\n" - }, - { - "title": "Pick Keys from Object", - "description": "Creates a new object with only the specified keys.", - "author": "axorax", - "tags": [ - "object", - "pick" - ], - "contributors": [], - "code": "function pickKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\npickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }\n" - }, - { - "title": "Unique By Key", - "description": "Filters an array of objects to only include unique objects by a specified key.", - "author": "realvishalrana", - "tags": [ - "array", - "unique" - ], - "contributors": [], - "code": "const uniqueByKey = (key, arr) =>\n arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));\n\n// Usage:\nconst arr = [\n { id: 1, name: 'John' },\n { id: 2, name: 'Jane' },\n { id: 1, name: 'John' }\n];\nuniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "Capitalize String", - "description": "Capitalizes the first letter of a string.", - "author": "dostonnabotov", - "tags": [ - "string", - "capitalize" - ], - "contributors": [], - "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n" - }, - { - "title": "Check if String is a Palindrome", - "description": "Checks whether a given string is a palindrome.", - "author": "axorax", - "tags": [ - "check", - "palindrome", - "string" - ], - "contributors": [], - "code": "function isPalindrome(str) {\n const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\n// Example usage:\nisPalindrome('A man, a plan, a canal, Panama'); // Returns: true\n" - }, - { - "title": "Convert String to Camel Case", - "description": "Converts a given string into camelCase.", - "author": "aumirza", - "tags": [ - "string", - "case", - "camelCase" - ], - "contributors": [], - "code": "function toCamelCase(str) {\n return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoCamelCase('hello world test'); // Returns: 'helloWorldTest'\n" - }, - { - "title": "Convert String to Param Case", - "description": "Converts a given string into param-case.", - "author": "aumirza", - "tags": [ - "string", - "case", - "paramCase" - ], - "contributors": [], - "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Usage:\ntoParamCase('Hello World Test'); // Returns: 'hello-world-test'\n" - }, - { - "title": "Convert String to Pascal Case", - "description": "Converts a given string into Pascal Case.", - "author": "aumirza", - "tags": [ - "string", - "case", - "pascalCase" - ], - "contributors": [], - "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoPascalCase('hello world test'); // Returns: 'HelloWorldTest'\n" - }, - { - "title": "Convert String to Snake Case", - "description": "Converts a given string into snake_case.", - "author": "axorax", - "tags": [ - "string", - "case", - "snake_case" - ], - "contributors": [], - "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Usage:\ntoSnakeCase('Hello World Test'); // Returns: 'hello_world_test'\n" - }, - { - "title": "Convert String to Title Case", - "description": "Converts a given string into Title Case.", - "author": "aumirza", - "tags": [ - "string", - "case", - "titleCase" - ], - "contributors": [], - "code": "function toTitleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, (s) => s.toUpperCase());\n}\n\n// Usage:\ntoTitleCase('hello world test'); // Returns: 'Hello World Test'\n" - }, - { - "title": "Convert Tabs to Spaces", - "description": "Converts all tab characters in a string to spaces.", - "author": "axorax", - "tags": [ - "string", - "tabs", - "spaces" - ], - "contributors": [], - "code": "function tabsToSpaces(str, spacesPerTab = 4) {\n return str.replace(/\\t/g, ' '.repeat(spacesPerTab));\n}\n\n// Usage:\ntabsToSpaces('Hello\\tWorld', 2); // Returns: 'Hello World'\n" - }, - { - "title": "Count Words in a String", - "description": "Counts the number of words in a string.", - "author": "axorax", - "tags": [ - "string", - "manipulation", - "word count", - "count" - ], - "contributors": [], - "code": "function countWords(str) {\n return str.trim().split(/\\s+/).length;\n}\n\n// Usage:\ncountWords('Hello world! This is a test.'); // Returns: 6\n" - }, - { - "title": "Data with Prefix", - "description": "Adds a prefix and postfix to data, with a fallback value.", - "author": "realvishalrana", - "tags": [ - "data", - "prefix", - "postfix", - "format" - ], - "contributors": [], - "code": "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {\n return data ? `${prefix}${data}${postfix}` : fallback;\n};\n\n// Usage:\ndataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'\ndataWithPrefix('', '-', '(', ')'); // Returns: '-'\ndataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'\ndataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'\n" - }, - { - "title": "Extract Initials from Name", - "description": "Extracts and returns the initials from a full name.", - "author": "axorax", - "tags": [ - "string", - "initials", - "name" - ], - "contributors": [], - "code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Usage:\ngetInitials('John Doe'); // Returns: 'JD'\n" - }, - { - "title": "Generate UUID", - "description": "Generates a UUID (v4) string.", - "author": "jjcantu", - "tags": [ - "uuid", - "generate", - "string" - ], - "contributors": [], - "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n" - }, - { - "title": "Mask Sensitive Information", - "description": "Masks parts of a sensitive string, like a credit card or email address.", - "author": "axorax", - "tags": [ - "string", - "mask", - "sensitive" - ], - "contributors": [], - "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Usage:\nmaskSensitiveInfo('123456789', 4); // Returns: '1234*****'\nmaskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'\n" - }, - { - "title": "Pad String on Both Sides", - "description": "Pads a string on both sides with a specified character until it reaches the desired length.", - "author": "axorax", - "tags": [ - "string", - "pad", - "manipulation" - ], - "contributors": [], - "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Usage:\npadString('hello', 10, '*'); // Returns: '**hello***'\n" - }, - { - "title": "Random string", - "description": "Generates a random string of characters of a certain length", - "author": "kruimol", - "tags": [ - "function", - "random" - ], - "contributors": [], - "code": "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {\n return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');\n}\n\nmakeid(3); // Returns: gDs (Random)\nmakeid(5, \"1234\" /* (optional) */); // Returns: \"35453\" (Random)\n" - }, - { - "title": "Remove All Whitespace", - "description": "Removes all whitespace from a string.", - "author": "axorax", - "tags": [ - "string", - "whitespace" - ], - "contributors": [], - "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n" - }, - { - "title": "Remove Vowels from a String", - "description": "Removes all vowels from a given string.", - "author": "axorax", - "tags": [ - "string", - "remove", - "vowels" - ], - "contributors": [], - "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n" - }, - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "author": "dostonnabotov", - "tags": [ - "string", - "reverse" - ], - "contributors": [], - "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n" - }, - { - "title": "Slugify String", - "description": "Converts a string into a URL-friendly slug format.", - "author": "dostonnabotov", - "tags": [ - "string", - "slug" - ], - "contributors": [], - "code": "const slugify = (string, separator = \"-\") => {\n return string\n .toString() // Cast to string (optional)\n .toLowerCase() // Convert the string to lowercase letters\n .trim() // Remove whitespace from both sides of a string (optional)\n .replace(/\\s+/g, separator) // Replace spaces with {separator}\n .replace(/[^\\w\\-]+/g, \"\") // Remove all non-word chars\n .replace(/\\_/g, separator) // Replace _ with {separator}\n .replace(/\\-\\-+/g, separator) // Replace multiple - with single {separator}\n .replace(/\\-$/g, \"\"); // Remove trailing -\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nslugify(title); // Returns: 'hello-world-this-is-a-test'\nslugify(title, \"_\"); // Returns: 'hello_world_this_is_a_test'\n" - }, - { - "title": "Truncate Text", - "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.", - "author": "realvishalrana", - "tags": [ - "string", - "truncate", - "text" - ], - "contributors": [], - "code": "const truncateText = (text = '', maxLength = 50) => {\n return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\ntruncateText(title); // Returns: 'Hello, World! This is a Test.'\ntruncateText(title, 10); // Returns: 'Hello, Wor...'\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/python.json b/public/consolidated/python.json deleted file mode 100644 index 8acadcfc..00000000 --- a/public/consolidated/python.json +++ /dev/null @@ -1,713 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "James-Beans", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n" - } - ] - }, - { - "name": "Datetime Utilities", - "snippets": [ - { - "title": "Calculate Date Difference in Milliseconds", - "description": "Calculates the difference between two dates in milliseconds.", - "author": "e3nviction", - "tags": [ - "datetime", - "difference" - ], - "contributors": [], - "code": "from datetime import datetime\n\ndef date_difference_in_millis(date1, date2):\n delta = date2 - date1\n return delta.total_seconds() * 1000\n\n# Usage:\nd1 = datetime(2023, 1, 1, 12, 0, 0)\nd2 = datetime(2023, 1, 1, 12, 1, 0)\ndate_difference_in_millis(d1, d2) # Returns: 60000\n" - }, - { - "title": "Check if Date is a Weekend", - "description": "Checks whether a given date falls on a weekend.", - "author": "axorax", - "tags": [ - "datetime", - "weekend" - ], - "contributors": [], - "code": "from datetime import datetime\n\ndef is_weekend(date):\n try:\n return date.weekday() >= 5 # Saturday = 5, Sunday = 6\n except AttributeError:\n raise TypeError(\"Input must be a datetime object\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nis_weekend(date) # Returns: True (Sunday)\n" - }, - { - "title": "Day of the Week String", - "description": "Gets the string of the day of the week for a given date.", - "author": "axorax", - "tags": [ - "datetime", - "weekday" - ], - "contributors": [], - "code": "from datetime import datetime\n\ndef get_day_of_week(date):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n try:\n return days[date.weekday()]\n except IndexError:\n raise ValueError(\"Invalid date\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nget_day_of_week(date) # Returns: 'Sunday'\n" - }, - { - "title": "Generate Date Range List", - "description": "Generates a list of dates between two given dates.", - "author": "axorax", - "tags": [ - "datetime", - "range" - ], - "contributors": [], - "code": "from datetime import datetime, timedelta\n\ndef generate_date_range(start_date, end_date):\n if start_date > end_date:\n raise ValueError(\"start_date must be before end_date\")\n\n current_date = start_date\n date_list = []\n while current_date <= end_date:\n date_list.append(current_date)\n current_date += timedelta(days=1)\n\n return date_list\n\n# Usage:\nstart = datetime(2023, 1, 1)\nend = datetime(2023, 1, 5)\ndates = generate_date_range(start, end)\nfor d in dates:\n print(d.strftime('%Y-%m-%d'))\n# Outputs: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'\n" - }, - { - "title": "Get Current Date and Time as String", - "description": "Fetches the current date and time as a formatted string.", - "author": "e3nviction", - "tags": [ - "datetime", - "current", - "string" - ], - "contributors": [], - "code": "from datetime import datetime\n\ndef get_current_datetime_string():\n return datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# Usage:\nget_current_datetime_string() # Returns: '2023-01-01 12:00:00'\n" - }, - { - "title": "Get Number of Days in a Month", - "description": "Determines the number of days in a specific month and year.", - "author": "axorax", - "tags": [ - "datetime", - "calendar" - ], - "contributors": [], - "code": "from calendar import monthrange\nfrom datetime import datetime\n\ndef get_days_in_month(year, month):\n try:\n return monthrange(year, month)[1]\n except ValueError as e:\n raise ValueError(f\"Invalid month or year: {e}\")\n\n# Usage:\nget_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)\n" - }, - { - "title": "Measure Execution Time", - "description": "Measures the execution time of a code block.", - "author": "dostonnabotov", - "tags": [ - "time", - "execution" - ], - "contributors": [], - "code": "import time\n\ndef measure_time(func, *args):\n start = time.time()\n result = func(*args)\n end = time.time()\n print(f'Execution time: {end - start:.6f} seconds')\n return result\n\n# Usage:\ndef slow_function():\n time.sleep(2)\n\nmeasure_time(slow_function) # Outputs an execution time of ~2s\n" - } - ] - }, - { - "name": "Error Handling", - "snippets": [ - { - "title": "Create Custom Exception Type", - "description": "Create a Custom Exception Type that can be called with raise.", - "author": "mrcool7387", - "tags": [ - "python", - "error-creation", - "organisation", - "utility" - ], - "contributors": [], - "code": "class ExceptionName(BaseException):\n def __init__(message: str):\n super().__init__(message)\n\n# Usage\na: int = 1\n\nif a > 0:\n raise ExceptionName('Error Message')\n" - }, - { - "title": "Retry Function Execution on Exception", - "description": "Retries a function execution a specified number of times if it raises an exception.", - "author": "axorax", - "tags": [ - "error-handling", - "retry" - ], - "contributors": [], - "code": "import time\n\ndef retry(func, retries=3, delay=1):\n for attempt in range(retries):\n try:\n return func()\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n time.sleep(delay)\n raise Exception(\"All retry attempts failed\")\n\n# Usage:\ndef unstable_function():\n raise ValueError(\"Simulated failure\")\n\n# Retry 3 times with 2 seconds delay:\ntry:\n retry(unstable_function, retries=3, delay=2)\nexcept Exception as e:\n print(e) # Output: All retry attempts failed\n" - } - ] - }, - { - "name": "File Handling", - "snippets": [ - { - "title": "Find Files", - "description": "Finds all files of the specified type within a given directory.", - "author": "Jackeastern", - "tags": [ - "os", - "filesystem", - "file_search" - ], - "contributors": [], - "code": "import os\n\ndef find_files(directory, file_type):\n file_type = file_type.lower() # Convert file_type to lowercase\n found_files = []\n\n for root, _, files in os.walk(directory):\n for file in files:\n file_ext = os.path.splitext(file)[1].lower()\n if file_ext == file_type:\n full_path = os.path.join(root, file)\n found_files.append(full_path)\n\n return found_files\n\n# Example Usage:\nfind_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory\n" - }, - { - "title": "Get File Extension", - "description": "Gets the extension of a file.", - "author": "axorax", - "tags": [ - "file", - "extension" - ], - "contributors": [], - "code": "import os\n\ndef get_file_extension(filepath):\n return os.path.splitext(filepath)[1]\n\n# Usage:\nget_file_extension('example.txt') # Returns: '.txt'\n" - }, - { - "title": "List Files in Directory", - "description": "Lists all files in a specified directory.", - "author": "axorax", - "tags": [ - "file", - "list", - "directory" - ], - "contributors": [], - "code": "import os\n\ndef list_files(directory):\n return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n\n# Usage:\nlist_files('/path/to/directory') # Returns: List of file in the directory\n" - }, - { - "title": "Read File in Chunks", - "description": "Reads a file in chunks of a specified size.", - "author": "axorax", - "tags": [ - "file", - "read", - "chunks" - ], - "contributors": [], - "code": "def read_file_in_chunks(filepath, chunk_size):\n with open(filepath, 'r') as file:\n while chunk := file.read(chunk_size):\n yield chunk\n\n# Usage:\nfor chunk in read_file_in_chunks('example.txt', 1024):\n print(chunk) # Outputs: Chucks of 1024 bytes\n" - } - ] - }, - { - "name": "Json Manipulation", - "snippets": [ - { - "title": "Filter JSON Data", - "description": "Filters a JSON object based on a condition and returns the filtered data.", - "author": "axorax", - "tags": [ - "json", - "filter", - "data" - ], - "contributors": [], - "code": "import json\n\ndef filter_json_data(filepath, condition):\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Filter data based on the provided condition\n filtered_data = [item for item in data if condition(item)]\n\n return filtered_data\n\n# Usage:\ncondition = lambda x: x['age'] > 25\nfilter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition`\n" - }, - { - "title": "Flatten Nested JSON", - "description": "Flattens a nested JSON object into a flat dictionary.", - "author": "axorax", - "tags": [ - "json", - "flatten", - "nested" - ], - "contributors": [], - "code": "def flatten_json(nested_json, prefix=''):\n flat_dict = {}\n for key, value in nested_json.items():\n if isinstance(value, dict):\n flat_dict.update(flatten_json(value, prefix + key + '.'))\n else:\n flat_dict[prefix + key] = value\n return flat_dict\n\n# Usage:\nnested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}\nflatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}\n" - }, - { - "title": "Merge Multiple JSON Files", - "description": "Merges multiple JSON files into one and writes the merged data into a new file.", - "author": "axorax", - "tags": [ - "json", - "merge", - "file" - ], - "contributors": [], - "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n" - }, - { - "title": "Read JSON File", - "description": "Reads a JSON file and parses its content.", - "author": "e3nviction", - "tags": [ - "json", - "file", - "read" - ], - "contributors": [], - "code": "import json\n\ndef read_json(filepath):\n with open(filepath, 'r') as file:\n return json.load(file)\n\n# Usage:\nread_json('data.json') # Returns: Content of file as dict\n" - }, - { - "title": "Update JSON File", - "description": "Updates an existing JSON file with new data or modifies the existing values.", - "author": "axorax", - "tags": [ - "json", - "update", - "file" - ], - "contributors": [], - "code": "import json\n\ndef update_json(filepath, new_data):\n # Read the existing JSON data\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Update the data with the new content\n data.update(new_data)\n\n # Write the updated data back to the JSON file\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\nnew_data = {'age': 31}\nupdate_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys\n" - }, - { - "title": "Write JSON File", - "description": "Writes a dictionary to a JSON file.", - "author": "e3nviction", - "tags": [ - "json", - "file", - "write" - ], - "contributors": [], - "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n" - } - ] - }, - { - "name": "List Manipulation", - "snippets": [ - { - "title": "Find Duplicates in a List", - "description": "Identifies duplicate elements in a list.", - "author": "axorax", - "tags": [ - "list", - "duplicates" - ], - "contributors": [], - "code": "def find_duplicates(lst):\n seen = set()\n duplicates = set()\n for item in lst:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n return list(duplicates)\n\n# Usage:\ndata = [1, 2, 3, 2, 4, 5, 1]\nfind_duplicates(data) # Returns: [1, 2]\n" - }, - { - "title": "Find Intersection of Two Lists", - "description": "Finds the common elements between two lists.", - "author": "axorax", - "tags": [ - "list", - "intersection" - ], - "contributors": [], - "code": "def list_intersection(lst1, lst2):\n return [item for item in lst1 if item in lst2]\n\n# Usage:\nlist_a = [1, 2, 3, 4]\nlist_b = [3, 4, 5, 6]\nlist_intersection(list_a, list_b) # Returns: [3, 4]\n" - }, - { - "title": "Find Maximum Difference in List", - "description": "Finds the maximum difference between any two elements in a list.", - "author": "axorax", - "tags": [ - "list", - "difference" - ], - "contributors": [], - "code": "def max_difference(lst):\n if not lst or len(lst) < 2:\n return 0\n return max(lst) - min(lst)\n\n# Usage:\ndata = [10, 3, 5, 20, 7]\nmax_difference(data) # Returns: 17\n" - }, - { - "title": "Flatten Nested List", - "description": "Flattens a multi-dimensional list into a single list.", - "author": "dostonnabotov", - "tags": [ - "list", - "flatten" - ], - "contributors": [], - "code": "def flatten_list(lst):\n return [item for sublist in lst for item in sublist]\n\n# Usage:\nnested_list = [[1, 2], [3, 4], [5]]\nflatten_list(nested_list) # Returns: [1, 2, 3, 4, 5]\n" - }, - { - "title": "Flatten Unevenly Nested Lists", - "description": "Converts unevenly nested lists of any depth into a single flat list.", - "author": "agilarasu", - "tags": [ - "list", - "flattening", - "nested-lists", - "depth" - ], - "contributors": [], - "code": "def flatten(nested_list):\n for item in nested_list:\n if isinstance(item, list):\n yield from flatten(item)\n else:\n yield item\n\n# Usage:\nnested_list = [1, [2, [3, 4]], 5]\nlist(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5]\n" - }, - { - "title": "Partition List", - "description": "Partitions a list into sublists of a given size.", - "author": "axorax", - "tags": [ - "list", - "partition" - ], - "contributors": [], - "code": "def partition_list(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\n# Usage:\ndata = [1, 2, 3, 4, 5, 6, 7]\nlist(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]]\n" - }, - { - "title": "Remove Duplicates", - "description": "Removes duplicate elements from a list while maintaining order.", - "author": "dostonnabotov", - "tags": [ - "list", - "duplicates", - "filter" - ], - "contributors": [], - "code": "def remove_duplicates(lst):\n return list(dict.fromkeys(lst))\n\n# Usage:\nremove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5]\n" - } - ] - }, - { - "name": "Math And Numbers", - "snippets": [ - { - "title": "Calculate Compound Interest", - "description": "Calculates compound interest for a given principal amount, rate, and time period.", - "author": "axorax", - "tags": [ - "python", - "math", - "compound interest", - "finance" - ], - "contributors": [], - "code": "def compound_interest(principal, rate, time, n=1):\n return principal * (1 + rate / n) ** (n * time)\n\n# Usage:\ncompound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003\ncompound_interest(1000, 0.05, 5, 12) # Returns: 1283.68\n" - }, - { - "title": "Check Perfect Square", - "description": "Checks if a number is a perfect square.", - "author": "axorax", - "tags": [ - "math", - "perfect square", - "check" - ], - "contributors": [], - "code": "def is_perfect_square(n):\n if n < 0:\n return False\n root = int(n**0.5)\n return root * root == n\n\n# Usage:\nis_perfect_square(16) # Returns: True\nis_perfect_square(20) # Returns: False\n" - }, - { - "title": "Check Prime Number", - "description": "Checks if a number is a prime number.", - "author": "dostonnabotov", - "tags": [ - "math", - "prime", - "check" - ], - "contributors": [], - "code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Usage:\nis_prime(17) # Returns: True\n" - }, - { - "title": "Convert Binary to Decimal", - "description": "Converts a binary string to its decimal equivalent.", - "author": "axorax", - "tags": [ - "math", - "binary", - "decimal", - "conversion" - ], - "contributors": [], - "code": "def binary_to_decimal(binary_str):\n return int(binary_str, 2)\n\n# Usage:\nbinary_to_decimal('1010') # Returns: 10\nbinary_to_decimal('1101') # Returns: 13\n" - }, - { - "title": "Convert Bytes to Human-Readable Format", - "description": "Converts a size in bytes to a human-readable format.", - "author": "axorax", - "tags": [ - "bytes", - "format" - ], - "contributors": [], - "code": "def bytes_to_human_readable(num):\n for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:\n if num < 1024:\n return f\"{num:.2f} {unit}\"\n num /= 1024\n\n# Usage:\nbytes_to_human_readable(123456789) # Returns: '117.74 MB'\n" - }, - { - "title": "Find LCM (Least Common Multiple)", - "description": "Calculates the least common multiple (LCM) of two numbers.", - "author": "axorax", - "tags": [ - "python", - "math", - "lcm", - "gcd", - "utility" - ], - "contributors": [], - "code": "def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\n# Usage:\nlcm(12, 15) # Returns: 60\nlcm(7, 5) # Returns: 35\n" - }, - { - "title": "Solve Quadratic Equation", - "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.", - "author": "axorax", - "tags": [ - "math", - "quadratic", - "equation", - "solver" - ], - "contributors": [], - "code": "import cmath\n\ndef solve_quadratic(a, b, c):\n discriminant = cmath.sqrt(b**2 - 4 * a * c)\n root1 = (-b + discriminant) / (2 * a)\n root2 = (-b - discriminant) / (2 * a)\n return root1, root2\n\n# Usage:\nsolve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j))\nsolve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j))\n" - } - ] - }, - { - "name": "Sqlite Database", - "snippets": [ - { - "title": "Create SQLite Database Table", - "description": "Creates a table in an SQLite database with a dynamic schema.", - "author": "e3nviction", - "tags": [ - "sqlite", - "database", - "table" - ], - "contributors": [], - "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n" - }, - { - "title": "Insert Data into Sqlite Table", - "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.", - "author": "e3nviction", - "tags": [ - "sqlite", - "database" - ], - "contributors": [], - "code": "import sqlite3\n\ndef insert_into_table(db_path, table_name, data):\n with sqlite3.connect(db_path) as conn:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"\n conn.execute(sql, tuple(data.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ndata = {\n 'name': 'John Doe',\n 'email': 'john@example.com',\n 'age': 30\n}\ninsert_into_table(db_path, table_name, data)\n" - }, - { - "title": "Query Data from Sqlite Table", - "description": "Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.", - "author": "pl44t", - "tags": [ - "sqlite", - "database" - ], - "contributors": [], - "code": "import sqlite3\n\ndef query_table(db_path, table_name, columns='*', where_clause=None):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n sql = f\"SELECT {columns} FROM {table_name}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n cursor.execute(sql)\n return cursor.fetchall()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ncolumns = 'id, name, email'\nwhere_clause = 'age > 25'\nresult = query_table(db_path, table_name, columns, where_clause)\nfor row in result:\n print(row)\n\n" - }, - { - "title": "Update Records in Sqlite Table", - "description": "Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.", - "author": "pl44t", - "tags": [ - "sqlite", - "database" - ], - "contributors": [], - "code": "import sqlite3\n\ndef update_table(db_path, table_name, updates, where_clause=None):\n with sqlite3.connect(db_path) as conn:\n set_clause = ', '.join([f\"{col} = ?\" for col in updates.keys()])\n sql = f\"UPDATE {table_name} SET {set_clause}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n conn.execute(sql, tuple(updates.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\nupdates = {'name': 'Jane Doe', 'age': 28}\nwhere_clause = \"id = 1\"\nupdate_table(db_path, table_name, updates, where_clause)\n\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "Capitalize Words", - "description": "Capitalizes the first letter of each word in a string.", - "author": "axorax", - "tags": [ - "string", - "capitalize" - ], - "contributors": [], - "code": "def capitalize_words(s):\n return ' '.join(word.capitalize() for word in s.split())\n\n# Usage:\ncapitalize_words('hello world') # Returns: 'Hello World'\n" - }, - { - "title": "Check Anagram", - "description": "Checks if two strings are anagrams of each other.", - "author": "SteliosGee", - "tags": [ - "string", - "anagram", - "check" - ], - "contributors": [], - "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n" - }, - { - "title": "Check Palindrome", - "description": "Checks if a string is a palindrome.", - "author": "dostonnabotov", - "tags": [ - "string", - "palindrome" - ], - "contributors": [], - "code": "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]\n\n# Usage:\nis_palindrome('A man a plan a canal Panama') # Returns: True\n" - }, - { - "title": "Convert Snake Case to Camel Case", - "description": "Converts a snake_case string to camelCase.", - "author": "axorax", - "tags": [ - "string", - "snake-case", - "camel-case", - "convert" - ], - "contributors": [], - "code": "def snake_to_camel(s):\n parts = s.split('_')\n return parts[0] + ''.join(word.capitalize() for word in parts[1:])\n\n# Usage:\nsnake_to_camel('hello_world') # Returns: 'helloWorld'\n" - }, - { - "title": "Convert String to ASCII", - "description": "Converts a string into its ASCII representation.", - "author": "axorax", - "tags": [ - "string", - "ascii", - "convert" - ], - "contributors": [], - "code": "def string_to_ascii(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_ascii('hello') # Returns: [104, 101, 108, 108, 111]\n" - }, - { - "title": "Count Character Frequency", - "description": "Counts the frequency of each character in a string.", - "author": "axorax", - "tags": [ - "string", - "character-frequency" - ], - "contributors": [], - "code": "from collections import Counter\n\ndef char_frequency(s):\n return dict(Counter(s))\n\n# Usage:\nchar_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1}\n" - }, - { - "title": "Count Vowels", - "description": "Counts the number of vowels in a string.", - "author": "SteliosGee", - "tags": [ - "string", - "vowels", - "count" - ], - "contributors": [], - "code": "def count_vowels(s):\n vowels = 'aeiou'\n return len([char for char in s.lower() if char in vowels])\n\n# Usage:\ncount_vowels('hello') # Returns: 2\n" - }, - { - "title": "Count Words", - "description": "Counts the number of words in a string.", - "author": "axorax", - "tags": [ - "string", - "word-count" - ], - "contributors": [], - "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n" - }, - { - "title": "Find All Substrings", - "description": "Finds all substrings of a given string.", - "author": "axorax", - "tags": [ - "string", - "substring", - "find" - ], - "contributors": [], - "code": "def find_substrings(s):\n substrings = []\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n substrings.append(s[i:j])\n return substrings\n\n# Usage:\nfind_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c']\n" - }, - { - "title": "Find Longest Word", - "description": "Finds the longest word in a string.", - "author": "axorax", - "tags": [ - "string", - "longest-word" - ], - "contributors": [], - "code": "def find_longest_word(s):\n words = s.split()\n return max(words, key=len) if words else ''\n\n# Usage:\nfind_longest_word('The quick brown fox') # Returns: 'quick'\n" - }, - { - "title": "Find Unique Characters", - "description": "Finds all unique characters in a string.", - "author": "axorax", - "tags": [ - "string", - "unique", - "characters" - ], - "contributors": [], - "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n" - }, - { - "title": "Generate Random String", - "description": "Generates a random alphanumeric string.", - "author": "dostonnabotov", - "tags": [ - "random", - "string" - ], - "contributors": [], - "code": "import random\nimport string\n\ndef random_string(length):\n letters_and_digits = string.ascii_letters + string.digits\n return ''.join(random.choice(letters_and_digits) for _ in range(length))\n\n# Usage:\nrandom_string(10) # Results: Random 10-character string\n" - }, - { - "title": "Remove Duplicate Characters", - "description": "Removes duplicate characters from a string while maintaining the order.", - "author": "axorax", - "tags": [ - "string", - "duplicates", - "remove" - ], - "contributors": [], - "code": "def remove_duplicate_chars(s):\n seen = set()\n return ''.join(char for char in s if not (char in seen or seen.add(char)))\n\n# Usage:\nremove_duplicate_chars('programming') # Returns: 'progamin'\n" - }, - { - "title": "Remove Punctuation", - "description": "Removes punctuation from a string.", - "author": "SteliosGee", - "tags": [ - "string", - "punctuation", - "remove" - ], - "contributors": [], - "code": "import string\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n# Usage:\nremove_punctuation('Hello, World!') # Returns: 'Hello World'\n" - }, - { - "title": "Remove Specific Characters", - "description": "Removes specific characters from a string.", - "author": "axorax", - "tags": [ - "string", - "remove", - "characters" - ], - "contributors": [], - "code": "def remove_chars(s, chars):\n return ''.join(c for c in s if c not in chars)\n\n# Usage:\nremove_chars('hello world', 'eo') # Returns: 'hll wrld'\n" - }, - { - "title": "Remove Whitespace", - "description": "Removes all whitespace from a string.", - "author": "axorax", - "tags": [ - "string", - "whitespace", - "remove" - ], - "contributors": [], - "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n" - }, - { - "title": "Reverse String", - "description": "Reverses the characters in a string.", - "author": "dostonnabotov", - "tags": [ - "string", - "reverse" - ], - "contributors": [], - "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n" - }, - { - "title": "Split Camel Case", - "description": "Splits a camel case string into separate words.", - "author": "axorax", - "tags": [ - "string", - "camel-case", - "split" - ], - "contributors": [], - "code": "import re\n\ndef split_camel_case(s):\n return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))\n\n# Usage:\nsplit_camel_case('camelCaseString') # Returns: 'camel Case String'\n" - }, - { - "title": "Truncate String", - "description": "Truncates a string to a specified length and adds an ellipsis.", - "author": "axorax", - "tags": [ - "string", - "truncate" - ], - "contributors": [], - "code": "def truncate_string(s, length):\n return s[:length] + '...' if len(s) > length else s\n\n# Usage:\ntruncate_string('This is a long string', 10) # Returns: 'This is a ...'\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json deleted file mode 100644 index 201f84ae..00000000 --- a/public/consolidated/regex.json +++ /dev/null @@ -1,74 +0,0 @@ -[ - { - "name": "Miscellaneous", - "snippets": [ - { - "title": "Hexadecimal Color", - "description": "Matches hex color codes", - "author": "majvax", - "tags": [ - "color", - "hexadecimal" - ], - "contributors": [], - "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n" - }, - { - "title": "IPv4", - "description": "Matches IPv4 address", - "author": "majvax", - "tags": [ - "ipv4", - "networking" - ], - "contributors": [], - "code": "^((25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$\n\n\n-> Usage:\n123.300.0.101 ✗\n127.0.0.1 ✓\n192.168.0.1 ✓\n" - }, - { - "title": "Unintentional Duplication", - "description": "Matches duplicated word in a text.", - "author": "majvax", - "tags": [ - "duplication" - ], - "contributors": [], - "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n" - }, - { - "title": "Whitespace Trimmer", - "description": "Matches leading and/or trailing whitespace.", - "author": "majvax", - "tags": [ - "trim" - ], - "contributors": [], - "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n" - } - ] - }, - { - "name": "Validation pattern", - "snippets": [ - { - "title": "Email Address", - "description": "Match any email address", - "author": "majvax", - "tags": [ - "email" - ], - "contributors": [], - "code": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\n\n-> Usage:\nexample.name@domain.com.ru ✓\nname.surname@gmail.com ✓\n" - }, - { - "title": "Strong Password", - "description": "Match password with at least 12 characters, one uppercased letter, one number, and one special character.", - "author": "majvax", - "tags": [ - "password" - ], - "contributors": [], - "code": "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{12,}$\n\n-> Usage:\nlongpassword ✗\nlongpassw0rd ✗\nlongp@ssw0rd ✗\nLongp@ssw0rd ✓\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json deleted file mode 100644 index 90a66a2c..00000000 --- a/public/consolidated/ruby.json +++ /dev/null @@ -1,222 +0,0 @@ -[ - { - "name": "Array Manipulation", - "snippets": [ - { - "title": "Binary Search", - "description": "Searches for an element in a sorted array using binary search.", - "author": "ACR1209", - "tags": [ - "array", - "binary-search", - "search" - ], - "contributors": [], - "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage:\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n" - }, - { - "title": "Chunk Array", - "description": "Splits an array into chunks of a specified size.", - "author": "ACR1209", - "tags": [ - "array", - "chunk" - ], - "contributors": [], - "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n" - }, - { - "title": "Matrix Transpose", - "description": "Transposes a 2D matrix.", - "author": "ACR1209", - "tags": [ - "array", - "matrix", - "transpose" - ], - "contributors": [], - "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage:\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n" - } - ] - }, - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "ACR1209", - "tags": [ - "printing", - "hello-world", - "utility" - ], - "contributors": [], - "code": "puts 'Hello, World!'\n" - } - ] - }, - { - "name": "Error Handling", - "snippets": [ - { - "title": "Custom Error Class", - "description": "Defines and raises a custom error class in Ruby.", - "author": "ACR1209", - "tags": [ - "error handling", - "custom error" - ], - "contributors": [], - "code": "class MyCustomError < StandardError; end\n\ndef risky_method(value)\n raise MyCustomError, \"Value must be positive\" if value <= 0\n \"Valid value: #{value}\"\nend\n\n# Usage:\nbegin\n puts risky_method(-1)\nrescue MyCustomError => e\n puts e.message # Output: \"Value must be positive\"\nend\n" - } - ] - }, - { - "name": "Math And Numbers", - "snippets": [ - { - "title": "Calculate Compound Interest", - "description": "Calculates compound interest for a given principal amount, rate, and time period.", - "author": "ACR1209", - "tags": [ - "math", - "compound interest", - "finance" - ], - "contributors": [ - "axorax" - ], - "code": "def compound_interest(principal, rate, time, n = 1)\n principal * (1 + rate / n) ** (n * time)\nend\n\n# Usage:\nputs compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003\nputs compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118\n" - }, - { - "title": "Calculate Factorial", - "description": "Computes the factorial of a given integer.", - "author": "ACR1209", - "tags": [ - "math", - "factorial" - ], - "contributors": [], - "code": "def factorial(n)\n return 1 if n <= 1\n (2..n).reduce(1, :*)\nend\n\n# Usage:\nputs factorial(5) # Output: 120\n" - }, - { - "title": "Check Prime Number", - "description": "Checks if a number is a prime number.", - "author": "ACR1209", - "tags": [ - "math", - "prime", - "check" - ], - "contributors": [ - "dostonnabotov" - ], - "code": "def is_prime?(n)\n return false if n <= 1\n (2..Math.sqrt(n)).each do |i|\n return false if n % i == 0\n end\n true\nend\n\n# Usage:\nputs is_prime?(29) # Output: true\nputs is_prime?(30) # Output: false\n" - }, - { - "title": "Find all primes up to integer (Sieve of Sundaram)", - "description": "Finds all the prime numbers up to a specific integer.", - "author": "ACR1209", - "tags": [ - "math", - "prime numbers" - ], - "contributors": [], - "code": "def sieve_of_sundaram(limit)\n n = (limit - 1) / 2\n marked = Array.new(n + 1, false)\n\n (1..n).each do |i|\n j = i\n while (i + j + 2 * i * j) <= n\n marked[i + j + 2 * i * j] = true\n j += 1\n end\n end\n\n primes = [2]\n (1..n).each do |i|\n primes << (2 * i + 1) unless marked[i]\n end\n\n primes\nend\n\n# Usage:\nprint sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "Capitalize Words", - "description": "Capitalizes the first letter of each word in a string.", - "author": "ACR1209", - "tags": [ - "string", - "capitalize", - "words" - ], - "contributors": [], - "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage:\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" - }, - { - "title": "Count Word Occurrences in String", - "description": "Counts the occurrences of each word in a given string.", - "author": "ACR1209", - "tags": [ - "string", - "occurrences", - "word-count" - ], - "contributors": [], - "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage:\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" - }, - { - "title": "Remove Punctuation", - "description": "Removes all punctuation from a given string.", - "author": "ACR1209", - "tags": [ - "string", - "punctuation", - "remove" - ], - "contributors": [], - "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage:\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" - }, - { - "title": "Transform Camel Case to Snake Case", - "description": "Converts a Camel or Pascal Case string to Snake case.", - "author": "ACR1209", - "tags": [ - "string", - "convert", - "camel-case", - "snake-case", - "pascal-case" - ], - "contributors": [], - "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').sub(/^_/, '').downcase\nend\n\n# Usage:\ncamel_case = \"camelCaseToSnakeCase\"\npascal_case = \"PascalCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\nputs camel_to_snake(pascal_case) # Output: \"pascal_case_to_snake_case\"\n" - }, - { - "title": "Transform from Snake Case to Camel Case", - "description": "Converts a Snake Case string to Camel Case.", - "author": "ACR1209", - "tags": [ - "string", - "convert", - "snake-case", - "camel-case" - ], - "contributors": [], - "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" - }, - { - "title": "Transform from Snake Case to Pascal Case", - "description": "Converts a Snake Case string to Pascal Case.", - "author": "ACR1209", - "tags": [ - "string", - "convert", - "snake-case", - "pascal-case" - ], - "contributors": [], - "code": "def snake_to_pascal(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_pascal(snake_case) # Output: \"SnakeCaseToPascalCase\"\n" - }, - { - "title": "Truncate String", - "description": "Truncates a string to a specified length, optionally adding an ellipsis.", - "author": "ACR1209", - "tags": [ - "string", - "truncate" - ], - "contributors": [], - "code": "def truncate_string(str, max_length)\n return str if str.length <= max_length || max_length <= 3\n str[0, max_length - 3] + '...'\nend\n\n# Usage:\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/rust.json b/public/consolidated/rust.json deleted file mode 100644 index d3bd8f67..00000000 --- a/public/consolidated/rust.json +++ /dev/null @@ -1,61 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Prints Hello, World! to the terminal.", - "author": "James-Beans", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n" - } - ] - }, - { - "name": "File Handling", - "snippets": [ - { - "title": "Find Files", - "description": "Finds all files of the specified extension within a given directory.", - "author": "Mathys-Gasnier", - "tags": [ - "file", - "search" - ], - "contributors": [], - "code": "fn find_files(directory: &str, file_type: &str) -> std::io::Result> {\n let mut result = vec![];\n\n for entry in std::fs::read_dir(directory)? {\n let dir = entry?;\n let path = dir.path();\n if dir.file_type().is_ok_and(|t| !t.is_file()) &&\n path.extension().is_some_and(|ext| ext != file_type) {\n continue;\n }\n result.push(path)\n }\n\n Ok(result)\n}\n\n// Usage:\nfind_files(\"/path/to/your/directory\", \".pdf\"); // Returns: if Ok(), a vector of path to `.pdf` files in the directory\n" - }, - { - "title": "Read File Lines", - "description": "Reads all lines from a file and returns them as a vector of strings.", - "author": "Mathys-Gasnier", - "tags": [ - "file", - "read" - ], - "contributors": [], - "code": "fn read_lines(file_name: &str) -> std::io::Result>\n Ok(\n std::fs::read_to_string(file_name)?\n .lines()\n .map(String::from)\n .collect()\n )\n}\n\n// Usage:\nread_lines(\"path/to/file.txt\"); // Returns: If Ok(), a Vec of the lines of the file\n" - } - ] - }, - { - "name": "String Manipulation", - "snippets": [ - { - "title": "Capitalize String", - "description": "Makes the first letter of a string uppercase.", - "author": "Mathys-Gasnier", - "tags": [ - "string", - "capitalize" - ], - "contributors": [], - "code": "fn capitalized(str: &str) -> String {\n let mut chars = str.chars();\n match chars.next() {\n None => String::new(),\n Some(f) => f.to_uppercase().chain(chars).collect(),\n }\n}\n\n// Usage:\ncapitalized(\"lower_case\"); // Returns: Lower_case\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json deleted file mode 100644 index 4963e39b..00000000 --- a/public/consolidated/scss.json +++ /dev/null @@ -1,228 +0,0 @@ -[ - { - "name": "Animations", - "snippets": [ - { - "title": "Fade In Animation", - "description": "Animates the fade-in effect.", - "author": "dostonnabotov", - "tags": [ - "animation", - "fade", - "css" - ], - "contributors": [], - "code": "@keyframes fade-in {\n from {\n opacity: 0;\n }\n to {\n opacity: 1;\n }\n}\n\n@mixin fade-in($duration: 1s, $easing: ease-in-out) {\n animation: fade-in $duration $easing;\n}\n" - }, - { - "title": "Slide In From Left", - "description": "Animates content sliding in from the left.", - "author": "dostonnabotov", - "tags": [ - "animation", - "slide", - "css" - ], - "contributors": [], - "code": "@keyframes slide-in-left {\n from {\n transform: translateX(-100%);\n }\n to {\n transform: translateX(0);\n }\n}\n\n@mixin slide-in-left($duration: 0.5s, $easing: ease-out) {\n animation: slide-in-left $duration $easing;\n}\n" - } - ] - }, - { - "name": "Borders Shadows", - "snippets": [ - { - "title": "Border Radius Helper", - "description": "Applies a customizable border-radius.", - "author": "dostonnabotov", - "tags": [ - "border", - "radius", - "css" - ], - "contributors": [], - "code": "@mixin border-radius($radius: 4px) {\n border-radius: $radius;\n}\n" - }, - { - "title": "Box Shadow Helper", - "description": "Generates a box shadow with customizable values.", - "author": "dostonnabotov", - "tags": [ - "box-shadow", - "css", - "effects" - ], - "contributors": [], - "code": "@mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {\n box-shadow: $x $y $blur $spread $color;\n}\n" - } - ] - }, - { - "name": "Components", - "snippets": [ - { - "title": "Primary Button", - "description": "Generates a styled primary button.", - "author": "dostonnabotov", - "tags": [ - "button", - "primary", - "css" - ], - "contributors": [], - "code": "@mixin primary-button($bg: #007bff, $color: #fff) {\n background-color: $bg;\n color: $color;\n padding: 0.5rem 1rem;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n\n &:hover {\n background-color: darken($bg, 10%);\n }\n}\n" - } - ] - }, - { - "name": "Layouts", - "snippets": [ - { - "title": "Aspect Ratio", - "description": "Ensures that elements maintain a specific aspect ratio.", - "author": "dostonnabotov", - "tags": [ - "aspect-ratio", - "layout", - "css" - ], - "contributors": [], - "code": "@mixin aspect-ratio($width, $height) {\n position: relative;\n width: 100%;\n padding-top: ($height / $width) * 100%;\n > * {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n }\n}\n" - }, - { - "title": "Dark Theme", - "description": "SCSS mixin to change styles for dark themes.", - "author": "gihanrangana", - "tags": [ - "css", - "mixin", - "snippet", - "dark-theme", - "layout" - ], - "contributors": [], - "code": "@mixin isDark($type: 'module') {\n $root: &;\n\n @if $type == 'module' {\n :global {\n @at-root body[theme='dark'] #{$root} {\n @content;\n }\n }\n } @else {\n &[theme='dark'] {\n @content;\n }\n }\n}\n\n// Usage:\n.container{\n\tbackground: #f0f0f0;\n\t@include isDark {\n\t\tbackground: #222;\n\t}\n}\n" - }, - { - "title": "Flex Center", - "description": "A mixin to center content using flexbox.", - "author": "dostonnabotov", - "tags": [ - "flex", - "center", - "css" - ], - "contributors": [], - "code": "@mixin flex-center {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n" - }, - { - "title": "Grid Container", - "description": "Creates a responsive grid container with customizable column counts.", - "author": "dostonnabotov", - "tags": [ - "grid", - "layout", - "css" - ], - "contributors": [], - "code": "@mixin grid-container($columns: 12, $gap: 1rem) {\n display: grid;\n grid-template-columns: repeat($columns, 1fr);\n gap: $gap;\n}\n" - } - ] - }, - { - "name": "Typography", - "snippets": [ - { - "title": "Font Import Helper", - "description": "Simplifies importing custom fonts in Sass.", - "author": "dostonnabotov", - "tags": [ - "mixin", - "fonts", - "css" - ], - "contributors": [], - "code": "@mixin import-font($family, $weight: 400, $style: normal) {\n @font-face {\n font-family: #{$family};\n font-weight: #{$weight};\n font-style: #{$style};\n src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),\n url('/fonts/#{$family}-#{$weight}.woff') format('woff');\n }\n}\n" - }, - { - "title": "Line Clamp Mixin", - "description": "A Sass mixin to clamp text to a specific number of lines.", - "author": "dostonnabotov", - "tags": [ - "mixin", - "typography", - "css" - ], - "contributors": [], - "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" - }, - { - "title": "PX to REM Helper", - "description": "This function will convert px values to rem values.", - "author": "gihanrangana", - "tags": [ - "function", - "pixel", - "rem", - "px-to-rem" - ], - "contributors": [], - "code": "@function px-to-rem($px, $base: 16px) {\n @return ($px / $base) * 1rem;\n}\n\n// Usage:\ndiv {\n font-size: px-to-rem(12px); // Output: 0.75rem\n padding: px-to-rem(16px); // Output: 1rem\n margin: px-to-rem(32px) // Output 2rem\n}\n" - }, - { - "title": "Text Gradient", - "description": "Adds a gradient color effect to text.", - "author": "dostonnabotov", - "tags": [ - "mixin", - "gradient", - "text", - "css" - ], - "contributors": [], - "code": "@mixin text-gradient($from, $to) {\n background: linear-gradient(to right, $from, $to);\n -webkit-background-clip: text;\n -webkit-text-fill-color: transparent;\n}\n" - }, - { - "title": "Text Overflow Ellipsis", - "description": "Ensures long text is truncated with an ellipsis.", - "author": "dostonnabotov", - "tags": [ - "mixin", - "text", - "css" - ], - "contributors": [], - "code": "@mixin text-ellipsis {\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n}\n" - } - ] - }, - { - "name": "Utilities", - "snippets": [ - { - "title": "Clearfix", - "description": "Provides a clearfix utility for floating elements.", - "author": "dostonnabotov", - "tags": [ - "clearfix", - "utility", - "css" - ], - "contributors": [], - "code": "@mixin clearfix {\n &::after {\n content: '';\n display: block;\n clear: both;\n }\n}\n" - }, - { - "title": "Responsive Breakpoints", - "description": "Generates media queries for responsive design.", - "author": "dostonnabotov", - "tags": [ - "responsive", - "media-queries", - "css" - ], - "contributors": [], - "code": "@mixin breakpoint($breakpoint) {\n @if $breakpoint == sm {\n @media (max-width: 576px) { @content; }\n } @else if $breakpoint == md {\n @media (max-width: 768px) { @content; }\n } @else if $breakpoint == lg {\n @media (max-width: 992px) { @content; }\n } @else if $breakpoint == xl {\n @media (max-width: 1200px) { @content; }\n }\n}\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/typescript.json b/public/consolidated/typescript.json deleted file mode 100644 index 1d3ece20..00000000 --- a/public/consolidated/typescript.json +++ /dev/null @@ -1,19 +0,0 @@ -[ - { - "name": "Helper Types", - "snippets": [ - { - "title": "Exclusive Types", - "description": "Allows to have a type which conforms to either/or.", - "author": "px-d", - "tags": [ - "typescript", - "helper-types", - "typedefinition" - ], - "contributors": [], - "code": "type Exclusive = T | U extends Record\n ?\n | ({ [P in Exclude]?: never } & U)\n | ({ [P in Exclude]?: never } & T)\n : T | U;\n\n\n// Usage:\ntype A = { name: string; email?: string; provider?: string };\ntype B = { name: string; phone?: string; country?: string };\n\ntype EitherOr = Exclusive;\n\nconst w: EitherOr = { name: \"John\", email: \"j@d.c\" }; // ✅\nconst x: EitherOr = { name: \"John\", phone: \"+123 456\" }; // ✅\nconst y: EitherOr = { name: \"John\", email: \"\", phone: \"\" }; // ⛔️\nconst z: EitherOr = { name: \"John\", phne: \"\", provider: \"\" }; // ⛔️\n" - } - ] - } -] \ No newline at end of file diff --git a/public/icons/c.svg b/public/icons/c.svg deleted file mode 100644 index 94ebe6d9..00000000 --- a/public/icons/c.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/public/icons/cpp.svg b/public/icons/cpp.svg deleted file mode 100644 index 7e75c38c..00000000 --- a/public/icons/cpp.svg +++ /dev/null @@ -1,10 +0,0 @@ - -C++ logo -A two tone blue hexagon with the letters C++ inside in white - - - - - - - \ No newline at end of file diff --git a/public/icons/csharp.svg b/public/icons/csharp.svg deleted file mode 100644 index 96cf5abc..00000000 --- a/public/icons/csharp.svg +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/public/icons/css.svg b/public/icons/css.svg deleted file mode 100644 index c981c7ac..00000000 --- a/public/icons/css.svg +++ /dev/null @@ -1,6 +0,0 @@ - -CSS Logo Square -A purple square with the letters CSS inside in white - - - \ No newline at end of file diff --git a/public/icons/haskell.svg b/public/icons/haskell.svg deleted file mode 100644 index 8163876f..00000000 --- a/public/icons/haskell.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/public/icons/html.svg b/public/icons/html.svg deleted file mode 100644 index 59345ce4..00000000 --- a/public/icons/html.svg +++ /dev/null @@ -1,8 +0,0 @@ - -HTML5 Logo -A two tone orange shield with a white number 5 in it - - - - - \ No newline at end of file diff --git a/public/icons/java.svg b/public/icons/java.svg deleted file mode 100644 index e51aae9c..00000000 --- a/public/icons/java.svg +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/public/icons/javascript.svg b/public/icons/javascript.svg deleted file mode 100644 index 25ccdbaa..00000000 --- a/public/icons/javascript.svg +++ /dev/null @@ -1,6 +0,0 @@ - -JS Logo Square -A yellow square with the letters JS inside in white - - - diff --git a/public/icons/python.svg b/public/icons/python.svg deleted file mode 100644 index 3755e98e..00000000 --- a/public/icons/python.svg +++ /dev/null @@ -1,21 +0,0 @@ - -Python Logo -A blue and yellow snake symbol forming a plus with a somewhat circular or rounded shape - - - - - - - - - - - - - - - - - - diff --git a/public/icons/regex.svg b/public/icons/regex.svg deleted file mode 100644 index bdbe2fc2..00000000 --- a/public/icons/regex.svg +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - diff --git a/public/icons/ruby.svg b/public/icons/ruby.svg deleted file mode 100644 index 10ec5836..00000000 --- a/public/icons/ruby.svg +++ /dev/null @@ -1,139 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/public/icons/rust.svg b/public/icons/rust.svg deleted file mode 100644 index 3f62b3c2..00000000 --- a/public/icons/rust.svg +++ /dev/null @@ -1,9 +0,0 @@ - - -Rust Logo -A black gear with the letter R in the center - - - - - diff --git a/public/icons/scss.svg b/public/icons/scss.svg deleted file mode 100644 index e68fea23..00000000 --- a/public/icons/scss.svg +++ /dev/null @@ -1,5 +0,0 @@ - -Sass or SCSS Logo -The word Sass in pink cursive font - - diff --git a/public/icons/typescript.svg b/public/icons/typescript.svg deleted file mode 100644 index c1d6592b..00000000 --- a/public/icons/typescript.svg +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/snippets/bash/icon.svg b/snippets/bash/icon.svg new file mode 100644 index 00000000..9fb1be15 --- /dev/null +++ b/snippets/bash/icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/snippets/bash/system/kill-previous-instances.md b/snippets/bash/system/kill-previous-instances.md new file mode 100644 index 00000000..0fcafce3 --- /dev/null +++ b/snippets/bash/system/kill-previous-instances.md @@ -0,0 +1,20 @@ +--- +title: Kill Previous Instances +description: Kill all previous instances of a script +author: saminjay +tags: kill,process,background +--- + +```bash +function kill_prev() { + # $$ contains current pid (grep ignore so it doesn't suicide) + local processes + readarray -t processes < <(pgrep -f "$0" | grep -v "$$") + kill "${processes[@]}" >/dev/null 2>&1 +} + +# Usage: +# Add this function to your background running script +# It will make sure that only one instance of your script is running at a time +kill_prev +``` diff --git a/snippets/bash/system/system-resource-monitor.md b/snippets/bash/system/system-resource-monitor.md new file mode 100644 index 00000000..c382e5ab --- /dev/null +++ b/snippets/bash/system/system-resource-monitor.md @@ -0,0 +1,22 @@ +--- +title: System Resource Monitor +description: Monitors system resources (CPU, RAM, disk, users) +author: sponkurtus2 +tags: file,system +--- + +```bash +system_resources () { + echo "CPU Load: $(top -bn1 | grep "Cpu(s)" | awk '{print $2}')%" + echo "Memory Used: $(free -m | awk 'NR==2{printf "%.2f%%", $3*100/$2}')" + echo "Disk Used: $(df -h / | awk 'NR==2{print $5}')" + echo "Active Users: $(who | wc -l)" +} + +system_resources "$@" + +# Usage: +chmod a+x system-resource-monitor.sh # First make it executable for all the users + +./system-resource-monitor.sh # It will print the following system resources (CPU, RAM, disk, and active users) +``` diff --git a/snippets/c/mathematical-functions/linear-mapping.md b/snippets/c/mathematical-functions/linear-mapping.md new file mode 100644 index 00000000..0d4e360b --- /dev/null +++ b/snippets/c/mathematical-functions/linear-mapping.md @@ -0,0 +1,18 @@ +--- +title: Linear Mapping +description: remaps a value from one range to another +author: JasimAlrawie +tags: math,number-theory,algebra +--- + +```c +float linearMapping(float value, float minIn, float maxIn, float minOut, float maxOut) { + return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut; +} + + +// Usage: +linearMapping(value, 0, 1, 0, 255); // remaps the value from (0,1) to (0,255) +linearMapping(value, 0, PI*2, 0, 360); // remaps the value from rad to deg +linearMapping(value, -1, 1, 1, 8); // remaps the value from (-1,1) to (1,8) +``` \ No newline at end of file diff --git a/snippets/c/search/binary-search.md b/snippets/c/search/binary-search.md new file mode 100644 index 00000000..7f65d37e --- /dev/null +++ b/snippets/c/search/binary-search.md @@ -0,0 +1,36 @@ +--- +title: Binary Search +description: Searches for an element in a sorted array using the Binary Search algorithm. +author: 0xHouss +tags: search,binarysearch,array,algorithm +--- + +```c +int binarySearch(int arr[], int low, int high, int x) { + while (low <= high) { + int mid = low + (high - low) / 2; + + // Check if x is present at mid + if (arr[mid] == x) { + return mid; + } + + // If x is smaller, search the left half + if (arr[mid] > x) { + high = mid - 1; + } else { // If x is larger, search the right half + low = mid + 1; + } + } + return -1; // Element not found +} + +// Usage: +int arr[] = {2, 3, 4, 10, 40}; +int n = sizeof(arr) / sizeof(arr[0]); +int x = 10; +int result = binarySearch(arr, 0, n - 1, x); +// result = 3 (index of the element 10) + + +``` \ No newline at end of file diff --git a/snippets/c/search/linear-search.md b/snippets/c/search/linear-search.md new file mode 100644 index 00000000..3e6f4f29 --- /dev/null +++ b/snippets/c/search/linear-search.md @@ -0,0 +1,25 @@ +--- +title: Linear Search +description: Searches for an element in an array using the Linear Search algorithm. +author: 0xHouss +tags: search,linearsearch,array,algorithm +--- + +```c +int linearSearch(int arr[], int n, int x) { + for (int i = 0; i < n; i++) { + if (arr[i] == x) { + return i; // Element found at index i + } + } + return -1; // Element not found +} + +// Usage: +int arr[] = {10, 20, 30, 40, 50}; +int n = sizeof(arr) / sizeof(arr[0]); +int x = 30; +int result = linearSearch(arr, n, x); +// result = 2 (index of the element 30) + +``` \ No newline at end of file diff --git a/snippets/c/sorting/bubble-sort.md b/snippets/c/sorting/bubble-sort.md new file mode 100644 index 00000000..e6c81508 --- /dev/null +++ b/snippets/c/sorting/bubble-sort.md @@ -0,0 +1,27 @@ +--- +title: Bubble Sort +description: Sorts an array of integers using the Bubble Sort algorithm. +author: 0xHouss +tags: sorting,bubblesort,array,algorithm +--- + +```c +void bubbleSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + // Swap arr[j] and arr[j + 1] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +// Usage: +int arr[] = {64, 34, 25, 12, 22, 11, 90}; +int n = sizeof(arr) / sizeof(arr[0]); +bubbleSort(arr, n); +// Now arr[] is sorted: {11, 12, 22, 25, 34, 64, 90} +``` \ No newline at end of file diff --git a/snippets/c/sorting/insertion-sort.md b/snippets/c/sorting/insertion-sort.md new file mode 100644 index 00000000..c26cf552 --- /dev/null +++ b/snippets/c/sorting/insertion-sort.md @@ -0,0 +1,30 @@ +--- +title: Insertion Sort +description: Sorts an array of integers using the Insertion Sort algorithm. +author: 0xHouss +tags: sorting,insertionsort,array,algorithm +--- + +```c +void insertionSort(int arr[], int n) { + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + + // Move elements of arr[0..i-1] that are greater than key + // to one position ahead of their current position + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = key; + } +} + +// Usage: +int arr[] = {12, 11, 13, 5, 6}; +int n = sizeof(arr) / sizeof(arr[0]); +insertionSort(arr, n); +// Now arr[] is sorted: {5, 6, 11, 12, 13} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/merge-sort.md b/snippets/c/sorting/merge-sort.md new file mode 100644 index 00000000..71fc0315 --- /dev/null +++ b/snippets/c/sorting/merge-sort.md @@ -0,0 +1,71 @@ +--- +title: Merge Sort +description: Sorts an array of integers using the Merge Sort algorithm. +author: 0xHouss +tags: sorting,mergesort,array,algorithm +--- + +```c +#include + +void merge(int arr[], int l, int m, int r) { + int n1 = m - l + 1; + int n2 = r - m; + + // Temporary arrays + int L[n1], R[n2]; + + // Copy data to temporary arrays L[] and R[] + for (int i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (int j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + int i = 0, j = 0, k = l; + + // Merge the temporary arrays back into arr[l..r] + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + // Copy remaining elements of L[], if any + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + // Copy remaining elements of R[], if any + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + +void mergeSort(int arr[], int l, int r) { + if (l < r) { + int m = l + (r - l) / 2; + + // Sort first and second halves + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + +// Usage: +int arr[] = {38, 27, 43, 3, 9, 82, 10}; +int n = sizeof(arr) / sizeof(arr[0]); +mergeSort(arr, 0, n - 1); +// Now arr[] is sorted: {3, 9, 10, 27, 38, 43, 82} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/quick-sort.md b/snippets/c/sorting/quick-sort.md new file mode 100644 index 00000000..be259147 --- /dev/null +++ b/snippets/c/sorting/quick-sort.md @@ -0,0 +1,47 @@ +--- +title: Quick Sort +description: Sorts an array of integers using the Quick Sort algorithm. +author: 0xHouss +tags: sorting,quicksort,array,algorithm +--- + +```c +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // Pivot element + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + // Swap arr[i] and arr[j] + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + // Swap arr[i + 1] and arr[high] (pivot) + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + + return i + 1; +} + +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + + // Recursively sort elements before and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +// Usage: +int arr[] = {10, 7, 8, 9, 1, 5}; +int n = sizeof(arr) / sizeof(arr[0]); +quickSort(arr, 0, n - 1); +// Now arr[] is sorted: {1, 5, 7, 8, 9, 10} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/selection-sort.md b/snippets/c/sorting/selection-sort.md new file mode 100644 index 00000000..3bdfda99 --- /dev/null +++ b/snippets/c/sorting/selection-sort.md @@ -0,0 +1,33 @@ +--- +title: Selection Sort +description: Sorts an array of integers using the Selection Sort algorithm. +author: 0xHouss +tags: sorting,selectionsort,array,algorithm +--- + +```c +void selectionSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + int minIdx = i; + + // Find the minimum element in the unsorted part of the array + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum element with the first element of the unsorted part + int temp = arr[minIdx]; + arr[minIdx] = arr[i]; + arr[i] = temp; + } +} + +// Usage: +int arr[] = {64, 25, 12, 22, 11}; +int n = sizeof(arr) / sizeof(arr[0]); +selectionSort(arr, n); +// Now arr[] is sorted: {11, 12, 22, 25, 64} + +``` \ No newline at end of file diff --git a/snippets/cpp/array-manipulation/filter-vector.md b/snippets/cpp/array-manipulation/filter-vector.md new file mode 100644 index 00000000..083f7899 --- /dev/null +++ b/snippets/cpp/array-manipulation/filter-vector.md @@ -0,0 +1,25 @@ +--- +Title: Filter Vector +Description: Filters a vector using a predicate function. +Author: majvax +Tags: array,filter,c++23 +--- + +```cpp +#include +#include + +template +auto filter(const std::vector& vec, P&& predicate) { + return vec + | std::views::filter(std::forward

    (predicate)) + | std::ranges::to>(); +} + + + +// Usage: +std::vector vec = {1, 2, 3, 4, 5}; +std::vector filtered = filter(vec, [](int i){ return i % 2 == 0; }); +// filtered contains 2 and 4 +``` diff --git a/snippets/cpp/array-manipulation/transform-vector.md b/snippets/cpp/array-manipulation/transform-vector.md new file mode 100644 index 00000000..e01cbabe --- /dev/null +++ b/snippets/cpp/array-manipulation/transform-vector.md @@ -0,0 +1,26 @@ +--- +Title: Transform Vector +Description: Transforms a vector using a function. +Author: majvax +Tags: array,transform,c++23 +--- + +```cpp +#include +#include + +template +auto transform(const std::vector& vec, F&& transformer) { + using U = std::invoke_result_t; + return vec + | std::views::transform(std::forward(transformer)) + | std::ranges::to>(); +} + + + +// Usage: +std::vector vec = {1, 2, 3, 4, 5}; +std::vector transformed = transform(vec, [](int i){ return i * 2; }); +// transformed contains 2, 4, 6, 8, 10 +``` diff --git a/snippets/cpp/file-handling/find-files-recursively.md b/snippets/cpp/file-handling/find-files-recursively.md new file mode 100644 index 00000000..83d974e4 --- /dev/null +++ b/snippets/cpp/file-handling/find-files-recursively.md @@ -0,0 +1,57 @@ +--- +Title: Find files recursively +Description: Find all the files in a directory and subdirectories using a predicate function. +Author: majvax +Tags: filesystem,file_search,c++17 +--- + +```cpp +#include +#include +#include + +template +std::vector find_files_recursive(const std::string& path, P&& predicate) { + std::vector files; + std::error_code ec; + + if (!std::filesystem::exists(path, ec) || ec) + return files; + if (!std::filesystem::is_directory(path, ec) || ec) + return files; + + auto it = std::filesystem::recursive_directory_iterator(path, ec); + if (ec) + return files; + + for (const auto& entry : it) + if (!std::filesystem::is_directory(entry) && predicate(entry.path())) + files.push_back(entry.path()); + + return files; +} + + + +// Usage: + +// Find all files with size greater than 10MB +auto files = find_files_recursive("Path", [](const auto& p) { + return std::filesystem::file_size(p) > 10 * 1024 * 1024; +}); + +// Find all files with ".pdf" as extension +auto files = find_files_recursive("Path", [](const auto& p) { + return p.extension() == ".pdf"; +}); + +// Find all files writed after The New Year +#include +// need std=c++20 +auto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys( + std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}} +); +auto files = find_files_recursive("Path", [jan_1_2025](const auto& p) { + return std::filesystem::last_write_time(p) > jan_1_2025; +}), +``` diff --git a/snippets/cpp/file-handling/find-files.md b/snippets/cpp/file-handling/find-files.md new file mode 100644 index 00000000..c0ff9331 --- /dev/null +++ b/snippets/cpp/file-handling/find-files.md @@ -0,0 +1,57 @@ +--- +Title: Find files +Description: Find all the files in a directory using a predicate function. +Author: majvax +Tags: filesystem,file_search,c++17 +--- + +```cpp +#include +#include +#include + +template +std::vector find_files(const std::string& path, P&& predicate) { + std::vector files; + std::error_code ec; + + if (!std::filesystem::exists(path, ec) || ec) + return files; + if (!std::filesystem::is_directory(path, ec) || ec) + return files; + + auto it = std::filesystem::directory_iterator(path, ec); + if (ec) + return files; + + for (const auto& entry : it) + if (!std::filesystem::is_directory(entry) && predicate(entry.path())) + files.push_back(entry.path()); + + return files; +} + + + +// Usage: + +// Find all files with size greater than 10MB +auto files = find_files("Path", [](const auto& p) { + return std::filesystem::file_size(p) > 10 * 1024 * 1024; +}); + +// Find all files with ".pdf" as extension +auto files = find_files("Path", [](const auto& p) { + return p.extension() == ".pdf"; +}); + +// Find all files writed after The New Year +#include +// need std=c++20 +auto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys( + std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}} +); +auto files = find_files("Path", [jan_1_2025](const auto& p) { + return std::filesystem::last_write_time(p) > jan_1_2025; +}), +``` diff --git a/snippets/cpp/file-handling/list-directories.md b/snippets/cpp/file-handling/list-directories.md new file mode 100644 index 00000000..028bc095 --- /dev/null +++ b/snippets/cpp/file-handling/list-directories.md @@ -0,0 +1,37 @@ +--- +Title: List Directories +Description: Lists all the directories in a path. +Author: majvax +Tags: filesystem,directories,c++17 +--- + +```cpp +#include +#include +#include + +std::vector list_directories(const std::string& path) { + std::vector files; + std::error_code ec; + + if (!std::filesystem::exists(path, ec) || ec) + return files; + if (!std::filesystem::is_directory(path, ec) || ec) + return files; + + auto it = std::filesystem::directory_iterator(path, ec); + if (ec) + return files; + + for (const auto& entry : it) + if (std::filesystem::is_directory(entry)) + files.push_back(entry.path()); + + return files; +} + + + +// Usage: +auto directories = list_directories("Path"); +``` diff --git a/snippets/cpp/string-manipulation/filter.md b/snippets/cpp/string-manipulation/filter.md new file mode 100644 index 00000000..b09b50f5 --- /dev/null +++ b/snippets/cpp/string-manipulation/filter.md @@ -0,0 +1,25 @@ +--- +title: Filter +description: Filter a string with a predicate function +author: majvax +tags: string,filtering,c++23 +--- + +```cpp +#include +#include + +template +std::string filter(const std::string& str, P&& predicate) { + return str + | std::ranges::views::filter(std::forward

    (predicate)) + | std::ranges::to(); +} + + + +// Usage: +std::string str = "Hello, World!"; +std::string filtered = filter(str, [](char c){ return std::isalpha(c); }); +std::cout << filtered << std::endl; // HelloWorld +``` diff --git a/snippets/cpp/string-manipulation/palindrome.md b/snippets/cpp/string-manipulation/palindrome.md new file mode 100644 index 00000000..b563e22c --- /dev/null +++ b/snippets/cpp/string-manipulation/palindrome.md @@ -0,0 +1,26 @@ +--- +title: Palindrome +description: Check if a string is a palindrome or not. +author: majvax +tags: string,c++23 +--- + +```cpp +#include +#include +#include + +bool is_palindrome(const std::string& str) { + std::string sanitized_string = str + | std::ranges::views::filter([](char c){ return std::isalnum(c); }) + | std::ranges::views::transform([](char c){ return std::tolower(c); }) + | std::ranges::to(); + + return std::ranges::equal(sanitized_string, sanitized_string | std::views::reverse); +} + + + +// Usage: +bool pal = is_palindrome("A man, a plan, a canal, Panama"); // true +``` diff --git a/snippets/cpp/string-manipulation/reverse-string.md b/snippets/cpp/string-manipulation/reverse-string.md index 615189b1..ed3c3995 100644 --- a/snippets/cpp/string-manipulation/reverse-string.md +++ b/snippets/cpp/string-manipulation/reverse-string.md @@ -2,7 +2,7 @@ title: Reverse String description: Reverses the characters in a string. author: Vaibhav-kesarwani -tags: array,reverse +tags: array,reverse,c++23 --- ```cpp diff --git a/snippets/cpp/string-manipulation/transform.md b/snippets/cpp/string-manipulation/transform.md new file mode 100644 index 00000000..3d0ee01d --- /dev/null +++ b/snippets/cpp/string-manipulation/transform.md @@ -0,0 +1,25 @@ +--- +title: Transform +description: Transform a string with a function +author: majvax +tags: string,transform,c++23 +--- + +```cpp +#include +#include + +template +std::string transform(const std::string& str, F&& transformer) { + return str + | std::ranges::views::transform(std::forward(transformer)) + | std::ranges::to(); +} + + + +// Usage: +std::string str = "Hello, World!"; +std::string transformed = transform(str, [](char c){ return std::toupper(c); }); +std::cout << transformed << std::endl; // HELLO, WORLD! +``` diff --git a/snippets/css/animations/pulse-animation.md b/snippets/css/animations/pulse-animation.md index f7aeb2f1..6e2cff26 100644 --- a/snippets/css/animations/pulse-animation.md +++ b/snippets/css/animations/pulse-animation.md @@ -3,25 +3,22 @@ title: Pulse Animation description: Adds a smooth pulsing animation with opacity and scale effects author: AlsoKnownAs-Ax tags: animation,pulse,pulse-scale +contributors: alanb4rt --- ```css .pulse { - animation: pulse 2s ease-in-out infinite; + animation: pulse 1s ease-in-out infinite alternate; } @keyframes pulse { - 0% { + from { opacity: 0.5; transform: scale(1); } - 50% { + to { opacity: 1; transform: scale(1.05); } - 100% { - opacity: 0.5; - transform: scale(1); - } } ``` diff --git a/snippets/java/array-manipulation/remove-duplicates.md b/snippets/java/array-manipulation/remove-duplicates.md new file mode 100644 index 00000000..4f25da30 --- /dev/null +++ b/snippets/java/array-manipulation/remove-duplicates.md @@ -0,0 +1,22 @@ +--- +title: Remove duplicates +description: Removes duplicate elements from an list +author: Mcbencrafter +tags: list,duplicates,unique +--- + +```java +import java.util.List; +import java.util.stream.Collectors; + +public static List removeDuplicates(List list) { + return list.stream() + .distinct() + .collect(Collectors.toList()); +} + +// Usage: +List list = List.of(1, 2, 3, 4, 5, 1, 2, 3, 4, 5); +List result = removeDuplicates(list); +System.out.println("List with duplicates removed: " + result); // [1, 2, 3, 4, 5] +``` \ No newline at end of file diff --git a/snippets/java/date-time/date-time-formatting-american.md b/snippets/java/date-time/date-time-formatting-american.md new file mode 100644 index 00000000..c2bf6f93 --- /dev/null +++ b/snippets/java/date-time/date-time-formatting-american.md @@ -0,0 +1,32 @@ +--- +title: Date time formatting american +description: Formats a timestamp to a human-readable date-time string in the format "MM/dd/yyyy hh:mm:ss a" +author: Mcbencrafter +tags: date,time,date-time,formatting,american +--- + +```java +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.TimeUnit; + +// using the system default time zone +public static String formatDateTimeAmerican(long time, TimeUnit timeUnit) { + return formatDateTimeAmerican(time, timeUnit, ZoneId.systemDefault()); +} + +public static String formatDateTimeAmerican(long time, TimeUnit timeUnit, ZoneId timeZone) { + return DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a") + .withZone( + timeZone != null ? timeZone : ZoneId.systemDefault() + ) + .format(Instant.ofEpochSecond( + timeUnit.toSeconds(time) + )); +} + +// Usage: +System.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS)); // "12/31/2024 | 11:59:59 PM" for GMT+0000 +System.out.println(formatDateTimeAmerican(1735689599, TimeUnit.SECONDS, ZoneId.of("GMT+0000"))); // "12/31/2024 | 11:59:59 PM" +``` \ No newline at end of file diff --git a/snippets/java/date-time/date-time-formatting-european.md b/snippets/java/date-time/date-time-formatting-european.md new file mode 100644 index 00000000..7c78eba2 --- /dev/null +++ b/snippets/java/date-time/date-time-formatting-european.md @@ -0,0 +1,32 @@ +--- +title: Date time formatting european +description: Formats a timestamp to a human-readable date-time string in the format "dd.MM.yyyy HH:mm:ss" +author: Mcbencrafter +tags: date,time,date-time,formatting,european +--- + +```java +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.util.concurrent.TimeUnit; + +// using the system default time zone +public static String formatDateTimeEuropean(long time, TimeUnit timeUnit) { + return formatDateTimeEuropean(time, timeUnit, ZoneId.systemDefault()); +} + +public static String formatDateTimeEuropean(long time, TimeUnit timeUnit, ZoneId timeZone) { + return DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss") + .withZone( + timeZone != null ? timeZone : ZoneId.systemDefault() + ) + .format(Instant.ofEpochSecond( + timeUnit.toSeconds(time) + )); +} + +// Usage: +System.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS)); // "31.12.2024 | 23:59:59" for GMT+0000 +System.out.println(formatDateTimeEuropean(1735689599, TimeUnit.SECONDS, ZoneId.of("GMT+0000"))); // "31.12.2024 | 23:59:59" +``` \ No newline at end of file diff --git a/snippets/java/date-time/duration-formatting-hours-minutes-seconds.md b/snippets/java/date-time/duration-formatting-hours-minutes-seconds.md new file mode 100644 index 00000000..718fd39b --- /dev/null +++ b/snippets/java/date-time/duration-formatting-hours-minutes-seconds.md @@ -0,0 +1,33 @@ +--- +title: Duration formatting hours minutes seconds +description: Converts a given time duration to a human-readable string in the format "hh:mm(:ss)" +author: Mcbencrafter +tags: time,formatting,hours,minutes,seconds +--- + +```java +import java.util.concurrent.TimeUnit; + +public static String formatDurationToHoursMinutesAndSeconds(int time, TimeUnit timeUnit, boolean showSeconds) { + long totalSeconds = timeUnit.toSeconds(time); + + if (totalSeconds < 0) + throw new IllegalArgumentException("Duration must be a non-negative value."); + + // These variables can be directly used in the return statement, + // but are kept as separate variables here for better readability. + long hours = totalSeconds / 3600; + long minutes = (totalSeconds % 3600) / 60; + long seconds = totalSeconds % 60; + + if (showSeconds) { + return String.format("%02d:%02d:%02d", hours, minutes, seconds); + } else { + return String.format("%02d:%02d", hours, minutes); + } +} + +// Usage: +System.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, true)); // "01:03:30" +System.out.println(formatDurationToHoursMinutesAndSeconds(3810, TimeUnit.SECONDS, false)); // "01:03" +``` \ No newline at end of file diff --git a/snippets/java/date-time/duration-formatting-minutes-seconds.md b/snippets/java/date-time/duration-formatting-minutes-seconds.md new file mode 100644 index 00000000..49107f58 --- /dev/null +++ b/snippets/java/date-time/duration-formatting-minutes-seconds.md @@ -0,0 +1,28 @@ +--- +title: Duration formatting minutes seconds +description: Converts a given time duration to a human-readable string in the format "mm:ss" +author: Mcbencrafter +tags: time,formatting,minutes,seconds +--- + +```java +import java.util.concurrent.TimeUnit; + +public static String formatDurationToMinutesAndSeconds(int time, TimeUnit timeUnit) { + long totalSeconds = timeUnit.toSeconds(time); + + if (totalSeconds < 0) + throw new IllegalArgumentException("Duration must be a non-negative value."); + + // These variables can be directly used in the return statement, + // but are kept here as separate variables for better readability. + long minutes = totalSeconds / 60; + long seconds = totalSeconds % 60; + + return String.format("%02d:%02d", minutes, seconds); +} + +// Usage: +System.out.println(formatDurationToMinutesAndSeconds(120, TimeUnit.SECONDS)); // "02:00" +System.out.println(formatDurationToMinutesAndSeconds(75, TimeUnit.SECONDS)); // "01:15" +``` \ No newline at end of file diff --git a/snippets/javascript/color-manipulation/hex-to-rgb-color.md b/snippets/javascript/color-manipulation/hex-to-rgb-color.md new file mode 100644 index 00000000..3d0108d1 --- /dev/null +++ b/snippets/javascript/color-manipulation/hex-to-rgb-color.md @@ -0,0 +1,28 @@ +--- +title: Hex to RGB Color +description: Converts hexadecimal color code to RGB color values. +author: pvictordev +tags: color,conversion +--- + +```js +function hexToRgb(hex) { + let sanitizedHex = hex.startsWith("#") ? hex.slice(1) : hex; + + if (sanitizedHex.length === 3) { + sanitizedHex = [...sanitizedHex].map((char) => char + char).join(""); + } + + const bigint = parseInt(sanitizedHex, 16); + + return { + r: (bigint >> 16) & 0xff, + g: (bigint >> 8) & 0xff, + b: bigint & 0xff, + }; +} + +// Usage: +console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 } +console.log(hexToRgb("#ffff")); // { r: 0, g: 255, b: 255 } +``` \ No newline at end of file diff --git a/snippets/javascript/color-manipulation/hsl-to-rgb-color.md b/snippets/javascript/color-manipulation/hsl-to-rgb-color.md new file mode 100644 index 00000000..23390237 --- /dev/null +++ b/snippets/javascript/color-manipulation/hsl-to-rgb-color.md @@ -0,0 +1,34 @@ +--- +title: HSL to RGB Color +description: Converts HSL color values to RGB color values. +author: pvictordev +tags: color,conversion +--- + +```js +function hslToRgb(h, s, l) { + s /= 100; + l /= 100; + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs((h / 60) % 2 - 1)); + const m = l - c / 2; + + const [r, g, b] = + h < 60 ? [c, x, 0] : + h < 120 ? [x, c, 0] : + h < 180 ? [0, c, x] : + h < 240 ? [0, x, c] : + h < 300 ? [x, 0, c] : + [c, 0, x]; + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + }; +} + +// Usage: +console.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 } +console.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 } +``` \ No newline at end of file diff --git a/snippets/javascript/color-manipulation/rgb-to-hsl-color.md b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md new file mode 100644 index 00000000..51e29a86 --- /dev/null +++ b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md @@ -0,0 +1,37 @@ +--- +title: RGB to HSL Color +description: Converts RGB color values to HSL color values. +author: pvictordev +tags: color,conversion +--- + +```js +function rgbToHsl(r, g, b) { + [r, g, b] = [r, g, b].map((v) => v / 255); + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + + const l = (max + min) / 2; + + if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) }; + + const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min); + + const h = + max === r ? ((g - b) / delta + (g < b ? 6 : 0)) : + max === g ? (b - r) / delta + 2 : + (r - g) / delta + 4; + + return { + h: Math.round(h * 60), + s: Math.round(s * 100), + l: Math.round(l * 100), + }; +} + +// Usage: +console.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 } +console.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 } +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/combinations.md b/snippets/javascript/mathematical-functions/combinations.md new file mode 100644 index 00000000..080c8fd9 --- /dev/null +++ b/snippets/javascript/mathematical-functions/combinations.md @@ -0,0 +1,31 @@ +--- +title: Combinations +description: Calculates the number of combinations (denoted as C(n,r) or "n choose r"), which determines how many ways you can select r items from n items without considering the order. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function combinations(n, r) { + if (n < 0 || r < 0 || n < r) { + throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.'); + } + + function factorial(x) { + if (x === 0 || x === 1) return 1; + let result = 1; + for (let i = 2; i <= x; i++) { + result *= i; + } + return result; + } + + const numerator = factorial(n); + const denominator = factorial(r) * factorial(n - r); + return numerator / denominator; +} + +// Usage: +combinations(24,22); // Returns: 276 +combinations(5,3); // Returns: 10 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/cross-product.md b/snippets/javascript/mathematical-functions/cross-product.md new file mode 100644 index 00000000..4ed5404f --- /dev/null +++ b/snippets/javascript/mathematical-functions/cross-product.md @@ -0,0 +1,23 @@ +--- +title: Cross Product +description: Computes the cross product of two 3D vectors, which results in a vector perpendicular to both. +author: JanluOfficial +tags: math,vector-algebra +--- + +```js +function crossProduct(a, b) { + if (a.length !== 3 || b.length !== 3) { + throw new Error('Vectors must be 3-dimensional'); + } + + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0] + ]; +} + +// Usage: +crossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3] +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/dot-product.md b/snippets/javascript/mathematical-functions/dot-product.md new file mode 100644 index 00000000..d1b1e397 --- /dev/null +++ b/snippets/javascript/mathematical-functions/dot-product.md @@ -0,0 +1,19 @@ +--- +title: Dot Product +description: Computes the dot product of two vectors, which is the sum of the products of corresponding elements. +author: JanluOfficial +tags: math,vector-algebra +--- + +```js +function dotProduct(a, b) { + if (a.length !== b.length) { + throw new Error('Vectors must be of the same length'); + } + + return a.reduce((sum, value, index) => sum + value * b[index], 0); +} + +// Usage: +dotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/error-function.md b/snippets/javascript/mathematical-functions/error-function.md new file mode 100644 index 00000000..211171d8 --- /dev/null +++ b/snippets/javascript/mathematical-functions/error-function.md @@ -0,0 +1,21 @@ +--- +title: Error function +description: Computes the error function (erf(x)) for a given input x, which is a mathematical function used frequently in probability, statistics, and partial differential equations. +author: JanluOfficial +tags: math +--- + +```js +function erf(x) { + const sign = Math.sign(x); + const absX = Math.abs(x); + const t = 1 / (1 + 0.3275911 * absX); + const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429; + const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5)))); + return sign * (1 - poly * Math.exp(-absX * absX)); +} + +// Usage: +erf(-1); // Returns: -0.8427006897475899 +erf(1); // Returns: 0.8427006897475899 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/greatest-common-divisor.md b/snippets/javascript/mathematical-functions/greatest-common-divisor.md index f70101e2..fec36324 100644 --- a/snippets/javascript/mathematical-functions/greatest-common-divisor.md +++ b/snippets/javascript/mathematical-functions/greatest-common-divisor.md @@ -2,7 +2,7 @@ title: Greatest Common Divisor description: Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios. author: JanluOfficial -tags: math,division +tags: math,division,number-theory,algebra --- ```js diff --git a/snippets/javascript/mathematical-functions/least-common-multiple.md b/snippets/javascript/mathematical-functions/least-common-multiple.md new file mode 100644 index 00000000..40ac9721 --- /dev/null +++ b/snippets/javascript/mathematical-functions/least-common-multiple.md @@ -0,0 +1,25 @@ +--- +title: Least common multiple +description: Computes the least common multiple (LCM) of two numbers 𝑎 and b. The LCM is the smallest positive integer that is divisible by both a and b. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function lcm(a, b) { + function gcd(x, y) { + while (y !== 0) { + const temp = y; + y = x % y; + x = temp; + } + return Math.abs(x); + } + return Math.abs(a * b) / gcd(a, b); +} + +// Usage: +lcm(12,16); // Returns: 48 +lcm(8,20); // Returns: 40 +lcm(16,17); // Returns: 272 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/linear-mapping.md b/snippets/javascript/mathematical-functions/linear-mapping.md new file mode 100644 index 00000000..5baada59 --- /dev/null +++ b/snippets/javascript/mathematical-functions/linear-mapping.md @@ -0,0 +1,17 @@ +--- +title: Linear Mapping +description: remaps a value from one range to another +author: JasimAlrawie +tags: math,number-theory,algebra +--- + +```js +function linearMapping(value, minIn, maxIn, minOut, maxOut) { + return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut +} + +// Usage: +linearMapping(value, 0, 1, 0, 255) // remaps the value from (0,1) to (0,255) +linearMapping(value, 0, PI*2, 0, 360) // remaps the value from rad to deg +linearMapping(value, -1, 1, 1, 8) // remaps the value from (-1,1) to (1,8) +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/matrix-multiplication.md b/snippets/javascript/mathematical-functions/matrix-multiplication.md new file mode 100644 index 00000000..65799530 --- /dev/null +++ b/snippets/javascript/mathematical-functions/matrix-multiplication.md @@ -0,0 +1,34 @@ +--- +title: Matrix Multiplication +description: Multiplies two matrices, where the number of columns in the first matrix equals the number of rows in the second. +author: JanluOfficial +tags: math,matrix-algebra +--- + +```js +function matrixMultiply(A, B) { + const rowsA = A.length; + const colsA = A[0].length; + const rowsB = B.length; + const colsB = B[0].length; + + if (colsA !== rowsB) { + throw new Error('Number of columns of A must equal the number of rows of B'); + } + + let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0)); + + for (let i = 0; i < rowsA; i++) { + for (let j = 0; j < colsB; j++) { + for (let k = 0; k < colsA; k++) { + result[i][j] += A[i][k] * B[k][j]; + } + } + } + + return result; +} + +// Usage: +matrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]] +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/modular-inverse.md b/snippets/javascript/mathematical-functions/modular-inverse.md new file mode 100644 index 00000000..313ab46a --- /dev/null +++ b/snippets/javascript/mathematical-functions/modular-inverse.md @@ -0,0 +1,33 @@ +--- +title: Modular Inverse +description: Computes the modular multiplicative inverse of a number a under modulo m, which is the integer x such that (a*x) mod m=1. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function modInverse(a, m) { + function extendedGCD(a, b) { + if (b === 0) { + return { gcd: a, x: 1, y: 0 }; + } + const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b); + const x = y1; + const y = x1 - Math.floor(a / b) * y1; + return { gcd, x, y }; + } + + const { gcd, x } = extendedGCD(a, m); + + if (gcd !== 1) { + return null; + } + + return (x % m + m) % m; +} + +// Usage: +modInverse(3, 26); // Returns: 9 +modInverse(10, 17); // Returns: 12 +modInverse(6, 9); // Returns: null +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/prime-number.md b/snippets/javascript/mathematical-functions/prime-number.md new file mode 100644 index 00000000..028b8567 --- /dev/null +++ b/snippets/javascript/mathematical-functions/prime-number.md @@ -0,0 +1,24 @@ +--- +title: Prime Number +description: Checks if a number is a prime number or not. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function isPrime(num) { + if (num <= 1) return false; // 0 and 1 are not prime numbers + if (num <= 3) return true; // 2 and 3 are prime numbers + if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3 + + // Check divisors from 5 to √num, skipping multiples of 2 and 3 + for (let i = 5; i * i <= num; i += 6) { + if (num % i === 0 || num % (i + 2) === 0) return false; + } + return true; +} + +// Usage: +isPrime(69); // Returns: false +isPrime(17); // Returns: true +``` \ No newline at end of file diff --git a/snippets/python/math-and-numbers/calculate-compound-interest.md b/snippets/python/math-and-numbers/calculate-compound-interest.md index 0685a678..18f81a9e 100644 --- a/snippets/python/math-and-numbers/calculate-compound-interest.md +++ b/snippets/python/math-and-numbers/calculate-compound-interest.md @@ -2,7 +2,7 @@ title: Calculate Compound Interest description: Calculates compound interest for a given principal amount, rate, and time period. author: axorax -tags: python,math,compound interest,finance +tags: math,compound interest,finance --- ```py diff --git a/snippets/python/math-and-numbers/linear-mapping.md b/snippets/python/math-and-numbers/linear-mapping.md new file mode 100644 index 00000000..3f7f5daf --- /dev/null +++ b/snippets/python/math-and-numbers/linear-mapping.md @@ -0,0 +1,16 @@ +--- +title: Linear Mapping +description: remaps a value from one range to another +author: JasimAlrawie +tags: math,number-theory,algebra +--- + +```py +def linear_mapping(value, min_in, max_in, min_out, max_out): + return (value - min_in) * (max_out - min_out) / (max_in - min_in) + min_out + +#Usage: +linear_mapping(value, 0, 1, 0, 255) # remaps the value from (0,1) to (0,255) +linear_mapping(value, 0, PI*2, 0, 360) # remaps the value from rad to deg +linear_mapping(value, -1, 1, 1, 8) # remaps the value from (-1,1) to (1,8) +``` \ No newline at end of file diff --git a/snippets/python/string-manipulation/convert-string-to-ascii.md b/snippets/python/string-manipulation/convert-string-to-ascii.md deleted file mode 100644 index 61e830ba..00000000 --- a/snippets/python/string-manipulation/convert-string-to-ascii.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Convert String to ASCII -description: Converts a string into its ASCII representation. -author: axorax -tags: string,ascii,convert ---- - -```py -def string_to_ascii(s): - return [ord(char) for char in s] - -# Usage: -string_to_ascii('hello') # Returns: [104, 101, 108, 108, 111] -``` diff --git a/snippets/python/string-manipulation/convert-string-to-unicode.md b/snippets/python/string-manipulation/convert-string-to-unicode.md new file mode 100644 index 00000000..28d3f676 --- /dev/null +++ b/snippets/python/string-manipulation/convert-string-to-unicode.md @@ -0,0 +1,14 @@ +--- +title: Convert String to Unicode +description: Converts a string into its Unicode representation. +author: axorax +tags: string,ascii,unicode,convert +--- + +```py +def string_to_unicode(s): + return [ord(char) for char in s] + +# Usage: +string_to_unicode('hello') # Returns: [104, 101, 108, 108, 111] +``` diff --git a/snippets/python/string-manipulation/remove-specific-characters.md b/snippets/python/string-manipulation/remove-characters.md similarity index 88% rename from snippets/python/string-manipulation/remove-specific-characters.md rename to snippets/python/string-manipulation/remove-characters.md index 3965ae9b..b4a5366a 100644 --- a/snippets/python/string-manipulation/remove-specific-characters.md +++ b/snippets/python/string-manipulation/remove-characters.md @@ -1,5 +1,5 @@ --- -title: Remove Specific Characters +title: Remove Characters description: Removes specific characters from a string. author: axorax tags: string,remove,characters diff --git a/snippets/python/string-manipulation/reverse-string.md b/snippets/python/string-manipulation/reverse-string.md index fa045607..1334a775 100644 --- a/snippets/python/string-manipulation/reverse-string.md +++ b/snippets/python/string-manipulation/reverse-string.md @@ -6,7 +6,7 @@ tags: string,reverse --- ```py -def reverse_string(s): +def reverse_string(s:str) -> str: return s[::-1] # Usage: diff --git a/snippets/python/string-manipulation/truncate-string.md b/snippets/python/string-manipulation/truncate-string.md deleted file mode 100644 index 9788ac3e..00000000 --- a/snippets/python/string-manipulation/truncate-string.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Truncate String -description: Truncates a string to a specified length and adds an ellipsis. -author: axorax -tags: string,truncate ---- - -```py -def truncate_string(s, length): - return s[:length] + '...' if len(s) > length else s - -# Usage: -truncate_string('This is a long string', 10) # Returns: 'This is a ...' -``` diff --git a/snippets/python/string-manipulation/truncate.md b/snippets/python/string-manipulation/truncate.md new file mode 100644 index 00000000..5238f53b --- /dev/null +++ b/snippets/python/string-manipulation/truncate.md @@ -0,0 +1,16 @@ +--- +title: Truncate +description: Truncates a string to a specified length and a toggleable truncation notation. +author: axorax +contributors: MinerMinerMods +tags: string,truncate +--- + +```py +def truncate(s:str, length:int, suffix:bool = True) -> str : + return (s[:length] + ("..." if suffix else "")) if len(s) > length else s + +# Usage: +truncate('This is a long string', 10) # Returns: 'This is a ...' +truncate('This is a long string', 10, False) # Returns: 'This is a ' +``` diff --git a/snippets/rust/linux/get-desktop-enviroment.md b/snippets/rust/linux/get-desktop-enviroment.md new file mode 100644 index 00000000..a728d249 --- /dev/null +++ b/snippets/rust/linux/get-desktop-enviroment.md @@ -0,0 +1,44 @@ +--- +title: Get Desktop Enviroment +description: Get the Desktop Enviroment that the user is currently using. +author: sponkurtus2 +tags: linux,file +--- + +```rust +fn get_desktop_env() -> String { + // Return empty string if no X display is available + if env::var("DISPLAY").is_err() { + return String::new(); + } + + // Check common desktop environment variables. + for env_var in &[ + "XDG_SESSION_DESKTOP", + "XDG_CURRENT_DESKTOP", + "DESKTOP_SESSION", + ] { + if let Ok(de) = env::var(env_var) { + return de; + } + } + + // As fallback, try to get desktop name from last word of last line in .xinitrc + let path = format!("{}/.xinitrc", env::var("HOME").unwrap_or_default()); + if let Ok(mut file) = File::open(&path) { + let mut buf = String::new(); + if file.read_to_string(&mut buf).is_ok() { + if let Some(last_line) = buf.lines().last() { + let last_word = last_line.split(' ').last().unwrap_or(""); + return last_word.to_string(); + } + } + } + + // Return "N/A" if no desktop environment could be detected + String::from("N/A") +} + +// Usage: +get_desktop_env(); // Returns: the desktop enviroment that the user actually has e.g. i3. +``` \ No newline at end of file diff --git a/src/components/CodePreview.tsx b/src/components/CodePreview.tsx index 5e72711f..b936fbaa 100644 --- a/src/components/CodePreview.tsx +++ b/src/components/CodePreview.tsx @@ -40,7 +40,7 @@ const CodePreview = ({ language = "markdown", code }: Props) => { language={language} style={theme === "dark" ? oneDark : oneLight} wrapLines={true} - customStyle={{ margin: "0", maxHeight: "20rem" }} + customStyle={{ margin: "0", maxHeight: "32rem" }} > {code} diff --git a/src/components/SnippetModal.tsx b/src/components/SnippetModal.tsx index 7055e8e9..e91a6ab8 100644 --- a/src/components/SnippetModal.tsx +++ b/src/components/SnippetModal.tsx @@ -61,29 +61,31 @@ const SnippetModal: React.FC = ({ - -

    - Description: - {snippet.description} -

    -
    -
      - {snippet.tags.map((tag) => ( -
    • - {tag} -
    • - ))} -
    +
    + +

    + Description: + {snippet.description} +

    +

    + Contributed by{" "} + + @{snippet.author} + +

    +
      + {snippet.tags.map((tag) => ( +
    • + {tag} +
    • + ))} +
    +
    , modalRoot diff --git a/src/styles/main.css b/src/styles/main.css index 80328239..703c837e 100644 --- a/src/styles/main.css +++ b/src/styles/main.css @@ -577,22 +577,19 @@ abbr { border-radius: var(--br-lg); padding: 0.75em; text-align: start; - filter: grayscale(100%); &:is(:hover, :focus-visible) { - outline: 3px solid var(--clr-border-primary); - filter: grayscale(0); + outline: 2px solid var(--clr-border-primary); } } .snippet__preview { width: 100%; overflow: hidden; - aspect-ratio: 10 / 3; + aspect-ratio: 9 / 3; background-color: var(--clr-bg-secondary); /* background-image: var(--gradient-secondary); */ border: 1px solid var(--clr-border-primary); - border-radius: var(--br-md); position: relative; padding-inline: 1em; display: grid; @@ -626,20 +623,34 @@ body:has(.modal-overlay) { .modal { background-color: var(--clr-bg-secondary); - padding: 2rem; - width: 90%; - max-width: 800px; + width: fit-content; + min-width: 50%; + max-width: 1000px; + max-height: 90%; border-radius: var(--br-lg); box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + gap: 0; position: relative; - gap: 1rem; + overflow: auto; } .modal__header { + z-index: 50; display: flex; + position: sticky; + top: 0; align-items: center; justify-content: space-between; gap: 1rem; + padding: 1rem 1.5rem; + background-color: var(--clr-bg-secondary); + border-radius: var(--br-lg); +} + +.modal__body { + padding: 1.5rem; + padding-top: 0; + gap: 1rem; } .code-preview { diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js index aeaea0ce..7052be17 100644 --- a/utils/consolidateSnippets.js +++ b/utils/consolidateSnippets.js @@ -1,7 +1,7 @@ import { exit } from 'process'; import { parseAllSnippets, reverseSlugify, slugify } from './snippetParser.js'; import { join } from 'path'; -import { copyFileSync, writeFileSync } from 'fs'; +import { copyFileSync, mkdirSync, writeFileSync } from 'fs'; const dataPath = 'public/consolidated/'; const indexPath = join(dataPath, '_index.json'); @@ -12,6 +12,9 @@ const [ errored, languages ] = parseAllSnippets(); if(errored) exit(1); +mkdirSync(dataPath, { recursive: true }); +mkdirSync(iconPath, { recursive: true }); + const index = []; for(const language of languages) { copyFileSync(language.icon, join(iconPath, `${slugify(language.name)}.svg`)); diff --git a/vite.config.ts b/vite.config.ts index 653ca674..2fde2a3d 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,10 +1,37 @@ +import { spawnSync } from "child_process"; + import react from "@vitejs/plugin-react-swc"; import { defineConfig } from "vite"; import tsconfigPaths from "vite-tsconfig-paths"; +function consolidateSnippets(projectRoot: string) { + const cmd = spawnSync("node", ["utils/consolidateSnippets.js"], { + cwd: projectRoot, + }); + + if (cmd.status === 0) return; + + console.log(`Consolidating snippets failed:\n${cmd.output.toString()}`); +} + // https://vitejs.dev/config/ export default defineConfig({ - plugins: [react(), tsconfigPaths()], + plugins: [ + react(), + tsconfigPaths(), + { + name: "Consolidate Snippet", + configResolved({ root }) { + consolidateSnippets(root); + }, + handleHotUpdate({ file, server }) { + const relativePath = file.slice(server.config.root.length); + if (!relativePath.startsWith("/snippets/")) return; + + consolidateSnippets(server.config.root); + }, + }, + ], build: { rollupOptions: { output: { From 03aa0a4d29b4f872bbb9937d389157b65b8518fc Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Sat, 11 Jan 2025 18:50:52 -0500 Subject: [PATCH 10/19] Remove pushed consolidated changes and remove unrelated changes --- .../cpp/array-manipulation/filter-vector.md | 25 ------------------ .../array-manipulation/transform-vector.md | 26 ------------------- 2 files changed, 51 deletions(-) delete mode 100644 snippets/cpp/array-manipulation/filter-vector.md delete mode 100644 snippets/cpp/array-manipulation/transform-vector.md diff --git a/snippets/cpp/array-manipulation/filter-vector.md b/snippets/cpp/array-manipulation/filter-vector.md deleted file mode 100644 index 083f7899..00000000 --- a/snippets/cpp/array-manipulation/filter-vector.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -Title: Filter Vector -Description: Filters a vector using a predicate function. -Author: majvax -Tags: array,filter,c++23 ---- - -```cpp -#include -#include - -template -auto filter(const std::vector& vec, P&& predicate) { - return vec - | std::views::filter(std::forward

    (predicate)) - | std::ranges::to>(); -} - - - -// Usage: -std::vector vec = {1, 2, 3, 4, 5}; -std::vector filtered = filter(vec, [](int i){ return i % 2 == 0; }); -// filtered contains 2 and 4 -``` diff --git a/snippets/cpp/array-manipulation/transform-vector.md b/snippets/cpp/array-manipulation/transform-vector.md deleted file mode 100644 index e01cbabe..00000000 --- a/snippets/cpp/array-manipulation/transform-vector.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -Title: Transform Vector -Description: Transforms a vector using a function. -Author: majvax -Tags: array,transform,c++23 ---- - -```cpp -#include -#include - -template -auto transform(const std::vector& vec, F&& transformer) { - using U = std::invoke_result_t; - return vec - | std::views::transform(std::forward(transformer)) - | std::ranges::to>(); -} - - - -// Usage: -std::vector vec = {1, 2, 3, 4, 5}; -std::vector transformed = transform(vec, [](int i){ return i * 2; }); -// transformed contains 2, 4, 6, 8, 10 -``` From 20acee18119ea09715e92eb7c5603dff3a9911fa Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Sat, 11 Jan 2025 18:53:03 -0500 Subject: [PATCH 11/19] Remove unused json --- public/consolidated/javascript--react.json | 18 ------------------ public/consolidated/python--fastapi.json | 20 -------------------- public/icons/javascript--react.svg | 9 --------- public/icons/python--fastapi.svg | 1 - 4 files changed, 48 deletions(-) delete mode 100644 public/consolidated/javascript--react.json delete mode 100644 public/consolidated/python--fastapi.json delete mode 100644 public/icons/javascript--react.svg delete mode 100644 public/icons/python--fastapi.svg diff --git a/public/consolidated/javascript--react.json b/public/consolidated/javascript--react.json deleted file mode 100644 index 2530b7b6..00000000 --- a/public/consolidated/javascript--react.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Show Hello World on the page.", - "author": "ACR1209", - "tags": [ - "printing", - "hello-world" - ], - "contributors": [], - "code": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => {\n return (\n

    \n

    Hello, World!

    \n
    \n );\n};\n\nReactDOM.render(, document.getElementById('root'));\n" - } - ] - } -] \ No newline at end of file diff --git a/public/consolidated/python--fastapi.json b/public/consolidated/python--fastapi.json deleted file mode 100644 index 2614a56e..00000000 --- a/public/consolidated/python--fastapi.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "name": "Basics", - "snippets": [ - { - "title": "Hello, World!", - "description": "Returns Hello, World! when it recives a GET request made to the root endpoint.", - "author": "ACR1209", - "tags": [ - "printing", - "hello-world", - "web", - "api" - ], - "contributors": [], - "code": "from typing import Union\nfrom fastapi import FastAPI\n\napp = FastAPI()\n\n\n@app.get(\"/\")\ndef read_root():\n return {\"msg\": \"Hello, World!\"}\n\n# Usage: \n# -> Go to http://127.0.0.1:8000/ and you'll see {\"msg\", \"Hello, World!\"}\n" - } - ] - } -] \ No newline at end of file diff --git a/public/icons/javascript--react.svg b/public/icons/javascript--react.svg deleted file mode 100644 index b9025712..00000000 --- a/public/icons/javascript--react.svg +++ /dev/null @@ -1,9 +0,0 @@ - - React Logo - - - - - - - \ No newline at end of file diff --git a/public/icons/python--fastapi.svg b/public/icons/python--fastapi.svg deleted file mode 100644 index a7be660d..00000000 --- a/public/icons/python--fastapi.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file From bfbc34762a41559d158db7939a04e47f6c16cb04 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Tue, 14 Jan 2025 23:16:13 -0500 Subject: [PATCH 12/19] Bugfix the keyboard navigation conflict and the arrow not flipping on keyboard navigation --- src/components/LanguageSelector.tsx | 2 +- src/components/SubLanguageSelector.tsx | 15 +++------------ 2 files changed, 4 insertions(+), 13 deletions(-) diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index f39a192a..1fb55484 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -92,7 +92,7 @@ const LanguageSelector = () => { if (language.mainLanguage) { handleToggleSublanguage(language.mainLanguage); } - }, [language]); + }, [language, handleToggleSublanguage]); useEffect(() => { if (isOpen && focusedIndex >= 0) { diff --git a/src/components/SubLanguageSelector.tsx b/src/components/SubLanguageSelector.tsx index 0f18a835..0b88210e 100644 --- a/src/components/SubLanguageSelector.tsx +++ b/src/components/SubLanguageSelector.tsx @@ -1,5 +1,3 @@ -import { useState } from "react"; - import { useAppContext } from "@contexts/AppContext"; import { LanguageType } from "@types"; @@ -17,15 +15,9 @@ const SubLanguageSelector = ({ opened, }: SubLanguageSelectorProps) => { const { language, setLanguage } = useAppContext(); - const [isOpen, setIsOpen] = useState( - mainLanguage.subLanguages.some( - (subLanguage) => language.name === subLanguage.name - ) - ); const handleSelect = (selected: LanguageType) => { setLanguage(selected); - setIsOpen(false); onDropdownToggle(mainLanguage); afterSelect(); }; @@ -48,11 +40,11 @@ const SubLanguageSelector = ({

    - Contributed by{" "} - - @{snippet.author} - -