13 | std::string filter(const std::string& str, P&& predicate) {
14 | return str
15 | | std::ranges::views::filter(std::forward(predicate))
16 | | std::ranges::to();
17 | }
18 |
19 |
20 |
21 | // Usage:
22 | std::string str = "Hello, World!";
23 | std::string filtered = filter(str, [](char c){ return std::isalpha(c); });
24 | std::cout << filtered << std::endl; // HelloWorld
25 | ```
26 |
--------------------------------------------------------------------------------
/snippets/cpp/string-manipulation/palindrome.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Palindrome
3 | description: Check if a string is a palindrome or not.
4 | author: majvax
5 | tags: string,c++23
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 | #include
12 |
13 | bool is_palindrome(const std::string& str) {
14 | std::string sanitized_string = str
15 | | std::ranges::views::filter([](char c){ return std::isalnum(c); })
16 | | std::ranges::views::transform([](char c){ return std::tolower(c); })
17 | | std::ranges::to();
18 |
19 | return std::ranges::equal(sanitized_string, sanitized_string | std::views::reverse);
20 | }
21 |
22 |
23 |
24 | // Usage:
25 | bool pal = is_palindrome("A man, a plan, a canal, Panama"); // true
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/cpp/string-manipulation/reverse-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Reverse String
3 | description: Reverses the characters in a string.
4 | author: Vaibhav-kesarwani
5 | tags: array,reverse,c++23
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 |
12 | std::string reverseString(const std::string& input) {
13 | std::string reversed = input;
14 | std::reverse(reversed.begin(), reversed.end());
15 | return reversed;
16 | }
17 |
18 | reverseString("quicksnip"); // Returns: "pinskciuq"
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/cpp/string-manipulation/split-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Split String
3 | description: Splits a string by a delimiter
4 | author: saminjay
5 | tags: string,split
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 |
12 | std::vector split_string(std::string str, std::string delim) {
13 | std::vector splits;
14 | int i = 0, j;
15 | int inc = delim.length();
16 | while (j != std::string::npos) {
17 | j = str.find(delim, i);
18 | splits.push_back(str.substr(i, j - i));
19 | i = j + inc;
20 | }
21 | return splits;
22 | }
23 |
24 | // Usage:
25 | split_string("quick_-snip", "_-"); // Returns: std::vector { "quick", "snip" }
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/cpp/string-manipulation/transform.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Transform
3 | description: Transform a string with a function
4 | author: majvax
5 | tags: string,transform,c++23
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 |
12 | template
13 | std::string transform(const std::string& str, F&& transformer) {
14 | return str
15 | | std::ranges::views::transform(std::forward(transformer))
16 | | std::ranges::to();
17 | }
18 |
19 |
20 |
21 | // Usage:
22 | std::string str = "Hello, World!";
23 | std::string transformed = transform(str, [](char c){ return std::toupper(c); });
24 | std::cout << transformed << std::endl; // HELLO, WORLD!
25 | ```
26 |
--------------------------------------------------------------------------------
/snippets/cpp/vector-manipulation.md/filter.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Filter
3 | Description: Filters a vector using a predicate function.
4 | Author: majvax
5 | Tags: array,filter,c++23
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 |
12 | template
13 | auto filter(const std::vector& vec, P&& predicate) {
14 | return vec
15 | | std::views::filter(std::forward(predicate))
16 | | std::ranges::to>();
17 | }
18 |
19 |
20 |
21 | // Usage:
22 | std::vector vec = {1, 2, 3, 4, 5};
23 | std::vector filtered = filter(vec, [](int i){ return i % 2 == 0; });
24 | // filtered contains 2 and 4
25 | ```
26 |
--------------------------------------------------------------------------------
/snippets/cpp/vector-manipulation.md/transform.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Transform
3 | Description: Transforms a vector using a function.
4 | Author: majvax
5 | Tags: array,transform,c++23
6 | ---
7 |
8 | ```cpp
9 | #include
10 | #include
11 |
12 | template
13 | auto transform(const std::vector& vec, F&& transformer) {
14 | using U = std::invoke_result_t;
15 | return vec
16 | | std::views::transform(std::forward(transformer))
17 | | std::ranges::to>();
18 | }
19 |
20 |
21 |
22 | // Usage:
23 | std::vector vec = {1, 2, 3, 4, 5};
24 | std::vector transformed = transform(vec, [](int i){ return i * 2; });
25 | // transformed contains 2, 4, 6, 8, 10
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/csharp/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: chaitanya-jvnm
5 | tags: printing,hello-world
6 | ---
7 |
8 | ```csharp
9 | public class Program {
10 | public static void Main(string[] args) {
11 | System.Console.WriteLine("Hello, World!");
12 | }
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/csharp/guid-utilities/generate-guid.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Generate GUID
3 | description: Generates a new GUID
4 | author: chaitanya-jvnm
5 | tags: guid,generate
6 | ---
7 |
8 | ```csharp
9 | public static string GenerateGuid() {
10 | return Guid.NewGuid().ToString();
11 | }
12 |
13 | // Usage:
14 | GenerateGuid(); // Returns: 1c4c38d8-64e4-431b-884a-c6eec2ab02cd (Uuid is random)
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/csharp/guid-utilities/validate-guid.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Validate GUID
3 | description: Checks if a string is a valid GUID.
4 | author: chaitanya-jvnm
5 | tags: guid,validate
6 | ---
7 |
8 | ```csharp
9 | public static bool IsGuid(string str) {
10 | return Guid.TryParse(str, out _);
11 | }
12 |
13 | // Usage:
14 | IsGuid("1c4c38d8-64e4-431b-884a-c6eec2ab02cd"); // Returns: true
15 | IsGuid("quicksnip"); // Returns: false
16 | ```
--------------------------------------------------------------------------------
/snippets/csharp/jwt-utilities/decode-jwt.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Decode JWT
3 | description: Decodes a JWT.
4 | author: chaitanya-jvnm
5 | tags: jwt,decode
6 | ---
7 |
8 | ```csharp
9 | public static string DecodeJwt(string token) {
10 | return new JwtSecurityTokenHandler().ReadJwtToken(token).ToString();
11 | }
12 |
13 | // Usage:
14 | string token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
15 | DecodeJwt(token); // Returns: "{\"alg\":\"HS256\",\"typ\":\"JWT\"}.{\"sub\":\"1234567890\",\"name\":\"John Doe\",\"iat\":1516239022}"
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/csharp/list-utilities/swap-items-at-index.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Swap items at index
3 | description: Swaps two items at determined indexes
4 | author: omegaleo
5 | tags: list,swapping
6 | ---
7 |
8 | ```csharp
9 | public static IList Swap(this IList list, int indexA, int indexB)
10 | {
11 | (list[indexA], list[indexB]) = (list[indexB], list[indexA]);
12 | return list;
13 | }
14 |
15 | var list = new List() {"Test", "Test2"};
16 |
17 | list.Swap(0, 1); // Swaps "Test" and "Test2" in place
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/csharp/string-utilities/capitalize-first-letter.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize first letter
3 | description: Makes the first letter of a string uppercase.
4 | author: chaitanya-jvnm
5 | tags: string,capitalize
6 | ---
7 |
8 | ```csharp
9 | public static string Capitalize(this string str) {
10 | return str.Substring(0, 1).ToUpper() + str.Substring(1);
11 | }
12 |
13 | // Usage:
14 | "quicksnip".Capitalize(); // Returns: "Quicksnip"
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/csharp/string-utilities/truncate-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate String
3 | description: Cut off a string once it reaches a determined amount of characters and add '...' to the end of the string
4 | author: omegaleo
5 | tags: string,truncate
6 | ---
7 |
8 | ```csharp
9 | public static string Truncate(this string value, int maxChars)
10 | {
11 | return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
12 | }
13 |
14 | // Usage:
15 | "Quicksnip".Truncate(5); // Returns: "Quick..."
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/css/animations/blink-animation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Blink Animation
3 | description: Adds an infinite blinking animation to an element
4 | author: AlsoKnownAs-Ax
5 | tags: animation,blink,infinite
6 | ---
7 |
8 | ```css
9 | .blink {
10 | animation: blink 1s linear infinite;
11 | }
12 |
13 | @keyframes blink{
14 | 0%{
15 | opacity: 0;
16 | }
17 | 50%{
18 | opacity: 1;
19 | }
20 | 100%{
21 | opacity: 0;
22 | }
23 | }
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/css/animations/pulse-animation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Pulse Animation
3 | description: Adds a smooth pulsing animation with opacity and scale effects
4 | author: AlsoKnownAs-Ax
5 | tags: animation,pulse,pulse-scale
6 | contributors: alanb4rt
7 | ---
8 |
9 | ```css
10 | .pulse {
11 | animation: pulse 1s ease-in-out infinite alternate;
12 | }
13 |
14 | @keyframes pulse {
15 | from {
16 | opacity: 0.5;
17 | transform: scale(1);
18 | }
19 | to {
20 | opacity: 1;
21 | transform: scale(1.05);
22 | }
23 | }
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/css/animations/shake-animation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Shake Animation
3 | description: Adds a shake animation ( commonly used to mark invalid fields )
4 | author: AlsoKnownAs-Ax
5 | tags: shake,shake-horizontal
6 | ---
7 |
8 | ```css
9 | .shake {
10 | animation: shake .5s ease-in-out;
11 | }
12 |
13 | @keyframes shake {
14 | 0%, 100% {
15 | transform: translateX(0);
16 | }
17 | 25% {
18 | transform: translateX(-10px);
19 | }
20 | 50% {
21 | transform: translateX(10px);
22 | }
23 | 75% {
24 | transform: translateX(-10px);
25 | }
26 | }
27 | ```
28 |
--------------------------------------------------------------------------------
/snippets/css/animations/slide-in-animation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Slide-in Animation
3 | description: Adds a slide-in from the right side of the screen
4 | author: AlsoKnownAs-Ax
5 | tags: animation,slide-in,slide-right
6 | ---
7 |
8 | ```css
9 | .slide-in {
10 | animation: slide-in 1s ease-in-out;
11 | }
12 |
13 | @keyframes slide-in {
14 | from {
15 | scale: 300% 1;
16 | translate: 150vw 0;
17 | }
18 |
19 | to {
20 | scale: 100% 1;
21 | translate: 0 0;
22 | }
23 | }
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/css/buttons/3d-button-effect.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: 3D Button Effect
3 | description: Adds a 3D effect to a button when clicked.
4 | author: technoph1le
5 | tags: button,3D,effect
6 | ---
7 |
8 | ```css
9 | .button {
10 | background-color: #28a745;
11 | color: white;
12 | padding: 10px 20px;
13 | border: none;
14 | border-radius: 5px;
15 | box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
16 | transition: transform 0.1s;
17 | }
18 |
19 | .button:active {
20 | transform: translateY(2px);
21 | box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
22 | }
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/css/buttons/button-hover-effect.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Button Hover Effect
3 | description: Creates a hover effect with a color transition.
4 | author: technoph1le
5 | tags: button,hover,transition
6 | ---
7 |
8 | ```css
9 | .button {
10 | background-color: #007bff;
11 | color: white;
12 | padding: 10px 20px;
13 | border: none;
14 | border-radius: 5px;
15 | cursor: pointer;
16 | transition: background-color 0.3s ease;
17 | }
18 |
19 | .button:hover {
20 | background-color: #0056b3;
21 | }
22 | ```
23 |
--------------------------------------------------------------------------------
/snippets/css/effects/blur-background.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Blur Background
3 | description: Applies a blur effect to the background of an element.
4 | author: technoph1le
5 | tags: blur,background,effects
6 | ---
7 |
8 | ```css
9 | .blur-background {
10 | backdrop-filter: blur(10px);
11 | background: rgba(255, 255, 255, 0.5);
12 | }
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/css/effects/hover-glow-effect.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hover Glow Effect
3 | description: Adds a glowing effect on hover.
4 | author: technoph1le
5 | tags: hover,glow,effects
6 | ---
7 |
8 | ```css
9 | .glow {
10 | background-color: #f39c12;
11 | padding: 10px 20px;
12 | border-radius: 5px;
13 | transition: box-shadow 0.3s ease;
14 | }
15 |
16 | .glow:hover {
17 | box-shadow: 0 0 15px rgba(243, 156, 18, 0.8);
18 | }
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/css/effects/hover-to-reveal-color.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hover to Reveal Color
3 | description: A card with an image that transitions from grayscale to full color on hover.
4 | author: Haider-Mukhtar
5 | tags: hover,image,effects
6 | ---
7 |
8 | ```css
9 | .card {
10 | height: 300px;
11 | width: 200px;
12 | border-radius: 5px;
13 | overflow: hidden;
14 | }
15 |
16 | .card img{
17 | height: 100%;
18 | width: 100%;
19 | object-fit: cover;
20 | filter: grayscale(100%);
21 | transition: all 0.3s;
22 | transition-duration: 200ms;
23 | cursor: pointer;
24 | }
25 |
26 | .card:hover img {
27 | filter: grayscale(0%);
28 | scale: 1.05;
29 | }
30 | ```
31 |
--------------------------------------------------------------------------------
/snippets/css/layouts/css-reset.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: CSS Reset
3 | description: Resets some default browser styles, ensuring consistency across browsers.
4 | author: AmeerMoustafa
5 | tags: reset,browser,layout
6 | ---
7 |
8 | ```css
9 | * {
10 | margin: 0;
11 | padding: 0;
12 | box-sizing: border-box
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/css/layouts/equal-width-columns.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Equal-Width Columns
3 | description: Creates columns with equal widths using flexbox.
4 | author: technoph1le
5 | tags: flexbox,columns,layout
6 | ---
7 |
8 | ```css
9 | .columns {
10 | display: flex;
11 | justify-content: space-between;
12 | }
13 |
14 | .column {
15 | flex: 1;
16 | margin: 0 10px;
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/css/layouts/sticky-footer.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Sticky Footer
3 | description: Ensures the footer always stays at the bottom of the page.
4 | author: technoph1le
5 | tags: layout,footer,sticky
6 | ---
7 |
8 | ```css
9 | body {
10 | display: flex;
11 | flex-direction: column;
12 | min-height: 100vh;
13 | }
14 |
15 | footer {
16 | margin-top: auto;
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/css/typography/letter-spacing.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Letter Spacing
3 | description: Adds space between letters for better readability.
4 | author: technoph1le
5 | tags: typography,spacing
6 | ---
7 |
8 | ```css
9 | p {
10 | letter-spacing: 0.05em;
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/css/typography/responsive-font-sizing.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Responsive Font Sizing
3 | description: Adjusts font size based on viewport width.
4 | author: technoph1le
5 | tags: font,responsive,typography
6 | ---
7 |
8 | ```css
9 | h1 {
10 | font-size: calc(1.5rem + 2vw);
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/haskell/array-manipulation/chunk-array.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Chunk Array
3 | description: Splits an array into chunks of a specified size.
4 | author: ACR1209
5 | tags: array,chunk,utility
6 | ---
7 |
8 | ```hs
9 | chunkArray :: Int -> [a] -> [[a]]
10 | chunkArray _ [] = []
11 | chunkArray n xs = take n xs : chunkArray n (drop n xs)
12 |
13 | -- Usage:
14 | main :: IO ()
15 | main = do
16 | let array = [1, 2, 3, 4, 5, 6]
17 | print $ chunkArray 2 array -- Output: [[1, 2], [3, 4], [5, 6]]
18 | ```
--------------------------------------------------------------------------------
/snippets/haskell/array-manipulation/matrix-transpose.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Matrix Transpose
3 | description: Transposes a 2D matrix.
4 | author: ACR1209
5 | tags: array,matrix,transpose
6 | ---
7 |
8 | ```hs
9 | transposeMatrix :: [[a]] -> [[a]]
10 | transposeMatrix [] = []
11 | transposeMatrix ([]:_) = []
12 | transposeMatrix xs = map head xs : transposeMatrix (map tail xs)
13 |
14 | -- Usage:
15 | main :: IO ()
16 | main = do
17 | let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
18 | print $ transposeMatrix matrix -- Output: [[1,4,7],[2,5,8],[3,6,9]]
19 | ```
--------------------------------------------------------------------------------
/snippets/haskell/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: ACR1209
5 | tags: printing,hello-world,utility
6 | ---
7 |
8 | ```haskell
9 | putStrLn "Hello, World!"
10 | ```
11 |
--------------------------------------------------------------------------------
/snippets/haskell/file-handling/find-files-in-directory-by-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Files in Directory by Type
3 | description: Finds all files in a directory with a specific extension.
4 | author: ACR1209
5 | tags: file,search,extension,filesystem
6 | ---
7 |
8 | ```hs
9 | import System.Directory (listDirectory)
10 | import System.FilePath (takeExtension)
11 |
12 | findFilesByExtension :: FilePath -> String -> IO [FilePath]
13 | findFilesByExtension dir ext = do
14 | files <- listDirectory dir
15 | return $ filter (\f -> takeExtension f == ext) files
16 |
17 | -- Usage:
18 | main :: IO ()
19 | main = do
20 | let directory = "."
21 | let ext = ".txt"
22 | files <- findFilesByExtension directory ext
23 | mapM_ putStrLn files -- Output: list of txt files on the current directory
24 | ```
--------------------------------------------------------------------------------
/snippets/haskell/icon.svg:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/snippets/haskell/monads/either-monad-for-error-handling.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Either Monad for Error Handling
3 | description: Using the Either monad to handle errors in a computation.
4 | author: ACR1209
5 | tags: monads, either, error handling
6 | ---
7 |
8 | ```hs
9 | safeDiv :: Int -> Int -> Either String Int
10 | safeDiv _ 0 = Left "Division by zero error"
11 | safeDiv x y = Right (x `div` y)
12 |
13 | -- Usage:
14 | main :: IO ()
15 | main = do
16 | let result = do
17 | a <- safeDiv 10 2
18 | b <- safeDiv a 0 -- This will trigger an error
19 | return b
20 | print result -- Output: Left "Division by zero error"
21 | ```
--------------------------------------------------------------------------------
/snippets/haskell/monads/maybe-monad.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Maybe Monad
3 | description: Using the Maybe monad to handle computations that might fail.
4 | author: ACR1209
5 | tags: monads, maybe
6 | ---
7 |
8 | ```hs
9 | safeDiv :: Int -> Int -> Maybe Int
10 | safeDiv _ 0 = Nothing
11 | safeDiv x y = Just (x `div` y)
12 |
13 | -- Usage:
14 | main :: IO ()
15 | main = do
16 | let result = do
17 | a <- safeDiv 10 2
18 | b <- safeDiv a 2
19 | return b
20 | print result -- Output: Just 2
21 | ```
--------------------------------------------------------------------------------
/snippets/haskell/monads/state-monad.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: State Monad
3 | description: Managing mutable state using the State monad.
4 | author: ACR1209
5 | tags: monads, state, state-management
6 | ---
7 |
8 | ```hs
9 | import Control.Monad.State
10 |
11 | increment :: State Int Int
12 | increment = do
13 | count <- get
14 | put (count + 1)
15 | return count
16 |
17 | -- Usage:
18 | main :: IO ()
19 | main = do
20 | let (res1, intermediateState) = runState increment 0
21 | print res1 -- Output: 0
22 | let (result, finalState) = runState increment intermediateState
23 | print result -- Output: 1
24 | print finalState -- Output: 2
25 |
26 | ```
--------------------------------------------------------------------------------
/snippets/haskell/monads/writer-monad.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Writer Monad
3 | description: Using the Writer monad to accumulate logs or other outputs alongside a computation.
4 | author: ACR1209
5 | tags: monads, writer, logs
6 | ---
7 |
8 | ```hs
9 | import Control.Monad.Writer
10 |
11 | addAndLog :: Int -> Int -> Writer [String] Int
12 | addAndLog x y = do
13 | tell ["Adding " ++ show x ++ " and " ++ show y]
14 | return (x + y)
15 |
16 | -- Usage:
17 | main :: IO ()
18 | main = do
19 | let (result, logs) = runWriter $ do
20 | res1 <- addAndLog 3 5
21 | addAndLog res1 1
22 | print result -- Output: 9
23 | print logs -- Output: ["Adding 3 and 5", "Adding 8 and 1"]
24 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/camelcase-to-snake-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: CamelCase to snake_case
3 | description: Converts a Camel Case string to Snake case.
4 | author: ACR1209
5 | tags: string,convert,camel-case,snake-case,utility
6 | ---
7 |
8 | ```hs
9 | import Data.Char (isUpper, toLower)
10 |
11 | camelToSnake :: String -> String
12 | camelToSnake [] = []
13 | camelToSnake (x:xs)
14 | | isUpper x = '_' : toLower x : camelToSnake xs
15 | | otherwise = x : camelToSnake xs
16 |
17 | -- Usage:
18 | main :: IO ()
19 | main = do
20 | let camelCase = "camelCaseToSnakeCase"
21 | print $ camelToSnake camelCase -- Output: "camel_case_to_snake_case"
22 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/capitalize-words.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize Words
3 | description: Capitalizes the first letter of each word in a string.
4 | author: ACR1209
5 | tags: string,capitalize,words
6 | ---
7 |
8 | ```hs
9 | import Data.Char (toUpper)
10 |
11 | capitalizeWords :: String -> String
12 | capitalizeWords = unwords . map capitalize . words
13 | where
14 | capitalize [] = []
15 | capitalize (x:xs) = toUpper x : xs
16 |
17 | -- Usage:
18 | main :: IO ()
19 | main = do
20 | let sentence = "haskell is awesome"
21 | print $ capitalizeWords sentence -- Output: "Haskell Is Awesome"
22 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/count-word-occurrences-in-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Word Occurrences in String
3 | description: Counts the occurrences of each word in a given string.
4 | author: ACR1209
5 | tags: string,occurrences,word-count
6 | ---
7 |
8 | ```hs
9 | import Data.List (group, sort)
10 |
11 | countWordOccurrences :: String -> [(String, Int)]
12 | countWordOccurrences = map (\(w:ws) -> (w, length (w:ws))) . group . sort . words
13 |
14 | -- Usage:
15 | main :: IO ()
16 | main = do
17 | let text = "haskell is awesome and haskell is fun"
18 | print $ countWordOccurrences text -- Output: [("and",1),("awesome",1),("fun",1),("haskell",2),("is",2)]
19 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/remove-punctuation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Punctuation
3 | description: Removes all punctuation from a given string.
4 | author: ACR1209
5 | tags: string,punctuation,remove
6 | ---
7 |
8 | ```hs
9 | import Data.Char (isPunctuation)
10 |
11 | removePunctuation :: String -> String
12 | removePunctuation = filter (not . isPunctuation)
13 |
14 | -- Usage:
15 | main :: IO ()
16 | main = do
17 | let text = "Hello, Haskell! How's it going?"
18 | print $ removePunctuation text -- Output: "Hello Haskell Hows it going"
19 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/snake-case-to-camelcase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Snake_Case to CamelCase
3 | description: Converts a Snake Case string to Camel Case.
4 | author: ACR1209
5 | tags: string,convert,snake-case,camel-case,utilty
6 | ---
7 |
8 | ```hs
9 | import Data.Char (toUpper)
10 |
11 | snakeToCamel :: String -> String
12 | snakeToCamel [] = []
13 | snakeToCamel ('_':x:xs) = toUpper x : snakeToCamel xs
14 | snakeToCamel (x:xs) = x : snakeToCamel xs
15 |
16 | -- Usage:
17 | main :: IO ()
18 | main = do
19 | let snakeCase = "snake_case_to_camel_case"
20 | print $ snakeToCamel snakeCase -- Output: "snakeCaseToCamelCase"
21 | ```
--------------------------------------------------------------------------------
/snippets/haskell/string-manipulation/truncate-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate String
3 | description: Truncates a string to a specified length, optionally adding an ellipsis.
4 | author: ACR1209
5 | tags: string,truncate,utility
6 | ---
7 |
8 | ```hs
9 | truncateString :: Int -> String -> String
10 | truncateString maxLength str
11 | | length str <= maxLength = str
12 | | otherwise = take (maxLength - 3) str ++ "..."
13 |
14 | -- Usage:
15 | main :: IO ()
16 | main = do
17 | let longString = "Haskell is a powerful functional programming language."
18 | print $ truncateString 20 longString -- Output: "Haskell is a powe..."
19 | print $ truncateString 54 longString -- Output: "Haskell is a powerful functional programming language."
20 | ```
--------------------------------------------------------------------------------
/snippets/java/array-manipulation/remove-duplicates.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove duplicates
3 | description: Removes duplicate elements from an list
4 | author: Mcbencrafter
5 | tags: list,duplicates,unique
6 | ---
7 |
8 | ```java
9 | import java.util.List;
10 | import java.util.stream.Collectors;
11 |
12 | public static List removeDuplicates(List list) {
13 | return list.stream()
14 | .distinct()
15 | .collect(Collectors.toList());
16 | }
17 |
18 | // Usage:
19 | List list = List.of(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
20 | List result = removeDuplicates(list);
21 | System.out.println("List with duplicates removed: " + result); // [1, 2, 3, 4, 5]
22 | ```
--------------------------------------------------------------------------------
/snippets/java/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello-World
3 | description: Prints Hello world in the console
4 | author: SarvariHarshitha
5 | tags: java, console, printing
6 | ---
7 |
8 | ```java
9 | // This is the main class of the Java program
10 | public class Main {
11 | // The main method is the entry point of the program
12 | public static void main(String args[]) {
13 | // This statement prints "Hello, World!" to the console
14 | System.out.println("Hello, World!");
15 | }
16 | }
17 |
18 | ```
--------------------------------------------------------------------------------
/snippets/java/bit-manipulation/bit-counting.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Bit Counting
3 | description: Counts the set bits in the binary representation of an integer
4 | author: Mcbencrafter
5 | tags: math,number,bits,bit-counting
6 | ---
7 |
8 | ```java
9 | public static int countBits(int number) {
10 | int bits = 0;
11 |
12 | while (number > 0) {
13 | bits += number & 1;
14 | number >>= 1;
15 | }
16 |
17 | return bits;
18 | }
19 |
20 | // Usage:
21 | int number = 5;
22 | System.out.println(countBits(5)); // 2 (101)
23 | ```
--------------------------------------------------------------------------------
/snippets/java/bit-manipulation/is-power-of-two.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Is Power Of Two
3 | description: Checks if a number is a power of two
4 | author: Mcbencrafter
5 | tags: math,number,bit,power-of-two
6 | ---
7 |
8 | ```java
9 | public static boolean isPowerOfTwo(int number) {
10 | return (number > 0) && ((number & (number - 1)) == 0);
11 | }
12 |
13 | // Usage:
14 | int number = 16;
15 | System.out.println(isPowerOfTwo(number)); // true (2^4)
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/java/math/checksum.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Checksum
3 | description: Calculates the checksum of an int
4 | author: Mcbencrafter
5 | tags: math,number,checksum
6 | ---
7 |
8 | ```java
9 | public static int checksum(int number) {
10 | number = Math.abs(number);
11 | int sum = 0;
12 |
13 | while (number != 0) {
14 | sum += number % 10;
15 | number /= 10;
16 | }
17 |
18 | return sum;
19 | }
20 |
21 | // Usage:
22 | int number = 12345;
23 | System.out.println(checksum(number)); // 15 = 1+2+3+4+5
24 | ```
--------------------------------------------------------------------------------
/snippets/java/math/factorial.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Factorial
3 | description: Computes the factorial of a given number
4 | author: Mcbencrafter
5 | tags: math,number,factorial
6 | ---
7 |
8 | ```java
9 | import java.math.BigInteger;
10 |
11 | public static BigInteger factorial(int number) {
12 | BigInteger result = BigInteger.ONE;
13 |
14 | for (int currentNumber = 1; currentNumber <= number; currentNumber++) {
15 | result = result.multiply(BigInteger.valueOf(currentNumber));
16 | }
17 |
18 | return result;
19 | }
20 |
21 | // Usage:
22 | int number = 6;
23 | System.out.println(factorial(number)); // 720 = 6*5*4*3*2
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/java/math/fibonacci.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Fibonacci
3 | description: Calculates the nth fibonacci number
4 | author: Mcbencrafter
5 | tags: math,number,fibonacci
6 | ---
7 |
8 | ```java
9 | public static int fibonacci(int number) {
10 | if (number <= 1)
11 | return number;
12 |
13 | return fibonacci(number - 1) + fibonacci(number - 2);
14 | }
15 |
16 | // Usage:
17 | int number = 5;
18 | System.out.println(fibonacci(number)) // 3 (0, 1, 1, 2, 3)
19 | ```
--------------------------------------------------------------------------------
/snippets/java/math/greatest-common-divisor.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Greatest Common Divisor
3 | description: Calculates the greatest common divisor (gcd) of two numbers
4 | author: Mcbencrafter
5 | tags: math,number,greatest-common-devisor,gcd,euclidean-algorithm
6 | ---
7 |
8 | ```java
9 | public static int gcd(int number1, int number2) {
10 | while (number2 != 0) {
11 | int remainder = number2;
12 | number2 = number1 % number2;
13 | number1 = remainder;
14 | }
15 |
16 | return number1;
17 | }
18 |
19 | // Usage:
20 | int a = 16;
21 | int b = 12;
22 | System.out.println(gcd(a, b)); // 4
23 | ```
--------------------------------------------------------------------------------
/snippets/java/math/least-common-multiple.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Least Common Multiple
3 | description: Calculates the least common multiple (lcm) of two numbers
4 | author: Mcbencrafter
5 | tags: math,number,least-common-multiple,lcm,euclidean-algorithm
6 | ---
7 |
8 | ```java
9 | public static int lcm(int number1, int number2) {
10 | int gcdNumber1 = number1;
11 | int gcdNumber2 = number2;
12 |
13 | while (gcdNumber2 != 0) {
14 | int remainder = gcdNumber2;
15 | gcdNumber2 = gcdNumber1 % gcdNumber2;
16 | gcdNumber1 = remainder;
17 | }
18 |
19 | return (number1 / gcdNumber1) * number2;
20 | }
21 |
22 | // Usage:
23 | int a = 16;
24 | int b = 12;
25 | System.out.println(lcm(a, b)); // 48
26 | ```
--------------------------------------------------------------------------------
/snippets/java/math/prime-check.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Prime Check
3 | description: Checks if a number is a prime
4 | author: Mcbencrafter
5 | tags: math,number,prime
6 | ---
7 |
8 | ```java
9 | public static boolean isPrime(int number) {
10 | if (number <= 1)
11 | return false;
12 |
13 | if (number <= 3)
14 | return true;
15 |
16 | boolean prime = true;
17 | for (int divisor = 3; divisor < number; divisor++) {
18 | if (number % divisor != 0)
19 | continue;
20 |
21 | prime = false;
22 | break;
23 | }
24 |
25 | return prime;
26 | }
27 |
28 | // Usage:
29 | int number = 31;
30 | System.out.println(isPrime(number)); // true
31 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/ascii-to-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Ascii To String
3 | description: Converts a list of ascii numbers into a string
4 | author: Mcbencrafter
5 | tags: string,ascii,encoding,decode,conversion
6 | ---
7 |
8 | ```java
9 | import java.util.List;
10 |
11 | public static String asciiToString(List asciiCodes) {
12 | StringBuilder text = new StringBuilder();
13 |
14 | for (int asciiCode : asciiCodes) {
15 | text.append((char) asciiCode);
16 | }
17 |
18 | return text.toString();
19 | }
20 |
21 | // Usage:
22 | System.out.println(asciiToString(List.of(104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100))); // "hello world"
23 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/camelcase-to-snake-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: camelCase to snake_case
3 | description: Converts a camelCase string into snake_case
4 | author: Mcbencrafter
5 | tags: string,conversion,camel-case,snake-case
6 | ---
7 |
8 | ```java
9 | public static String camelToSnake(String camelCase) {
10 | return camelCase.replaceAll("([a-z])([A-Z])", "$1_$2").toLowerCase();
11 | }
12 |
13 | // Usage:
14 | System.out.println(camelToSnake("helloWorld")); // "hello_world"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/check-palindrome.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Palindrome
3 | description: Checks if a string reads the same backward as forward, ignoring whitespaces and case sensitivity
4 | author: Mcbencrafter
5 | tags: string,palindrome,compare,reverse
6 | ---
7 |
8 | ```java
9 | public static boolean isPalindrome(String text) {
10 | String cleanText = text.toLowerCase().replaceAll("\\s+", "");
11 |
12 | return new StringBuilder(cleanText)
13 | .reverse()
14 | .toString()
15 | .equals(cleanText);
16 | }
17 |
18 | // Usage:
19 | System.out.println(isPalindrome("A man a plan a canal Panama")); // true
20 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/count-character-occurrences.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Character Occurrences
3 | description: Counts the occurrences of the specified characters in a given string
4 | author: Mcbencrafter
5 | tags: string,characters,counter,occurence
6 | ---
7 |
8 | ```java
9 | import java.util.List;
10 |
11 | public static int countCharacterOccurrences(String text, List characters) {
12 | int count = 0;
13 |
14 | for (char character : text.toCharArray()) {
15 | if (characters.indexOf(character) == -1)
16 | continue;
17 |
18 | count++;
19 | }
20 |
21 | return count;
22 | }
23 |
24 | // Usage:
25 | System.out.println(countCharacterOccurrences("hello world", List.of('l', 'o'))); // 5
26 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/count-words.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Words
3 | description: Counts the number of words in a string
4 | author: Mcbencrafter
5 | tags: string,word,count
6 | ---
7 |
8 | ```java
9 | public static int countWords(String text) {
10 | return text.split("\\s+").length;
11 | }
12 |
13 | // Usage:
14 | System.out.println(countWords("hello world")); // 2
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/extract-text-between-delimiters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Extract Text Between Delimiters
3 | description: Extracts a text between two given delimiters from a string
4 | author: Mcbencrafter
5 | tags: string,delimiters,start,end
6 | ---
7 |
8 | ```java
9 | public static String extractBetweenDelimiters(String text, String start, String end) {
10 | int startIndex = text.indexOf(start);
11 | int endIndex = text.indexOf(end, startIndex + start.length());
12 |
13 | if (startIndex == -1 || endIndex == -1)
14 | return "";
15 |
16 | return text.substring(startIndex + start.length(), endIndex);
17 | }
18 |
19 | // Usage:
20 | System.out.println(extractBetweenDelimiters("hello, world!", ",", "!")); // " world"
21 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/find-longest-word.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Longest Word
3 | description: Returns the longest word in a string
4 | author: Mcbencrafter
5 | tags: string,length,words
6 | ---
7 |
8 | ```java
9 | public static String findLongestWord(String text) {
10 | String[] words = text.split("\\s+");
11 | String longestWord = words[0];
12 |
13 | for (String word : words) {
14 | if (word.length() <= longestWord.length())
15 | continue;
16 |
17 | longestWord = word;
18 | }
19 |
20 | return longestWord;
21 | }
22 |
23 | // Usage:
24 | System.out.println(findLongestWord("hello world123")); // "world123"
25 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/normalize-whitespace.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Normalize Whitespace
3 | description: Replaces consecutive whitespaces with a single space
4 | author: Mcbencrafter
5 | tags: string,whitespace,normalize
6 | ---
7 |
8 | ```java
9 | public static String normalizeWhitespace(String text) {
10 | return text.replaceAll(" {2,}", " ");
11 | }
12 |
13 | // Usage:
14 | System.out.println(normalizeWhitespace("hello world")); // "hello world"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/remove-punctuation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Punctuation
3 | description: Removes punctuation (, . !) from a string
4 | author: Mcbencrafter
5 | tags: string,punctuation,clean,normalization
6 | ---
7 |
8 | ```java
9 | public static String removePunctuation(String text) {
10 | return text.replaceAll("[,!.?;:]", "");
11 | }
12 |
13 | // Usage:
14 | System.out.println(removePunctuation("hello, world!")); // "hello world"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/remove-special-characters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Special Characters
3 | description: Removes any character which is not alphabetic (A-Z, a-z) or numeric (0-9)
4 | author: Mcbencrafter
5 | tags: string,special-characters,clean,normalization
6 | ---
7 |
8 | ```java
9 | public static String removeSpecialCharacters(String text) {
10 | return text.replaceAll("[^a-zA-Z0-9]", "");
11 | }
12 |
13 | // Usage:
14 | System.out.println(removeSpecialCharacters("hello, world!#%")); // "hello world"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/reverse-word-contents.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Reverse Word Contents
3 | Description: Reverses the characters of each word in a string while preserving word order
4 | Author: Mcbencrafter
5 | Tags: string,reverse,words,transformation,order
6 | ---
7 |
8 | ```java
9 | public static String reverseWords(String text) {
10 | String[] words = text.split("\\s+");
11 | StringBuilder reversedText = new StringBuilder();
12 |
13 | for (String word : words) {
14 | StringBuilder reversedWord = new StringBuilder(word).reverse();
15 | reversedText.append(reversedWord).append(" ");
16 | }
17 |
18 | return reversedText.toString().trim();
19 | }
20 |
21 | // Usage:
22 | System.out.println(reverseWordContents("hello world")); // "olleh dlrow"
23 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/reverse-word-order.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Reverse Word Order
3 | Description: Reverses the order of words in a sentence while preserving the content of each word
4 | Author: Mcbencrafter
5 | Tags: string,reverse,words,transformation,sentence
6 | ---
7 |
8 | ```java
9 | public static String reverseWords(String text) {
10 | String[] words = text.split("\\s+");
11 | StringBuilder reversedSentence = new StringBuilder();
12 |
13 | for (int currentWord = words.length - 1; currentWord >= 0; currentWord--) {
14 | reversedSentence.append(words[currentWord]).append(" ");
15 | }
16 |
17 | return reversedSentence.toString().trim();
18 | }
19 |
20 | // Usage:
21 | System.out.println(reverseWords("hello world")); // Output: world hello
22 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/snake-case-to-camelcase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: snake_case to camelCase
3 | description: Converts a snake_case string into camelCase
4 | author: Mcbencrafter
5 | tags: string,conversion,camel-case,snake-case
6 | ---
7 |
8 | ```java
9 | import java.util.regex.Pattern;
10 |
11 | public static String snakeToCamel(String snakeCase) {
12 | return Pattern.compile("(_)([a-z])")
13 | .matcher(snakeCase)
14 | .replaceAll(match -> match.group(2).toUpperCase());
15 | }
16 |
17 | // Usage:
18 | System.out.println(snakeToCamel("hello_world")); // "helloWorld"
19 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/spaces-to-tabs.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Spaces To Tabs
3 | description: Converts spaces into tabs
4 | author: Mcbencrafter
5 | tags: string,tab,space,conversion
6 | ---
7 |
8 | ```java
9 | public static String convertSpacesToTab(String text, int spacesPerTab) {
10 | return text.replaceAll(" ".repeat(spacesPerTab), "\t");
11 | }
12 |
13 | // Usage:
14 | System.out.println(convertSpacesToTab("hello world", 4)); // Output: hello\tworld
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-ascii.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To Ascii
3 | description: Converts a string into ascii numbers
4 | author: Mcbencrafter
5 | tags: string,ascii,encoding,conversion
6 | ---
7 |
8 | ```java
9 | import java.util.ArrayList;
10 | import java.util.List;
11 |
12 | public static List stringToAscii(String text) {
13 | List asciiCodes = new ArrayList<>();
14 |
15 | for (char character : text.toCharArray()) {
16 | asciiCodes.add((int) character);
17 | }
18 |
19 | return asciiCodes;
20 | }
21 |
22 | // Usage:
23 | System.out.println(stringToAscii("hello world")); // [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
24 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-camelcase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To camelCase
3 | description: Converts a string into camelCase
4 | author: Mcbencrafter
5 | tags: string,conversion,camel-case
6 | ---
7 |
8 | ```java
9 | public static String stringToCamelCase(String text) {
10 | String[] words = text.split("\\s+");
11 | StringBuilder camelCase = new StringBuilder(
12 | words[0].substring(0, 1).toLowerCase() + words[0].substring(1)
13 | );
14 |
15 | for (int i = 1; i < words.length; i++) {
16 | camelCase.append(words[i].substring(0, 1).toUpperCase());
17 | camelCase.append(words[i].substring(1));
18 | }
19 |
20 | return camelCase.toString();
21 | }
22 |
23 | // Usage:
24 | System.out.println(stringToCamelCase("Hello world test")); // "helloWorldTest"
25 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-param-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To param-case
3 | description: Converts a string into param-case
4 | author: Mcbencrafter
5 | tags: string,conversion,param-case
6 | ---
7 |
8 | ```java
9 | public static String stringToParamCase(String text) {
10 | return text.toLowerCase().replaceAll("\\s+", "-");
11 | }
12 |
13 | // Usage:
14 | System.out.println(stringToParamCase("Hello World 123")); // "hello-world-123"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-pascalcase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To PascalCase
3 | description: Converts a string into PascalCase
4 | author: Mcbencrafter
5 | tags: string,conversion,pascal-case
6 | ---
7 |
8 | ```java
9 | public static String stringToPascalCase(String text) {
10 | String[] words = text.split("\\s+");
11 | StringBuilder pascalCase = new StringBuilder();
12 |
13 | for (String word : words) {
14 | pascalCase.append(word.substring(0, 1).toUpperCase());
15 | pascalCase.append(word.substring(1).toLowerCase());
16 | }
17 |
18 | return pascalCase.toString();
19 | }
20 |
21 | // Usage:
22 | System.out.println(stringToPascalCase("hello world")); // "HelloWorld"
23 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-snake-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To snake_case
3 | description: Converts a string into snake_case
4 | author: Mcbencrafter
5 | tags: string,conversion,snake-case
6 | ---
7 |
8 | ```java
9 | public static String stringToSnakeCase(String text) {
10 | return text.toLowerCase().replaceAll("\\s+", "_");
11 | }
12 |
13 | // Usage:
14 | System.out.println(stringToSnakeCase("Hello World 123")); // "hello_world_123"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/string-to-unicode.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: String To Unicode
3 | description: Converts characters of a string into their unicode representation
4 | author: Mcbencrafter
5 | tags: string,unicode,encoding,conversion
6 | ---
7 |
8 | ```java
9 | public static String stringToUnicode(String text) {
10 | StringBuilder unicodeText = new StringBuilder();
11 |
12 | for (char character : text.toCharArray()) {
13 | unicodeText.append(String.format("\\u%04x", (int) character));
14 | }
15 |
16 | return unicodeText.toString();
17 | }
18 |
19 | // Usage:
20 | System.out.println(stringToUnicode("hello world")); // \u0068\u0065\u006C\u006C\u006F\u0020\u0077\u006F\u0072\u006C\u0064
21 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/tabs-to-spaces.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Tabs To Spaces
3 | description: Converts tabs into spaces
4 | author: Mcbencrafter
5 | tags: string,tab,space,conversion
6 | ---
7 |
8 | ```java
9 | public static String convertTabToSpace(String text, int spacesPerTab) {
10 | return text.replaceAll("\t", " ".repeat(spacesPerTab));
11 | }
12 |
13 | // Usage:
14 | System.out.println(convertTabToSpace("hello\tworld", 2)); // "hello world"
15 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/truncate-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate String
3 | description: Truncates a string after a specified length (can also be used for hiding information)
4 | author: Mcbencrafter
5 | tags: string,truncate,mask,hide
6 | ---
7 |
8 | ```java
9 | public static String truncate(String text, int length, String suffix) {
10 | if (text.length() <= length)
11 | return text;
12 |
13 | return text.substring(0, length).trim() + (suffix != null ? suffix : "");
14 | }
15 |
16 | // Usage:
17 | System.out.println(truncate("hello world", 5, "...")); // "hello..."
18 | ```
--------------------------------------------------------------------------------
/snippets/java/string-manipulation/unicode-to-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Unicode To String
3 | description: Converts a unicode String into its normal representation
4 | author: Mcbencrafter
5 | tags: string,unicode,encoding,decoding,conversion
6 | ---
7 |
8 | ```java
9 | public static String unicodeToString(String unicode) {
10 | StringBuilder string = new StringBuilder();
11 | String[] hex = unicode.split("\\\\u");
12 |
13 | for (int symbol = 1; symbol < hex.length; symbol++) {
14 | int data = Integer.parseInt(hex[symbol], 16);
15 | string.append((char) data);
16 | }
17 |
18 | return string.toString();
19 | }
20 |
21 | // Usage:
22 | System.out.println(unicodeToString("\\u0068\\u0065\\u006c\\u006c\\u006f\\u0020\\u0077\\u006f\\u0072\\u006c\\u0064")); // "hello world"
23 | ```
--------------------------------------------------------------------------------
/snippets/javascript/[react]/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Show Hello World on the page.
4 | author: ACR1209
5 | tags: printing,hello-world
6 | ---
7 |
8 | ```tsx
9 | import React from 'react';
10 | import ReactDOM from 'react-dom';
11 |
12 | const App = () => {
13 | return (
14 |
15 |
Hello, World!
16 |
17 | );
18 | };
19 |
20 | ReactDOM.render(, document.getElementById('root'));
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/javascript/[react]/icon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/snippets/javascript/array-manipulation/partition-array.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Partition Array
3 | description: Splits an array into two arrays based on a callback function.
4 | author: Swaraj-Singh-30
5 | tags: array,partition,reduce
6 | ---
7 |
8 | ```js
9 | const partition = (arr, callback) =>
10 | arr.reduce(
11 | ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),
12 | [[], []]
13 | );
14 |
15 | // Usage:
16 | const numbers = [1, 2, 3, 4, 5, 6];
17 | const isEven = (n) => n % 2 === 0;
18 | partition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]
19 | ```
--------------------------------------------------------------------------------
/snippets/javascript/array-manipulation/remove-duplicates.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Duplicates
3 | description: Removes duplicate values from an array.
4 | author: technoph1le
5 | tags: array,deduplicate
6 | ---
7 |
8 | ```js
9 | const removeDuplicates = (arr) => [...new Set(arr)];
10 |
11 | // Usage:
12 | const numbers = [1, 2, 2, 3, 4, 4, 5];
13 | removeDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/javascript/array-manipulation/remove-falsy-values.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Falsy Values
3 | description: Removes falsy values from an array.
4 | author: mubasshir
5 | tags: array,falsy,filter
6 | ---
7 |
8 | ```js
9 | const removeFalsy = (arr) => arr.filter(Boolean);
10 |
11 | // Usage:
12 | const array = [0, 1, false, 2, "", 3, null];
13 | removeFalsy(array); // Returns: [1, 2, 3]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/javascript/array-manipulation/shuffle-array.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Shuffle Array
3 | description: Shuffles an Array.
4 | author: loxt-nixo
5 | tags: array,shuffle
6 | ---
7 |
8 | ```js
9 | function shuffleArray(array) {
10 | for (let i = array.length - 1; i >= 0; i--) {
11 | const j = Math.floor(Math.random() * (i + 1));
12 | [array[i], array[j]] = [array[j], array[i]];
13 | }
14 | }
15 |
16 | // Usage:
17 | const array = [1, 2, 3, 4, 5];
18 | shuffleArray(array); // Shuffles `array` in place
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/javascript/array-manipulation/zip-arrays.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Zip Arrays
3 | description: Combines two arrays by pairing corresponding elements from each array.
4 | author: Swaraj-Singh-30
5 | tags: array,map
6 | ---
7 |
8 | ```js
9 | const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);
10 |
11 | // Usage:
12 | const arr1 = ['a', 'b', 'c'];
13 | const arr2 = [1, 2, 3];
14 | console.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: James-Beans
5 | tags: printing,hello-world
6 | ---
7 |
8 | ```js
9 | console.log("Hello, World!"); // Prints Hello, World! to the console
10 | ```
11 |
--------------------------------------------------------------------------------
/snippets/javascript/color-manipulation/hex-to-rgb-color.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hex to RGB Color
3 | description: Converts hexadecimal color code to RGB color values.
4 | author: pvictordev
5 | tags: color,conversion
6 | ---
7 |
8 | ```js
9 | function hexToRgb(hex) {
10 | let sanitizedHex = hex.startsWith("#") ? hex.slice(1) : hex;
11 |
12 | if (sanitizedHex.length === 3) {
13 | sanitizedHex = [...sanitizedHex].map((char) => char + char).join("");
14 | }
15 |
16 | const bigint = parseInt(sanitizedHex, 16);
17 |
18 | return {
19 | r: (bigint >> 16) & 0xff,
20 | g: (bigint >> 8) & 0xff,
21 | b: bigint & 0xff,
22 | };
23 | }
24 |
25 | // Usage:
26 | console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 }
27 | console.log(hexToRgb("#ffff")); // { r: 0, g: 255, b: 255 }
28 | ```
--------------------------------------------------------------------------------
/snippets/javascript/color-manipulation/rgb-to-hex-color.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: RGB to Hex Color
3 | description: Converts RGB color values to hexadecimal color code.
4 | author: jjcantu
5 | tags: color,conversion
6 | ---
7 |
8 | ```js
9 | function rgbToHex(r, g, b) {
10 | const toHex = (n) => {
11 | const hex = n.toString(16);
12 | return hex.length === 1 ? "0" + hex : hex;
13 | };
14 |
15 | return "#" + toHex(r) + toHex(g) + toHex(b);
16 | }
17 |
18 | // Usage:
19 | console.log(rgbToHex(255, 128, 0)); // Output: "#ff8000"
20 | console.log(rgbToHex(0, 255, 0)); // Output: "#00ff00"
21 | ```
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/check-leap-year.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Leap Year
3 | description: Determines if a given year is a leap year.
4 | author: axorax
5 | tags: date,leap-year
6 | ---
7 |
8 | ```js
9 | const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
10 |
11 | // Usage:
12 | isLeapYear(2024); // Returns: true
13 | isLeapYear(2023); // Returns: false
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/format-date.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Format Date
3 | description: Formats a date in 'YYYY-MM-DD' format.
4 | author: technoph1le
5 | tags: date,format
6 | ---
7 |
8 | ```js
9 | const formatDate = (date) => date.toISOString().split('T')[0];
10 |
11 | // Usage:
12 | formatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/get-day-of-the-year.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Day of the Year
3 | description: Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.
4 | author: axorax
5 | tags: date,day-of-year
6 | ---
7 |
8 | ```js
9 | const getDayOfYear = (date) => {
10 | const startOfYear = new Date(date.getFullYear(), 0, 0);
11 | const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;
12 | return Math.floor(diff / (1000 * 60 * 60 * 24));
13 | };
14 |
15 | // Usage:
16 | getDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/get-days-in-month.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Days in Month
3 | description: Calculates the number of days in a specific month of a given year.
4 | author: axorax
5 | tags: date,days-in-month
6 | ---
7 |
8 | ```js
9 | const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();
10 |
11 | // Usage:
12 | getDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)
13 | getDaysInMonth(2023, 1); // Returns: 28
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/get-time-difference.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Time Difference
3 | description: Calculates the time difference in days between two dates.
4 | author: technoph1le
5 | tags: date,time-difference
6 | ---
7 |
8 | ```js
9 | const getTimeDifference = (date1, date2) => {
10 | const diff = Math.abs(date2 - date1);
11 | return Math.ceil(diff / (1000 * 60 * 60 * 24));
12 | };
13 |
14 | // Usage:
15 | const date1 = new Date('2024-01-01');
16 | const date2 = new Date('2024-12-31');
17 | getTimeDifference(date1, date2); // Returns: 365
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/date-and-time/start-of-the-day.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Start of the Day
3 | description: Returns the start of the day (midnight) for a given date.
4 | author: axorax
5 | tags: date,start-of-day
6 | ---
7 |
8 | ```js
9 | const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));
10 |
11 | // Usage:
12 | const today = new Date();
13 | startOfDay(today); // Returns: Date object for midnight
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/javascript/dom-manipulation/change-element-style.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Change Element Style
3 | description: Changes the inline style of an element.
4 | author: axorax
5 | tags: dom,style
6 | ---
7 |
8 | ```js
9 | const changeElementStyle = (element, styleObj) => {
10 | Object.entries(styleObj).forEach(([property, value]) => {
11 | element.style[property] = value;
12 | });
13 | };
14 |
15 | // Usage:
16 | const element = document.querySelector('.my-element');
17 | changeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/dom-manipulation/remove-element.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Element
3 | description: Removes a specified element from the DOM.
4 | author: axorax
5 | tags: dom,remove
6 | ---
7 |
8 | ```js
9 | const removeElement = (element) => {
10 | if (element && element.parentNode) {
11 | element.parentNode.removeChild(element);
12 | }
13 | };
14 |
15 | // Usage:
16 | const element = document.querySelector('.my-element');
17 | removeElement(element);
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/compose-functions.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Compose Functions
3 | description: Composes multiple functions into a single function, where the output of one function becomes the input of the next.
4 | author: axorax
5 | tags: function,compose
6 | ---
7 |
8 | ```js
9 | const compose = (...funcs) => (initialValue) => {
10 | return funcs.reduce((acc, func) => func(acc), initialValue);
11 | };
12 |
13 | // Usage:
14 | const add2 = (x) => x + 2;
15 | const multiply3 = (x) => x * 3;
16 | const composed = compose(multiply3, add2);
17 | composed(5); // Returns: 17 ((5 * 3) + 2)
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/curry-function.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Curry Function
3 | description: Transforms a function into its curried form.
4 | author: axorax
5 | tags: curry,function
6 | ---
7 |
8 | ```js
9 | const curry = (func) => {
10 | const curried = (...args) => {
11 | if (args.length >= func.length) {
12 | return func(...args);
13 | }
14 | return (...nextArgs) => curried(...args, ...nextArgs);
15 | };
16 | return curried;
17 | };
18 |
19 | // Usage:
20 | const add = (a, b, c) => a + b + c;
21 | const curriedAdd = curry(add);
22 | curriedAdd(1)(2)(3); // Returns: 6
23 | curriedAdd(1, 2)(3); // Returns: 6
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/debounce-function.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Debounce Function
3 | description: Delays a function execution until after a specified time.
4 | author: technoph1le
5 | tags: debounce,performance
6 | ---
7 |
8 | ```js
9 | const debounce = (func, delay) => {
10 | let timeout;
11 |
12 | return (...args) => {
13 | clearTimeout(timeout);
14 | timeout = setTimeout(() => func(...args), delay);
15 | };
16 | };
17 |
18 | // Usage:
19 | window.addEventListener(
20 | 'resize',
21 | debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms
22 | );
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/memoize-function.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Memoize Function
3 | description: Caches the result of a function based on its arguments to improve performance.
4 | author: axorax
5 | tags: memoization,optimization
6 | ---
7 |
8 | ```js
9 | const memoize = (func) => {
10 | const cache = new Map();
11 | return (...args) => {
12 | const key = JSON.stringify(args);
13 | if (cache.has(key)) {
14 | return cache.get(key);
15 | }
16 | const result = func(...args);
17 | cache.set(key, result);
18 | return result;
19 | };
20 | };
21 |
22 | // Usage:
23 | const factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));
24 | factorial(5); // Returns: 120
25 | factorial(5); // Returns: 120 (retrieved from cache)
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/once-function.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Once Function
3 | description: Ensures a function is only called once.
4 | author: axorax
5 | tags: function,once
6 | ---
7 |
8 | ```js
9 | const once = (func) => {
10 | let called = false;
11 | return (...args) => {
12 | if (!called) {
13 | called = true;
14 | return func(...args);
15 | }
16 | };
17 | };
18 |
19 | // Usage:
20 | const initialize = once(() => console.log('Initialized!'));
21 | initialize(); // Output: Initialized!
22 | initialize(); // No output
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/repeat-function-invocation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Repeat Function Invocation
3 | description: Invokes a function a specified number of times.
4 | author: technoph1le
5 | tags: function,repeat
6 | ---
7 |
8 | ```js
9 | const times = (func, n) => {
10 | Array.from(Array(n)).forEach(() => {
11 | func();
12 | });
13 | };
14 |
15 | // Usage:
16 | const randomFunction = () => console.log('Function called!');
17 | times(randomFunction, 3); // Logs 'Function called!' three times
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/function-utilities/sleep-function.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Sleep Function
3 | description: Waits for a specified amount of milliseconds before resolving.
4 | author: 0xHouss
5 | tags: javascript,sleep,delay,utility,promises
6 | ---
7 |
8 | ```js
9 | const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
10 |
11 | // Usage:
12 | console.log('Hello');
13 | await sleep(2000); // Waits for 2 seconds
14 | console.log('World!');
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/local-storage/add-item-to-localstorage.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Add Item to localStorage
3 | description: Stores a value in localStorage under the given key.
4 | author: technoph1le
5 | tags: localStorage,storage
6 | ---
7 |
8 | ```js
9 | const addToLocalStorage = (key, value) => {
10 | localStorage.setItem(key, JSON.stringify(value));
11 | };
12 |
13 | // Usage:
14 | addToLocalStorage('user', { name: 'John', age: 30 });
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/local-storage/check-if-item-exists-in-localstorage.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check if Item Exists in localStorage
3 | description: Checks if a specific item exists in localStorage.
4 | author: axorax
5 | tags: localStorage,storage
6 | ---
7 |
8 | ```js
9 | const isItemInLocalStorage = (key) => {
10 | return localStorage.getItem(key) !== null;
11 | };
12 |
13 | // Usage:
14 | console.log(isItemInLocalStorage('user')); // Output: true or false
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/local-storage/retrieve-item-from-localstorage.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Retrieve Item from localStorage
3 | description: Retrieves a value from localStorage by key and parses it.
4 | author: technoph1le
5 | tags: localStorage,storage
6 | ---
7 |
8 | ```js
9 | const getFromLocalStorage = (key) => {
10 | const item = localStorage.getItem(key);
11 | return item ? JSON.parse(item) : null;
12 | };
13 |
14 | // Usage:
15 | getFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/cross-product.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Cross Product
3 | description: Computes the cross product of two 3D vectors, which results in a vector perpendicular to both.
4 | author: JanluOfficial
5 | tags: math,vector-algebra
6 | ---
7 |
8 | ```js
9 | function crossProduct(a, b) {
10 | if (a.length !== 3 || b.length !== 3) {
11 | throw new Error('Vectors must be 3-dimensional');
12 | }
13 |
14 | return [
15 | a[1] * b[2] - a[2] * b[1],
16 | a[2] * b[0] - a[0] * b[2],
17 | a[0] * b[1] - a[1] * b[0]
18 | ];
19 | }
20 |
21 | // Usage:
22 | crossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3]
23 | ```
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/dot-product.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Dot Product
3 | description: Computes the dot product of two vectors, which is the sum of the products of corresponding elements.
4 | author: JanluOfficial
5 | tags: math,vector-algebra
6 | ---
7 |
8 | ```js
9 | function dotProduct(a, b) {
10 | if (a.length !== b.length) {
11 | throw new Error('Vectors must be of the same length');
12 | }
13 |
14 | return a.reduce((sum, value, index) => sum + value * b[index], 0);
15 | }
16 |
17 | // Usage:
18 | dotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32
19 | ```
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/greatest-common-divisor.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Greatest Common Divisor
3 | description: Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.
4 | author: JanluOfficial
5 | tags: math,division,number-theory,algebra
6 | ---
7 |
8 | ```js
9 | function gcd(a, b) {
10 | while (b !== 0) {
11 | let temp = b;
12 | b = a % b;
13 | a = temp;
14 | }
15 | return a;
16 | }
17 |
18 | // Usage:
19 | gcd(1920, 1080); // Returns: 120
20 | gcd(1920, 1200); // Returns: 240
21 | gcd(5,12); // Returns: 1
22 | ```
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/least-common-multiple.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Least common multiple
3 | 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.
4 | author: JanluOfficial
5 | tags: math,number-theory,algebra
6 | ---
7 |
8 | ```js
9 | function lcm(a, b) {
10 | function gcd(x, y) {
11 | while (y !== 0) {
12 | const temp = y;
13 | y = x % y;
14 | x = temp;
15 | }
16 | return Math.abs(x);
17 | }
18 | return Math.abs(a * b) / gcd(a, b);
19 | }
20 |
21 | // Usage:
22 | lcm(12,16); // Returns: 48
23 | lcm(8,20); // Returns: 40
24 | lcm(16,17); // Returns: 272
25 | ```
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/linear-mapping.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Linear Mapping
3 | description: remaps a value from one range to another
4 | author: JasimAlrawie
5 | tags: math,number-theory,algebra
6 | ---
7 |
8 | ```js
9 | function linearMapping(value, minIn, maxIn, minOut, maxOut) {
10 | return (value - minIn) * (maxOut - minOut)/(maxIn - minIn) + minOut
11 | }
12 |
13 | // Usage:
14 | linearMapping(value, 0, 1, 0, 255) // remaps the value from (0,1) to (0,255)
15 | linearMapping(value, 0, PI*2, 0, 360) // remaps the value from rad to deg
16 | linearMapping(value, -1, 1, 1, 8) // remaps the value from (-1,1) to (1,8)
17 | ```
--------------------------------------------------------------------------------
/snippets/javascript/mathematical-functions/prime-number.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Prime Number
3 | description: Checks if a number is a prime number or not.
4 | author: JanluOfficial
5 | tags: math,number-theory,algebra
6 | ---
7 |
8 | ```js
9 | function isPrime(num) {
10 | if (num <= 1) return false; // 0 and 1 are not prime numbers
11 | if (num <= 3) return true; // 2 and 3 are prime numbers
12 | if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3
13 |
14 | // Check divisors from 5 to √num, skipping multiples of 2 and 3
15 | for (let i = 5; i * i <= num; i += 6) {
16 | if (num % i === 0 || num % (i + 2) === 0) return false;
17 | }
18 | return true;
19 | }
20 |
21 | // Usage:
22 | isPrime(69); // Returns: false
23 | isPrime(17); // Returns: true
24 | ```
--------------------------------------------------------------------------------
/snippets/javascript/number-formatting/convert-number-to-currency.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Number to Currency
3 | description: Converts a number to a currency format with a specific locale.
4 | author: axorax
5 | tags: number,currency
6 | ---
7 |
8 | ```js
9 | const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {
10 | return new Intl.NumberFormat(locale, {
11 | style: 'currency',
12 | currency: currency
13 | }).format(num);
14 | };
15 |
16 | // Usage:
17 | convertToCurrency(1234567.89); // Returns: '$1,234,567.89'
18 | convertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/javascript/number-formatting/convert-number-to-roman-numerals.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Number to Roman Numerals
3 | description: Converts a number to Roman numeral representation.
4 | author: axorax
5 | tags: number,roman
6 | ---
7 |
8 | ```js
9 | const numberToRoman = (num) => {
10 | const romanNumerals = {
11 | 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',
12 | 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'
13 | };
14 | let result = '';
15 | Object.keys(romanNumerals).reverse().forEach(value => {
16 | while (num >= value) {
17 | result += romanNumerals[value];
18 | num -= value;
19 | }
20 | });
21 | return result;
22 | };
23 |
24 | // Usage:
25 | numberToRoman(1994); // Returns: 'MCMXCIV'
26 | numberToRoman(58); // Returns: 'LVIII'
27 | ```
28 |
--------------------------------------------------------------------------------
/snippets/javascript/number-formatting/format-file-size.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Format File Size
3 | description: Converts bytes into human-readable file size format.
4 | author: jjcantu
5 | tags: format,size
6 | ---
7 |
8 | ```js
9 | function formatFileSize(bytes) {
10 | if (bytes === 0) return '0 Bytes';
11 |
12 | const k = 1024;
13 | const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
14 | const i = Math.floor(Math.log(bytes) / Math.log(k));
15 |
16 | return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
17 | }
18 |
19 | // Usage:
20 | console.log(formatFileSize(1234)); // Output: "1.21 KB"
21 | console.log(formatFileSize(1234567)); // Output: "1.18 MB"
22 | ```
--------------------------------------------------------------------------------
/snippets/javascript/number-formatting/format-number-with-commas.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Format Number with Commas
3 | description: Formats a number with commas for better readability (e.g., 1000 -> 1,000).
4 | author: axorax
5 | tags: number,format
6 | ---
7 |
8 | ```js
9 | const formatNumberWithCommas = (num) => {
10 | return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
11 | };
12 |
13 | // Usage:
14 | formatNumberWithCommas(1000); // Returns: '1,000'
15 | formatNumberWithCommas(1234567); // Returns: '1,234,567'
16 | formatNumberWithCommas(987654321); // Returns: '987,654,321'
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/javascript/number-formatting/number-formatter.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Number Formatter
3 | description: Formats a number with suffixes (K, M, B, etc.).
4 | author: realvishalrana
5 | tags: number,format
6 | ---
7 |
8 | ```js
9 | const nFormatter = (num) => {
10 | if (!num) return;
11 | num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));
12 | const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];
13 | let index = 0;
14 | while (num >= 1000 && index < suffixes.length - 1) {
15 | num /= 1000;
16 | index++;
17 | }
18 | return num.toFixed(2).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];
19 | };
20 |
21 | // Usage:
22 | nFormatter(1234567); // Returns: '1.23M'
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/check-if-object-is-empty.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check if Object is Empty
3 | description: Checks whether an object has no own enumerable properties.
4 | author: axorax
5 | tags: object,check,empty
6 | ---
7 |
8 | ```js
9 | function isEmptyObject(obj) {
10 | return Object.keys(obj).length === 0;
11 | }
12 |
13 | // Usage:
14 | isEmptyObject({}); // Returns: true
15 | isEmptyObject({ a: 1 }); // Returns: false
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/compare-two-objects-shallowly.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Compare Two Objects Shallowly
3 | description: Compares two objects shallowly and returns whether they are equal.
4 | author: axorax
5 | tags: object,compare,shallow
6 | ---
7 |
8 | ```js
9 | function shallowEqual(obj1, obj2) {
10 | const keys1 = Object.keys(obj1);
11 | const keys2 = Object.keys(obj2);
12 | if (keys1.length !== keys2.length) return false;
13 | return keys1.every(key => obj1[key] === obj2[key]);
14 | }
15 |
16 | // Usage:
17 | const obj1 = { a: 1, b: 2 };
18 | const obj2 = { a: 1, b: 2 };
19 | const obj3 = { a: 1, b: 3 };
20 | shallowEqual(obj1, obj2); // Returns: true
21 | shallowEqual(obj1, obj3); // Returns: false
22 | ```
23 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/convert-object-to-query-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Object to Query String
3 | description: Converts an object to a query string for use in URLs.
4 | author: axorax
5 | tags: object,query string,url
6 | ---
7 |
8 | ```js
9 | function toQueryString(obj) {
10 | return Object.entries(obj)
11 | .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))
12 | .join('&');
13 | }
14 |
15 | // Usage:
16 | const params = { search: 'test', page: 1 };
17 | toQueryString(params); // Returns: 'search=test&page=1'
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/count-properties-in-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Properties in Object
3 | description: Counts the number of own properties in an object.
4 | author: axorax
5 | tags: object,count,properties
6 | ---
7 |
8 | ```js
9 | function countProperties(obj) {
10 | return Object.keys(obj).length;
11 | }
12 |
13 | // Usage:
14 | const obj = { a: 1, b: 2, c: 3 };
15 | countProperties(obj); // Returns: 3
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/deep-clone-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Deep Clone Object
3 | description: Creates a deep copy of an object or array without reference.
4 | author: jjcantu
5 | tags: object,clone
6 | ---
7 |
8 | ```js
9 | function deepClone(obj) {
10 | if (obj === null || typeof obj !== 'object') return obj;
11 |
12 | const clone = Array.isArray(obj) ? [] : {};
13 |
14 | for (let key in obj) {
15 | if (Object.prototype.hasOwnProperty.call(obj, key)) {
16 | clone[key] = deepClone(obj[key]);
17 | }
18 | }
19 |
20 | return clone;
21 | }
22 |
23 | // Usage:
24 | const original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };
25 | const cloned = deepClone(original);
26 | console.log(cloned); // Output: 'original' but cloned
27 | ```
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/flatten-nested-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Flatten Nested Object
3 | description: Flattens a nested object into a single-level object with dot notation for keys.
4 | author: axorax
5 | tags: object,flatten
6 | ---
7 |
8 | ```js
9 | function flattenObject(obj, prefix = '') {
10 | return Object.keys(obj).reduce((acc, key) => {
11 | const fullPath = prefix ? `${prefix}.${key}` : key;
12 | if (typeof obj[key] === 'object' && obj[key] !== null) {
13 | Object.assign(acc, flattenObject(obj[key], fullPath));
14 | } else {
15 | acc[fullPath] = obj[key];
16 | }
17 | return acc;
18 | }, {});
19 | }
20 |
21 | // Usage:
22 | const nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };
23 | flattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/freeze-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Freeze Object
3 | description: Freezes an object to make it immutable.
4 | author: axorax
5 | tags: object,freeze,immutable
6 | ---
7 |
8 | ```js
9 | function freezeObject(obj) {
10 | return Object.freeze(obj);
11 | }
12 |
13 | // Usage:
14 | const obj = { a: 1, b: 2 };
15 | const frozenObj = freezeObject(obj);
16 | frozenObj.a = 42; // This will fail silently in strict mode.
17 | frozenObj.a; // Returns: 1
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/get-nested-value.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Nested Value
3 | description: Retrieves the value at a given path in a nested object.
4 | author: realvishalrana
5 | tags: object,nested
6 | ---
7 |
8 | ```js
9 | const getNestedValue = (obj, path) => {
10 | const keys = path.split('.');
11 | return keys.reduce((currentObject, key) => {
12 | return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;
13 | }, obj);
14 | };
15 |
16 | // Usage:
17 | const obj = { a: { b: { c: 42 } } };
18 | getNestedValue(obj, 'a.b.c'); // Returns: 42
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/invert-object-keys-and-values.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Invert Object Keys and Values
3 | description: Creates a new object by swapping keys and values of the given object.
4 | author: axorax
5 | tags: object,invert
6 | ---
7 |
8 | ```js
9 | function invertObject(obj) {
10 | return Object.fromEntries(
11 | Object.entries(obj).map(([key, value]) => [value, key])
12 | );
13 | }
14 |
15 | // Usage:
16 | const obj = { a: 1, b: 2, c: 3 };
17 | invertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/merge-objects-deeply.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Merge Objects Deeply
3 | description: Deeply merges two or more objects, including nested properties.
4 | author: axorax
5 | tags: object,merge,deep
6 | ---
7 |
8 | ```js
9 | function deepMerge(...objects) {
10 | return objects.reduce((acc, obj) => {
11 | Object.keys(obj).forEach(key => {
12 | if (typeof obj[key] === 'object' && obj[key] !== null) {
13 | acc[key] = deepMerge(acc[key] || {}, obj[key]);
14 | } else {
15 | acc[key] = obj[key];
16 | }
17 | });
18 | return acc;
19 | }, {});
20 | }
21 |
22 | // Usage:
23 | const obj1 = { a: 1, b: { c: 2 } };
24 | const obj2 = { b: { d: 3 }, e: 4 };
25 | deepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/omit-keys-from-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Omit Keys from Object
3 | description: Creates a new object with specific keys omitted.
4 | author: axorax
5 | tags: object,omit
6 | ---
7 |
8 | ```js
9 | function omitKeys(obj, keys) {
10 | return Object.fromEntries(
11 | Object.entries(obj).filter(([key]) => !keys.includes(key))
12 | );
13 | }
14 |
15 | // Usage:
16 | const obj = { a: 1, b: 2, c: 3 };
17 | omitKeys(obj, ['b', 'c']); // Returns: { a: 1 }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/pick-keys-from-object.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Pick Keys from Object
3 | description: Creates a new object with only the specified keys.
4 | author: axorax
5 | tags: object,pick
6 | ---
7 |
8 | ```js
9 | function pickKeys(obj, keys) {
10 | return Object.fromEntries(
11 | Object.entries(obj).filter(([key]) => keys.includes(key))
12 | );
13 | }
14 |
15 | // Usage:
16 | const obj = { a: 1, b: 2, c: 3 };
17 | pickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/object-manipulation/unique-by-key.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Unique By Key
3 | description: Filters an array of objects to only include unique objects by a specified key.
4 | author: realvishalrana
5 | tags: array,unique
6 | ---
7 |
8 | ```js
9 | const uniqueByKey = (key, arr) =>
10 | arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));
11 |
12 | // Usage:
13 | const arr = [
14 | { id: 1, name: 'John' },
15 | { id: 2, name: 'Jane' },
16 | { id: 1, name: 'John' }
17 | ];
18 | uniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/capitalize-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize String
3 | description: Capitalizes the first letter of a string.
4 | author: technoph1le
5 | tags: string,capitalize
6 | ---
7 |
8 | ```js
9 | function capitalize(str) {
10 | return str.charAt(0).toUpperCase() + str.slice(1);
11 | }
12 |
13 | // Usage:
14 | capitalize('hello'); // Returns: 'Hello'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/check-if-string-is-a-palindrome.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check if String is a Palindrome
3 | description: Checks whether a given string is a palindrome.
4 | author: axorax
5 | tags: check,palindrome,string
6 | ---
7 |
8 | ```js
9 | function isPalindrome(str) {
10 | const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
11 | return cleanStr === cleanStr.split('').reverse().join('');
12 | }
13 |
14 | // Example usage:
15 | isPalindrome('A man, a plan, a canal, Panama'); // Returns: true
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-string-to-camel-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Camel Case
3 | description: Converts a given string into camelCase.
4 | author: aumirza
5 | tags: string,case,camelCase
6 | ---
7 |
8 | ```js
9 | function toCamelCase(str) {
10 | return str.replace(/\W+(.)/g, (match, chr) => chr.toUpperCase());
11 | }
12 |
13 | // Usage:
14 | toCamelCase('hello world test'); // Returns: 'helloWorldTest'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-string-to-param-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Param Case
3 | description: Converts a given string into param-case.
4 | author: aumirza
5 | tags: string,case,paramCase
6 | ---
7 |
8 | ```js
9 | function toParamCase(str) {
10 | return str.toLowerCase().replace(/\s+/g, '-');
11 | }
12 |
13 | // Usage:
14 | toParamCase('Hello World Test'); // Returns: 'hello-world-test'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-string-to-pascal-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Pascal Case
3 | description: Converts a given string into Pascal Case.
4 | author: aumirza
5 | tags: string,case,pascalCase
6 | ---
7 |
8 | ```js
9 | function toPascalCase(str) {
10 | return str.replace(/\b\w/g, (s) => s.toUpperCase()).replace(/\W+(.)/g, (match, chr) => chr.toUpperCase());
11 | }
12 |
13 | // Usage:
14 | toPascalCase('hello world test'); // Returns: 'HelloWorldTest'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-string-to-snake-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Snake Case
3 | description: Converts a given string into snake_case.
4 | author: axorax
5 | tags: string,case,snake_case
6 | ---
7 |
8 | ```js
9 | function toSnakeCase(str) {
10 | return str.replace(/([a-z])([A-Z])/g, '$1_$2')
11 | .replace(/\s+/g, '_')
12 | .toLowerCase();
13 | }
14 |
15 | // Usage:
16 | toSnakeCase('Hello World Test'); // Returns: 'hello_world_test'
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-string-to-title-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Title Case
3 | description: Converts a given string into Title Case.
4 | author: aumirza
5 | tags: string,case,titleCase
6 | ---
7 |
8 | ```js
9 | function toTitleCase(str) {
10 | return str.toLowerCase().replace(/\b\w/g, (s) => s.toUpperCase());
11 | }
12 |
13 | // Usage:
14 | toTitleCase('hello world test'); // Returns: 'Hello World Test'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/convert-tabs-to-spaces.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Tabs to Spaces
3 | description: Converts all tab characters in a string to spaces.
4 | author: axorax
5 | tags: string,tabs,spaces
6 | ---
7 |
8 | ```js
9 | function tabsToSpaces(str, spacesPerTab = 4) {
10 | return str.replace(/\t/g, ' '.repeat(spacesPerTab));
11 | }
12 |
13 | // Usage:
14 | tabsToSpaces('Hello\tWorld', 2); // Returns: 'Hello World'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/count-words-in-a-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Words in a String
3 | description: Counts the number of words in a string.
4 | author: axorax
5 | tags: string,manipulation,word count,count
6 | ---
7 |
8 | ```js
9 | function countWords(str) {
10 | return str.trim().split(/\s+/).length;
11 | }
12 |
13 | // Usage:
14 | countWords('Hello world! This is a test.'); // Returns: 6
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/data-with-prefix.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Data with Prefix
3 | description: Adds a prefix and postfix to data, with a fallback value.
4 | author: realvishalrana
5 | tags: data,prefix,postfix,format
6 | ---
7 |
8 | ```js
9 | const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {
10 | return data ? `${prefix}${data}${postfix}` : fallback;
11 | };
12 |
13 | // Usage:
14 | dataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'
15 | dataWithPrefix('', '-', '(', ')'); // Returns: '-'
16 | dataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'
17 | dataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/extract-initials-from-name.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Extract Initials from Name
3 | description: Extracts and returns the initials from a full name.
4 | author: axorax
5 | tags: string,initials,name
6 | ---
7 |
8 | ```js
9 | function getInitials(name) {
10 | return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');
11 | }
12 |
13 | // Usage:
14 | getInitials('John Doe'); // Returns: 'JD'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/generate-uuid.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Generate UUID
3 | description: Generates a UUID (v4) string.
4 | author: jjcantu
5 | tags: uuid, generate, string
6 | ---
7 |
8 | ```js
9 | function generateUUID() {
10 | return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
11 | const r = Math.random() * 16 | 0;
12 | const v = c === 'x' ? r : (r & 0x3 | 0x8);
13 | return v.toString(16);
14 | });
15 | }
16 |
17 | // Usage:
18 | console.log(generateUUID()); // Output: "a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5"
19 | ```
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/mask-sensitive-information.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Mask Sensitive Information
3 | description: Masks parts of a sensitive string, like a credit card or email address.
4 | author: axorax
5 | tags: string,mask,sensitive
6 | ---
7 |
8 | ```js
9 | function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {
10 | return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));
11 | }
12 |
13 | // Usage:
14 | maskSensitiveInfo('123456789', 4); // Returns: '1234*****'
15 | maskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/pad-string-on-both-sides.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Pad String on Both Sides
3 | description: Pads a string on both sides with a specified character until it reaches the desired length.
4 | author: axorax
5 | tags: string,pad,manipulation
6 | ---
7 |
8 | ```js
9 | function padString(str, length, char = ' ') {
10 | const totalPad = length - str.length;
11 | const padStart = Math.floor(totalPad / 2);
12 | const padEnd = totalPad - padStart;
13 | return char.repeat(padStart) + str + char.repeat(padEnd);
14 | }
15 |
16 | // Usage:
17 | padString('hello', 10, '*'); // Returns: '**hello***'
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/random-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Random string
3 | description: Generates a random string of characters of a certain length
4 | author: kruimol
5 | tags: function,random
6 | ---
7 |
8 | ```js
9 | function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
10 | return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
11 | }
12 |
13 | makeid(3); // Returns: gDs (Random)
14 | makeid(5, "1234" /* (optional) */); // Returns: "35453" (Random)
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/remove-all-whitespace.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove All Whitespace
3 | description: Removes all whitespace from a string.
4 | author: axorax
5 | tags: string,whitespace
6 | ---
7 |
8 | ```js
9 | function removeWhitespace(str) {
10 | return str.replace(/\s+/g, '');
11 | }
12 |
13 | // Usage:
14 | removeWhitespace('Hello world!'); // Returns: 'Helloworld!'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/remove-vowels-from-a-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Vowels from a String
3 | description: Removes all vowels from a given string.
4 | author: axorax
5 | tags: string,remove,vowels
6 | ---
7 |
8 | ```js
9 | function removeVowels(str) {
10 | return str.replace(/[aeiouAEIOU]/g, '');
11 | }
12 |
13 | // Usage:
14 | removeVowels('Hello World'); // Returns: 'Hll Wrld'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/reverse-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Reverse String
3 | description: Reverses the characters in a string.
4 | author: technoph1le
5 | tags: string,reverse
6 | ---
7 |
8 | ```js
9 | const reverseString = (str) => str.split('').reverse().join('');
10 |
11 | // Usage:
12 | reverseString('hello'); // Returns: 'olleh'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/javascript/string-manipulation/truncate-text.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate Text
3 | description: Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.
4 | author: realvishalrana
5 | tags: string,truncate,text
6 | ---
7 |
8 | ```js
9 | const truncateText = (text = '', maxLength = 50) => {
10 | return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;
11 | };
12 |
13 | // Usage:
14 | const title = "Hello, World! This is a Test.";
15 | truncateText(title); // Returns: 'Hello, World! This is a Test.'
16 | truncateText(title, 10); // Returns: 'Hello, Wor...'
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/python/[fastapi]/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Returns Hello, World! when it recives a GET request made to the root endpoint.
4 | author: ACR1209
5 | tags: printing,hello-world,web,api
6 | ---
7 |
8 | ```py
9 | from typing import Union
10 | from fastapi import FastAPI
11 |
12 | app = FastAPI()
13 |
14 |
15 | @app.get("/")
16 | def read_root():
17 | return {"msg": "Hello, World!"}
18 |
19 | # Usage:
20 | # -> Go to http://127.0.0.1:8000/ and you'll see {"msg", "Hello, World!"}
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/python/[fastapi]/icon.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Creates a basic Tkinter window with a "Hello, World!" label.
4 | author: Legopitstop
5 | tags: app,hello-world,object-oriented
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Label
10 |
11 | class App(Tk):
12 | def __init__(self):
13 | Tk.__init__(self)
14 | self.geometry("200x200")
15 |
16 | self.lbl = Label(self, text='Hello, World!')
17 | self.lbl.pack(expand=1)
18 |
19 | # Usage:
20 | root = App()
21 | root.mainloop()
22 | ```
23 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-alphanumeric.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Alphanumeric
3 | description: A validation function to allow alphanumeric characters.
4 | author: Legopitstop
5 | tags: validation,alphanumeric
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_alphanumeric(value):
13 | return value.isalnum() or value == ""
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_alphanumeric)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-decimal.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Decimal
3 | description: A validation function to allow only decimal numbers.
4 | author: Legopitstop
5 | tags: validation,decimals
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_decimal(action, value):
13 | if action == "1":
14 | if value == "":
15 | return True
16 | try:
17 | float(value)
18 | return True
19 | except ValueError:
20 | return False
21 | return True
22 |
23 |
24 | # Usage:
25 | root = Tk()
26 | root.geometry("200x200")
27 |
28 | reg = root.register(allow_decimal)
29 | Entry(root, validate="key", validatecommand=(reg, "%d", "%P")).pack()
30 |
31 | root.mainloop()
32 | ```
33 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-digits-with-a-max-length.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Digits with A Max Length
3 | description: A validation function to allow only digits with a specified maximum length.
4 | author: Legopitstop
5 | tags: validation,max,length
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_digits_with_max_length(action, value, max_length):
13 | if action == "1":
14 | return value == "" or (value.isdigit() and len(value) <= int(max_length))
15 | return True
16 |
17 |
18 | # Usage:
19 | root = Tk()
20 | root.geometry("200x200")
21 |
22 | reg = root.register(allow_digits_with_max_length)
23 | # 4 is the max length
24 | Entry(root, validate="key", validatecommand=(reg, "%d", "%P", 4)).pack()
25 |
26 | root.mainloop()
27 | ```
28 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-lowercase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Lowercase
3 | description: A validation function to allow only lowercase alphabetic characters.
4 | author: Legopitstop
5 | tags: validation,lowercase
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_lowercase(value):
13 | return value.islower() or value == ""
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_lowercase)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-negative-integers.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Negative Integers
3 | description: A validation function to allow only negative integers.
4 | author: Legopitstop
5 | tags: validation,negative,integers
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_negative_integers(value):
13 | return (
14 | value in ("", "-") or value.startswith("-") and value[1:].isdigit()
15 | if value
16 | else True
17 | )
18 |
19 |
20 | # Usage:
21 | root = Tk()
22 | root.geometry("200x200")
23 |
24 | reg = root.register(allow_negative_integers)
25 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
26 |
27 | root.mainloop()
28 | ```
29 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-only-alphabets.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Only Alphabets
3 | description: A validation function to allow only alphabetic characters.
4 | author: Legopitstop
5 | tags: validation,alphabets
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_only_alphabets(value):
13 | return value.isalpha() or value == ""
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_only_alphabets)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-only-digits.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Only Digits
3 | description: A validation function to allow only digits.
4 | author: Legopitstop
5 | tags: validation,digits
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_only_digits(value):
13 | return value.isdigit() or value == ""
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_only_digits)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-positive-integers.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Positive Integers
3 | description: A validation function to allow only positive integers.
4 | author: Legopitstop
5 | tags: validation,positive,integers
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_positive_integers(value):
13 | return value.isdigit() and (value == "" or int(value) > 0)
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_positive_integers)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-signed-integers.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Signed Integers
3 | description: A validation function to allow only signed integers.
4 | author: Legopitstop
5 | tags: validation,signed,integers
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_signed_integers(action, value):
13 | if action == "1":
14 | return (
15 | value in ("", "-")
16 | or value.isdigit()
17 | or (value.startswith("-") and value[1:].isdigit())
18 | )
19 | return True
20 |
21 |
22 | # Usage:
23 | root = Tk()
24 | root.geometry("200x200")
25 |
26 | reg = root.register(allow_signed_integers)
27 | Entry(root, validate="key", validatecommand=(reg, "%d", "%P")).pack()
28 |
29 | root.mainloop()
30 | ```
31 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-specific-characters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Specific Characters
3 | description: A validation function to allow specific characters.
4 | author: Legopitstop
5 | tags: validation,regex
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_specific_characters(value, allowed_chars):
13 | return all(char in allowed_chars for char in value)
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_specific_characters)
21 | allowed_chars = "0123456789ABCDEFabcdef" # Hexadecimal characters
22 | Entry(root, validate="key", validatecommand=(reg, "%P", allowed_chars)).pack()
23 |
24 | root.mainloop()
25 | ```
26 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/allow-uppercase.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Allow Uppercase
3 | description: A validation function to allow uppercase letters.
4 | author: Legopitstop
5 | tags: validation,uppercase
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def allow_uppercase(value):
13 | return value.isupper() or value == ""
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(allow_uppercase)
21 | Entry(root, validate="key", validatecommand=(reg, "%P")).pack()
22 |
23 | root.mainloop()
24 | ```
25 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/custom-regular-expression.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Custom Regular Expression
3 | description: A validation function to match a regular expression pattern.
4 | author: Legopitstop
5 | tags: validation,regex,pattern
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 | import re
11 |
12 |
13 | def custom_regular_expression(action, value, pattern):
14 | if action == "1":
15 | return re.fullmatch(pattern, value) is not None
16 | return True
17 |
18 |
19 | # Usage:
20 | root = Tk()
21 | root.geometry("200x200")
22 |
23 | reg = root.register(custom_regular_expression)
24 | pattern = r"^\d{0,4}$" # Allow up to 4 digits
25 | Entry(root, validate="key", validatecommand=(reg, "%d", "%P", pattern)).pack()
26 |
27 | root.mainloop()
28 | ```
29 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/restrict-length.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Restrict Length
3 | description: A validation function to limit the length.
4 | author: Legopitstop
5 | tags: validation,length
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 |
11 |
12 | def restrict_length(value, max_length):
13 | return len(value) <= int(max_length)
14 |
15 |
16 | # Usage:
17 | root = Tk()
18 | root.geometry("200x200")
19 |
20 | reg = root.register(restrict_length)
21 | # 10 is the maximum length allowed
22 | Entry(root, validate="key", validatecommand=(reg, "%P", 10)).pack()
23 |
24 | root.mainloop()
25 | ```
26 |
--------------------------------------------------------------------------------
/snippets/python/[tkinter]/entry-validation/validate-file-path.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Validate File Path
3 | description: A validation function to ensure the file path exists.
4 | author: Legopitstop
5 | tags: validation,filepath,fp
6 | ---
7 |
8 | ```py
9 | from tkinter import Tk, Entry
10 | import os
11 |
12 |
13 | def validate_file_path(action, value):
14 | if action == "1":
15 | return value == "" or os.path.exists(os.path.expandvars(value))
16 | return True
17 |
18 |
19 | # Usage:
20 | root = Tk()
21 | root.geometry("200x200")
22 |
23 | reg = root.register(validate_file_path)
24 | Entry(root, validate="key", validatecommand=(reg, "%d", "%P")).pack()
25 |
26 | root.mainloop()
27 | ```
28 |
--------------------------------------------------------------------------------
/snippets/python/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: James-Beans
5 | tags: printing,hello-world
6 | ---
7 |
8 | ```py
9 | print("Hello, World!") # Prints Hello, World! to the terminal.
10 | ```
11 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/calculate-date-difference-in-milliseconds.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Calculate Date Difference in Milliseconds
3 | description: Calculates the difference between two dates in milliseconds.
4 | author: e3nviction
5 | tags: datetime,difference
6 | ---
7 |
8 | ```py
9 | from datetime import datetime
10 |
11 | def date_difference_in_millis(date1, date2):
12 | delta = date2 - date1
13 | return delta.total_seconds() * 1000
14 |
15 | # Usage:
16 | d1 = datetime(2023, 1, 1, 12, 0, 0)
17 | d2 = datetime(2023, 1, 1, 12, 1, 0)
18 | date_difference_in_millis(d1, d2) # Returns: 60000
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/check-if-date-is-a-weekend.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check if Date is a Weekend
3 | description: Checks whether a given date falls on a weekend.
4 | author: axorax
5 | tags: datetime,weekend
6 | ---
7 |
8 | ```py
9 | from datetime import datetime
10 |
11 | def is_weekend(date):
12 | try:
13 | return date.weekday() >= 5 # Saturday = 5, Sunday = 6
14 | except AttributeError:
15 | raise TypeError("Input must be a datetime object")
16 |
17 | # Usage:
18 | date = datetime(2023, 1, 1)
19 | is_weekend(date) # Returns: True (Sunday)
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/day-of-the-week-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Day of the Week String
3 | description: Gets the string of the day of the week for a given date.
4 | author: axorax
5 | tags: datetime,weekday
6 | ---
7 |
8 | ```py
9 | from datetime import datetime
10 |
11 | def get_day_of_week(date):
12 | days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
13 | try:
14 | return days[date.weekday()]
15 | except IndexError:
16 | raise ValueError("Invalid date")
17 |
18 | # Usage:
19 | date = datetime(2023, 1, 1)
20 | get_day_of_week(date) # Returns: 'Sunday'
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/get-current-date-and-time-as-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Current Date and Time as String
3 | description: Fetches the current date and time as a formatted string.
4 | author: e3nviction
5 | tags: datetime,current,string
6 | ---
7 |
8 | ```py
9 | from datetime import datetime
10 |
11 | def get_current_datetime_string():
12 | return datetime.now().strftime('%Y-%m-%d %H:%M:%S')
13 |
14 | # Usage:
15 | get_current_datetime_string() # Returns: '2023-01-01 12:00:00'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/get-number-of-days-in-a-month.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get Number of Days in a Month
3 | description: Determines the number of days in a specific month and year.
4 | author: axorax
5 | tags: datetime,calendar
6 | ---
7 |
8 | ```py
9 | from calendar import monthrange
10 | from datetime import datetime
11 |
12 | def get_days_in_month(year, month):
13 | try:
14 | return monthrange(year, month)[1]
15 | except ValueError as e:
16 | raise ValueError(f"Invalid month or year: {e}")
17 |
18 | # Usage:
19 | get_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/python/datetime-utilities/measure-execution-time.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Measure Execution Time
3 | description: Measures the execution time of a code block.
4 | author: technoph1le
5 | tags: time,execution
6 | ---
7 |
8 | ```py
9 | import time
10 |
11 | def measure_time(func, *args):
12 | start = time.time()
13 | result = func(*args)
14 | end = time.time()
15 | print(f'Execution time: {end - start:.6f} seconds')
16 | return result
17 |
18 | # Usage:
19 | def slow_function():
20 | time.sleep(2)
21 |
22 | measure_time(slow_function) # Outputs an execution time of ~2s
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/python/error-handling/create-custom-exception-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Create Custom Exception Type
3 | description: Create a Custom Exception Type that can be called with raise.
4 | author: mrcool7387
5 | tags: python,error-creation,organisation,utility
6 | ---
7 |
8 | ```py
9 | class ExceptionName(BaseException):
10 | def __init__(message: str):
11 | super().__init__(message)
12 |
13 | # Usage
14 | a: int = 1
15 |
16 | if a > 0:
17 | raise ExceptionName('Error Message')
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/python/file-handling/find-files.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Files
3 | description: Finds all files of the specified type within a given directory.
4 | author: Jackeastern
5 | tags: os,filesystem,file_search
6 | ---
7 |
8 | ```py
9 | import os
10 |
11 | def find_files(directory, file_type):
12 | file_type = file_type.lower() # Convert file_type to lowercase
13 | found_files = []
14 |
15 | for root, _, files in os.walk(directory):
16 | for file in files:
17 | file_ext = os.path.splitext(file)[1].lower()
18 | if file_ext == file_type:
19 | full_path = os.path.join(root, file)
20 | found_files.append(full_path)
21 |
22 | return found_files
23 |
24 | # Example Usage:
25 | find_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/python/file-handling/get-file-extension.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Get File Extension
3 | description: Gets the extension of a file.
4 | author: axorax
5 | tags: file,extension
6 | ---
7 |
8 | ```py
9 | import os
10 |
11 | def get_file_extension(filepath):
12 | return os.path.splitext(filepath)[1]
13 |
14 | # Usage:
15 | get_file_extension('example.txt') # Returns: '.txt'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/file-handling/list-files-in-directory.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: List Files in Directory
3 | description: Lists all files in a specified directory.
4 | author: axorax
5 | tags: file,list,directory
6 | ---
7 |
8 | ```py
9 | import os
10 |
11 | def list_files(directory):
12 | return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
13 |
14 | # Usage:
15 | list_files('/path/to/directory') # Returns: List of file in the directory
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/file-handling/read-file-in-chunks.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Read File in Chunks
3 | description: Reads a file in chunks of a specified size.
4 | author: axorax
5 | tags: file,read,chunks
6 | ---
7 |
8 | ```py
9 | def read_file_in_chunks(filepath, chunk_size):
10 | with open(filepath, 'r') as file:
11 | while chunk := file.read(chunk_size):
12 | yield chunk
13 |
14 | # Usage:
15 | for chunk in read_file_in_chunks('example.txt', 1024):
16 | print(chunk) # Outputs: Chucks of 1024 bytes
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/python/json-manipulation/filter-json-data.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Filter JSON Data
3 | description: Filters a JSON object based on a condition and returns the filtered data.
4 | author: axorax
5 | tags: json,filter,data
6 | ---
7 |
8 | ```py
9 | import json
10 |
11 | def filter_json_data(filepath, condition):
12 | with open(filepath, 'r') as file:
13 | data = json.load(file)
14 |
15 | # Filter data based on the provided condition
16 | filtered_data = [item for item in data if condition(item)]
17 |
18 | return filtered_data
19 |
20 | # Usage:
21 | condition = lambda x: x['age'] > 25
22 | filter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition`
23 | ```
24 |
--------------------------------------------------------------------------------
/snippets/python/json-manipulation/flatten-nested-json.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Flatten Nested JSON
3 | description: Flattens a nested JSON object into a flat dictionary.
4 | author: axorax
5 | tags: json,flatten,nested
6 | ---
7 |
8 | ```py
9 | def flatten_json(nested_json, prefix=''):
10 | flat_dict = {}
11 | for key, value in nested_json.items():
12 | if isinstance(value, dict):
13 | flat_dict.update(flatten_json(value, prefix + key + '.'))
14 | else:
15 | flat_dict[prefix + key] = value
16 | return flat_dict
17 |
18 | # Usage:
19 | nested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}
20 | flatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/python/json-manipulation/read-json-file.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Read JSON File
3 | description: Reads a JSON file and parses its content.
4 | author: e3nviction
5 | tags: json,file,read
6 | ---
7 |
8 | ```py
9 | import json
10 |
11 | def read_json(filepath):
12 | with open(filepath, 'r') as file:
13 | return json.load(file)
14 |
15 | # Usage:
16 | read_json('data.json') # Returns: Content of file as dict
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/python/json-manipulation/update-json-file.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Update JSON File
3 | description: Updates an existing JSON file with new data or modifies the existing values.
4 | author: axorax
5 | tags: json,update,file
6 | ---
7 |
8 | ```py
9 | import json
10 |
11 | def update_json(filepath, new_data):
12 | # Read the existing JSON data
13 | with open(filepath, 'r') as file:
14 | data = json.load(file)
15 |
16 | # Update the data with the new content
17 | data.update(new_data)
18 |
19 | # Write the updated data back to the JSON file
20 | with open(filepath, 'w') as file:
21 | json.dump(data, file, indent=4)
22 |
23 | # Usage:
24 | new_data = {'age': 31}
25 | update_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys
26 | ```
27 |
--------------------------------------------------------------------------------
/snippets/python/json-manipulation/write-json-file.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Write JSON File
3 | description: Writes a dictionary to a JSON file.
4 | author: e3nviction
5 | tags: json,file,write
6 | ---
7 |
8 | ```py
9 | import json
10 |
11 | def write_json(filepath, data):
12 | with open(filepath, 'w') as file:
13 | json.dump(data, file, indent=4)
14 |
15 | # Usage:
16 | data = {'name': 'John', 'age': 30}
17 | write_json('data.json', data)
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/find-duplicates-in-a-list.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Duplicates in a List
3 | description: Identifies duplicate elements in a list.
4 | author: axorax
5 | tags: list,duplicates
6 | ---
7 |
8 | ```py
9 | def find_duplicates(lst):
10 | seen = set()
11 | duplicates = set()
12 | for item in lst:
13 | if item in seen:
14 | duplicates.add(item)
15 | else:
16 | seen.add(item)
17 | return list(duplicates)
18 |
19 | # Usage:
20 | data = [1, 2, 3, 2, 4, 5, 1]
21 | find_duplicates(data) # Returns: [1, 2]
22 | ```
23 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/find-intersection-of-two-lists.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Intersection of Two Lists
3 | description: Finds the common elements between two lists.
4 | author: axorax
5 | tags: list,intersection
6 | ---
7 |
8 | ```py
9 | def list_intersection(lst1, lst2):
10 | return [item for item in lst1 if item in lst2]
11 |
12 | # Usage:
13 | list_a = [1, 2, 3, 4]
14 | list_b = [3, 4, 5, 6]
15 | list_intersection(list_a, list_b) # Returns: [3, 4]
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/find-maximum-difference-in-list.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Maximum Difference in List
3 | description: Finds the maximum difference between any two elements in a list.
4 | author: axorax
5 | tags: list,difference
6 | ---
7 |
8 | ```py
9 | def max_difference(lst):
10 | if not lst or len(lst) < 2:
11 | return 0
12 | return max(lst) - min(lst)
13 |
14 | # Usage:
15 | data = [10, 3, 5, 20, 7]
16 | max_difference(data) # Returns: 17
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/flatten-nested-list.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Flatten Nested List
3 | description: Flattens a multi-dimensional list into a single list.
4 | author: technoph1le
5 | tags: list,flatten
6 | ---
7 |
8 | ```py
9 | def flatten_list(lst):
10 | return [item for sublist in lst for item in sublist]
11 |
12 | # Usage:
13 | nested_list = [[1, 2], [3, 4], [5]]
14 | flatten_list(nested_list) # Returns: [1, 2, 3, 4, 5]
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/flatten-unevenly-nested-lists.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Flatten Unevenly Nested Lists
3 | description: Converts unevenly nested lists of any depth into a single flat list.
4 | author: agilarasu
5 | tags: list,flattening,nested-lists,depth
6 | ---
7 |
8 | ```py
9 | def flatten(nested_list):
10 | for item in nested_list:
11 | if isinstance(item, list):
12 | yield from flatten(item)
13 | else:
14 | yield item
15 |
16 | # Usage:
17 | nested_list = [1, [2, [3, 4]], 5]
18 | list(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5]
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/partition-list.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Partition List
3 | description: Partitions a list into sublists of a given size.
4 | author: axorax
5 | tags: list,partition
6 | ---
7 |
8 | ```py
9 | def partition_list(lst, size):
10 | for i in range(0, len(lst), size):
11 | yield lst[i:i + size]
12 |
13 | # Usage:
14 | data = [1, 2, 3, 4, 5, 6, 7]
15 | list(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]]
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/list-manipulation/remove-duplicates.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Duplicates
3 | description: Removes duplicate elements from a list while maintaining order.
4 | author: technoph1le
5 | tags: list,duplicates,filter
6 | ---
7 |
8 | ```py
9 | def remove_duplicates(lst):
10 | return list(dict.fromkeys(lst))
11 |
12 | # Usage:
13 | remove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/calculate-compound-interest.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Calculate Compound Interest
3 | description: Calculates compound interest for a given principal amount, rate, and time period.
4 | author: axorax
5 | tags: math,compound interest,finance
6 | ---
7 |
8 | ```py
9 | def compound_interest(principal, rate, time, n=1):
10 | return principal * (1 + rate / n) ** (n * time)
11 |
12 | # Usage:
13 | compound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003
14 | compound_interest(1000, 0.05, 5, 12) # Returns: 1283.68
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/check-perfect-square.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Perfect Square
3 | description: Checks if a number is a perfect square.
4 | author: axorax
5 | tags: math,perfect square,check
6 | ---
7 |
8 | ```py
9 | def is_perfect_square(n):
10 | if n < 0:
11 | return False
12 | root = int(n**0.5)
13 | return root * root == n
14 |
15 | # Usage:
16 | is_perfect_square(16) # Returns: True
17 | is_perfect_square(20) # Returns: False
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/check-prime-number.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Prime Number
3 | description: Checks if a number is a prime number.
4 | author: technoph1le
5 | tags: math,prime,check
6 | ---
7 |
8 | ```py
9 | def is_prime(n):
10 | if n <= 1:
11 | return False
12 | for i in range(2, int(n**0.5) + 1):
13 | if n % i == 0:
14 | return False
15 | return True
16 |
17 | # Usage:
18 | is_prime(17) # Returns: True
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/convert-binary-to-decimal.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Binary to Decimal
3 | description: Converts a binary string to its decimal equivalent.
4 | author: axorax
5 | tags: math,binary,decimal,conversion
6 | ---
7 |
8 | ```py
9 | def binary_to_decimal(binary_str):
10 | return int(binary_str, 2)
11 |
12 | # Usage:
13 | binary_to_decimal('1010') # Returns: 10
14 | binary_to_decimal('1101') # Returns: 13
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/convert-bytes-to-human-readable-format.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Bytes to Human-Readable Format
3 | description: Converts a size in bytes to a human-readable format.
4 | author: axorax
5 | tags: bytes,format
6 | ---
7 |
8 | ```py
9 | def bytes_to_human_readable(num):
10 | for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:
11 | if num < 1024:
12 | return f"{num:.2f} {unit}"
13 | num /= 1024
14 |
15 | # Usage:
16 | bytes_to_human_readable(123456789) # Returns: '117.74 MB'
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/find-lcm-least-common-multiple.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find LCM (Least Common Multiple)
3 | description: Calculates the least common multiple (LCM) of two numbers.
4 | author: axorax
5 | tags: python,math,lcm,gcd,utility
6 | ---
7 |
8 | ```py
9 | def lcm(a, b):
10 | return abs(a * b) // gcd(a, b)
11 |
12 | # Usage:
13 | lcm(12, 15) # Returns: 60
14 | lcm(7, 5) # Returns: 35
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/linear-mapping.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Linear Mapping
3 | description: remaps a value from one range to another
4 | author: JasimAlrawie
5 | tags: math,number-theory,algebra
6 | ---
7 |
8 | ```py
9 | def linear_mapping(value, min_in, max_in, min_out, max_out):
10 | return (value - min_in) * (max_out - min_out) / (max_in - min_in) + min_out
11 |
12 | #Usage:
13 | linear_mapping(value, 0, 1, 0, 255) # remaps the value from (0,1) to (0,255)
14 | linear_mapping(value, 0, PI*2, 0, 360) # remaps the value from rad to deg
15 | linear_mapping(value, -1, 1, 1, 8) # remaps the value from (-1,1) to (1,8)
16 | ```
--------------------------------------------------------------------------------
/snippets/python/math-and-numbers/solve-quadratic-equation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Solve Quadratic Equation
3 | description: Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.
4 | author: axorax
5 | tags: math,quadratic,equation,solver
6 | ---
7 |
8 | ```py
9 | import cmath
10 |
11 | def solve_quadratic(a, b, c):
12 | discriminant = cmath.sqrt(b**2 - 4 * a * c)
13 | root1 = (-b + discriminant) / (2 * a)
14 | root2 = (-b - discriminant) / (2 * a)
15 | return root1, root2
16 |
17 | # Usage:
18 | solve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j))
19 | solve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j))
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/capitalize-words.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize Words
3 | description: Capitalizes the first letter of each word in a string.
4 | author: axorax
5 | tags: string,capitalize
6 | ---
7 |
8 | ```py
9 | def capitalize_words(s):
10 | return ' '.join(word.capitalize() for word in s.split())
11 |
12 | # Usage:
13 | capitalize_words('hello world') # Returns: 'Hello World'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/check-anagram.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Anagram
3 | description: Checks if two strings are anagrams of each other.
4 | author: SteliosGee
5 | tags: string,anagram,check
6 | ---
7 |
8 | ```py
9 | def is_anagram(s1, s2):
10 | return sorted(s1) == sorted(s2)
11 |
12 | # Usage:
13 | is_anagram('listen', 'silent') # Returns: True
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/check-palindrome.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Palindrome
3 | description: Checks if a string is a palindrome.
4 | author: technoph1le
5 | tags: string,palindrome
6 | ---
7 |
8 | ```py
9 | def is_palindrome(s):
10 | s = s.lower().replace(' ', '')
11 | return s == s[::-1]
12 |
13 | # Usage:
14 | is_palindrome('A man a plan a canal Panama') # Returns: True
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/convert-snake-case-to-camel-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert Snake Case to Camel Case
3 | description: Converts a snake_case string to camelCase.
4 | author: axorax
5 | tags: string,snake-case,camel-case,convert
6 | ---
7 |
8 | ```py
9 | def snake_to_camel(s):
10 | parts = s.split('_')
11 | return parts[0] + ''.join(word.capitalize() for word in parts[1:])
12 |
13 | # Usage:
14 | snake_to_camel('hello_world') # Returns: 'helloWorld'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/convert-string-to-unicode.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Convert String to Unicode
3 | description: Converts a string into its Unicode representation.
4 | author: axorax
5 | tags: string,ascii,unicode,convert
6 | ---
7 |
8 | ```py
9 | def string_to_unicode(s):
10 | return [ord(char) for char in s]
11 |
12 | # Usage:
13 | string_to_unicode('hello') # Returns: [104, 101, 108, 108, 111]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/count-character-frequency.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Character Frequency
3 | description: Counts the frequency of each character in a string.
4 | author: axorax
5 | tags: string,character-frequency
6 | ---
7 |
8 | ```py
9 | from collections import Counter
10 |
11 | def char_frequency(s):
12 | return dict(Counter(s))
13 |
14 | # Usage:
15 | char_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/count-vowels.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Vowels
3 | description: Counts the number of vowels in a string.
4 | author: SteliosGee
5 | tags: string,vowels,count
6 | ---
7 |
8 | ```py
9 | def count_vowels(s):
10 | vowels = 'aeiou'
11 | return len([char for char in s.lower() if char in vowels])
12 |
13 | # Usage:
14 | count_vowels('hello') # Returns: 2
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/count-words.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Words
3 | description: Counts the number of words in a string.
4 | author: axorax
5 | tags: string,word-count
6 | ---
7 |
8 | ```py
9 | def count_words(s):
10 | return len(s.split())
11 |
12 | # Usage:
13 | count_words('The quick brown fox') # Returns: 4
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/find-all-substrings.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find All Substrings
3 | description: Finds all substrings of a given string.
4 | author: axorax
5 | tags: string,substring,find
6 | ---
7 |
8 | ```py
9 | def find_substrings(s):
10 | substrings = []
11 | for i in range(len(s)):
12 | for j in range(i + 1, len(s) + 1):
13 | substrings.append(s[i:j])
14 | return substrings
15 |
16 | # Usage:
17 | find_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c']
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/find-longest-word.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Longest Word
3 | description: Finds the longest word in a string.
4 | author: axorax
5 | tags: string,longest-word
6 | ---
7 |
8 | ```py
9 | def find_longest_word(s):
10 | words = s.split()
11 | return max(words, key=len) if words else ''
12 |
13 | # Usage:
14 | find_longest_word('The quick brown fox') # Returns: 'quick'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/find-unique-characters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Find Unique Characters
3 | description: Finds all unique characters in a string.
4 | author: axorax
5 | tags: string,unique,characters
6 | ---
7 |
8 | ```py
9 | def find_unique_chars(s):
10 | return ''.join(sorted(set(s)))
11 |
12 | # Usage:
13 | find_unique_chars('banana') # Results: 'abn'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/generate-random-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Generate Random String
3 | description: Generates a random alphanumeric string.
4 | author: technoph1le
5 | tags: random,string
6 | ---
7 |
8 | ```py
9 | import random
10 | import string
11 |
12 | def random_string(length):
13 | letters_and_digits = string.ascii_letters + string.digits
14 | return ''.join(random.choice(letters_and_digits) for _ in range(length))
15 |
16 | # Usage:
17 | random_string(10) # Results: Random 10-character string
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/remove-characters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Characters
3 | description: Removes specific characters from a string.
4 | author: axorax
5 | tags: string,remove,characters
6 | ---
7 |
8 | ```py
9 | def remove_chars(s, chars):
10 | return ''.join(c for c in s if c not in chars)
11 |
12 | # Usage:
13 | remove_chars('hello world', 'eo') # Returns: 'hll wrld'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/remove-duplicate-characters.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Duplicate Characters
3 | description: Removes duplicate characters from a string while maintaining the order.
4 | author: axorax
5 | tags: string,duplicates,remove
6 | ---
7 |
8 | ```py
9 | def remove_duplicate_chars(s):
10 | seen = set()
11 | return ''.join(char for char in s if not (char in seen or seen.add(char)))
12 |
13 | # Usage:
14 | remove_duplicate_chars('programming') # Returns: 'progamin'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/remove-punctuation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Punctuation
3 | description: Removes punctuation from a string.
4 | author: SteliosGee
5 | tags: string,punctuation,remove
6 | ---
7 |
8 | ```py
9 | import string
10 |
11 | def remove_punctuation(s):
12 | return s.translate(str.maketrans('', '', string.punctuation))
13 |
14 | # Usage:
15 | remove_punctuation('Hello, World!') # Returns: 'Hello World'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/remove-whitespace.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Whitespace
3 | description: Removes all whitespace from a string.
4 | author: axorax
5 | tags: string,whitespace,remove
6 | ---
7 |
8 | ```py
9 | def remove_whitespace(s):
10 | return ''.join(s.split())
11 |
12 | # Usage:
13 | remove_whitespace('hello world') # Returns: 'helloworld'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/reverse-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Reverse String
3 | description: Reverses the characters in a string.
4 | author: technoph1le
5 | tags: string,reverse
6 | ---
7 |
8 | ```py
9 | def reverse_string(s:str) -> str:
10 | return s[::-1]
11 |
12 | # Usage:
13 | reverse_string('hello') # Returns: 'olleh'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/split-camel-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Split Camel Case
3 | description: Splits a camel case string into separate words.
4 | author: axorax
5 | tags: string,camel-case,split
6 | ---
7 |
8 | ```py
9 | import re
10 |
11 | def split_camel_case(s):
12 | return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))
13 |
14 | # Usage:
15 | split_camel_case('camelCaseString') # Returns: 'camel Case String'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/python/string-manipulation/truncate.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate
3 | description: Truncates a string to a specified length and a toggleable truncation notation.
4 | author: axorax
5 | contributors: MinerMinerMods
6 | tags: string,truncate
7 | ---
8 |
9 | ```py
10 | def truncate(s:str, length:int, suffix:bool = True) -> str :
11 | return (s[:length] + ("..." if suffix else "")) if len(s) > length else s
12 |
13 | # Usage:
14 | truncate('This is a long string', 10) # Returns: 'This is a ...'
15 | truncate('This is a long string', 10, False) # Returns: 'This is a '
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/regex/miscellaneous/hexadecimal-color.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Hexadecimal Color
3 | Description: Matches hex color codes
4 | Author: majvax
5 | Tags: color,hexadecimal
6 | ---
7 |
8 |
9 | ```regex
10 | ^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$
11 |
12 |
13 | -> Usage:
14 | #FFF1 ✗
15 | #FFF ✓
16 | #FFF000 ✓
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/regex/miscellaneous/ipv4.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: IPv4
3 | Description: Matches IPv4 address
4 | Author: majvax
5 | Tags: ipv4,networking
6 | ---
7 |
8 |
9 | ```regex
10 | ^((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})$
11 |
12 |
13 | -> Usage:
14 | 123.300.0.101 ✗
15 | 127.0.0.1 ✓
16 | 192.168.0.1 ✓
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/regex/miscellaneous/unintentional-duplication.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Unintentional Duplication
3 | Description: Matches duplicated word in a text.
4 | Author: majvax
5 | Tags: duplication
6 | ---
7 |
8 |
9 | ```regex
10 | \b(\w+)\s+\1\b
11 |
12 |
13 | -> Usage:
14 | I need to finish this task ✗
15 | I need to to finish this task ✓
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/regex/miscellaneous/whitespace-trimmer.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Whitespace Trimmer
3 | Description: Matches leading and/or trailing whitespace.
4 | Author: majvax
5 | Tags: trim
6 | ---
7 |
8 |
9 | ```regex
10 | ^\s+|\s+$
11 |
12 |
13 | -> Usage:
14 | (don't account for the quotation marks, it just to visualize whitespace)
15 | "Hello World" ✗
16 | " Hello World" ✓
17 | "Hello World " ✓
18 | " Hello World " ✓
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/regex/validation pattern/email-address.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Email Address
3 | Description: Match any email address
4 | Author: majvax
5 | Tags: email
6 | ---
7 |
8 |
9 | ```regex
10 | ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
11 |
12 | -> Usage:
13 | example.name@domain.com.ru ✓
14 | name.surname@gmail.com ✓
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/regex/validation pattern/strong-password.md:
--------------------------------------------------------------------------------
1 | ---
2 | Title: Strong Password
3 | Description: Match password with at least 12 characters, one uppercased letter, one number, and one special character.
4 | Author: majvax
5 | Tags: password
6 | ---
7 |
8 |
9 | ```regex
10 | ^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$
11 |
12 | -> Usage:
13 | longpassword ✗
14 | longpassw0rd ✗
15 | longp@ssw0rd ✗
16 | Longp@ssw0rd ✓
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/ruby/array-manipulation/binary-search.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Binary Search
3 | description: Searches for an element in a sorted array using binary search.
4 | author: ACR1209
5 | tags: array,binary-search,search
6 | ---
7 |
8 | ```rb
9 | def binary_search(array, target)
10 | low = 0
11 | high = array.length - 1
12 |
13 | while low <= high
14 | mid = (low + high) / 2
15 | guess = array[mid]
16 |
17 | if guess == target
18 | return mid
19 | elsif guess > target
20 | high = mid - 1
21 | else
22 | low = mid + 1
23 | end
24 | end
25 |
26 | return nil
27 | end
28 |
29 | # Usage:
30 | array = [1, 3, 5, 7, 9]
31 | target = 5
32 | result = binary_search(array, target)
33 | puts result # Output: 2
34 | ```
--------------------------------------------------------------------------------
/snippets/ruby/array-manipulation/chunk-array.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Chunk Array
3 | description: Splits an array into chunks of a specified size.
4 | author: ACR1209
5 | tags: array,chunk
6 | ---
7 |
8 | ```rb
9 | def chunk_array(array, size)
10 | array.each_slice(size).to_a
11 | end
12 |
13 | # Usage:
14 | arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
15 | chunked_arr = chunk_array(arr, 2)
16 | puts chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
17 | ```
--------------------------------------------------------------------------------
/snippets/ruby/array-manipulation/matrix-transpose.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Matrix Transpose
3 | description: Transposes a 2D matrix.
4 | author: ACR1209
5 | tags: array,matrix,transpose
6 | ---
7 |
8 | ```ruby
9 | def transpose_matrix(matrix)
10 | return [] if matrix.empty?
11 | return [] if matrix.first.empty?
12 |
13 | matrix.first.zip(*matrix[1..-1])
14 | end
15 |
16 | # Usage:
17 | matrix = [
18 | [1, 2, 3],
19 | [4, 5, 6],
20 | [7, 8, 9]
21 | ]
22 | print transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
23 | ```
--------------------------------------------------------------------------------
/snippets/ruby/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: ACR1209
5 | tags: printing,hello-world,utility
6 | ---
7 |
8 | ```rb
9 | puts 'Hello, World!'
10 | ```
11 |
--------------------------------------------------------------------------------
/snippets/ruby/error-handling/custom-error-class.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Custom Error Class
3 | description: Defines and raises a custom error class in Ruby.
4 | author: ACR1209
5 | tags: error handling,custom error
6 | ---
7 |
8 | ```rb
9 | class MyCustomError < StandardError; end
10 |
11 | def risky_method(value)
12 | raise MyCustomError, "Value must be positive" if value <= 0
13 | "Valid value: #{value}"
14 | end
15 |
16 | # Usage:
17 | begin
18 | puts risky_method(-1)
19 | rescue MyCustomError => e
20 | puts e.message # Output: "Value must be positive"
21 | end
22 | ```
--------------------------------------------------------------------------------
/snippets/ruby/math-and-numbers/calculate-compound-interest.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Calculate Compound Interest
3 | description: Calculates compound interest for a given principal amount, rate, and time period.
4 | author: ACR1209
5 | contributors: axorax
6 | tags: math,compound interest,finance
7 | ---
8 |
9 | ```rb
10 | def compound_interest(principal, rate, time, n = 1)
11 | principal * (1 + rate / n) ** (n * time)
12 | end
13 |
14 | # Usage:
15 | puts compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003
16 | puts compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/ruby/math-and-numbers/calculate-factorial.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Calculate Factorial
3 | description: Computes the factorial of a given integer.
4 | author: ACR1209
5 | tags: math,factorial
6 | ---
7 |
8 | ```rb
9 | def factorial(n)
10 | return 1 if n <= 1
11 | (2..n).reduce(1, :*)
12 | end
13 |
14 | # Usage:
15 | puts factorial(5) # Output: 120
16 | ```
--------------------------------------------------------------------------------
/snippets/ruby/math-and-numbers/check-prime-number.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Check Prime Number
3 | description: Checks if a number is a prime number.
4 | author: ACR1209
5 | contributors: technoph1le
6 | tags: math,prime,check
7 | ---
8 |
9 | ```rb
10 | def is_prime?(n)
11 | return false if n <= 1
12 | (2..Math.sqrt(n)).each do |i|
13 | return false if n % i == 0
14 | end
15 | true
16 | end
17 |
18 | # Usage:
19 | puts is_prime?(29) # Output: true
20 | puts is_prime?(30) # Output: false
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/capitalize-words.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize Words
3 | description: Capitalizes the first letter of each word in a string.
4 | author: ACR1209
5 | tags: string,capitalize,words
6 | ---
7 |
8 | ```rb
9 | def capitalize_words(str)
10 | str.split.map(&:capitalize).join(' ')
11 | end
12 |
13 | # Usage:
14 | sentence = "ruby is awesome"
15 | puts capitalize_words(sentence) # Output: "Ruby Is Awesome"
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Count Word Occurrences in String
3 | description: Counts the occurrences of each word in a given string.
4 | author: ACR1209
5 | tags: string,occurrences,word-count
6 | ---
7 |
8 | ```rb
9 | def count_word_occurrences(text)
10 | words = text.downcase.scan(/\w+/)
11 | occurrences = Hash.new(0)
12 | words.each { |word| occurrences[word] += 1 }
13 | occurrences
14 | end
15 |
16 | # Usage:
17 | text = "ruby is awesome and Ruby is fun"
18 | puts count_word_occurrences(text) # Output: {"ruby"=>2, "is"=>2, "awesome"=>1, "and"=>1, "fun"=>1}
19 | ```
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/remove-punctuation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Remove Punctuation
3 | description: Removes all punctuation from a given string.
4 | author: ACR1209
5 | tags: string,punctuation,remove
6 | ---
7 |
8 | ```rb
9 | def remove_punctuation(str)
10 | str.gsub(/[[:punct:]]/, '')
11 | end
12 |
13 | # Usage:
14 | text = "Hello, Ruby! How's it going?"
15 | puts remove_punctuation(text) # Output: "Hello Ruby Hows it going"
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Transform Camel Case to Snake Case
3 | description: Converts a Camel or Pascal Case string to Snake case.
4 | author: ACR1209
5 | tags: string,convert,camel-case,snake-case,pascal-case
6 | ---
7 |
8 | ```rb
9 | def camel_to_snake(str)
10 | str.gsub(/([A-Z])/, '_\1').sub(/^_/, '').downcase
11 | end
12 |
13 | # Usage:
14 | camel_case = "camelCaseToSnakeCase"
15 | pascal_case = "PascalCaseToSnakeCase"
16 | puts camel_to_snake(camel_case) # Output: "camel_case_to_snake_case"
17 | puts camel_to_snake(pascal_case) # Output: "pascal_case_to_snake_case"
18 | ```
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Transform from Snake Case to Camel Case
3 | description: Converts a Snake Case string to Camel Case.
4 | author: ACR1209
5 | tags: string,convert,snake-case,camel-case
6 | ---
7 |
8 | ```rb
9 | def snake_to_camel(str)
10 | str.split('_').map.with_index { |word, index|
11 | index == 0 ? word : word.capitalize
12 | }.join
13 | end
14 |
15 | # Usage:
16 | snake_case = "snake_case_to_camel_case"
17 | puts snake_to_camel(snake_case) # Output: "snakeCaseToCamelCase"
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Transform from Snake Case to Pascal Case
3 | description: Converts a Snake Case string to Pascal Case.
4 | author: ACR1209
5 | tags: string,convert,snake-case,pascal-case
6 | ---
7 |
8 | ```rb
9 | def snake_to_pascal(str)
10 | str.split('_').map.with_index { |word, index|
11 | word.capitalize
12 | }.join
13 | end
14 |
15 | # Usage:
16 | snake_case = "snake_case_to_pascal_case"
17 | puts snake_to_pascal(snake_case) # Output: "SnakeCaseToPascalCase"
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/ruby/string-manipulation/truncate-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Truncate String
3 | description: Truncates a string to a specified length, optionally adding an ellipsis.
4 | author: ACR1209
5 | tags: string,truncate
6 | ---
7 |
8 | ```rb
9 | def truncate_string(str, max_length)
10 | return str if str.length <= max_length || max_length <= 3
11 | str[0, max_length - 3] + '...'
12 | end
13 |
14 | # Usage:
15 | long_string = "Ruby is a dynamic, open source programming language."
16 | puts truncate_string(20, long_string) # Output: "Ruby is a dynamic..."
17 | puts truncate_string(54, long_string) # Output: "Ruby is a dynamic, open source programming language."
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/rust/basics/hello-world.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Hello, World!
3 | description: Prints Hello, World! to the terminal.
4 | author: James-Beans
5 | tags: printing,hello-world
6 | ---
7 |
8 | ```rust
9 | fn main() { // Defines the main running function
10 | println!("Hello, World!"); // Prints Hello, World! to the terminal.
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/rust/file-handling/read-file-lines.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Read File Lines
3 | description: Reads all lines from a file and returns them as a vector of strings.
4 | author: Mathys-Gasnier
5 | tags: file,read
6 | ---
7 |
8 | ```rust
9 | fn read_lines(file_name: &str) -> std::io::Result>
10 | Ok(
11 | std::fs::read_to_string(file_name)?
12 | .lines()
13 | .map(String::from)
14 | .collect()
15 | )
16 | }
17 |
18 | // Usage:
19 | read_lines("path/to/file.txt"); // Returns: If Ok(), a Vec of the lines of the file
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/rust/string-manipulation/capitalize-string.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Capitalize String
3 | description: Makes the first letter of a string uppercase.
4 | author: Mathys-Gasnier
5 | tags: string,capitalize
6 | ---
7 |
8 | ```rust
9 | fn capitalized(str: &str) -> String {
10 | let mut chars = str.chars();
11 | match chars.next() {
12 | None => String::new(),
13 | Some(f) => f.to_uppercase().chain(chars).collect(),
14 | }
15 | }
16 |
17 | // Usage:
18 | capitalized("lower_case"); // Returns: Lower_case
19 | ```
20 |
--------------------------------------------------------------------------------
/snippets/scss/animations/fade-in-animation.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Fade In Animation
3 | description: Animates the fade-in effect.
4 | author: technoph1le
5 | tags: animation,fade,css
6 | ---
7 |
8 | ```scss
9 | @keyframes fade-in {
10 | from {
11 | opacity: 0;
12 | }
13 | to {
14 | opacity: 1;
15 | }
16 | }
17 |
18 | @mixin fade-in($duration: 1s, $easing: ease-in-out) {
19 | animation: fade-in $duration $easing;
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/scss/animations/slide-in-from-left.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Slide In From Left
3 | description: Animates content sliding in from the left.
4 | author: technoph1le
5 | tags: animation,slide,css
6 | ---
7 |
8 | ```scss
9 | @keyframes slide-in-left {
10 | from {
11 | transform: translateX(-100%);
12 | }
13 | to {
14 | transform: translateX(0);
15 | }
16 | }
17 |
18 | @mixin slide-in-left($duration: 0.5s, $easing: ease-out) {
19 | animation: slide-in-left $duration $easing;
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/scss/borders-shadows/border-radius-helper.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Border Radius Helper
3 | description: Applies a customizable border-radius.
4 | author: technoph1le
5 | tags: border,radius,css
6 | ---
7 |
8 | ```scss
9 | @mixin border-radius($radius: 4px) {
10 | border-radius: $radius;
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/scss/borders-shadows/box-shadow-helper.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Box Shadow Helper
3 | description: Generates a box shadow with customizable values.
4 | author: technoph1le
5 | tags: box-shadow,css,effects
6 | ---
7 |
8 | ```scss
9 | @mixin box-shadow($x: 0px, $y: 4px, $blur: 10px, $spread: 0px, $color: rgba(0, 0, 0, 0.1)) {
10 | box-shadow: $x $y $blur $spread $color;
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/scss/components/primary-button.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Primary Button
3 | description: Generates a styled primary button.
4 | author: technoph1le
5 | tags: button,primary,css
6 | ---
7 |
8 | ```scss
9 | @mixin primary-button($bg: #007bff, $color: #fff) {
10 | background-color: $bg;
11 | color: $color;
12 | padding: 0.5rem 1rem;
13 | border: none;
14 | border-radius: 4px;
15 | cursor: pointer;
16 |
17 | &:hover {
18 | background-color: darken($bg, 10%);
19 | }
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/scss/layouts/aspect-ratio.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Aspect Ratio
3 | description: Ensures that elements maintain a specific aspect ratio.
4 | author: technoph1le
5 | tags: aspect-ratio,layout,css
6 | ---
7 |
8 | ```scss
9 | @mixin aspect-ratio($width, $height) {
10 | position: relative;
11 | width: 100%;
12 | padding-top: ($height / $width) * 100%;
13 | > * {
14 | position: absolute;
15 | top: 0;
16 | left: 0;
17 | width: 100%;
18 | height: 100%;
19 | }
20 | }
21 | ```
22 |
--------------------------------------------------------------------------------
/snippets/scss/layouts/dark-theme.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Dark Theme
3 | description: SCSS mixin to change styles for dark themes.
4 | author: gihanrangana
5 | tags: css, mixin, snippet, dark-theme, layout
6 | ---
7 |
8 | ```scss
9 | @mixin isDark($type: 'module') {
10 | $root: &;
11 |
12 | @if $type == 'module' {
13 | :global {
14 | @at-root body[theme='dark'] #{$root} {
15 | @content;
16 | }
17 | }
18 | } @else {
19 | &[theme='dark'] {
20 | @content;
21 | }
22 | }
23 | }
24 |
25 | // Usage:
26 | .container{
27 | background: #f0f0f0;
28 | @include isDark {
29 | background: #222;
30 | }
31 | }
32 | ```
--------------------------------------------------------------------------------
/snippets/scss/layouts/flex-center.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Flex Center
3 | description: A mixin to center content using flexbox.
4 | author: technoph1le
5 | tags: flex,center,css
6 | ---
7 |
8 | ```scss
9 | @mixin flex-center {
10 | display: flex;
11 | justify-content: center;
12 | align-items: center;
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/scss/layouts/grid-container.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Grid Container
3 | description: Creates a responsive grid container with customizable column counts.
4 | author: technoph1le
5 | tags: grid,layout,css
6 | ---
7 |
8 | ```scss
9 | @mixin grid-container($columns: 12, $gap: 1rem) {
10 | display: grid;
11 | grid-template-columns: repeat($columns, 1fr);
12 | gap: $gap;
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/scss/typography/font-import-helper.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Font Import Helper
3 | description: Simplifies importing custom fonts in Sass.
4 | author: technoph1le
5 | tags: mixin,fonts,css
6 | ---
7 |
8 | ```scss
9 | @mixin import-font($family, $weight: 400, $style: normal) {
10 | @font-face {
11 | font-family: #{$family};
12 | font-weight: #{$weight};
13 | font-style: #{$style};
14 | src: url('/fonts/#{$family}-#{$weight}.woff2') format('woff2'),
15 | url('/fonts/#{$family}-#{$weight}.woff') format('woff');
16 | }
17 | }
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/scss/typography/line-clamp-mixin.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Line Clamp Mixin
3 | description: A Sass mixin to clamp text to a specific number of lines.
4 | author: technoph1le
5 | tags: mixin,typography,css
6 | ---
7 |
8 | ```scss
9 | @mixin line-clamp($number) {
10 | display: -webkit-box;
11 | -webkit-box-orient: vertical;
12 | -webkit-line-clamp: $number;
13 | overflow: hidden;
14 | }
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/scss/typography/px-to-rem-helper.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: PX to REM Helper
3 | description: This function will convert px values to rem values.
4 | author: gihanrangana
5 | tags: function,pixel,rem,px-to-rem
6 | ---
7 |
8 | ```scss
9 | @function px-to-rem($px, $base: 16px) {
10 | @return ($px / $base) * 1rem;
11 | }
12 |
13 | // Usage:
14 | div {
15 | font-size: px-to-rem(12px); // Output: 0.75rem
16 | padding: px-to-rem(16px); // Output: 1rem
17 | margin: px-to-rem(32px) // Output 2rem
18 | }
19 | ```
--------------------------------------------------------------------------------
/snippets/scss/typography/text-gradient.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Text Gradient
3 | description: Adds a gradient color effect to text.
4 | author: technoph1le
5 | tags: mixin,gradient,text,css
6 | ---
7 |
8 | ```scss
9 | @mixin text-gradient($from, $to) {
10 | background: linear-gradient(to right, $from, $to);
11 | -webkit-background-clip: text;
12 | -webkit-text-fill-color: transparent;
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/scss/typography/text-overflow-ellipsis.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Text Overflow Ellipsis
3 | description: Ensures long text is truncated with an ellipsis.
4 | author: technoph1le
5 | tags: mixin,text,css
6 | ---
7 |
8 | ```scss
9 | @mixin text-ellipsis {
10 | overflow: hidden;
11 | white-space: nowrap;
12 | text-overflow: ellipsis;
13 | }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/scss/utilities/clearfix.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Clearfix
3 | description: Provides a clearfix utility for floating elements.
4 | author: technoph1le
5 | tags: clearfix,utility,css
6 | ---
7 |
8 | ```scss
9 | @mixin clearfix {
10 | &::after {
11 | content: '';
12 | display: block;
13 | clear: both;
14 | }
15 | }
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/scss/utilities/responsive-breakpoints.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Responsive Breakpoints
3 | description: Generates media queries for responsive design.
4 | author: technoph1le
5 | tags: responsive,media-queries,css
6 | ---
7 |
8 | ```scss
9 | @mixin breakpoint($breakpoint) {
10 | @if $breakpoint == sm {
11 | @media (max-width: 576px) { @content; }
12 | } @else if $breakpoint == md {
13 | @media (max-width: 768px) { @content; }
14 | } @else if $breakpoint == lg {
15 | @media (max-width: 992px) { @content; }
16 | } @else if $breakpoint == xl {
17 | @media (max-width: 1200px) { @content; }
18 | }
19 | }
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/at-least-one-key.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: At Least One Key
3 | description: Ensures that at least one property of an object is required.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition
6 | ---
7 |
8 | ```ts
9 | type AtLeastOne = {
10 | [K in keyof T]: Pick & Partial>;
11 | }[keyof T];
12 |
13 |
14 | // Usage:
15 | type A = {
16 | id?: string;
17 | name?: string;
18 | isActive?: boolean;
19 | };
20 |
21 | type AtLeastOneA = AtLeastOne;
22 | // Requires at least one of 'id', 'name', or 'isActive' to be defined
23 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/deep-partial-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Deep Partial Type
3 | description: Converts all properties of a type, including nested objects, into optional.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,optional
6 | ---
7 |
8 | ```ts
9 | type DeepPartial = {
10 | [K in keyof T]?: T[K] extends object ? DeepPartial : T[K];
11 | };
12 |
13 |
14 | // Usage:
15 | type A = {
16 | name: string;
17 | details: {
18 | age: number;
19 | address: { city: string; zip: string };
20 | };
21 | };
22 |
23 | type PartialA = DeepPartial;
24 | /*
25 | Type PartialA:
26 | {
27 | name?: string;
28 | details?: {
29 | age?: number;
30 | address?: { city?: string; zip?: string };
31 | };
32 | }
33 | */
34 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/deep-required-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Deep Required Type
3 | description: Converts all properties of a type, including nested objects, into required.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,required
6 | ---
7 |
8 | ```ts
9 | type DeepRequired = T extends object
10 | ? { [K in keyof T]-?: DeepRequired }
11 | : T;
12 |
13 |
14 | // Usage:
15 | type A = {
16 | id?: string;
17 | name?: string;
18 | details?: {
19 | age?: number;
20 | address?: { city?: string; zip?: string };
21 | };
22 | };
23 |
24 | type RequiredA = DeepRequired;
25 | // Result: { id: string; name: string; details: { age: number; address: { city: string; zip: string }; }; }
26 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/keys-of-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Keys of Type
3 | description: Extracts keys from an object type that match a specified value type.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition
6 | ---
7 |
8 | ```ts
9 | type KeysOfType = { [K in keyof T]: T[K] extends U ? K : never }[keyof T];
10 |
11 |
12 | // Usage:
13 | type A = { name: string; age: number; isActive: boolean, isDeleted: boolean };
14 | type StringKeys = KeysOfType; // "name"
15 | type BooleanKeys = KeysOfType; // "isActive" | "isDeleted"
16 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/keys-to-optional.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Keys to Optional
3 | description: Makes only the specified keys of an object type optional.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,optional
6 | ---
7 |
8 | ```ts
9 | type OptionalKeys = Omit & Partial>;
10 |
11 |
12 | // Usage:
13 | type A = {
14 | id: string;
15 | name: string;
16 | age: number;
17 | };
18 |
19 | type WithOptionalName = OptionalKeys;
20 | // { id: string; age: number; name?: string }
21 |
22 | type WithOptionalNameAndAge = OptionalKeys;
23 | // Result: { id: string; name?: string; age?: number }
24 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/nullable-keys.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Nullable Keys
3 | description: Extracts keys from an object type that allow null or undefined values.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,nullable
6 | ---
7 |
8 | ```ts
9 | type NullableKeys = {
10 | [K in keyof T]: null extends T[K] ? K : undefined extends T[K] ? K : never;
11 | }[keyof T];
12 |
13 |
14 | // Usage:
15 | type A = {
16 | id: string;
17 | name?: string;
18 | description: string | null;
19 | };
20 |
21 | type Nullable = NullableKeys; // "name" | "description"
22 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/omit-keys-of-type.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Omit Keys of Type
3 | description: Removes keys of a specified type from an object type.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,omit,keys
6 | ---
7 |
8 | ```ts
9 | type OmitKeysOfType = {
10 | [K in keyof T as T[K] extends U ? never : K]: T[K];
11 | };
12 |
13 |
14 | // Usage:
15 | type A = {
16 | id: string;
17 | isActive: boolean;
18 | data: number[];
19 | };
20 |
21 | type WithoutBoolean = OmitKeysOfType; // { id: string; data: number[] }
22 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/required-keys.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Required Keys
3 | description: Extracts required keys from an object.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,required
6 | ---
7 |
8 | ```ts
9 | type RequiredKeys = {
10 | [K in keyof T]-?: {} extends Pick ? never : K;
11 | }[keyof T];
12 |
13 |
14 | // Usage:
15 | type A = {
16 | id: string;
17 | name?: string;
18 | isActive: boolean;
19 | };
20 |
21 | type ReqKeys = RequiredKeys; // "id" | "isActive"
22 | ```
--------------------------------------------------------------------------------
/snippets/typescript/helper-types/union-to-intersection.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: Union to Intersection
3 | description: Converts a union type into an intersection type.
4 | author: aelshinawy
5 | tags: typescript,helper-types,typedefinition,intersection,union
6 | ---
7 |
8 | ```ts
9 | type UnionToIntersection = (U extends any ? (arg: U) => void : never) extends (arg: infer I) => void
10 | ? I
11 | : never;
12 |
13 |
14 | // Usage:
15 | type A = { id: string };
16 | type B = { name: string };
17 | type C = { age: number };
18 |
19 | type Intersected = UnionToIntersection;
20 | // { id: string } & { name: string } & { age: number }
21 | ```
--------------------------------------------------------------------------------