From 19c9437c040c2487d5e42e7cc5ccb0b43a29c1c8 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 2 Jan 2025 10:23:39 +0000 Subject: [PATCH 01/84] Update consolidated snippets --- public/icons/csharp.svg | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 public/icons/csharp.svg diff --git a/public/icons/csharp.svg b/public/icons/csharp.svg new file mode 100644 index 00000000..96cf5abc --- /dev/null +++ b/public/icons/csharp.svg @@ -0,0 +1,10 @@ + + + + + + + + + + From 73cbecba2dc42ba08f4903855f1c6a6eddbbca10 Mon Sep 17 00:00:00 2001 From: Gihan Rangana Date: Thu, 2 Jan 2025 21:04:34 +0530 Subject: [PATCH 02/84] Create auto-sync.yml --- .github/workflows/auto-sync.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .github/workflows/auto-sync.yml diff --git a/.github/workflows/auto-sync.yml b/.github/workflows/auto-sync.yml new file mode 100644 index 00000000..dd3fb1e7 --- /dev/null +++ b/.github/workflows/auto-sync.yml @@ -0,0 +1,26 @@ +name: Auto Sync with Main Repo + +on: + push: + branches: + - main + +jobs: + sync: + runs-on: ubuntu-latest + + steps: + - name: Checkout Target Repository + uses: actions/checkout@v2 + with: + repository: gihanrangana/quicksnip + ref: main + token: ${{ secrets.GITHUB_TOKEN }} + + - name: Sync with Main Repository + run: | + git remote add upstream https://github.com/gihanrangana/quicksnip.git + git fetch upstream + git checkout main + git merge upstream/main + git push origin main From 85ff2d86394656b5f6401635d9a1fe7ac39c4a78 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:04:01 -0500 Subject: [PATCH 03/84] Create Ruby programming language --- snippets/ruby/basics/hello-world.md | 10 ++ snippets/ruby/icon.svg | 139 ++++++++++++++++++++++++++++ 2 files changed, 149 insertions(+) create mode 100644 snippets/ruby/basics/hello-world.md create mode 100644 snippets/ruby/icon.svg diff --git a/snippets/ruby/basics/hello-world.md b/snippets/ruby/basics/hello-world.md new file mode 100644 index 00000000..353e89c8 --- /dev/null +++ b/snippets/ruby/basics/hello-world.md @@ -0,0 +1,10 @@ +--- +title: Hello, World! +description: Prints Hello, World! to the terminal. +author: ACR1209 +tags: ruby,printing,hello-world,utility +--- + +```rb +puts 'Hello, World!' +``` diff --git a/snippets/ruby/icon.svg b/snippets/ruby/icon.svg new file mode 100644 index 00000000..10ec5836 --- /dev/null +++ b/snippets/ruby/icon.svg @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From f1291ff3436b27a31554b790bea756c8dd534141 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:13:10 -0500 Subject: [PATCH 04/84] Added ruby array manipulation category and some snippets --- .../ruby/array-manipulation/binary-search.md | 34 +++++++++++++++++++ .../ruby/array-manipulation/chunk-array.md | 17 ++++++++++ .../array-manipulation/matrix-transpose.md | 23 +++++++++++++ 3 files changed, 74 insertions(+) create mode 100644 snippets/ruby/array-manipulation/binary-search.md create mode 100644 snippets/ruby/array-manipulation/chunk-array.md create mode 100644 snippets/ruby/array-manipulation/matrix-transpose.md diff --git a/snippets/ruby/array-manipulation/binary-search.md b/snippets/ruby/array-manipulation/binary-search.md new file mode 100644 index 00000000..ee7d16d1 --- /dev/null +++ b/snippets/ruby/array-manipulation/binary-search.md @@ -0,0 +1,34 @@ +--- +title: Binary Search +description: Searches for an element in a sorted array using binary search. +author: ACR1209 +tags: ruby,array,binary-search,search +--- + +```rb +def binary_search(array, target) + low = 0 + high = array.length - 1 + + while low <= high + mid = (low + high) / 2 + guess = array[mid] + + if guess == target + return mid + elsif guess > target + high = mid - 1 + else + low = mid + 1 + end + end + + return nil +end + +# Usage +array = [1, 3, 5, 7, 9] +target = 5 +result = binary_search(array, target) +puts result # Output: 2 +``` \ No newline at end of file diff --git a/snippets/ruby/array-manipulation/chunk-array.md b/snippets/ruby/array-manipulation/chunk-array.md new file mode 100644 index 00000000..32536ab3 --- /dev/null +++ b/snippets/ruby/array-manipulation/chunk-array.md @@ -0,0 +1,17 @@ +--- +title: Chunk Array +description: Splits an array into chunks of a specified size. +author: ACR1209 +tags: ruby,array,chunk,utility +--- + +```rb +def chunk_array(array, size) + array.each_slice(size).to_a +end + +# Example usage: +arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] +chunked_arr = chunk_array(arr, 2) +puts chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]] +``` \ No newline at end of file diff --git a/snippets/ruby/array-manipulation/matrix-transpose.md b/snippets/ruby/array-manipulation/matrix-transpose.md new file mode 100644 index 00000000..bb033c9b --- /dev/null +++ b/snippets/ruby/array-manipulation/matrix-transpose.md @@ -0,0 +1,23 @@ +--- +title: Matrix Transpose +description: Transposes a 2D matrix. +author: ACR1209 +tags: ruby,array,matrix,transpose +--- + +```ruby +def transpose_matrix(matrix) + return [] if matrix.empty? + return [] if matrix.first.empty? + + matrix.first.zip(*matrix[1..-1]) +end + +# Usage +matrix = [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] +] +print transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]] +``` \ No newline at end of file From 92c408cb845d3b209085afc406249cf4b26e912c Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:21:20 -0500 Subject: [PATCH 05/84] Add Ruby string manipulation snippets --- .../camelcase-to-snakecase.md | 15 +++++++++++++++ .../string-manipulation/capitalize-words.md | 15 +++++++++++++++ .../count-word-ocurrences.md | 18 ++++++++++++++++++ .../string-manipulation/remove-punctuation.md | 15 +++++++++++++++ .../snakecase-to-camelcase.md | 17 +++++++++++++++++ .../string-manipulation/truncate-string.md | 17 +++++++++++++++++ 6 files changed, 97 insertions(+) create mode 100644 snippets/ruby/string-manipulation/camelcase-to-snakecase.md create mode 100644 snippets/ruby/string-manipulation/capitalize-words.md create mode 100644 snippets/ruby/string-manipulation/count-word-ocurrences.md create mode 100644 snippets/ruby/string-manipulation/remove-punctuation.md create mode 100644 snippets/ruby/string-manipulation/snakecase-to-camelcase.md create mode 100644 snippets/ruby/string-manipulation/truncate-string.md diff --git a/snippets/ruby/string-manipulation/camelcase-to-snakecase.md b/snippets/ruby/string-manipulation/camelcase-to-snakecase.md new file mode 100644 index 00000000..675ac7a4 --- /dev/null +++ b/snippets/ruby/string-manipulation/camelcase-to-snakecase.md @@ -0,0 +1,15 @@ +--- +title: Transform Camel Case to Snake Case +description: Converts a Camel Case string to Snake case. +author: ACR1209 +tags: ruby,string,convert,camel-case,snake-case,utility +--- + +```rb +def camel_to_snake(str) + str.gsub(/([A-Z])/, '_\1').downcase +end + +camel_case = "camelCaseToSnakeCase" +puts camel_to_snake(camel_case) # Output: "camel_case_to_snake_case" +``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/capitalize-words.md b/snippets/ruby/string-manipulation/capitalize-words.md new file mode 100644 index 00000000..da5beace --- /dev/null +++ b/snippets/ruby/string-manipulation/capitalize-words.md @@ -0,0 +1,15 @@ +--- +title: Capitalize Words +description: Capitalizes the first letter of each word in a string. +author: ACR1209 +tags: ruby,string,capitalize,words +--- + +```rb +def capitalize_words(str) + str.split.map(&:capitalize).join(' ') +end + +sentence = "ruby is awesome" +puts capitalize_words(sentence) # Output: "Ruby Is Awesome" +``` diff --git a/snippets/ruby/string-manipulation/count-word-ocurrences.md b/snippets/ruby/string-manipulation/count-word-ocurrences.md new file mode 100644 index 00000000..42961093 --- /dev/null +++ b/snippets/ruby/string-manipulation/count-word-ocurrences.md @@ -0,0 +1,18 @@ +--- +title: Count Word Occurrences in String +description: Counts the occurrences of each word in a given string. +author: ACR1209 +tags: ruby,string,occurrences,word-count +--- + +```rb +def count_word_occurrences(text) + words = text.downcase.scan(/\w+/) + occurrences = Hash.new(0) + words.each { |word| occurrences[word] += 1 } + occurrences +end + +text = "ruby is awesome and Ruby is fun" +puts count_word_occurrences(text) # Output: {"ruby"=>2, "is"=>2, "awesome"=>1, "and"=>1, "fun"=>1} +``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/remove-punctuation.md b/snippets/ruby/string-manipulation/remove-punctuation.md new file mode 100644 index 00000000..e8e44b9d --- /dev/null +++ b/snippets/ruby/string-manipulation/remove-punctuation.md @@ -0,0 +1,15 @@ +--- +title: Remove Punctuation +description: Removes all punctuation from a given string. +author: ACR1209 +tags: ruby,string,punctuation,remove +--- + +```rb +def remove_punctuation(str) + str.gsub(/[[:punct:]]/, '') +end + +text = "Hello, Ruby! How's it going?" +puts remove_punctuation(text) # Output: "Hello Ruby Hows it going" +``` diff --git a/snippets/ruby/string-manipulation/snakecase-to-camelcase.md b/snippets/ruby/string-manipulation/snakecase-to-camelcase.md new file mode 100644 index 00000000..b36f7fe0 --- /dev/null +++ b/snippets/ruby/string-manipulation/snakecase-to-camelcase.md @@ -0,0 +1,17 @@ +--- +title: Transform from Snake Case to Camel Case +description: Converts a Snake Case string to Camel Case. +author: ACR1209 +tags: ruby,string,convert,snake-case,camel-case,utility +--- + +```rb +def snake_to_camel(str) + str.split('_').map.with_index { |word, index| + index == 0 ? word : word.capitalize + }.join +end + +snake_case = "snake_case_to_camel_case" +puts snake_to_camel(snake_case) # Output: "snakeCaseToCamelCase" +``` diff --git a/snippets/ruby/string-manipulation/truncate-string.md b/snippets/ruby/string-manipulation/truncate-string.md new file mode 100644 index 00000000..60ad5a22 --- /dev/null +++ b/snippets/ruby/string-manipulation/truncate-string.md @@ -0,0 +1,17 @@ +--- +title: Truncate Strings +description: Truncates a string to a specified length, optionally adding an ellipsis. +author: ACR1209 +tags: ruby,string,truncate,utility +--- + +```rb +def truncate_string(max_length, str) + return str if str.length <= max_length + str[0, max_length - 3] + '...' +end + +long_string = "Ruby is a dynamic, open source programming language." +puts truncate_string(20, long_string) # Output: "Ruby is a dynamic..." +puts truncate_string(54, long_string) # Output: "Ruby is a dynamic, open source programming language." +``` From 993a50a8241963e5f18d011007b6617995ebdf7a Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:30:42 -0500 Subject: [PATCH 06/84] Add Ruby snippet for calculating compound interest --- .../calculate-compound-interest.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 snippets/ruby/math-and-numbers/calculate-compound-interest.md diff --git a/snippets/ruby/math-and-numbers/calculate-compound-interest.md b/snippets/ruby/math-and-numbers/calculate-compound-interest.md new file mode 100644 index 00000000..594c1307 --- /dev/null +++ b/snippets/ruby/math-and-numbers/calculate-compound-interest.md @@ -0,0 +1,17 @@ +--- +title: Calculate Compound Interest +description: Calculates compound interest for a given principal amount, rate, and time period. +author: ACR1209 +contributors: axorax +tags: ruby,math,compound interest,finance +--- + +```ruby +def compound_interest(principal, rate, time, n = 1) + principal * (1 + rate / n) ** (n * time) +end + +# Usage: +puts compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003 +puts compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118 +``` From 43f49a1510d34995fdaaa82374d507e9e9eba173 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:34:43 -0500 Subject: [PATCH 07/84] Add Ruby Sieve of Sundaram snippet --- .../calculate-compound-interest.md | 2 +- .../math-and-numbers/sieve-of-sundaram.md | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 snippets/ruby/math-and-numbers/sieve-of-sundaram.md diff --git a/snippets/ruby/math-and-numbers/calculate-compound-interest.md b/snippets/ruby/math-and-numbers/calculate-compound-interest.md index 594c1307..ecdae54a 100644 --- a/snippets/ruby/math-and-numbers/calculate-compound-interest.md +++ b/snippets/ruby/math-and-numbers/calculate-compound-interest.md @@ -6,7 +6,7 @@ contributors: axorax tags: ruby,math,compound interest,finance --- -```ruby +```rb def compound_interest(principal, rate, time, n = 1) principal * (1 + rate / n) ** (n * time) end diff --git a/snippets/ruby/math-and-numbers/sieve-of-sundaram.md b/snippets/ruby/math-and-numbers/sieve-of-sundaram.md new file mode 100644 index 00000000..30de1c27 --- /dev/null +++ b/snippets/ruby/math-and-numbers/sieve-of-sundaram.md @@ -0,0 +1,31 @@ +--- +title: Find all primes up to integer (Sieve of Sundaram) +description: Finds all the prime numbers up to a specific integer. +author: ACR1209 +tags: ruby,math,prime numbers +--- + +```rb +def sieve_of_sundaram(limit) + n = (limit - 1) / 2 + marked = Array.new(n + 1, false) + + (1..n).each do |i| + j = i + while (i + j + 2 * i * j) <= n + marked[i + j + 2 * i * j] = true + j += 1 + end + end + + primes = [2] + (1..n).each do |i| + primes << (2 * i + 1) unless marked[i] + end + + primes +end + +# Usage: +print sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] +``` \ No newline at end of file From 3807b5c780f3effe249deb35fc714dc05e8f51d5 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:39:58 -0500 Subject: [PATCH 08/84] Add Ruby snippet for checking prime numbers --- .../math-and-numbers/check-prime-number.md | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/ruby/math-and-numbers/check-prime-number.md diff --git a/snippets/ruby/math-and-numbers/check-prime-number.md b/snippets/ruby/math-and-numbers/check-prime-number.md new file mode 100644 index 00000000..8919266d --- /dev/null +++ b/snippets/ruby/math-and-numbers/check-prime-number.md @@ -0,0 +1,21 @@ +--- +title: Check Prime Number +description: Checks if a number is a prime number. +author: ACR1209 +contributors: dostonnabotov +tags: ruby,math,prime,check +--- + +```rb +def is_prime?(n) + return false if n <= 1 + (2..Math.sqrt(n)).each do |i| + return false if n % i == 0 + end + true +end + +# Usage: +puts is_prime?(29) # Output: true +puts is_prime?(30) # Output: false +``` From ec3ee2b2fa76b3915de9af06ca440211a11e1718 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:40:24 -0500 Subject: [PATCH 09/84] Add Ruby snippet for calculating factorial --- .../ruby/math-and-numbers/calculate-factorial.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 snippets/ruby/math-and-numbers/calculate-factorial.md diff --git a/snippets/ruby/math-and-numbers/calculate-factorial.md b/snippets/ruby/math-and-numbers/calculate-factorial.md new file mode 100644 index 00000000..adc50b47 --- /dev/null +++ b/snippets/ruby/math-and-numbers/calculate-factorial.md @@ -0,0 +1,16 @@ +--- +title: Calculate Factorial +description: Computes the factorial of a given integer. +author: ACR1209 +tags: ruby,math,factorial +--- + +```rb +def factorial(n) + return 1 if n <= 1 + (2..n).reduce(1, :*) +end + +# Usage: +puts factorial(5) # Output: 120 +``` \ No newline at end of file From cdbd348674b84911669988d701e761f0a3a7717a Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:44:25 -0500 Subject: [PATCH 10/84] Add Ruby snippet for defining and raising a custom error class --- snippets/ruby/error-handling/custom-error.md | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 snippets/ruby/error-handling/custom-error.md diff --git a/snippets/ruby/error-handling/custom-error.md b/snippets/ruby/error-handling/custom-error.md new file mode 100644 index 00000000..3b98ad51 --- /dev/null +++ b/snippets/ruby/error-handling/custom-error.md @@ -0,0 +1,22 @@ +--- +title: Custom Error Class +description: Defines and raises a custom error class in Ruby. +author: ACR1209 +tags: ruby,error handling,custom error +--- + +```rb +class MyCustomError < StandardError; end + +def risky_method(value) + raise MyCustomError, "Value must be positive" if value <= 0 + "Valid value: #{value}" +end + +# Usage: +begin + puts risky_method(-1) +rescue MyCustomError => e + puts e.message # Output: "Value must be positive" +end +``` \ No newline at end of file From 88fcb81d1a47dee6590e0f38f750bd263bbc2f6d Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:50:01 -0500 Subject: [PATCH 11/84] Add Ruby snippet for implementing a basic binary tree with in-order traversal --- snippets/ruby/data-structures/binary-tree.md | 42 ++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 snippets/ruby/data-structures/binary-tree.md diff --git a/snippets/ruby/data-structures/binary-tree.md b/snippets/ruby/data-structures/binary-tree.md new file mode 100644 index 00000000..266eca5e --- /dev/null +++ b/snippets/ruby/data-structures/binary-tree.md @@ -0,0 +1,42 @@ +--- +title: Binary Tree +description: Implements a basic binary tree with in-order traversal. +author: ACR1209 +tags: ruby,data structures,binary tree +--- + +```rb +class TreeNode + attr_accessor :data, :left, :right + + def initialize(data) + @data = data + @left = nil + @right = nil + end +end + +class BinaryTree + attr_accessor :root + + def initialize(root_data) + @root = TreeNode.new(root_data) + end + + def in_order_traversal(node = @root, result = []) + return result unless node + + in_order_traversal(node.left, result) + result << node.data + in_order_traversal(node.right, result) + end +end + +# Usage: +tree = BinaryTree.new(10) +tree.root.left = TreeNode.new(5) +tree.root.right = TreeNode.new(15) +tree.root.left.left = TreeNode.new(3) + +print tree.in_order_traversal # Output: [3, 5, 10, 15] +``` \ No newline at end of file From d6364c6c56bce46ba7857ed0037b826c19d1acef Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:54:55 -0500 Subject: [PATCH 12/84] Add Ruby snippet for implementing a singly linked list with node insertion and traversal --- snippets/ruby/data-structures/linked-list.md | 50 ++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 snippets/ruby/data-structures/linked-list.md diff --git a/snippets/ruby/data-structures/linked-list.md b/snippets/ruby/data-structures/linked-list.md new file mode 100644 index 00000000..1a27d60b --- /dev/null +++ b/snippets/ruby/data-structures/linked-list.md @@ -0,0 +1,50 @@ +--- +title: Singly Linked List +description: Implements a basic singly linked list with node insertion and traversal. +author: ACR1209 +tags: ruby,data structures,linked list +--- + +```rb +class Node + attr_accessor :data, :next + + def initialize(data) + @data = data + @next = nil + end +end + +class LinkedList + def initialize + @head = nil + end + + def append(data) + new_node = Node.new(data) + if @head.nil? + @head = new_node + else + current = @head + current = current.next while current.next + current.next = new_node + end + end + + def display + current = @head + while current + print "#{current.data} -> " + current = current.next + end + puts "nil" + end +end + +# Usage: +list = LinkedList.new +list.append(1) +list.append(2) +list.append(3) +list.display # Output: 1 -> 2 -> 3 -> nil +``` \ No newline at end of file From 9f15bd9bb01cb3cc4c60a3cb7eb5598c80cf20d5 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 13:59:25 -0500 Subject: [PATCH 13/84] Add Ruby snippet for implementing a doubly linked list with node insertion and traversal --- .../data-structures/doubly-linked-list.md | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 snippets/ruby/data-structures/doubly-linked-list.md diff --git a/snippets/ruby/data-structures/doubly-linked-list.md b/snippets/ruby/data-structures/doubly-linked-list.md new file mode 100644 index 00000000..a0e2f949 --- /dev/null +++ b/snippets/ruby/data-structures/doubly-linked-list.md @@ -0,0 +1,75 @@ +--- +title: Doubly Linked List +description: Implements a doubly linked list with node insertion and traversal. +author: ACR1209 +tags: ruby,data structures,linked list,doubly linked list +--- + +```rb +class Node + attr_accessor :data, :next, :prev + + def initialize(data) + @data = data + @next = nil + @prev = nil + end +end + +class DoublyLinkedList + def initialize + @head = nil + @tail = nil + end + + def append(data) + new_node = Node.new(data) + if @head.nil? + @head = new_node + @tail = new_node + else + @tail.next = new_node + new_node.prev = @tail + @tail = new_node + end + end + + def prepend(data) + new_node = Node.new(data) + if @head.nil? + @head = new_node + @tail = new_node + else + new_node.next = @head + @head.prev = new_node + @head = new_node + end + end + + def display_forward + current = @head + while current + print "#{current.data} <-> " + current = current.next + end + puts "nil" + end + + def display_backward + current = @tail + while current + print "#{current.data} <-> " + current = current.prev + end + puts "nil" + end +end + +# Usage: +dll = DoublyLinkedList.new +dll.append(1) +dll.append(2) +dll.append(3) +dll.display_forward # Output: 1 <-> 2 <-> 3 <-> nil +dll.display_backward # Output: 3 <-> 2 <-> 1 <-> nil +``` \ No newline at end of file From 108ca7b89d234d98f65fc9d4fb15e328c527dc0b Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 2 Jan 2025 19:00:01 +0000 Subject: [PATCH 14/84] Update consolidated snippets --- public/consolidated/_index.json | 4 + public/consolidated/ruby.json | 269 ++++++++++++++++++++++++++++++++ public/icons/ruby.svg | 139 +++++++++++++++++ 3 files changed, 412 insertions(+) create mode 100644 public/consolidated/ruby.json create mode 100644 public/icons/ruby.svg diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json index 2591d382..c5ed3c1a 100644 --- a/public/consolidated/_index.json +++ b/public/consolidated/_index.json @@ -31,6 +31,10 @@ "lang": "PYTHON", "icon": "/icons/python.svg" }, + { + "lang": "RUBY", + "icon": "/icons/ruby.svg" + }, { "lang": "RUST", "icon": "/icons/rust.svg" diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json new file mode 100644 index 00000000..0bfdf295 --- /dev/null +++ b/public/consolidated/ruby.json @@ -0,0 +1,269 @@ +[ + { + "categoryName": "Array Manipulation", + "snippets": [ + { + "title": "Binary Search", + "description": "Searches for an element in a sorted array using binary search.", + "author": "ACR1209", + "tags": [ + "ruby", + "array", + "binary-search", + "search" + ], + "contributors": [], + "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n" + }, + { + "title": "Chunk Array", + "description": "Splits an array into chunks of a specified size.", + "author": "ACR1209", + "tags": [ + "ruby", + "array", + "chunk", + "utility" + ], + "contributors": [], + "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Example usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n" + }, + { + "title": "Matrix Transpose", + "description": "Transposes a 2D matrix.", + "author": "ACR1209", + "tags": [ + "ruby", + "array", + "matrix", + "transpose" + ], + "contributors": [], + "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n" + } + ] + }, + { + "categoryName": "Basics", + "snippets": [ + { + "title": "Hello, World!", + "description": "Prints Hello, World! to the terminal.", + "author": "ACR1209", + "tags": [ + "ruby", + "printing", + "hello-world", + "utility" + ], + "contributors": [], + "code": "puts 'Hello, World!'\n" + } + ] + }, + { + "categoryName": "Data Structures", + "snippets": [ + { + "title": "Binary Tree", + "description": "Implements a basic binary tree with in-order traversal.", + "author": "ACR1209", + "tags": [ + "ruby", + "data structures", + "binary tree" + ], + "contributors": [], + "code": "class TreeNode\n attr_accessor :data, :left, :right\n\n def initialize(data)\n @data = data\n @left = nil\n @right = nil\n end\nend\n\nclass BinaryTree\n attr_accessor :root\n\n def initialize(root_data)\n @root = TreeNode.new(root_data)\n end\n\n def in_order_traversal(node = @root, result = [])\n return result unless node\n\n in_order_traversal(node.left, result)\n result << node.data\n in_order_traversal(node.right, result)\n end\nend\n\n# Usage:\ntree = BinaryTree.new(10)\ntree.root.left = TreeNode.new(5)\ntree.root.right = TreeNode.new(15)\ntree.root.left.left = TreeNode.new(3)\n\nprint tree.in_order_traversal # Output: [3, 5, 10, 15]\n" + }, + { + "title": "Doubly Linked List", + "description": "Implements a doubly linked list with node insertion and traversal.", + "author": "ACR1209", + "tags": [ + "ruby", + "data structures", + "linked list", + "doubly linked list" + ], + "contributors": [], + "code": "class Node\n attr_accessor :data, :next, :prev\n\n def initialize(data)\n @data = data\n @next = nil\n @prev = nil\n end\nend\n\nclass DoublyLinkedList\n def initialize\n @head = nil\n @tail = nil\n end\n\n def append(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n @tail = new_node\n else\n @tail.next = new_node\n new_node.prev = @tail\n @tail = new_node\n end\n end\n\n def prepend(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n @tail = new_node\n else\n new_node.next = @head\n @head.prev = new_node\n @head = new_node\n end\n end\n\n def display_forward\n current = @head\n while current\n print \"#{current.data} <-> \"\n current = current.next\n end\n puts \"nil\"\n end\n\n def display_backward\n current = @tail\n while current\n print \"#{current.data} <-> \"\n current = current.prev\n end\n puts \"nil\"\n end\nend\n\n# Usage:\ndll = DoublyLinkedList.new\ndll.append(1)\ndll.append(2)\ndll.append(3)\ndll.display_forward # Output: 1 <-> 2 <-> 3 <-> nil\ndll.display_backward # Output: 3 <-> 2 <-> 1 <-> nil\n" + }, + { + "title": "Singly Linked List", + "description": "Implements a basic singly linked list with node insertion and traversal.", + "author": "ACR1209", + "tags": [ + "ruby", + "data structures", + "linked list" + ], + "contributors": [], + "code": "class Node\n attr_accessor :data, :next\n\n def initialize(data)\n @data = data\n @next = nil\n end\nend\n\nclass LinkedList\n def initialize\n @head = nil\n end\n\n def append(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n else\n current = @head\n current = current.next while current.next\n current.next = new_node\n end\n end\n\n def display\n current = @head\n while current\n print \"#{current.data} -> \"\n current = current.next\n end\n puts \"nil\"\n end\nend\n\n# Usage:\nlist = LinkedList.new\nlist.append(1)\nlist.append(2)\nlist.append(3)\nlist.display # Output: 1 -> 2 -> 3 -> nil\n" + } + ] + }, + { + "categoryName": "Error Handling", + "snippets": [ + { + "title": "Custom Error Class", + "description": "Defines and raises a custom error class in Ruby.", + "author": "ACR1209", + "tags": [ + "ruby", + "error handling", + "custom error" + ], + "contributors": [], + "code": "class MyCustomError < StandardError; end\n\ndef risky_method(value)\n raise MyCustomError, \"Value must be positive\" if value <= 0\n \"Valid value: #{value}\"\nend\n\n# Usage:\nbegin\n puts risky_method(-1)\nrescue MyCustomError => e\n puts e.message # Output: \"Value must be positive\"\nend\n" + } + ] + }, + { + "categoryName": "Math And Numbers", + "snippets": [ + { + "title": "Calculate Compound Interest", + "description": "Calculates compound interest for a given principal amount, rate, and time period.", + "author": "ACR1209", + "tags": [ + "ruby", + "math", + "compound interest", + "finance" + ], + "contributors": [ + "axorax" + ], + "code": "def compound_interest(principal, rate, time, n = 1)\n principal * (1 + rate / n) ** (n * time)\nend\n\n# Usage:\nputs compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003\nputs compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118\n" + }, + { + "title": "Calculate Factorial", + "description": "Computes the factorial of a given integer.", + "author": "ACR1209", + "tags": [ + "ruby", + "math", + "factorial" + ], + "contributors": [], + "code": "def factorial(n)\n return 1 if n <= 1\n (2..n).reduce(1, :*)\nend\n\n# Usage:\nputs factorial(5) # Output: 120\n" + }, + { + "title": "Check Prime Number", + "description": "Checks if a number is a prime number.", + "author": "ACR1209", + "tags": [ + "ruby", + "math", + "prime", + "check" + ], + "contributors": [ + "dostonnabotov" + ], + "code": "def is_prime?(n)\n return false if n <= 1\n (2..Math.sqrt(n)).each do |i|\n return false if n % i == 0\n end\n true\nend\n\n# Usage:\nputs is_prime?(29) # Output: true\nputs is_prime?(30) # Output: false\n" + }, + { + "title": "Find all primes up to integer (Sieve of Sundaram)", + "description": "Finds all the prime numbers up to a specific integer.", + "author": "ACR1209", + "tags": [ + "ruby", + "math", + "prime numbers" + ], + "contributors": [], + "code": "def sieve_of_sundaram(limit)\n n = (limit - 1) / 2\n marked = Array.new(n + 1, false)\n\n (1..n).each do |i|\n j = i\n while (i + j + 2 * i * j) <= n\n marked[i + j + 2 * i * j] = true\n j += 1\n end\n end\n\n primes = [2]\n (1..n).each do |i|\n primes << (2 * i + 1) unless marked[i]\n end\n\n primes\nend\n\n# Usage:\nprint sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n" + } + ] + }, + { + "categoryName": "String Manipulation", + "snippets": [ + { + "title": "Transform Camel Case to Snake Case", + "description": "Converts a Camel Case string to Snake case.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "convert", + "camel-case", + "snake-case", + "utility" + ], + "contributors": [], + "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').downcase\nend\n\ncamel_case = \"camelCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\n" + }, + { + "title": "Capitalize Words", + "description": "Capitalizes the first letter of each word in a string.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "capitalize", + "words" + ], + "contributors": [], + "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" + }, + { + "title": "Count Word Occurrences in String", + "description": "Counts the occurrences of each word in a given string.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "occurrences", + "word-count" + ], + "contributors": [], + "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" + }, + { + "title": "Remove Punctuation", + "description": "Removes all punctuation from a given string.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "punctuation", + "remove" + ], + "contributors": [], + "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" + }, + { + "title": "Transform from Snake Case to Camel Case", + "description": "Converts a Snake Case string to Camel Case.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "convert", + "snake-case", + "camel-case", + "utility" + ], + "contributors": [], + "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" + }, + { + "title": "Truncate Strings", + "description": "Truncates a string to a specified length, optionally adding an ellipsis.", + "author": "ACR1209", + "tags": [ + "ruby", + "string", + "truncate", + "utility" + ], + "contributors": [], + "code": "def truncate_string(max_length, str)\n return str if str.length <= max_length\n str[0, max_length - 3] + '...'\nend\n\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" + } + ] + } +] \ No newline at end of file diff --git a/public/icons/ruby.svg b/public/icons/ruby.svg new file mode 100644 index 00000000..10ec5836 --- /dev/null +++ b/public/icons/ruby.svg @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 5caa33ccb01ae48798c443563cf57b0f423aa7b2 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Thu, 2 Jan 2025 15:57:16 -0500 Subject: [PATCH 15/84] Fix to fit new guidelines for snippets --- snippets/ruby/array-manipulation/binary-search.md | 2 +- snippets/ruby/array-manipulation/chunk-array.md | 2 +- snippets/ruby/array-manipulation/matrix-transpose.md | 2 +- snippets/ruby/basics/hello-world.md | 2 +- snippets/ruby/data-structures/binary-tree.md | 2 +- snippets/ruby/data-structures/doubly-linked-list.md | 2 +- .../{linked-list.md => singly-linked-list.md} | 2 +- .../{custom-error.md => custom-error-class.md} | 2 +- .../ruby/math-and-numbers/calculate-compound-interest.md | 2 +- snippets/ruby/math-and-numbers/calculate-factorial.md | 2 +- snippets/ruby/math-and-numbers/check-prime-number.md | 2 +- ...md => find-all-primes-up-to-integer-sieve-of-sundaram.md} | 2 +- snippets/ruby/string-manipulation/capitalize-words.md | 3 ++- ...ord-ocurrences.md => count-word-occurrences-in-string.md} | 3 ++- snippets/ruby/string-manipulation/remove-punctuation.md | 3 ++- ...to-snakecase.md => transform-camel-case-to-snake-case.md} | 3 ++- ...melcase.md => transform-from-snake-case-to-camel-case.md} | 3 ++- snippets/ruby/string-manipulation/truncate-string.md | 5 +++-- 18 files changed, 25 insertions(+), 19 deletions(-) rename snippets/ruby/data-structures/{linked-list.md => singly-linked-list.md} (95%) rename snippets/ruby/error-handling/{custom-error.md => custom-error-class.md} (91%) rename snippets/ruby/math-and-numbers/{sieve-of-sundaram.md => find-all-primes-up-to-integer-sieve-of-sundaram.md} (95%) rename snippets/ruby/string-manipulation/{count-word-ocurrences.md => count-word-occurrences-in-string.md} (91%) rename snippets/ruby/string-manipulation/{camelcase-to-snakecase.md => transform-camel-case-to-snake-case.md} (84%) rename snippets/ruby/string-manipulation/{snakecase-to-camelcase.md => transform-from-snake-case-to-camel-case.md} (87%) diff --git a/snippets/ruby/array-manipulation/binary-search.md b/snippets/ruby/array-manipulation/binary-search.md index ee7d16d1..b181b8af 100644 --- a/snippets/ruby/array-manipulation/binary-search.md +++ b/snippets/ruby/array-manipulation/binary-search.md @@ -2,7 +2,7 @@ title: Binary Search description: Searches for an element in a sorted array using binary search. author: ACR1209 -tags: ruby,array,binary-search,search +tags: array,binary-search,search --- ```rb diff --git a/snippets/ruby/array-manipulation/chunk-array.md b/snippets/ruby/array-manipulation/chunk-array.md index 32536ab3..29bfb50d 100644 --- a/snippets/ruby/array-manipulation/chunk-array.md +++ b/snippets/ruby/array-manipulation/chunk-array.md @@ -2,7 +2,7 @@ title: Chunk Array description: Splits an array into chunks of a specified size. author: ACR1209 -tags: ruby,array,chunk,utility +tags: array,chunk --- ```rb diff --git a/snippets/ruby/array-manipulation/matrix-transpose.md b/snippets/ruby/array-manipulation/matrix-transpose.md index bb033c9b..499cea53 100644 --- a/snippets/ruby/array-manipulation/matrix-transpose.md +++ b/snippets/ruby/array-manipulation/matrix-transpose.md @@ -2,7 +2,7 @@ title: Matrix Transpose description: Transposes a 2D matrix. author: ACR1209 -tags: ruby,array,matrix,transpose +tags: array,matrix,transpose --- ```ruby diff --git a/snippets/ruby/basics/hello-world.md b/snippets/ruby/basics/hello-world.md index 353e89c8..962c50c3 100644 --- a/snippets/ruby/basics/hello-world.md +++ b/snippets/ruby/basics/hello-world.md @@ -2,7 +2,7 @@ title: Hello, World! description: Prints Hello, World! to the terminal. author: ACR1209 -tags: ruby,printing,hello-world,utility +tags: printing,hello-world,utility --- ```rb diff --git a/snippets/ruby/data-structures/binary-tree.md b/snippets/ruby/data-structures/binary-tree.md index 266eca5e..e1d41542 100644 --- a/snippets/ruby/data-structures/binary-tree.md +++ b/snippets/ruby/data-structures/binary-tree.md @@ -2,7 +2,7 @@ title: Binary Tree description: Implements a basic binary tree with in-order traversal. author: ACR1209 -tags: ruby,data structures,binary tree +tags: data structures,binary tree --- ```rb diff --git a/snippets/ruby/data-structures/doubly-linked-list.md b/snippets/ruby/data-structures/doubly-linked-list.md index a0e2f949..6d6ade07 100644 --- a/snippets/ruby/data-structures/doubly-linked-list.md +++ b/snippets/ruby/data-structures/doubly-linked-list.md @@ -2,7 +2,7 @@ title: Doubly Linked List description: Implements a doubly linked list with node insertion and traversal. author: ACR1209 -tags: ruby,data structures,linked list,doubly linked list +tags: data structures,linked list,doubly linked list --- ```rb diff --git a/snippets/ruby/data-structures/linked-list.md b/snippets/ruby/data-structures/singly-linked-list.md similarity index 95% rename from snippets/ruby/data-structures/linked-list.md rename to snippets/ruby/data-structures/singly-linked-list.md index 1a27d60b..f50aadce 100644 --- a/snippets/ruby/data-structures/linked-list.md +++ b/snippets/ruby/data-structures/singly-linked-list.md @@ -2,7 +2,7 @@ title: Singly Linked List description: Implements a basic singly linked list with node insertion and traversal. author: ACR1209 -tags: ruby,data structures,linked list +tags: data structures,linked list --- ```rb diff --git a/snippets/ruby/error-handling/custom-error.md b/snippets/ruby/error-handling/custom-error-class.md similarity index 91% rename from snippets/ruby/error-handling/custom-error.md rename to snippets/ruby/error-handling/custom-error-class.md index 3b98ad51..af9ed6ef 100644 --- a/snippets/ruby/error-handling/custom-error.md +++ b/snippets/ruby/error-handling/custom-error-class.md @@ -2,7 +2,7 @@ title: Custom Error Class description: Defines and raises a custom error class in Ruby. author: ACR1209 -tags: ruby,error handling,custom error +tags: error handling,custom error --- ```rb diff --git a/snippets/ruby/math-and-numbers/calculate-compound-interest.md b/snippets/ruby/math-and-numbers/calculate-compound-interest.md index ecdae54a..c13faf26 100644 --- a/snippets/ruby/math-and-numbers/calculate-compound-interest.md +++ b/snippets/ruby/math-and-numbers/calculate-compound-interest.md @@ -3,7 +3,7 @@ title: Calculate Compound Interest description: Calculates compound interest for a given principal amount, rate, and time period. author: ACR1209 contributors: axorax -tags: ruby,math,compound interest,finance +tags: math,compound interest,finance --- ```rb diff --git a/snippets/ruby/math-and-numbers/calculate-factorial.md b/snippets/ruby/math-and-numbers/calculate-factorial.md index adc50b47..b4110ee6 100644 --- a/snippets/ruby/math-and-numbers/calculate-factorial.md +++ b/snippets/ruby/math-and-numbers/calculate-factorial.md @@ -2,7 +2,7 @@ title: Calculate Factorial description: Computes the factorial of a given integer. author: ACR1209 -tags: ruby,math,factorial +tags: math,factorial --- ```rb diff --git a/snippets/ruby/math-and-numbers/check-prime-number.md b/snippets/ruby/math-and-numbers/check-prime-number.md index 8919266d..e6f60928 100644 --- a/snippets/ruby/math-and-numbers/check-prime-number.md +++ b/snippets/ruby/math-and-numbers/check-prime-number.md @@ -3,7 +3,7 @@ title: Check Prime Number description: Checks if a number is a prime number. author: ACR1209 contributors: dostonnabotov -tags: ruby,math,prime,check +tags: math,prime,check --- ```rb diff --git a/snippets/ruby/math-and-numbers/sieve-of-sundaram.md b/snippets/ruby/math-and-numbers/find-all-primes-up-to-integer-sieve-of-sundaram.md similarity index 95% rename from snippets/ruby/math-and-numbers/sieve-of-sundaram.md rename to snippets/ruby/math-and-numbers/find-all-primes-up-to-integer-sieve-of-sundaram.md index 30de1c27..123f970e 100644 --- a/snippets/ruby/math-and-numbers/sieve-of-sundaram.md +++ b/snippets/ruby/math-and-numbers/find-all-primes-up-to-integer-sieve-of-sundaram.md @@ -2,7 +2,7 @@ title: Find all primes up to integer (Sieve of Sundaram) description: Finds all the prime numbers up to a specific integer. author: ACR1209 -tags: ruby,math,prime numbers +tags: math,prime numbers --- ```rb diff --git a/snippets/ruby/string-manipulation/capitalize-words.md b/snippets/ruby/string-manipulation/capitalize-words.md index da5beace..a3baba1c 100644 --- a/snippets/ruby/string-manipulation/capitalize-words.md +++ b/snippets/ruby/string-manipulation/capitalize-words.md @@ -2,7 +2,7 @@ title: Capitalize Words description: Capitalizes the first letter of each word in a string. author: ACR1209 -tags: ruby,string,capitalize,words +tags: string,capitalize,words --- ```rb @@ -10,6 +10,7 @@ def capitalize_words(str) str.split.map(&:capitalize).join(' ') end +# Usage sentence = "ruby is awesome" puts capitalize_words(sentence) # Output: "Ruby Is Awesome" ``` diff --git a/snippets/ruby/string-manipulation/count-word-ocurrences.md b/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md similarity index 91% rename from snippets/ruby/string-manipulation/count-word-ocurrences.md rename to snippets/ruby/string-manipulation/count-word-occurrences-in-string.md index 42961093..b780b527 100644 --- a/snippets/ruby/string-manipulation/count-word-ocurrences.md +++ b/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md @@ -2,7 +2,7 @@ title: Count Word Occurrences in String description: Counts the occurrences of each word in a given string. author: ACR1209 -tags: ruby,string,occurrences,word-count +tags: string,occurrences,word-count --- ```rb @@ -13,6 +13,7 @@ def count_word_occurrences(text) occurrences end +# Usage text = "ruby is awesome and Ruby is fun" puts count_word_occurrences(text) # Output: {"ruby"=>2, "is"=>2, "awesome"=>1, "and"=>1, "fun"=>1} ``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/remove-punctuation.md b/snippets/ruby/string-manipulation/remove-punctuation.md index e8e44b9d..ff1411ec 100644 --- a/snippets/ruby/string-manipulation/remove-punctuation.md +++ b/snippets/ruby/string-manipulation/remove-punctuation.md @@ -2,7 +2,7 @@ title: Remove Punctuation description: Removes all punctuation from a given string. author: ACR1209 -tags: ruby,string,punctuation,remove +tags: string,punctuation,remove --- ```rb @@ -10,6 +10,7 @@ def remove_punctuation(str) str.gsub(/[[:punct:]]/, '') end +# Usage text = "Hello, Ruby! How's it going?" puts remove_punctuation(text) # Output: "Hello Ruby Hows it going" ``` diff --git a/snippets/ruby/string-manipulation/camelcase-to-snakecase.md b/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md similarity index 84% rename from snippets/ruby/string-manipulation/camelcase-to-snakecase.md rename to snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md index 675ac7a4..109e9364 100644 --- a/snippets/ruby/string-manipulation/camelcase-to-snakecase.md +++ b/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md @@ -2,7 +2,7 @@ title: Transform Camel Case to Snake Case description: Converts a Camel Case string to Snake case. author: ACR1209 -tags: ruby,string,convert,camel-case,snake-case,utility +tags: string,convert,camel-case,snake-case --- ```rb @@ -10,6 +10,7 @@ def camel_to_snake(str) str.gsub(/([A-Z])/, '_\1').downcase end +# Usage camel_case = "camelCaseToSnakeCase" puts camel_to_snake(camel_case) # Output: "camel_case_to_snake_case" ``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/snakecase-to-camelcase.md b/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md similarity index 87% rename from snippets/ruby/string-manipulation/snakecase-to-camelcase.md rename to snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md index b36f7fe0..8dcdf088 100644 --- a/snippets/ruby/string-manipulation/snakecase-to-camelcase.md +++ b/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md @@ -2,7 +2,7 @@ title: Transform from Snake Case to Camel Case description: Converts a Snake Case string to Camel Case. author: ACR1209 -tags: ruby,string,convert,snake-case,camel-case,utility +tags: string,convert,snake-case,camel-case --- ```rb @@ -12,6 +12,7 @@ def snake_to_camel(str) }.join end +# Usage snake_case = "snake_case_to_camel_case" puts snake_to_camel(snake_case) # Output: "snakeCaseToCamelCase" ``` diff --git a/snippets/ruby/string-manipulation/truncate-string.md b/snippets/ruby/string-manipulation/truncate-string.md index 60ad5a22..a2abd9bf 100644 --- a/snippets/ruby/string-manipulation/truncate-string.md +++ b/snippets/ruby/string-manipulation/truncate-string.md @@ -1,8 +1,8 @@ --- -title: Truncate Strings +title: Truncate String description: Truncates a string to a specified length, optionally adding an ellipsis. author: ACR1209 -tags: ruby,string,truncate,utility +tags: string,truncate --- ```rb @@ -11,6 +11,7 @@ def truncate_string(max_length, str) str[0, max_length - 3] + '...' end +# Usage long_string = "Ruby is a dynamic, open source programming language." puts truncate_string(20, long_string) # Output: "Ruby is a dynamic..." puts truncate_string(54, long_string) # Output: "Ruby is a dynamic, open source programming language." From 461ae2daff67cb2c7a576a15c415b2541025f1b4 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Thu, 2 Jan 2025 20:58:43 +0000 Subject: [PATCH 16/84] Update consolidated snippets --- public/consolidated/ruby.json | 66 ++++++++++++----------------------- 1 file changed, 22 insertions(+), 44 deletions(-) diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json index 0bfdf295..008f1c7e 100644 --- a/public/consolidated/ruby.json +++ b/public/consolidated/ruby.json @@ -7,7 +7,6 @@ "description": "Searches for an element in a sorted array using binary search.", "author": "ACR1209", "tags": [ - "ruby", "array", "binary-search", "search" @@ -20,10 +19,8 @@ "description": "Splits an array into chunks of a specified size.", "author": "ACR1209", "tags": [ - "ruby", "array", - "chunk", - "utility" + "chunk" ], "contributors": [], "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Example usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n" @@ -33,7 +30,6 @@ "description": "Transposes a 2D matrix.", "author": "ACR1209", "tags": [ - "ruby", "array", "matrix", "transpose" @@ -51,7 +47,6 @@ "description": "Prints Hello, World! to the terminal.", "author": "ACR1209", "tags": [ - "ruby", "printing", "hello-world", "utility" @@ -69,7 +64,6 @@ "description": "Implements a basic binary tree with in-order traversal.", "author": "ACR1209", "tags": [ - "ruby", "data structures", "binary tree" ], @@ -81,7 +75,6 @@ "description": "Implements a doubly linked list with node insertion and traversal.", "author": "ACR1209", "tags": [ - "ruby", "data structures", "linked list", "doubly linked list" @@ -94,7 +87,6 @@ "description": "Implements a basic singly linked list with node insertion and traversal.", "author": "ACR1209", "tags": [ - "ruby", "data structures", "linked list" ], @@ -111,7 +103,6 @@ "description": "Defines and raises a custom error class in Ruby.", "author": "ACR1209", "tags": [ - "ruby", "error handling", "custom error" ], @@ -128,7 +119,6 @@ "description": "Calculates compound interest for a given principal amount, rate, and time period.", "author": "ACR1209", "tags": [ - "ruby", "math", "compound interest", "finance" @@ -143,7 +133,6 @@ "description": "Computes the factorial of a given integer.", "author": "ACR1209", "tags": [ - "ruby", "math", "factorial" ], @@ -155,7 +144,6 @@ "description": "Checks if a number is a prime number.", "author": "ACR1209", "tags": [ - "ruby", "math", "prime", "check" @@ -170,7 +158,6 @@ "description": "Finds all the prime numbers up to a specific integer.", "author": "ACR1209", "tags": [ - "ruby", "math", "prime numbers" ], @@ -182,87 +169,78 @@ { "categoryName": "String Manipulation", "snippets": [ - { - "title": "Transform Camel Case to Snake Case", - "description": "Converts a Camel Case string to Snake case.", - "author": "ACR1209", - "tags": [ - "ruby", - "string", - "convert", - "camel-case", - "snake-case", - "utility" - ], - "contributors": [], - "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').downcase\nend\n\ncamel_case = \"camelCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\n" - }, { "title": "Capitalize Words", "description": "Capitalizes the first letter of each word in a string.", "author": "ACR1209", "tags": [ - "ruby", "string", "capitalize", "words" ], "contributors": [], - "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" + "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" }, { "title": "Count Word Occurrences in String", "description": "Counts the occurrences of each word in a given string.", "author": "ACR1209", "tags": [ - "ruby", "string", "occurrences", "word-count" ], "contributors": [], - "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" + "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" }, { "title": "Remove Punctuation", "description": "Removes all punctuation from a given string.", "author": "ACR1209", "tags": [ - "ruby", "string", "punctuation", "remove" ], "contributors": [], - "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" + "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" + }, + { + "title": "Transform Camel Case to Snake Case", + "description": "Converts a Camel Case string to Snake case.", + "author": "ACR1209", + "tags": [ + "string", + "convert", + "camel-case", + "snake-case" + ], + "contributors": [], + "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').downcase\nend\n\n# Usage\ncamel_case = \"camelCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\n" }, { "title": "Transform from Snake Case to Camel Case", "description": "Converts a Snake Case string to Camel Case.", "author": "ACR1209", "tags": [ - "ruby", "string", "convert", "snake-case", - "camel-case", - "utility" + "camel-case" ], "contributors": [], - "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" + "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" }, { - "title": "Truncate Strings", + "title": "Truncate String", "description": "Truncates a string to a specified length, optionally adding an ellipsis.", "author": "ACR1209", "tags": [ - "ruby", "string", - "truncate", - "utility" + "truncate" ], "contributors": [], - "code": "def truncate_string(max_length, str)\n return str if str.length <= max_length\n str[0, max_length - 3] + '...'\nend\n\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" + "code": "def truncate_string(max_length, str)\n return str if str.length <= max_length\n str[0, max_length - 3] + '...'\nend\n\n# Usage\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" } ] } From fea1063ecd861829ee44d9c43bc4d7e3c3b2c12d Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 02:38:46 +0100 Subject: [PATCH 17/84] =?UTF-8?q?=E2=9C=A8=20[css]=20Add=20blinking=20anim?= =?UTF-8?q?ation=20snippet?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/blink-animation.md | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 snippets/css/animations/blink-animation.md diff --git a/snippets/css/animations/blink-animation.md b/snippets/css/animations/blink-animation.md new file mode 100644 index 00000000..d80b481c --- /dev/null +++ b/snippets/css/animations/blink-animation.md @@ -0,0 +1,24 @@ +--- +title: Blink Animation +description: Adds an infinite blinking animation to an element +author: AlsoKnownAs-Ax +tags: css,animation +--- + +```css +.parent { + animation: blink 1s linear infinite; +} + +@keyframes blink{ + 0%{ + opacity: 0; + } + 50%{ + opacity: 1; + } + 100%{ + opacity: 0; + } +} +``` From f4f888f2728941e855d7e67dead4af3c63cb18c0 Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 02:41:48 +0100 Subject: [PATCH 18/84] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20[css]=20renamed=20th?= =?UTF-8?q?e=20parent=20element=20to=20blink?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/blink-animation.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/css/animations/blink-animation.md b/snippets/css/animations/blink-animation.md index d80b481c..6574157b 100644 --- a/snippets/css/animations/blink-animation.md +++ b/snippets/css/animations/blink-animation.md @@ -6,7 +6,7 @@ tags: css,animation --- ```css -.parent { +.blink { animation: blink 1s linear infinite; } From 66846d7d7fab2af86b5cddc82e56e839d9c84cf6 Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 02:46:43 +0100 Subject: [PATCH 19/84] =?UTF-8?q?=E2=9C=A8=20[css]=20Add=20slide-in=20anim?= =?UTF-8?q?ation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/slide-in-animation.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 snippets/css/animations/slide-in-animation.md diff --git a/snippets/css/animations/slide-in-animation.md b/snippets/css/animations/slide-in-animation.md new file mode 100644 index 00000000..29707a98 --- /dev/null +++ b/snippets/css/animations/slide-in-animation.md @@ -0,0 +1,24 @@ +--- +title: Slide-in Animation +description: Adds a slide-in from the right side of the screen +author: AlsoKnownAs-Ax +tags: css,animation +--- + +```css +.slide-in { + animation: slide-in 1s ease-in-out; +} + +@keyframes slide-in { + from { + scale: 300% 1; + translate: 150vw 0; + } + + to { + scale: 100% 1; + translate: 0 0; + } +} +``` From 60c13b3d275cfd732d12ec05c7fffeed43e7a02c Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 02:51:10 +0100 Subject: [PATCH 20/84] =?UTF-8?q?=E2=9C=A8=20[css]=20Add=20pulse=20animati?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/pulse-animation.md | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/css/animations/pulse-animation.md diff --git a/snippets/css/animations/pulse-animation.md b/snippets/css/animations/pulse-animation.md new file mode 100644 index 00000000..45eb1d45 --- /dev/null +++ b/snippets/css/animations/pulse-animation.md @@ -0,0 +1,27 @@ +--- +title: Pulse Animation +description: Adds a smooth pulsing animation with opacity and scale effects +author: AlsoKnownAs-Ax +tags: css,animation +--- + +```css +.pulse { + animation: pulse 2s ease-in-out infinite; +} + +@keyframes pulse { + 0% { + opacity: 0.5; + transform: scale(1); + } + 50% { + opacity: 1; + transform: scale(1.05); + } + 100% { + opacity: 0.5; + transform: scale(1); + } +} +``` From 2622a355801e29d575eb0b446bd5e7c61a535c9d Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 03:13:54 +0100 Subject: [PATCH 21/84] =?UTF-8?q?=E2=9C=A8=20[css]=20Add=20Shake=20animati?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/shake-animation.md | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 snippets/css/animations/shake-animation.md diff --git a/snippets/css/animations/shake-animation.md b/snippets/css/animations/shake-animation.md new file mode 100644 index 00000000..0eadb2a2 --- /dev/null +++ b/snippets/css/animations/shake-animation.md @@ -0,0 +1,27 @@ +--- +title: Shake Animation +description: Adds a shake animation ( commonly used to mark invalid fields ) +author: AlsoKnownAs-Ax +tags: css,animation +--- + +```css +.shake { + animation: shake .5s ease-in-out; +} + +@keyframes shake { + 0%, 100% { + transform: translateX(0); + } + 25% { + transform: translateX(-10px); + } + 50% { + transform: translateX(10px); + } + 75% { + transform: translateX(-10px); + } +} +``` From 22512d8a49526cac631eb75036e1e17416f8d16c Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 03:14:05 +0100 Subject: [PATCH 22/84] =?UTF-8?q?=E2=9C=A8=20[css]=20Add=20typewriter=20an?= =?UTF-8?q?imation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../css/animations/typewriter-animation.md | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 snippets/css/animations/typewriter-animation.md diff --git a/snippets/css/animations/typewriter-animation.md b/snippets/css/animations/typewriter-animation.md new file mode 100644 index 00000000..02f69f0f --- /dev/null +++ b/snippets/css/animations/typewriter-animation.md @@ -0,0 +1,50 @@ +--- +title: Typewriter Animation +description: Adds a typewriter animation + blinking cursor +author: AlsoKnownAs-Ax +tags: css,animation +--- + +```html +
+
+

Typerwriter Animation

+
+
+``` + +```css + .typewriter{ + display: flex; + justify-content: center; + } + + .typewriter p { + overflow: hidden; + font-size: 1.5rem; + font-family: monospace; + border-right: 1px solid; + margin-inline: auto; + white-space: nowrap; + /* Steps: number of chars (better to set directly in js)*/ + animation: typing 3s steps(21) forwards, + blink 1s step-end infinite; + } + + @keyframes typing{ + from{ + width: 0% + } + f + + to{ + width: 100% + } + } + + @keyframes blink{ + 50%{ + border-color: transparent; + } + } +``` From 5c1819fab785b4aa3a89911985aafd1cf6fdf454 Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 16:23:17 +0100 Subject: [PATCH 23/84] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20[css]=20Fix=20typewr?= =?UTF-8?q?ite=20typo=20+=20add=20comments=20for=20clarity=20+=20add=20uni?= =?UTF-8?q?que=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/blink-animation.md | 2 +- snippets/css/animations/pulse-animation.md | 2 +- snippets/css/animations/shake-animation.md | 2 +- snippets/css/animations/slide-in-animation.md | 2 +- snippets/css/animations/typewriter-animation.md | 6 +++--- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/snippets/css/animations/blink-animation.md b/snippets/css/animations/blink-animation.md index 6574157b..7f7149f9 100644 --- a/snippets/css/animations/blink-animation.md +++ b/snippets/css/animations/blink-animation.md @@ -2,7 +2,7 @@ title: Blink Animation description: Adds an infinite blinking animation to an element author: AlsoKnownAs-Ax -tags: css,animation +tags: css,animation,blink,infinite --- ```css diff --git a/snippets/css/animations/pulse-animation.md b/snippets/css/animations/pulse-animation.md index 45eb1d45..4c27afdf 100644 --- a/snippets/css/animations/pulse-animation.md +++ b/snippets/css/animations/pulse-animation.md @@ -2,7 +2,7 @@ title: Pulse Animation description: Adds a smooth pulsing animation with opacity and scale effects author: AlsoKnownAs-Ax -tags: css,animation +tags: css,animation,pulse,pulse-scale --- ```css diff --git a/snippets/css/animations/shake-animation.md b/snippets/css/animations/shake-animation.md index 0eadb2a2..64a7cc86 100644 --- a/snippets/css/animations/shake-animation.md +++ b/snippets/css/animations/shake-animation.md @@ -2,7 +2,7 @@ title: Shake Animation description: Adds a shake animation ( commonly used to mark invalid fields ) author: AlsoKnownAs-Ax -tags: css,animation +tags: css,shake,shake-horizontal --- ```css diff --git a/snippets/css/animations/slide-in-animation.md b/snippets/css/animations/slide-in-animation.md index 29707a98..fd10b24c 100644 --- a/snippets/css/animations/slide-in-animation.md +++ b/snippets/css/animations/slide-in-animation.md @@ -2,7 +2,7 @@ title: Slide-in Animation description: Adds a slide-in from the right side of the screen author: AlsoKnownAs-Ax -tags: css,animation +tags: css,animation,slide-in,slide-right --- ```css diff --git a/snippets/css/animations/typewriter-animation.md b/snippets/css/animations/typewriter-animation.md index 02f69f0f..bb1477cf 100644 --- a/snippets/css/animations/typewriter-animation.md +++ b/snippets/css/animations/typewriter-animation.md @@ -2,7 +2,7 @@ title: Typewriter Animation description: Adds a typewriter animation + blinking cursor author: AlsoKnownAs-Ax -tags: css,animation +tags: css,blinking,typewriter --- ```html @@ -26,6 +26,8 @@ tags: css,animation border-right: 1px solid; margin-inline: auto; white-space: nowrap; + /* The cursor will inherit the text's color by default */ + /* border-color: red */ /* Steps: number of chars (better to set directly in js)*/ animation: typing 3s steps(21) forwards, blink 1s step-end infinite; @@ -35,8 +37,6 @@ tags: css,animation from{ width: 0% } - f - to{ width: 100% } From 73907f89fa7b2fe83366c2730e66a048f388e79e Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Fri, 3 Jan 2025 17:07:54 +0100 Subject: [PATCH 24/84] Updating snippet parsing and consolidation to support sub languages --- utils/consolidateSnippets.js | 34 +++++++++--- utils/snippetParser.js | 102 +++++++++++++++++++++-------------- 2 files changed, 87 insertions(+), 49 deletions(-) diff --git a/utils/consolidateSnippets.js b/utils/consolidateSnippets.js index 6a7673a1..aeaea0ce 100644 --- a/utils/consolidateSnippets.js +++ b/utils/consolidateSnippets.js @@ -1,5 +1,5 @@ import { exit } from 'process'; -import { parseAllSnippets, reverseSlugify } from './snippetParser.js'; +import { parseAllSnippets, reverseSlugify, slugify } from './snippetParser.js'; import { join } from 'path'; import { copyFileSync, writeFileSync } from 'fs'; @@ -8,21 +8,39 @@ const indexPath = join(dataPath, '_index.json'); const iconPath = 'public/icons/'; const snippetsPath = 'snippets/'; -const [ errored, snippets ] = parseAllSnippets(); +const [ errored, languages ] = parseAllSnippets(); if(errored) exit(1); const index = []; -for(const [language, categories] of Object.entries(snippets)) { - const languageIconPath = join(snippetsPath, language, 'icon.svg'); +for(const language of languages) { + copyFileSync(language.icon, join(iconPath, `${slugify(language.name)}.svg`)); - copyFileSync(languageIconPath, join(iconPath, `${language}.svg`)); + const subIndexes = []; - index.push({ lang: reverseSlugify(language).toUpperCase(), icon: `/icons/${language}.svg` }); + for(const subLanguage of language.subLanguages) { + const joinedName = `${slugify(language.name)}--${slugify(subLanguage.name)}`; + const iconName = `${joinedName}.svg`; + const subLanguageFilePath = join(dataPath, `${joinedName}.json`); + + copyFileSync(subLanguage.icon, join(iconPath, iconName)); + subIndexes.push({ + name: subLanguage.name.toUpperCase(), + icon: `/icons/${iconName}`, + }); + + writeFileSync(subLanguageFilePath, JSON.stringify(subLanguage.categories, null, 4)); + } + + index.push({ + name: language.name.toUpperCase(), + icon: `/icons/${slugify(language.name)}.svg`, + subLanguages: subIndexes, + }); - const languageFilePath = join(dataPath, `${language}.json`); + const languageFilePath = join(dataPath, `${slugify(language.name)}.json`); - writeFileSync(languageFilePath, JSON.stringify(categories, null, 4)); + writeFileSync(languageFilePath, JSON.stringify(language.categories, null, 4)); } writeFileSync(indexPath, JSON.stringify(index, null, 4)); \ No newline at end of file diff --git a/utils/snippetParser.js b/utils/snippetParser.js index 0989ab5e..e7b502f8 100644 --- a/utils/snippetParser.js +++ b/utils/snippetParser.js @@ -31,13 +31,13 @@ const crlfRegex = /\r\n/gm; const propertyRegex = /^\s+([a-zA-Z]+):\s*(.+)/; const headerEndCodeStartRegex = /^\s*---\s*```.*\n/; const codeRegex = /^(.+)```/s -function parseSnippet(snippetPath, name, text) { - if(crlfRegex.exec(text) !== null) return raise('Found CRLF line endings instead of LF line endings', snippetPath); +function parseSnippet(path, name, text) { + if(crlfRegex.exec(text) !== null) return raise('Found CRLF line endings instead of LF line endings', path); let cursor = 0; const fromCursor = () => text.substring(cursor); - if(!fromCursor().trim().startsWith('---')) return raise('Missing header start delimiter \'---\'', snippetPath); + if(!fromCursor().trim().startsWith('---')) return raise('Missing header start delimiter \'---\'', path); cursor += 3; const properties = {}; @@ -47,19 +47,19 @@ function parseSnippet(snippetPath, name, text) { properties[match[1].toLowerCase()] = match[2]; } - if(!('title' in properties)) return raise(`Missing 'title' property`, snippetPath); - if(!('description' in properties)) return raise(`Missing 'description' property`, snippetPath); - if(!('author' in properties)) return raise(`Missing 'author' property`, snippetPath); - if(!('tags' in properties)) return raise(`Missing 'tags' property`, snippetPath); + if(!('title' in properties)) return raise(`Missing 'title' property`, path); + if(!('description' in properties)) return raise(`Missing 'description' property`, path); + if(!('author' in properties)) return raise(`Missing 'author' property`, path); + if(!('tags' in properties)) return raise(`Missing 'tags' property`, path); - if(slugify(properties.title) !== name) return raise(`slugifyed 'title' property doesn't match snippet file name`, snippetPath); + if(slugify(properties.title) !== name) return raise(`slugifyed 'title' property doesn't match snippet file name`, path); match = headerEndCodeStartRegex.exec(fromCursor()); - if(match === null) return raise('Missing header end \'---\' or code start \'```\'', snippetPath); + if(match === null) return raise('Missing header end \'---\' or code start \'```\'', path); cursor += match[0].length; match = codeRegex.exec(fromCursor()); - if(match === null) return raise('Missing code block end \'```\'', snippetPath); + if(match === null) return raise('Missing code block end \'```\'', path); const code = match[1]; return { @@ -72,43 +72,63 @@ function parseSnippet(snippetPath, name, text) { } } +function parseCategory(path, name) { + const snippets = []; + + for(const snippet of readdirSync(path)) { + const snippetPath = join(path, snippet); + const snippetContent = readFileSync(snippetPath).toString(); + const snippetFileName = snippet.slice(0, -3); + + const snippetData = parseSnippet(snippetPath, snippetFileName, snippetContent); + if(!snippetData) continue; + snippets.push(snippetData); + } + + return { + name: reverseSlugify(name), + snippets, + }; +} + +function parseLanguage(path, name, subLanguageOf = null) { + const iconPath = join(path, 'icon.svg'); + + if(!existsSync(iconPath)) return raise(`icon for '${subLanguageOf ? `${subLanguageOf}/` : '' }${name}' is missing`); + + const categories = []; + const subLanguages = []; + + for(const category of readdirSync(path)) { + if(category === 'icon.svg') continue; + const categoryPath = join(path, category); + + if(category.startsWith('[') && category.endsWith(']')) { + if(subLanguageOf !== null) { + return raise('Cannot have more than two level of language nesting'); + } + subLanguages.push(parseLanguage(categoryPath, category.slice(1, -1), name)); + }else { + categories.push(parseCategory(categoryPath, category)); + } + } + + return { + name: reverseSlugify(name), + icon: iconPath, + categories, subLanguages, + } +} + const snippetPath = "snippets/"; export function parseAllSnippets() { - const snippets = {}; + const languages = []; for(const language of readdirSync(snippetPath)) { const languagePath = join(snippetPath, language); - - const languageIconPath = join(languagePath, 'icon.svg'); - - if(!existsSync(languageIconPath)) { - raise(`icon for '${language}' is missing`); - continue; - } - - const categories = []; - for(const category of readdirSync(languagePath)) { - if(category === 'icon.svg') continue; - const categoryPath = join(languagePath, category); - - const categorySnippets = []; - for(const snippet of readdirSync(categoryPath)) { - const snippetPath = join(categoryPath, snippet); - const snippetContent = readFileSync(snippetPath).toString(); - const snippetFileName = snippet.slice(0, -3); - - const snippetData = parseSnippet(snippetPath, snippetFileName, snippetContent); - if(!snippetData) continue; - categorySnippets.push(snippetData); - } - categories.push({ - categoryName: reverseSlugify(category), - snippets: categorySnippets, - }); - } - snippets[language] = categories; + languages.push(parseLanguage(languagePath, language)); } - return [ errored, snippets ]; + return [ errored, languages ]; } From ce540cb73a9f22b9caf56939e5b0d78ee4017e59 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Fri, 3 Jan 2025 17:10:05 +0100 Subject: [PATCH 25/84] Update frontend to handle the changed format of consolidated snippets --- src/components/LanguageSelector.tsx | 10 +++++----- src/components/SnippetList.tsx | 4 ++-- src/contexts/AppContext.tsx | 3 ++- src/hooks/useCategories.ts | 13 ++++--------- src/hooks/useSnippets.ts | 13 ++++--------- src/types/index.ts | 8 ++++++-- 6 files changed, 23 insertions(+), 28 deletions(-) diff --git a/src/components/LanguageSelector.tsx b/src/components/LanguageSelector.tsx index ae30b12f..d8e208fe 100644 --- a/src/components/LanguageSelector.tsx +++ b/src/components/LanguageSelector.tsx @@ -79,7 +79,7 @@ const LanguageSelector = () => { >
- {language.lang || "Select a language"} + {language.name || "Select a language"}
@@ -92,18 +92,18 @@ const LanguageSelector = () => { > {fetchedLanguages.map((lang, index) => (
  • handleSelect(lang)} className={`selector__item ${ - language.lang === lang.lang ? "selected" : "" + language.name === lang.name ? "selected" : "" } ${focusedIndex === index ? "focused" : ""}`} - aria-selected={language.lang === lang.lang} + aria-selected={language.name === lang.name} >
  • ))} diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index eb5ef79d..9ebed528 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -63,7 +63,7 @@ const SnippetList = () => { whileTap={{ scale: 0.98 }} >
    - {language.lang} + {language.name}

    {snippet.title}

    @@ -77,7 +77,7 @@ const SnippetList = () => { )} diff --git a/src/contexts/AppContext.tsx b/src/contexts/AppContext.tsx index 78fc86ea..30dd366e 100644 --- a/src/contexts/AppContext.tsx +++ b/src/contexts/AppContext.tsx @@ -4,8 +4,9 @@ import { AppState, LanguageType, SnippetType } from "@types"; // tokens const defaultLanguage: LanguageType = { - lang: "JAVASCRIPT", + name: "JAVASCRIPT", icon: "/icons/javascript.svg", + subIndexes: [], }; // TODO: add custom loading and error handling diff --git a/src/hooks/useCategories.ts b/src/hooks/useCategories.ts index ac55a7d5..4bd00685 100644 --- a/src/hooks/useCategories.ts +++ b/src/hooks/useCategories.ts @@ -1,24 +1,19 @@ import { useMemo } from "react"; import { useAppContext } from "@contexts/AppContext"; -import { SnippetType } from "@types"; +import { CategoryType } from "@types"; import { slugify } from "@utils/slugify"; import { useFetch } from "./useFetch"; -type CategoryData = { - categoryName: string; - snippets: SnippetType[]; -}; - export const useCategories = () => { const { language } = useAppContext(); - const { data, loading, error } = useFetch( - `/consolidated/${slugify(language.lang)}.json` + const { data, loading, error } = useFetch( + `/consolidated/${slugify(language.name)}.json` ); const fetchedCategories = useMemo(() => { - return data ? data.map((item) => item.categoryName) : []; + return data ? data.map((item) => item.name) : []; }, [data]); return { fetchedCategories, loading, error }; diff --git a/src/hooks/useSnippets.ts b/src/hooks/useSnippets.ts index 1ceb0dd5..a9d85499 100644 --- a/src/hooks/useSnippets.ts +++ b/src/hooks/useSnippets.ts @@ -1,22 +1,17 @@ import { useAppContext } from "@contexts/AppContext"; -import { SnippetType } from "@types"; +import { CategoryType } from "@types"; import { slugify } from "@utils/slugify"; import { useFetch } from "./useFetch"; -type CategoryData = { - categoryName: string; - snippets: SnippetType[]; -}; - export const useSnippets = () => { const { language, category } = useAppContext(); - const { data, loading, error } = useFetch( - `/consolidated/${slugify(language.lang)}.json` + const { data, loading, error } = useFetch( + `/consolidated/${slugify(language.name)}.json` ); const fetchedSnippets = data - ? data.find((item) => item.categoryName === category)?.snippets + ? data.find((item) => item.name === category)?.snippets : []; return { fetchedSnippets, loading, error }; diff --git a/src/types/index.ts b/src/types/index.ts index b4eac550..9f6c4fb2 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,10 +1,14 @@ export type LanguageType = { - lang: string; + name: string; icon: string; + subIndexes: { + name: string; + icon: string; + }[]; }; export type CategoryType = { - categoryName: string; + name: string; snippets: SnippetType[]; }; From 82611299c2ce0a5550eb8e1bac8ca59ec7d981ed Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Fri, 3 Jan 2025 17:30:07 +0100 Subject: [PATCH 26/84] Consolidating snippets --- public/consolidated/_index.json | 60 +++++++++++++++++------------ public/consolidated/c.json | 4 +- public/consolidated/cpp.json | 8 ++-- public/consolidated/csharp.json | 10 ++--- public/consolidated/css.json | 8 ++-- public/consolidated/haskell.json | 10 ++--- public/consolidated/html.json | 2 +- public/consolidated/java.json | 2 +- public/consolidated/javascript.json | 18 ++++----- public/consolidated/python.json | 18 ++++----- public/consolidated/rust.json | 6 +-- public/consolidated/scss.json | 12 +++--- public/consolidated/typescript.json | 2 +- 13 files changed, 86 insertions(+), 74 deletions(-) diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json index 6f82a67a..5d11e44a 100644 --- a/public/consolidated/_index.json +++ b/public/consolidated/_index.json @@ -1,50 +1,62 @@ [ { - "lang": "C", - "icon": "/icons/c.svg" + "name": "C", + "icon": "/icons/c.svg", + "subLanguages": [] }, { - "lang": "CPP", - "icon": "/icons/cpp.svg" + "name": "CPP", + "icon": "/icons/cpp.svg", + "subLanguages": [] }, { - "lang": "CSHARP", - "icon": "/icons/csharp.svg" + "name": "CSHARP", + "icon": "/icons/csharp.svg", + "subLanguages": [] }, { - "lang": "CSS", - "icon": "/icons/css.svg" + "name": "CSS", + "icon": "/icons/css.svg", + "subLanguages": [] }, { - "lang": "HASKELL", - "icon": "/icons/haskell.svg" + "name": "HASKELL", + "icon": "/icons/haskell.svg", + "subLanguages": [] }, { - "lang": "HTML", - "icon": "/icons/html.svg" + "name": "HTML", + "icon": "/icons/html.svg", + "subLanguages": [] }, { - "lang": "JAVA", - "icon": "/icons/java.svg" + "name": "JAVA", + "icon": "/icons/java.svg", + "subLanguages": [] }, { - "lang": "JAVASCRIPT", - "icon": "/icons/javascript.svg" + "name": "JAVASCRIPT", + "icon": "/icons/javascript.svg", + "subLanguages": [] }, { - "lang": "PYTHON", - "icon": "/icons/python.svg" + "name": "PYTHON", + "icon": "/icons/python.svg", + "subLanguages": [] }, { - "lang": "RUST", - "icon": "/icons/rust.svg" + "name": "RUST", + "icon": "/icons/rust.svg", + "subLanguages": [] }, { - "lang": "SCSS", - "icon": "/icons/scss.svg" + "name": "SCSS", + "icon": "/icons/scss.svg", + "subLanguages": [] }, { - "lang": "TYPESCRIPT", - "icon": "/icons/typescript.svg" + "name": "TYPESCRIPT", + "icon": "/icons/typescript.svg", + "subLanguages": [] } ] \ No newline at end of file diff --git a/public/consolidated/c.json b/public/consolidated/c.json index a9a23234..53be5540 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -16,7 +16,7 @@ ] }, { - "categoryName": "Mathematical Functions", + "name": "Mathematical Functions", "snippets": [ { "title": "Factorial Function", diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index e560e82d..50218944 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -16,7 +16,7 @@ ] }, { - "categoryName": "Data Structure Conversion", + "name": "Data Structure Conversion", "snippets": [ { "title": "Vector to Queue", @@ -33,7 +33,7 @@ ] }, { - "categoryName": "Math And Numbers", + "name": "Math And Numbers", "snippets": [ { "title": "Check Prime Number", @@ -49,7 +49,7 @@ ] }, { - "categoryName": "String Manipulation", + "name": "String Manipulation", "snippets": [ { "title": "Reverse String", diff --git a/public/consolidated/csharp.json b/public/consolidated/csharp.json index 63ff0ec1..fbd87ed4 100644 --- a/public/consolidated/csharp.json +++ b/public/consolidated/csharp.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -16,7 +16,7 @@ ] }, { - "categoryName": "Guid Utilities", + "name": "Guid Utilities", "snippets": [ { "title": "Generate GUID", @@ -43,7 +43,7 @@ ] }, { - "categoryName": "Jwt Utilities", + "name": "Jwt Utilities", "snippets": [ { "title": "Decode JWT", @@ -70,7 +70,7 @@ ] }, { - "categoryName": "List Utilities", + "name": "List Utilities", "snippets": [ { "title": "Swap items at index", @@ -86,7 +86,7 @@ ] }, { - "categoryName": "String Utilities", + "name": "String Utilities", "snippets": [ { "title": "Capitalize first letter", diff --git a/public/consolidated/css.json b/public/consolidated/css.json index b759c611..359088c9 100644 --- a/public/consolidated/css.json +++ b/public/consolidated/css.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Buttons", + "name": "Buttons", "snippets": [ { "title": "3D Button Effect", @@ -42,7 +42,7 @@ ] }, { - "categoryName": "Effects", + "name": "Effects", "snippets": [ { "title": "Blur Background", @@ -83,7 +83,7 @@ ] }, { - "categoryName": "Layouts", + "name": "Layouts", "snippets": [ { "title": "CSS Reset", @@ -146,7 +146,7 @@ ] }, { - "categoryName": "Typography", + "name": "Typography", "snippets": [ { "title": "Letter Spacing", diff --git a/public/consolidated/haskell.json b/public/consolidated/haskell.json index b4a97f3c..d199bba5 100644 --- a/public/consolidated/haskell.json +++ b/public/consolidated/haskell.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Array Manipulation", + "name": "Array Manipulation", "snippets": [ { "title": "Binary Search", @@ -41,7 +41,7 @@ ] }, { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -58,7 +58,7 @@ ] }, { - "categoryName": "File Handling", + "name": "File Handling", "snippets": [ { "title": "Find Files in Directory by Type", @@ -89,7 +89,7 @@ ] }, { - "categoryName": "Monads", + "name": "Monads", "snippets": [ { "title": "Either Monad for Error Handling", @@ -141,7 +141,7 @@ ] }, { - "categoryName": "String Manipulation", + "name": "String Manipulation", "snippets": [ { "title": "CamelCase to snake_case", diff --git a/public/consolidated/html.json b/public/consolidated/html.json index f7635148..1509d6d5 100644 --- a/public/consolidated/html.json +++ b/public/consolidated/html.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basic Layouts", + "name": "Basic Layouts", "snippets": [ { "title": "Grid Layout with Navigation", diff --git a/public/consolidated/java.json b/public/consolidated/java.json index f00ab589..3a36e17d 100644 --- a/public/consolidated/java.json +++ b/public/consolidated/java.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello-World", diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 4ac0819f..7123cb52 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Array Manipulation", + "name": "Array Manipulation", "snippets": [ { "title": "Partition Array", @@ -62,7 +62,7 @@ ] }, { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -78,7 +78,7 @@ ] }, { - "categoryName": "Date And Time", + "name": "Date And Time", "snippets": [ { "title": "Check Leap Year", @@ -175,7 +175,7 @@ ] }, { - "categoryName": "Dom Manipulation", + "name": "Dom Manipulation", "snippets": [ { "title": "Change Element Style", @@ -202,7 +202,7 @@ ] }, { - "categoryName": "Function Utilities", + "name": "Function Utilities", "snippets": [ { "title": "Compose Functions", @@ -311,7 +311,7 @@ ] }, { - "categoryName": "Local Storage", + "name": "Local Storage", "snippets": [ { "title": "Add Item to localStorage", @@ -349,7 +349,7 @@ ] }, { - "categoryName": "Number Formatting", + "name": "Number Formatting", "snippets": [ { "title": "Convert Number to Currency", @@ -420,7 +420,7 @@ ] }, { - "categoryName": "Object Manipulation", + "name": "Object Manipulation", "snippets": [ { "title": "Check if Object is Empty", @@ -574,7 +574,7 @@ ] }, { - "categoryName": "String Manipulation", + "name": "String Manipulation", "snippets": [ { "title": "Capitalize String", diff --git a/public/consolidated/python.json b/public/consolidated/python.json index 953272b8..8acadcfc 100644 --- a/public/consolidated/python.json +++ b/public/consolidated/python.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -16,7 +16,7 @@ ] }, { - "categoryName": "Datetime Utilities", + "name": "Datetime Utilities", "snippets": [ { "title": "Calculate Date Difference in Milliseconds", @@ -99,7 +99,7 @@ ] }, { - "categoryName": "Error Handling", + "name": "Error Handling", "snippets": [ { "title": "Create Custom Exception Type", @@ -128,7 +128,7 @@ ] }, { - "categoryName": "File Handling", + "name": "File Handling", "snippets": [ { "title": "Find Files", @@ -180,7 +180,7 @@ ] }, { - "categoryName": "Json Manipulation", + "name": "Json Manipulation", "snippets": [ { "title": "Filter JSON Data", @@ -257,7 +257,7 @@ ] }, { - "categoryName": "List Manipulation", + "name": "List Manipulation", "snippets": [ { "title": "Find Duplicates in a List", @@ -342,7 +342,7 @@ ] }, { - "categoryName": "Math And Numbers", + "name": "Math And Numbers", "snippets": [ { "title": "Calculate Compound Interest", @@ -435,7 +435,7 @@ ] }, { - "categoryName": "Sqlite Database", + "name": "Sqlite Database", "snippets": [ { "title": "Create SQLite Database Table", @@ -485,7 +485,7 @@ ] }, { - "categoryName": "String Manipulation", + "name": "String Manipulation", "snippets": [ { "title": "Capitalize Words", diff --git a/public/consolidated/rust.json b/public/consolidated/rust.json index 4a150d77..d3bd8f67 100644 --- a/public/consolidated/rust.json +++ b/public/consolidated/rust.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Basics", + "name": "Basics", "snippets": [ { "title": "Hello, World!", @@ -16,7 +16,7 @@ ] }, { - "categoryName": "File Handling", + "name": "File Handling", "snippets": [ { "title": "Find Files", @@ -43,7 +43,7 @@ ] }, { - "categoryName": "String Manipulation", + "name": "String Manipulation", "snippets": [ { "title": "Capitalize String", diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json index dd8414b1..f64d083b 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Animations", + "name": "Animations", "snippets": [ { "title": "Fade In Animation", @@ -29,7 +29,7 @@ ] }, { - "categoryName": "Borders Shadows", + "name": "Borders Shadows", "snippets": [ { "title": "Border Radius Helper", @@ -58,7 +58,7 @@ ] }, { - "categoryName": "Components", + "name": "Components", "snippets": [ { "title": "Primary Button", @@ -75,7 +75,7 @@ ] }, { - "categoryName": "Layouts", + "name": "Layouts", "snippets": [ { "title": "Aspect Ratio", @@ -130,7 +130,7 @@ ] }, { - "categoryName": "Typography", + "name": "Typography", "snippets": [ { "title": "Font Import Helper", @@ -184,7 +184,7 @@ ] }, { - "categoryName": "Utilities", + "name": "Utilities", "snippets": [ { "title": "Clearfix", diff --git a/public/consolidated/typescript.json b/public/consolidated/typescript.json index 98a0680b..1d3ece20 100644 --- a/public/consolidated/typescript.json +++ b/public/consolidated/typescript.json @@ -1,6 +1,6 @@ [ { - "categoryName": "Helper Types", + "name": "Helper Types", "snippets": [ { "title": "Exclusive Types", From 52be1f002c67cb8692ca246d2c91b9d09eaec380 Mon Sep 17 00:00:00 2001 From: --Ax- Date: Fri, 3 Jan 2025 17:43:24 +0100 Subject: [PATCH 27/84] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20[css]=20Removed=20un?= =?UTF-8?q?necessary=20tags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- snippets/css/animations/blink-animation.md | 2 +- snippets/css/animations/pulse-animation.md | 2 +- snippets/css/animations/shake-animation.md | 2 +- snippets/css/animations/slide-in-animation.md | 2 +- snippets/css/animations/typewriter-animation.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/snippets/css/animations/blink-animation.md b/snippets/css/animations/blink-animation.md index 7f7149f9..d3a91390 100644 --- a/snippets/css/animations/blink-animation.md +++ b/snippets/css/animations/blink-animation.md @@ -2,7 +2,7 @@ title: Blink Animation description: Adds an infinite blinking animation to an element author: AlsoKnownAs-Ax -tags: css,animation,blink,infinite +tags: animation,blink,infinite --- ```css diff --git a/snippets/css/animations/pulse-animation.md b/snippets/css/animations/pulse-animation.md index 4c27afdf..f7aeb2f1 100644 --- a/snippets/css/animations/pulse-animation.md +++ b/snippets/css/animations/pulse-animation.md @@ -2,7 +2,7 @@ title: Pulse Animation description: Adds a smooth pulsing animation with opacity and scale effects author: AlsoKnownAs-Ax -tags: css,animation,pulse,pulse-scale +tags: animation,pulse,pulse-scale --- ```css diff --git a/snippets/css/animations/shake-animation.md b/snippets/css/animations/shake-animation.md index 64a7cc86..01f78088 100644 --- a/snippets/css/animations/shake-animation.md +++ b/snippets/css/animations/shake-animation.md @@ -2,7 +2,7 @@ title: Shake Animation description: Adds a shake animation ( commonly used to mark invalid fields ) author: AlsoKnownAs-Ax -tags: css,shake,shake-horizontal +tags: shake,shake-horizontal --- ```css diff --git a/snippets/css/animations/slide-in-animation.md b/snippets/css/animations/slide-in-animation.md index fd10b24c..02dd5a2a 100644 --- a/snippets/css/animations/slide-in-animation.md +++ b/snippets/css/animations/slide-in-animation.md @@ -2,7 +2,7 @@ title: Slide-in Animation description: Adds a slide-in from the right side of the screen author: AlsoKnownAs-Ax -tags: css,animation,slide-in,slide-right +tags: animation,slide-in,slide-right --- ```css diff --git a/snippets/css/animations/typewriter-animation.md b/snippets/css/animations/typewriter-animation.md index bb1477cf..b8e0ad11 100644 --- a/snippets/css/animations/typewriter-animation.md +++ b/snippets/css/animations/typewriter-animation.md @@ -2,7 +2,7 @@ title: Typewriter Animation description: Adds a typewriter animation + blinking cursor author: AlsoKnownAs-Ax -tags: css,blinking,typewriter +tags: blinking,typewriter --- ```html From 470a9e84ce3ff2b61a76f29c2bd3d0460cc5bed6 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 3 Jan 2025 22:59:23 +0000 Subject: [PATCH 28/84] Update consolidated snippets --- public/consolidated/cpp.json | 17 +++++++++++++++++ public/consolidated/javascript.json | 18 ++++++------------ 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index e560e82d..6427f04f 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -32,6 +32,23 @@ } ] }, + { + "categoryName": "Debuging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "categoryName": "Math And Numbers", "snippets": [ diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 99588330..c7b78ff8 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -85,10 +85,8 @@ "description": "Converts RGB color values to hexadecimal color code.", "author": "jjcantu", "tags": [ - "javascript", "color", - "conversion", - "utility" + "conversion" ], "contributors": [], "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" @@ -407,10 +405,8 @@ "description": "Converts bytes into human-readable file size format.", "author": "jjcantu", "tags": [ - "javascript", "format", - "size", - "utility" + "size" ], "contributors": [], "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n" @@ -506,13 +502,11 @@ "description": "Creates a deep copy of an object or array without reference.", "author": "jjcantu", "tags": [ - "javascript", "object", - "clone", - "utility" + "clone" ], "contributors": [], - "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n" + "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n" }, { "title": "Filter Object", @@ -758,9 +752,9 @@ "description": "Generates a UUID (v4) string.", "author": "jjcantu", "tags": [ - "javascript", "uuid", - "utility" + "generate", + "string" ], "contributors": [], "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n" From ba6337fc8997ec0518dc483d882a9478b4a002b5 Mon Sep 17 00:00:00 2001 From: christianfuttrup Date: Sat, 4 Jan 2025 00:10:11 +0100 Subject: [PATCH 29/84] Refactored keyboard navigation --- src/hooks/useKeyboardNavigation.ts | 50 ++++++++++++++++++------------ 1 file changed, 31 insertions(+), 19 deletions(-) diff --git a/src/hooks/useKeyboardNavigation.ts b/src/hooks/useKeyboardNavigation.ts index 7b814e78..46bda82c 100644 --- a/src/hooks/useKeyboardNavigation.ts +++ b/src/hooks/useKeyboardNavigation.ts @@ -9,6 +9,16 @@ interface UseKeyboardNavigationProps { onClose: () => void; } +const keyboardEventKeys = { + arrowDown: "ArrowDown", + arrowUp: "ArrowUp", + enter: "Enter", + escape: "Escape", +} as const; + +type KeyboardEventKeys = + (typeof keyboardEventKeys)[keyof typeof keyboardEventKeys]; + export const useKeyboardNavigation = ({ items, isOpen, @@ -20,25 +30,27 @@ export const useKeyboardNavigation = ({ const handleKeyDown = (event: React.KeyboardEvent) => { if (!isOpen) return; - switch (event.key) { - case "ArrowDown": - event.preventDefault(); - setFocusedIndex((prev) => (prev < items.length - 1 ? prev + 1 : 0)); - break; - case "ArrowUp": - event.preventDefault(); - setFocusedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1)); - break; - case "Enter": - event.preventDefault(); - if (focusedIndex >= 0) { - onSelect(items[focusedIndex]); - } - break; - case "Escape": - event.preventDefault(); - onClose(); - break; + const key = event.key as KeyboardEventKeys; + + if (Object.values(keyboardEventKeys).includes(key)) { + event.preventDefault(); + + switch (key) { + case "ArrowDown": + setFocusedIndex((prev) => (prev < items.length - 1 ? prev + 1 : 0)); + break; + case "ArrowUp": + setFocusedIndex((prev) => (prev > 0 ? prev - 1 : items.length - 1)); + break; + case "Enter": + if (focusedIndex >= 0) { + onSelect(items[focusedIndex]); + } + break; + case "Escape": + onClose(); + break; + } } }; From 28703fa5e4c6bbf5fd4d9ed22d43c5714e544c3d Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Fri, 3 Jan 2025 18:51:20 -0500 Subject: [PATCH 30/84] Apply feedback to align with contributing guidelines and add new snippet to transform from sc to pc --- .../ruby/array-manipulation/binary-search.md | 2 +- .../ruby/array-manipulation/chunk-array.md | 2 +- .../array-manipulation/matrix-transpose.md | 2 +- snippets/ruby/data-structures/binary-tree.md | 42 ----------- .../data-structures/doubly-linked-list.md | 75 ------------------- .../data-structures/singly-linked-list.md | 50 ------------- .../string-manipulation/capitalize-words.md | 2 +- .../count-word-occurrences-in-string.md | 2 +- .../string-manipulation/remove-punctuation.md | 2 +- .../transform-camel-case-to-snake-case.md | 10 ++- ...transform-from-snake-case-to-camel-case.md | 2 +- ...ransform-from-snake-case-to-pascal-case.md | 18 +++++ .../string-manipulation/truncate-string.md | 6 +- 13 files changed, 34 insertions(+), 181 deletions(-) delete mode 100644 snippets/ruby/data-structures/binary-tree.md delete mode 100644 snippets/ruby/data-structures/doubly-linked-list.md delete mode 100644 snippets/ruby/data-structures/singly-linked-list.md create mode 100644 snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md diff --git a/snippets/ruby/array-manipulation/binary-search.md b/snippets/ruby/array-manipulation/binary-search.md index b181b8af..1ed1e34d 100644 --- a/snippets/ruby/array-manipulation/binary-search.md +++ b/snippets/ruby/array-manipulation/binary-search.md @@ -26,7 +26,7 @@ def binary_search(array, target) return nil end -# Usage +# Usage: array = [1, 3, 5, 7, 9] target = 5 result = binary_search(array, target) diff --git a/snippets/ruby/array-manipulation/chunk-array.md b/snippets/ruby/array-manipulation/chunk-array.md index 29bfb50d..102de3c6 100644 --- a/snippets/ruby/array-manipulation/chunk-array.md +++ b/snippets/ruby/array-manipulation/chunk-array.md @@ -10,7 +10,7 @@ def chunk_array(array, size) array.each_slice(size).to_a end -# Example usage: +# Usage: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] chunked_arr = chunk_array(arr, 2) puts chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]] diff --git a/snippets/ruby/array-manipulation/matrix-transpose.md b/snippets/ruby/array-manipulation/matrix-transpose.md index 499cea53..041d35ea 100644 --- a/snippets/ruby/array-manipulation/matrix-transpose.md +++ b/snippets/ruby/array-manipulation/matrix-transpose.md @@ -13,7 +13,7 @@ def transpose_matrix(matrix) matrix.first.zip(*matrix[1..-1]) end -# Usage +# Usage: matrix = [ [1, 2, 3], [4, 5, 6], diff --git a/snippets/ruby/data-structures/binary-tree.md b/snippets/ruby/data-structures/binary-tree.md deleted file mode 100644 index e1d41542..00000000 --- a/snippets/ruby/data-structures/binary-tree.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Binary Tree -description: Implements a basic binary tree with in-order traversal. -author: ACR1209 -tags: data structures,binary tree ---- - -```rb -class TreeNode - attr_accessor :data, :left, :right - - def initialize(data) - @data = data - @left = nil - @right = nil - end -end - -class BinaryTree - attr_accessor :root - - def initialize(root_data) - @root = TreeNode.new(root_data) - end - - def in_order_traversal(node = @root, result = []) - return result unless node - - in_order_traversal(node.left, result) - result << node.data - in_order_traversal(node.right, result) - end -end - -# Usage: -tree = BinaryTree.new(10) -tree.root.left = TreeNode.new(5) -tree.root.right = TreeNode.new(15) -tree.root.left.left = TreeNode.new(3) - -print tree.in_order_traversal # Output: [3, 5, 10, 15] -``` \ No newline at end of file diff --git a/snippets/ruby/data-structures/doubly-linked-list.md b/snippets/ruby/data-structures/doubly-linked-list.md deleted file mode 100644 index 6d6ade07..00000000 --- a/snippets/ruby/data-structures/doubly-linked-list.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Doubly Linked List -description: Implements a doubly linked list with node insertion and traversal. -author: ACR1209 -tags: data structures,linked list,doubly linked list ---- - -```rb -class Node - attr_accessor :data, :next, :prev - - def initialize(data) - @data = data - @next = nil - @prev = nil - end -end - -class DoublyLinkedList - def initialize - @head = nil - @tail = nil - end - - def append(data) - new_node = Node.new(data) - if @head.nil? - @head = new_node - @tail = new_node - else - @tail.next = new_node - new_node.prev = @tail - @tail = new_node - end - end - - def prepend(data) - new_node = Node.new(data) - if @head.nil? - @head = new_node - @tail = new_node - else - new_node.next = @head - @head.prev = new_node - @head = new_node - end - end - - def display_forward - current = @head - while current - print "#{current.data} <-> " - current = current.next - end - puts "nil" - end - - def display_backward - current = @tail - while current - print "#{current.data} <-> " - current = current.prev - end - puts "nil" - end -end - -# Usage: -dll = DoublyLinkedList.new -dll.append(1) -dll.append(2) -dll.append(3) -dll.display_forward # Output: 1 <-> 2 <-> 3 <-> nil -dll.display_backward # Output: 3 <-> 2 <-> 1 <-> nil -``` \ No newline at end of file diff --git a/snippets/ruby/data-structures/singly-linked-list.md b/snippets/ruby/data-structures/singly-linked-list.md deleted file mode 100644 index f50aadce..00000000 --- a/snippets/ruby/data-structures/singly-linked-list.md +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Singly Linked List -description: Implements a basic singly linked list with node insertion and traversal. -author: ACR1209 -tags: data structures,linked list ---- - -```rb -class Node - attr_accessor :data, :next - - def initialize(data) - @data = data - @next = nil - end -end - -class LinkedList - def initialize - @head = nil - end - - def append(data) - new_node = Node.new(data) - if @head.nil? - @head = new_node - else - current = @head - current = current.next while current.next - current.next = new_node - end - end - - def display - current = @head - while current - print "#{current.data} -> " - current = current.next - end - puts "nil" - end -end - -# Usage: -list = LinkedList.new -list.append(1) -list.append(2) -list.append(3) -list.display # Output: 1 -> 2 -> 3 -> nil -``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/capitalize-words.md b/snippets/ruby/string-manipulation/capitalize-words.md index a3baba1c..4287d12f 100644 --- a/snippets/ruby/string-manipulation/capitalize-words.md +++ b/snippets/ruby/string-manipulation/capitalize-words.md @@ -10,7 +10,7 @@ def capitalize_words(str) str.split.map(&:capitalize).join(' ') end -# Usage +# Usage: sentence = "ruby is awesome" puts capitalize_words(sentence) # Output: "Ruby Is Awesome" ``` diff --git a/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md b/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md index b780b527..7765d4b3 100644 --- a/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md +++ b/snippets/ruby/string-manipulation/count-word-occurrences-in-string.md @@ -13,7 +13,7 @@ def count_word_occurrences(text) occurrences end -# Usage +# Usage: text = "ruby is awesome and Ruby is fun" puts count_word_occurrences(text) # Output: {"ruby"=>2, "is"=>2, "awesome"=>1, "and"=>1, "fun"=>1} ``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/remove-punctuation.md b/snippets/ruby/string-manipulation/remove-punctuation.md index ff1411ec..d549d53e 100644 --- a/snippets/ruby/string-manipulation/remove-punctuation.md +++ b/snippets/ruby/string-manipulation/remove-punctuation.md @@ -10,7 +10,7 @@ def remove_punctuation(str) str.gsub(/[[:punct:]]/, '') end -# Usage +# Usage: text = "Hello, Ruby! How's it going?" puts remove_punctuation(text) # Output: "Hello Ruby Hows it going" ``` diff --git a/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md b/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md index 109e9364..1828c98f 100644 --- a/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md +++ b/snippets/ruby/string-manipulation/transform-camel-case-to-snake-case.md @@ -1,16 +1,18 @@ --- title: Transform Camel Case to Snake Case -description: Converts a Camel Case string to Snake case. +description: Converts a Camel or Pascal Case string to Snake case. author: ACR1209 -tags: string,convert,camel-case,snake-case +tags: string,convert,camel-case,snake-case,pascal-case --- ```rb def camel_to_snake(str) - str.gsub(/([A-Z])/, '_\1').downcase + str.gsub(/([A-Z])/, '_\1').sub(/^_/, '').downcase end -# Usage +# Usage: camel_case = "camelCaseToSnakeCase" +pascal_case = "PascalCaseToSnakeCase" puts camel_to_snake(camel_case) # Output: "camel_case_to_snake_case" +puts camel_to_snake(pascal_case) # Output: "pascal_case_to_snake_case" ``` \ No newline at end of file diff --git a/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md b/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md index 8dcdf088..4714ca3b 100644 --- a/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md +++ b/snippets/ruby/string-manipulation/transform-from-snake-case-to-camel-case.md @@ -12,7 +12,7 @@ def snake_to_camel(str) }.join end -# Usage +# Usage: snake_case = "snake_case_to_camel_case" puts snake_to_camel(snake_case) # Output: "snakeCaseToCamelCase" ``` diff --git a/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md b/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md new file mode 100644 index 00000000..92a51a51 --- /dev/null +++ b/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md @@ -0,0 +1,18 @@ +--- +title: Transform from Snake Case to Pascal Case +description: Converts a Snake Case string to Pascal Case. +author: ACR1209 +tags: string,convert,snake-case,pascal-case +--- + +```rb +def snake_to_camel(str) + str.split('_').map.with_index { |word, index| + word.capitalize + }.join +end + +# Usage: +snake_case = "snake_case_to_pascal_case" +puts snake_to_camel(snake_case) # Output: "SnakeCaseToPascalCase" +``` diff --git a/snippets/ruby/string-manipulation/truncate-string.md b/snippets/ruby/string-manipulation/truncate-string.md index a2abd9bf..8b6571ac 100644 --- a/snippets/ruby/string-manipulation/truncate-string.md +++ b/snippets/ruby/string-manipulation/truncate-string.md @@ -6,12 +6,12 @@ tags: string,truncate --- ```rb -def truncate_string(max_length, str) - return str if str.length <= max_length +def truncate_string(str, max_length) + return str if str.length <= max_length || max_length <= 3 str[0, max_length - 3] + '...' end -# Usage +# Usage: long_string = "Ruby is a dynamic, open source programming language." puts truncate_string(20, long_string) # Output: "Ruby is a dynamic..." puts truncate_string(54, long_string) # Output: "Ruby is a dynamic, open source programming language." From 0c2e2b33cb3ea6a6217954ee5646f7d1cf187d1f Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Fri, 3 Jan 2025 23:54:00 +0000 Subject: [PATCH 31/84] Update consolidated snippets --- public/consolidated/ruby.json | 75 ++++++++++++----------------------- 1 file changed, 25 insertions(+), 50 deletions(-) diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json index 008f1c7e..2432be6d 100644 --- a/public/consolidated/ruby.json +++ b/public/consolidated/ruby.json @@ -12,7 +12,7 @@ "search" ], "contributors": [], - "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n" + "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage:\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n" }, { "title": "Chunk Array", @@ -23,7 +23,7 @@ "chunk" ], "contributors": [], - "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Example usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n" + "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n" }, { "title": "Matrix Transpose", @@ -35,7 +35,7 @@ "transpose" ], "contributors": [], - "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n" + "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage:\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n" } ] }, @@ -56,45 +56,6 @@ } ] }, - { - "categoryName": "Data Structures", - "snippets": [ - { - "title": "Binary Tree", - "description": "Implements a basic binary tree with in-order traversal.", - "author": "ACR1209", - "tags": [ - "data structures", - "binary tree" - ], - "contributors": [], - "code": "class TreeNode\n attr_accessor :data, :left, :right\n\n def initialize(data)\n @data = data\n @left = nil\n @right = nil\n end\nend\n\nclass BinaryTree\n attr_accessor :root\n\n def initialize(root_data)\n @root = TreeNode.new(root_data)\n end\n\n def in_order_traversal(node = @root, result = [])\n return result unless node\n\n in_order_traversal(node.left, result)\n result << node.data\n in_order_traversal(node.right, result)\n end\nend\n\n# Usage:\ntree = BinaryTree.new(10)\ntree.root.left = TreeNode.new(5)\ntree.root.right = TreeNode.new(15)\ntree.root.left.left = TreeNode.new(3)\n\nprint tree.in_order_traversal # Output: [3, 5, 10, 15]\n" - }, - { - "title": "Doubly Linked List", - "description": "Implements a doubly linked list with node insertion and traversal.", - "author": "ACR1209", - "tags": [ - "data structures", - "linked list", - "doubly linked list" - ], - "contributors": [], - "code": "class Node\n attr_accessor :data, :next, :prev\n\n def initialize(data)\n @data = data\n @next = nil\n @prev = nil\n end\nend\n\nclass DoublyLinkedList\n def initialize\n @head = nil\n @tail = nil\n end\n\n def append(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n @tail = new_node\n else\n @tail.next = new_node\n new_node.prev = @tail\n @tail = new_node\n end\n end\n\n def prepend(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n @tail = new_node\n else\n new_node.next = @head\n @head.prev = new_node\n @head = new_node\n end\n end\n\n def display_forward\n current = @head\n while current\n print \"#{current.data} <-> \"\n current = current.next\n end\n puts \"nil\"\n end\n\n def display_backward\n current = @tail\n while current\n print \"#{current.data} <-> \"\n current = current.prev\n end\n puts \"nil\"\n end\nend\n\n# Usage:\ndll = DoublyLinkedList.new\ndll.append(1)\ndll.append(2)\ndll.append(3)\ndll.display_forward # Output: 1 <-> 2 <-> 3 <-> nil\ndll.display_backward # Output: 3 <-> 2 <-> 1 <-> nil\n" - }, - { - "title": "Singly Linked List", - "description": "Implements a basic singly linked list with node insertion and traversal.", - "author": "ACR1209", - "tags": [ - "data structures", - "linked list" - ], - "contributors": [], - "code": "class Node\n attr_accessor :data, :next\n\n def initialize(data)\n @data = data\n @next = nil\n end\nend\n\nclass LinkedList\n def initialize\n @head = nil\n end\n\n def append(data)\n new_node = Node.new(data)\n if @head.nil?\n @head = new_node\n else\n current = @head\n current = current.next while current.next\n current.next = new_node\n end\n end\n\n def display\n current = @head\n while current\n print \"#{current.data} -> \"\n current = current.next\n end\n puts \"nil\"\n end\nend\n\n# Usage:\nlist = LinkedList.new\nlist.append(1)\nlist.append(2)\nlist.append(3)\nlist.display # Output: 1 -> 2 -> 3 -> nil\n" - } - ] - }, { "categoryName": "Error Handling", "snippets": [ @@ -179,7 +140,7 @@ "words" ], "contributors": [], - "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" + "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage:\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n" }, { "title": "Count Word Occurrences in String", @@ -191,7 +152,7 @@ "word-count" ], "contributors": [], - "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" + "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage:\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n" }, { "title": "Remove Punctuation", @@ -203,20 +164,21 @@ "remove" ], "contributors": [], - "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" + "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage:\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n" }, { "title": "Transform Camel Case to Snake Case", - "description": "Converts a Camel Case string to Snake case.", + "description": "Converts a Camel or Pascal Case string to Snake case.", "author": "ACR1209", "tags": [ "string", "convert", "camel-case", - "snake-case" + "snake-case", + "pascal-case" ], "contributors": [], - "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').downcase\nend\n\n# Usage\ncamel_case = \"camelCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\n" + "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').sub(/^_/, '').downcase\nend\n\n# Usage:\ncamel_case = \"camelCaseToSnakeCase\"\npascal_case = \"PascalCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\nputs camel_to_snake(pascal_case) # Output: \"pascal_case_to_snake_case\"\n" }, { "title": "Transform from Snake Case to Camel Case", @@ -229,7 +191,20 @@ "camel-case" ], "contributors": [], - "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" + "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n" + }, + { + "title": "Transform from Snake Case to Pascal Case", + "description": "Converts a Snake Case string to Pascal Case.", + "author": "ACR1209", + "tags": [ + "string", + "convert", + "snake-case", + "pascal-case" + ], + "contributors": [], + "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_camel(snake_case) # Output: \"SnakeCaseToPascalCase\"\n" }, { "title": "Truncate String", @@ -240,7 +215,7 @@ "truncate" ], "contributors": [], - "code": "def truncate_string(max_length, str)\n return str if str.length <= max_length\n str[0, max_length - 3] + '...'\nend\n\n# Usage\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" + "code": "def truncate_string(str, max_length)\n return str if str.length <= max_length || max_length <= 3\n str[0, max_length - 3] + '...'\nend\n\n# Usage:\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n" } ] } From 3aa6c51c4a0730f2bca72358244c99c6b1022792 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 01:11:01 +0100 Subject: [PATCH 32/84] Added code snippet for Greatest Common Divisor in JS --- public/consolidated/javascript.json | 34 ++++++++++++------- .../greatest-common-divisor.md | 20 +++++++++++ 2 files changed, 42 insertions(+), 12 deletions(-) create mode 100644 snippets/javascript/mathematical-functions/greatest-common-divisor.md diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 99588330..d3403fc4 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -85,10 +85,8 @@ "description": "Converts RGB color values to hexadecimal color code.", "author": "jjcantu", "tags": [ - "javascript", "color", - "conversion", - "utility" + "conversion" ], "contributors": [], "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" @@ -366,6 +364,22 @@ } ] }, + { + "categoryName": "Mathematical Functions", + "snippets": [ + { + "title": "Greatest Common Divisor", + "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.", + "author": "JanluOfficial", + "tags": [ + "math", + "division" + ], + "contributors": [], + "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage\ngcd(1920, 1080); // Returns: 120\n" + } + ] + }, { "categoryName": "Number Formatting", "snippets": [ @@ -407,10 +421,8 @@ "description": "Converts bytes into human-readable file size format.", "author": "jjcantu", "tags": [ - "javascript", "format", - "size", - "utility" + "size" ], "contributors": [], "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n" @@ -506,13 +518,11 @@ "description": "Creates a deep copy of an object or array without reference.", "author": "jjcantu", "tags": [ - "javascript", "object", - "clone", - "utility" + "clone" ], "contributors": [], - "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n" + "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n" }, { "title": "Filter Object", @@ -758,9 +768,9 @@ "description": "Generates a UUID (v4) string.", "author": "jjcantu", "tags": [ - "javascript", "uuid", - "utility" + "generate", + "string" ], "contributors": [], "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n" diff --git a/snippets/javascript/mathematical-functions/greatest-common-divisor.md b/snippets/javascript/mathematical-functions/greatest-common-divisor.md new file mode 100644 index 00000000..56fb3ad1 --- /dev/null +++ b/snippets/javascript/mathematical-functions/greatest-common-divisor.md @@ -0,0 +1,20 @@ +--- +title: Greatest Common Divisor +description: Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios. +author: JanluOfficial +tags: math,division +--- + +```js +function gcd(a, b) { + while (b !== 0) { + let temp = b; + b = a % b; + a = temp; + } + return a; +} + +// Usage +gcd(1920, 1080); // Returns: 120 +``` \ No newline at end of file From 3d4ebda726ef4fad971354afca9abb26ba009ed5 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 01:23:55 +0100 Subject: [PATCH 33/84] Added more examples for gcd --- public/consolidated/javascript.json | 2 +- .../mathematical-functions/greatest-common-divisor.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index d3403fc4..11de7601 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -376,7 +376,7 @@ "division" ], "contributors": [], - "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage\ngcd(1920, 1080); // Returns: 120\n" + "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n" } ] }, diff --git a/snippets/javascript/mathematical-functions/greatest-common-divisor.md b/snippets/javascript/mathematical-functions/greatest-common-divisor.md index 56fb3ad1..c4c7218d 100644 --- a/snippets/javascript/mathematical-functions/greatest-common-divisor.md +++ b/snippets/javascript/mathematical-functions/greatest-common-divisor.md @@ -16,5 +16,7 @@ function gcd(a, b) { } // Usage -gcd(1920, 1080); // Returns: 120 +gcd(1920, 1080); // Returns: 120 +gcd(1920, 1200); // Returns: 240 +gcd(5,12); // Returns: 1 ``` \ No newline at end of file From 794eccd629ad0c17d407d0c4eee716c3638e72a2 Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 12:53:07 +0530 Subject: [PATCH 34/84] new snippet - string to int --- .../cpp/string-manipulation/string-int.md | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 snippets/cpp/string-manipulation/string-int.md diff --git a/snippets/cpp/string-manipulation/string-int.md b/snippets/cpp/string-manipulation/string-int.md new file mode 100644 index 00000000..39f1ff8c --- /dev/null +++ b/snippets/cpp/string-manipulation/string-int.md @@ -0,0 +1,20 @@ +--- +title: String Int +description: Converts string to int without built in stoi() +author: Emosans +tags: string,int +--- + +```cpp +std::int to_num(const std::string& input){ + int num=0; + int len=input.size(); + for(int i=0;iint) +``` \ No newline at end of file From 943300610102c47d7aab1859e7617487abc768d7 Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 16:10:11 +0530 Subject: [PATCH 35/84] new snippet- swap numbers --- snippets/cpp/math-and-numbers/swap-numbers.md | 19 ++++++++++++++++++ .../cpp/string-manipulation/string-int.md | 20 ------------------- 2 files changed, 19 insertions(+), 20 deletions(-) create mode 100644 snippets/cpp/math-and-numbers/swap-numbers.md delete mode 100644 snippets/cpp/string-manipulation/string-int.md diff --git a/snippets/cpp/math-and-numbers/swap-numbers.md b/snippets/cpp/math-and-numbers/swap-numbers.md new file mode 100644 index 00000000..27496a31 --- /dev/null +++ b/snippets/cpp/math-and-numbers/swap-numbers.md @@ -0,0 +1,19 @@ +--- +title: Swap numbers +description: Swaps two numbers without using third variable +author: Emosans +tags: swap,numbers +--- + +```cpp +#include +std::tuple swap(int num1,int num2){ + num1=num1+num2; + num2=num1-num2; + num1=num1-num2; + return std::make_tuple(num1,num2); +} + +// Usage +auto swapped=swap(3,4); // Returns a tuple (access the values using std::get<0>(swapped)/std::get<1>(swapped)) +``` \ No newline at end of file diff --git a/snippets/cpp/string-manipulation/string-int.md b/snippets/cpp/string-manipulation/string-int.md deleted file mode 100644 index 39f1ff8c..00000000 --- a/snippets/cpp/string-manipulation/string-int.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: String Int -description: Converts string to int without built in stoi() -author: Emosans -tags: string,int ---- - -```cpp -std::int to_num(const std::string& input){ - int num=0; - int len=input.size(); - for(int i=0;iint) -``` \ No newline at end of file From 78fa4a1d96cde3279d9a8e5997f37c937f4e1208 Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 16:33:41 +0530 Subject: [PATCH 36/84] snippet- changed to C --- .../c/mathematical-functions/swap-numbers.md | 19 +++++++++++++++++++ snippets/cpp/math-and-numbers/swap-numbers.md | 19 ------------------- 2 files changed, 19 insertions(+), 19 deletions(-) create mode 100644 snippets/c/mathematical-functions/swap-numbers.md delete mode 100644 snippets/cpp/math-and-numbers/swap-numbers.md diff --git a/snippets/c/mathematical-functions/swap-numbers.md b/snippets/c/mathematical-functions/swap-numbers.md new file mode 100644 index 00000000..c07d39b0 --- /dev/null +++ b/snippets/c/mathematical-functions/swap-numbers.md @@ -0,0 +1,19 @@ +--- +title: Swap numbers +description: Swaps two numbers without using third variable +author: Emosans +tags: swap,numbers +--- + +```c +#include +void swap(int* num1,int* num2){ + *num1= *num1 + *num2; + *num2= *num1 - *num2; + *num1= *num1 - *num2; +} + +// Usage: +int a=3,b=4; +auto swapped=swap(&a,&b); // simply use printf after this to print swapped values +``` \ No newline at end of file diff --git a/snippets/cpp/math-and-numbers/swap-numbers.md b/snippets/cpp/math-and-numbers/swap-numbers.md deleted file mode 100644 index 27496a31..00000000 --- a/snippets/cpp/math-and-numbers/swap-numbers.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: Swap numbers -description: Swaps two numbers without using third variable -author: Emosans -tags: swap,numbers ---- - -```cpp -#include -std::tuple swap(int num1,int num2){ - num1=num1+num2; - num2=num1-num2; - num1=num1-num2; - return std::make_tuple(num1,num2); -} - -// Usage -auto swapped=swap(3,4); // Returns a tuple (access the values using std::get<0>(swapped)/std::get<1>(swapped)) -``` \ No newline at end of file From bf49d9c496adf9f42df75e74c0341e784896112d Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 16:45:06 +0530 Subject: [PATCH 37/84] changes --- snippets/c/mathematical-functions/swap-numbers.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/snippets/c/mathematical-functions/swap-numbers.md b/snippets/c/mathematical-functions/swap-numbers.md index c07d39b0..a655a4cf 100644 --- a/snippets/c/mathematical-functions/swap-numbers.md +++ b/snippets/c/mathematical-functions/swap-numbers.md @@ -8,12 +8,12 @@ tags: swap,numbers ```c #include void swap(int* num1,int* num2){ - *num1= *num1 + *num2; - *num2= *num1 - *num2; - *num1= *num1 - *num2; + *num1 = *num1 + *num2; + *num2 = *num1 - *num2; + *num1 = *num1 - *num2; } // Usage: -int a=3,b=4; -auto swapped=swap(&a,&b); // simply use printf after this to print swapped values +int a = 3,b = 4; +swap(&a,&b); // simply use printf after this to print swapped values ``` \ No newline at end of file From 6381a89ca52eeece5dae4165d26bdc26a5921c88 Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 16:57:37 +0530 Subject: [PATCH 38/84] small typo --- public/consolidated/c.json | 11 +++++++++++ public/consolidated/cpp.json | 17 +++++++++++++++++ public/consolidated/javascript.json | 18 ++++++------------ 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index a9a23234..1588cd69 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -28,6 +28,17 @@ ], "contributors": [], "code": "int factorial(int x) {\n int y = 1;\n\n for (int i = 2; i <= x; i++)\n y *= i;\n\n return y;\n}\n\n// Usage:\nfactorial(4); // Returns: 24\n" + }, + { + "title": "Swap numbers", + "description": "Swaps two numbers without using third variable", + "author": "Emosans", + "tags": [ + "swap", + "numbers" + ], + "contributors": [], + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" } ] } diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index e560e82d..6427f04f 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -32,6 +32,23 @@ } ] }, + { + "categoryName": "Debuging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "categoryName": "Math And Numbers", "snippets": [ diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 99588330..c7b78ff8 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -85,10 +85,8 @@ "description": "Converts RGB color values to hexadecimal color code.", "author": "jjcantu", "tags": [ - "javascript", "color", - "conversion", - "utility" + "conversion" ], "contributors": [], "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" @@ -407,10 +405,8 @@ "description": "Converts bytes into human-readable file size format.", "author": "jjcantu", "tags": [ - "javascript", "format", - "size", - "utility" + "size" ], "contributors": [], "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n" @@ -506,13 +502,11 @@ "description": "Creates a deep copy of an object or array without reference.", "author": "jjcantu", "tags": [ - "javascript", "object", - "clone", - "utility" + "clone" ], "contributors": [], - "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n" + "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n" }, { "title": "Filter Object", @@ -758,9 +752,9 @@ "description": "Generates a UUID (v4) string.", "author": "jjcantu", "tags": [ - "javascript", "uuid", - "utility" + "generate", + "string" ], "contributors": [], "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n" From 2917bb78910704288ccdf1ef465b202ae2baba4c Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 17:08:43 +0530 Subject: [PATCH 39/84] replaced framer-motion package with motion --- package-lock.json | 39 ++++++++++++++++++++++++++++----- package.json | 2 +- src/components/SnippetList.tsx | 2 +- src/components/SnippetModal.tsx | 2 +- 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index bc4dad3c..e45de524 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,7 +8,7 @@ "name": "quicksnip", "version": "0.0.0", "dependencies": { - "framer-motion": "^11.15.0", + "motion": "^11.15.0", "prismjs": "^1.29.0", "react": "^18.3.1", "react-dom": "^18.3.1", @@ -3585,10 +3585,11 @@ "node": ">=0.4.x" } }, - "node_modules/framer-motion": { + "node_modules/motion/react": { "version": "11.15.0", - "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.15.0.tgz", + "resolved": "https://registry.npmjs.org/motion/react/-/motion/react-11.15.0.tgz", "integrity": "sha512-MLk8IvZntxOMg7lDBLw2qgTHHv664bYoYmnFTmE0Gm/FW67aOJk0WM3ctMcG+Xhcv+vh5uyyXwxvxhSeJzSe+w==", + "license": "MIT", "dependencies": { "motion-dom": "^11.14.3", "motion-utils": "^11.14.3", @@ -4665,15 +4666,43 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/motion": { + "version": "11.15.0", + "resolved": "https://registry.npmjs.org/motion/-/motion-11.15.0.tgz", + "integrity": "sha512-iZ7dwADQJWGsqsSkBhNHdI2LyYWU+hA1Nhy357wCLZq1yHxGImgt3l7Yv0HT/WOskcYDq9nxdedyl4zUv7UFFw==", + "license": "MIT", + "dependencies": { + "motion/react": "^11.15.0", + "tslib": "^2.4.0" + }, + "peerDependencies": { + "@emotion/is-prop-valid": "*", + "react": "^18.0.0 || ^19.0.0", + "react-dom": "^18.0.0 || ^19.0.0" + }, + "peerDependenciesMeta": { + "@emotion/is-prop-valid": { + "optional": true + }, + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, "node_modules/motion-dom": { "version": "11.14.3", "resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-11.14.3.tgz", - "integrity": "sha512-lW+D2wBy5vxLJi6aCP0xyxTxlTfiu+b+zcpVbGVFUxotwThqhdpPRSmX8xztAgtZMPMeU0WGVn/k1w4I+TbPqA==" + "integrity": "sha512-lW+D2wBy5vxLJi6aCP0xyxTxlTfiu+b+zcpVbGVFUxotwThqhdpPRSmX8xztAgtZMPMeU0WGVn/k1w4I+TbPqA==", + "license": "MIT" }, "node_modules/motion-utils": { "version": "11.14.3", "resolved": "https://registry.npmjs.org/motion-utils/-/motion-utils-11.14.3.tgz", - "integrity": "sha512-Xg+8xnqIJTpr0L/cidfTTBFkvRw26ZtGGuIhA94J9PQ2p4mEa06Xx7QVYZH0BP+EpMSaDlu+q0I0mmvwADPsaQ==" + "integrity": "sha512-Xg+8xnqIJTpr0L/cidfTTBFkvRw26ZtGGuIhA94J9PQ2p4mEa06Xx7QVYZH0BP+EpMSaDlu+q0I0mmvwADPsaQ==", + "license": "MIT" }, "node_modules/ms": { "version": "2.1.3", diff --git a/package.json b/package.json index 4148b723..ff3e622e 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "snippets:consolidate": "node ./utils/consolidateSnippets.js" }, "dependencies": { - "framer-motion": "^11.15.0", + "motion": "^11.15.0", "prismjs": "^1.29.0", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index eb5ef79d..7dbd404c 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -1,4 +1,4 @@ -import { motion, AnimatePresence } from "framer-motion"; +import { motion, AnimatePresence } from "motion/react"; import { useState } from "react"; import { useAppContext } from "@contexts/AppContext"; diff --git a/src/components/SnippetModal.tsx b/src/components/SnippetModal.tsx index b5e2379e..c062a0a1 100644 --- a/src/components/SnippetModal.tsx +++ b/src/components/SnippetModal.tsx @@ -1,4 +1,4 @@ -import { motion } from "framer-motion"; +import { motion } from "motion/react"; import React from "react"; import ReactDOM from "react-dom"; From 65140ccf37b90c3cd61c3fe8e656a4890a8d4762 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 14:09:36 +0100 Subject: [PATCH 40/84] Punctiuation --- public/consolidated/javascript.json | 2 +- .../mathematical-functions/greatest-common-divisor.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 11de7601..2e8c8f97 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -376,7 +376,7 @@ "division" ], "contributors": [], - "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n" + "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n" } ] }, diff --git a/snippets/javascript/mathematical-functions/greatest-common-divisor.md b/snippets/javascript/mathematical-functions/greatest-common-divisor.md index c4c7218d..f70101e2 100644 --- a/snippets/javascript/mathematical-functions/greatest-common-divisor.md +++ b/snippets/javascript/mathematical-functions/greatest-common-divisor.md @@ -15,7 +15,7 @@ function gcd(a, b) { return a; } -// Usage +// Usage: gcd(1920, 1080); // Returns: 120 gcd(1920, 1200); // Returns: 240 gcd(5,12); // Returns: 1 From 14b3891596829ff8abb1a4ef694fff298e346a7f Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 18:49:10 +0530 Subject: [PATCH 41/84] smoothed modal and list items animations --- src/components/SnippetList.tsx | 82 +++++++++++++++++++-------------- src/components/SnippetModal.tsx | 4 +- src/types/index.ts | 1 + 3 files changed, 49 insertions(+), 38 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index 7dbd404c..c6920cb8 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -33,42 +33,54 @@ const SnippetList = () => { return ( <> - - {fetchedSnippets.map((snippet, idx) => ( - - handleOpenModal(snippet)} - whileHover={{ scale: 1.01 }} - whileTap={{ scale: 0.98 }} + + {fetchedSnippets.map((currentSnippet, idx) => { + return ( + -
    - {language.lang} -
    -

    {snippet.title}

    -
    -
    - ))} + + handleOpenModal({ + ...currentSnippet, + idx: idx + 1, + }) + } + whileHover={{ scale: 1.01 }} + whileTap={{ scale: 0.98 }} + > +
    + {language.lang} +
    +

    {currentSnippet.title}

    +
    + + ); + })}
    diff --git a/src/components/SnippetModal.tsx b/src/components/SnippetModal.tsx index c062a0a1..043adcda 100644 --- a/src/components/SnippetModal.tsx +++ b/src/components/SnippetModal.tsx @@ -47,9 +47,7 @@ const SnippetModal: React.FC = ({ key="modal-content" className="modal | flow" data-flow-space="lg" - initial={{ scale: 0.8, opacity: 0, y: 20 }} - animate={{ scale: 1, opacity: 1, y: 0 }} - exit={{ scale: 0.8, opacity: 0, y: 20 }} + layoutId={snippet.title + snippet.idx?.toString()} transition={{ type: "spring", duration: 0.5 }} >
    diff --git a/src/types/index.ts b/src/types/index.ts index b4eac550..e2ae7783 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -14,6 +14,7 @@ export type SnippetType = { code: string; tags: string[]; author: string; + idx?: number; // Add optional idx property }; export type AppState = { From 8a0703bf9e33d5f1e039d58e265a91371c128630 Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 18:54:57 +0530 Subject: [PATCH 42/84] added support for reduced motion --- src/components/SnippetList.tsx | 14 ++++++++------ src/components/SnippetModal.tsx | 8 +++++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index c6920cb8..ee266c04 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -1,4 +1,4 @@ -import { motion, AnimatePresence } from "motion/react"; +import { motion, AnimatePresence, useReducedMotion } from "motion/react"; import { useState } from "react"; import { useAppContext } from "@contexts/AppContext"; @@ -13,6 +13,8 @@ const SnippetList = () => { const { fetchedSnippets } = useSnippets(); const [isModalOpen, setIsModalOpen] = useState(false); + const shouldReduceMotion = useReducedMotion(); + if (!fetchedSnippets) return (
    @@ -38,14 +40,14 @@ const SnippetList = () => { return ( { y: -20, transition: { delay: idx * 0.01, - duration: 0.09, + duration: shouldReduceMotion ? 0 : 0.09, }, }} transition={{ type: "spring", - duration: 0.5, + duration: shouldReduceMotion ? 0 : 0.5, }} > = ({ }) => { const modalRoot = document.getElementById("modal-root"); + const shouldReduceMotion = useReducedMotion(); + useEscapeKey(handleCloseModal); if (!modalRoot) { @@ -41,14 +43,14 @@ const SnippetModal: React.FC = ({ initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} - transition={{ duration: 0.2 }} + transition={{ duration: shouldReduceMotion ? 0 : 0.2 }} >

    {snippet.title}

    From 9b18b00cd3ec8fca7ba652ec8d6303f3f036f812 Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 19:11:53 +0530 Subject: [PATCH 43/84] remove unnecessary prop from AnimatePresence in SnippetList component --- src/components/SnippetList.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index ee266c04..2fd50bcf 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -35,7 +35,7 @@ const SnippetList = () => { return ( <> - + {fetchedSnippets.map((currentSnippet, idx) => { return ( Date: Sat, 4 Jan 2025 19:16:21 +0530 Subject: [PATCH 44/84] doc: added some comments --- src/components/SnippetList.tsx | 3 ++- src/components/SnippetModal.tsx | 2 +- src/types/index.ts | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index 2fd50bcf..843851a7 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -40,7 +40,7 @@ const SnippetList = () => { return ( { onClick={() => handleOpenModal({ ...currentSnippet, + // added idx for the layout animation to work correctly idx: idx + 1, }) } diff --git a/src/components/SnippetModal.tsx b/src/components/SnippetModal.tsx index d8c15941..dd31728c 100644 --- a/src/components/SnippetModal.tsx +++ b/src/components/SnippetModal.tsx @@ -49,7 +49,7 @@ const SnippetModal: React.FC = ({ key="modal-content" className="modal | flow" data-flow-space="lg" - layoutId={snippet.title + snippet.idx?.toString()} + layoutId={snippet.title + snippet.idx?.toString()} // unique id for layout animation transition={{ type: "spring", duration: shouldReduceMotion ? 0 : 0.5 }} >
    diff --git a/src/types/index.ts b/src/types/index.ts index e2ae7783..255aa631 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -14,7 +14,7 @@ export type SnippetType = { code: string; tags: string[]; author: string; - idx?: number; // Add optional idx property + idx?: number; }; export type AppState = { From f701f7da9138c4b84ad3ae58facef628c857fec3 Mon Sep 17 00:00:00 2001 From: majvax Date: Sat, 4 Jan 2025 15:21:43 +0100 Subject: [PATCH 45/84] Initial commit, added icon and 3 snippets --- snippets/regex/icon.svg | 6 ++++++ .../regex/miscellaneous/hexadecimal-color.md | 17 +++++++++++++++++ .../regex/validation pattern/email-address.md | 15 +++++++++++++++ .../regex/validation pattern/strong-password.md | 17 +++++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 snippets/regex/icon.svg create mode 100644 snippets/regex/miscellaneous/hexadecimal-color.md create mode 100644 snippets/regex/validation pattern/email-address.md create mode 100644 snippets/regex/validation pattern/strong-password.md diff --git a/snippets/regex/icon.svg b/snippets/regex/icon.svg new file mode 100644 index 00000000..bdbe2fc2 --- /dev/null +++ b/snippets/regex/icon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/snippets/regex/miscellaneous/hexadecimal-color.md b/snippets/regex/miscellaneous/hexadecimal-color.md new file mode 100644 index 00000000..7f3dfce4 --- /dev/null +++ b/snippets/regex/miscellaneous/hexadecimal-color.md @@ -0,0 +1,17 @@ +--- +Title: Hexadecimal Color +Description: Matches hex color codes +Author: majvax +Tags: color,hexadecimal +--- + + +```regex +^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$ + + +-> Usage: +#FFF1 ✗ +#FFF ✓ +#FFF000 ✓ +``` diff --git a/snippets/regex/validation pattern/email-address.md b/snippets/regex/validation pattern/email-address.md new file mode 100644 index 00000000..5a89f76e --- /dev/null +++ b/snippets/regex/validation pattern/email-address.md @@ -0,0 +1,15 @@ +--- +Title: Email Address +Description: Match any email address +Author: majvax +Tags: email +--- + + +```regex +^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ + +-> Usage: +example.name@domain.com.ru ✓ +name.surname@gmail.com ✓ +``` diff --git a/snippets/regex/validation pattern/strong-password.md b/snippets/regex/validation pattern/strong-password.md new file mode 100644 index 00000000..bda4352b --- /dev/null +++ b/snippets/regex/validation pattern/strong-password.md @@ -0,0 +1,17 @@ +--- +Title: Strong Password +Description: Match password with at least 12 characters, one uppercased letter, one number, and one special character. +Author: majvax +Tags: password +--- + + +```regex +^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$ + +-> Usage: +longpassword ✗ +longpassw0rd ✗ +longp@ssw0rd ✗ +Longp@ssw0rd ✓ +``` From f1a7b49ddcb0c1ac12c8a374b07d049cec34d083 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 14:22:17 +0000 Subject: [PATCH 46/84] Update consolidated snippets --- public/consolidated/_index.json | 4 +++ public/consolidated/cpp.json | 17 ++++++++++++ public/consolidated/javascript.json | 18 ++++-------- public/consolidated/regex.json | 43 +++++++++++++++++++++++++++++ public/icons/regex.svg | 6 ++++ 5 files changed, 76 insertions(+), 12 deletions(-) create mode 100644 public/consolidated/regex.json create mode 100644 public/icons/regex.svg diff --git a/public/consolidated/_index.json b/public/consolidated/_index.json index 6f82a67a..48d9f945 100644 --- a/public/consolidated/_index.json +++ b/public/consolidated/_index.json @@ -35,6 +35,10 @@ "lang": "PYTHON", "icon": "/icons/python.svg" }, + { + "lang": "REGEX", + "icon": "/icons/regex.svg" + }, { "lang": "RUST", "icon": "/icons/rust.svg" diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index e560e82d..6427f04f 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -32,6 +32,23 @@ } ] }, + { + "categoryName": "Debuging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "categoryName": "Math And Numbers", "snippets": [ diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 99588330..c7b78ff8 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -85,10 +85,8 @@ "description": "Converts RGB color values to hexadecimal color code.", "author": "jjcantu", "tags": [ - "javascript", "color", - "conversion", - "utility" + "conversion" ], "contributors": [], "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" @@ -407,10 +405,8 @@ "description": "Converts bytes into human-readable file size format.", "author": "jjcantu", "tags": [ - "javascript", "format", - "size", - "utility" + "size" ], "contributors": [], "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n" @@ -506,13 +502,11 @@ "description": "Creates a deep copy of an object or array without reference.", "author": "jjcantu", "tags": [ - "javascript", "object", - "clone", - "utility" + "clone" ], "contributors": [], - "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: { a: 1, b: { c: 2 }, d: [1, 2, 3] }\n" + "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n" }, { "title": "Filter Object", @@ -758,9 +752,9 @@ "description": "Generates a UUID (v4) string.", "author": "jjcantu", "tags": [ - "javascript", "uuid", - "utility" + "generate", + "string" ], "contributors": [], "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n" diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json new file mode 100644 index 00000000..f41a59b9 --- /dev/null +++ b/public/consolidated/regex.json @@ -0,0 +1,43 @@ +[ + { + "categoryName": "Miscellaneous", + "snippets": [ + { + "title": "Hexadecimal Color", + "description": "Matches hex color codes", + "author": "majvax", + "tags": [ + "color", + "hexadecimal" + ], + "contributors": [], + "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n" + } + ] + }, + { + "categoryName": "Validation pattern", + "snippets": [ + { + "title": "Email Address", + "description": "Match any email address", + "author": "majvax", + "tags": [ + "email" + ], + "contributors": [], + "code": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\n\n-> Usage:\nexample.name@domain.com.ru ✓\nname.surname@gmail.com ✓\n" + }, + { + "title": "Strong Password", + "description": "Match password with at least 12 characters, one uppercased letter, one number, and one special character.", + "author": "majvax", + "tags": [ + "password" + ], + "contributors": [], + "code": "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{12,}$\n\n-> Usage:\nlongpassword ✗\nlongpassw0rd ✗\nlongp@ssw0rd ✗\nLongp@ssw0rd ✓\n" + } + ] + } +] \ No newline at end of file diff --git a/public/icons/regex.svg b/public/icons/regex.svg new file mode 100644 index 00000000..bdbe2fc2 --- /dev/null +++ b/public/icons/regex.svg @@ -0,0 +1,6 @@ + + + + + + From 5ac43f75d1a84af8c49bd2eea37c3a11d81d4e1a Mon Sep 17 00:00:00 2001 From: majvax Date: Sat, 4 Jan 2025 15:53:56 +0100 Subject: [PATCH 47/84] added 3 more snippets --- snippets/regex/miscellaneous/ipv4.md | 17 +++++++++++++++++ .../unintentional-duplication.md | 16 ++++++++++++++++ .../regex/miscellaneous/whitespace-trimmer.md | 19 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 snippets/regex/miscellaneous/ipv4.md create mode 100644 snippets/regex/miscellaneous/unintentional-duplication.md create mode 100644 snippets/regex/miscellaneous/whitespace-trimmer.md diff --git a/snippets/regex/miscellaneous/ipv4.md b/snippets/regex/miscellaneous/ipv4.md new file mode 100644 index 00000000..8ca4a157 --- /dev/null +++ b/snippets/regex/miscellaneous/ipv4.md @@ -0,0 +1,17 @@ +--- +Title: IPv4 +Description: Matches IPv4 address +Author: majvax +Tags: ipv4,networking +--- + + +```regex +^((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})$ + + +-> Usage: +123.300.0.101 ✗ +127.0.0.1 ✓ +192.168.0.1 ✓ +``` diff --git a/snippets/regex/miscellaneous/unintentional-duplication.md b/snippets/regex/miscellaneous/unintentional-duplication.md new file mode 100644 index 00000000..d03a089e --- /dev/null +++ b/snippets/regex/miscellaneous/unintentional-duplication.md @@ -0,0 +1,16 @@ +--- +Title: Unintentional Duplication +Description: Matches duplicated word in a text. +Author: majvax +Tags: trim +--- + + +```regex +\b(\w+)\s+\1\b + + +-> Usage: +I need to finish this task ✗ +I need to to finish this task ✓ +``` diff --git a/snippets/regex/miscellaneous/whitespace-trimmer.md b/snippets/regex/miscellaneous/whitespace-trimmer.md new file mode 100644 index 00000000..e55ae56f --- /dev/null +++ b/snippets/regex/miscellaneous/whitespace-trimmer.md @@ -0,0 +1,19 @@ +--- +Title: Whitespace Trimmer +Description: Matches leading and/or trailing whitespace. +Author: majvax +Tags: trim +--- + + +```regex +^\s+|\s+$ + + +-> Usage: +(don't account for the quotation marks, it just to visualize whitespace) +"Hello World" ✗ +" Hello World" ✓ +"Hello World " ✓ +" Hello World " ✓ +``` From 9eda0f6033a231f0be43bcccc10f07d72b421616 Mon Sep 17 00:00:00 2001 From: majvax Date: Sat, 4 Jan 2025 15:54:39 +0100 Subject: [PATCH 48/84] Auto stash before merge of "regex" and "origin/regex" --- public/consolidated/regex.json | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json index f41a59b9..759b8b79 100644 --- a/public/consolidated/regex.json +++ b/public/consolidated/regex.json @@ -12,6 +12,40 @@ ], "contributors": [], "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n" +<<<<<<< Updated upstream +======= + }, + { + "title": "IPv4", + "description": "Matches IPv4 address", + "author": "majvax", + "tags": [ + "ipv4", + "networking" + ], + "contributors": [], + "code": "^((25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$\n\n\n-> Usage:\n123.300.0.101 ✗\n127.0.0.1 ✓\n192.168.0.1 ✓\n" + }, + { + "title": "Unintentional Duplication", + "description": "Matches duplicated word in a text.", + "author": "majvax", + "tags": [ + "trim" + ], + "contributors": [], + "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n" + }, + { + "title": "Whitespace Trimmer", + "description": "Matches leading and/or trailing whitespace.", + "author": "majvax", + "tags": [ + "trim" + ], + "contributors": [], + "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n" +>>>>>>> Stashed changes } ] }, From 4b438ef8d7aa57b19f119e96bd5a5359c42a40ee Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 14:55:15 +0000 Subject: [PATCH 49/84] Update consolidated snippets --- public/consolidated/regex.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json index 759b8b79..274c9b2a 100644 --- a/public/consolidated/regex.json +++ b/public/consolidated/regex.json @@ -12,8 +12,6 @@ ], "contributors": [], "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n" -<<<<<<< Updated upstream -======= }, { "title": "IPv4", @@ -45,7 +43,6 @@ ], "contributors": [], "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n" ->>>>>>> Stashed changes } ] }, From b3ad9071a9b9d09da9d0c1cfd2da7529e812cb18 Mon Sep 17 00:00:00 2001 From: majvax Date: Sat, 4 Jan 2025 15:56:00 +0100 Subject: [PATCH 50/84] fixed a tag --- snippets/regex/miscellaneous/unintentional-duplication.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/regex/miscellaneous/unintentional-duplication.md b/snippets/regex/miscellaneous/unintentional-duplication.md index d03a089e..ee6713f3 100644 --- a/snippets/regex/miscellaneous/unintentional-duplication.md +++ b/snippets/regex/miscellaneous/unintentional-duplication.md @@ -2,7 +2,7 @@ Title: Unintentional Duplication Description: Matches duplicated word in a text. Author: majvax -Tags: trim +Tags: duplication --- From 124a614f2341078aebac968d726b2d97647e6c31 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 14:56:37 +0000 Subject: [PATCH 51/84] Update consolidated snippets --- public/consolidated/regex.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json index 274c9b2a..2d8330c7 100644 --- a/public/consolidated/regex.json +++ b/public/consolidated/regex.json @@ -29,7 +29,7 @@ "description": "Matches duplicated word in a text.", "author": "majvax", "tags": [ - "trim" + "duplication" ], "contributors": [], "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n" From e4b3b5f8c8568a36082495959190807fdd4828cc Mon Sep 17 00:00:00 2001 From: Emosans Date: Sat, 4 Jan 2025 21:45:42 +0530 Subject: [PATCH 52/84] changes --- snippets/c/mathematical-functions/swap-numbers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/c/mathematical-functions/swap-numbers.md b/snippets/c/mathematical-functions/swap-numbers.md index a655a4cf..bbbc4a2b 100644 --- a/snippets/c/mathematical-functions/swap-numbers.md +++ b/snippets/c/mathematical-functions/swap-numbers.md @@ -15,5 +15,5 @@ void swap(int* num1,int* num2){ // Usage: int a = 3,b = 4; -swap(&a,&b); // simply use printf after this to print swapped values +swap(&a,&b); // swaps the values of the a and b variables ``` \ No newline at end of file From cd6c616c3785d0a7d1fa11077f99641f15b4441d Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 21:46:29 +0530 Subject: [PATCH 53/84] removed idx from the snippet type and swtiched to title and description for unique key --- src/components/SnippetList.tsx | 17 ++++++----------- src/components/SnippetModal.tsx | 2 +- src/types/index.ts | 1 - 3 files changed, 7 insertions(+), 13 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index 843851a7..d959dc8c 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -36,11 +36,12 @@ const SnippetList = () => { <> - {fetchedSnippets.map((currentSnippet, idx) => { + {fetchedSnippets.map((snippet, idx) => { + const uniqueId = `${snippet.title}-${snippet.description}`; return ( { - handleOpenModal({ - ...currentSnippet, - // added idx for the layout animation to work correctly - idx: idx + 1, - }) - } + onClick={() => handleOpenModal(snippet)} whileHover={{ scale: 1.01 }} whileTap={{ scale: 0.98 }} >
    {language.lang}
    -

    {currentSnippet.title}

    +

    {snippet.title}

    ); diff --git a/src/components/SnippetModal.tsx b/src/components/SnippetModal.tsx index dd31728c..1981ab77 100644 --- a/src/components/SnippetModal.tsx +++ b/src/components/SnippetModal.tsx @@ -49,7 +49,7 @@ const SnippetModal: React.FC = ({ key="modal-content" className="modal | flow" data-flow-space="lg" - layoutId={snippet.title + snippet.idx?.toString()} // unique id for layout animation + layoutId={`${snippet.title}-${snippet.description}`} transition={{ type: "spring", duration: shouldReduceMotion ? 0 : 0.5 }} >
    diff --git a/src/types/index.ts b/src/types/index.ts index 255aa631..b4eac550 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -14,7 +14,6 @@ export type SnippetType = { code: string; tags: string[]; author: string; - idx?: number; }; export type AppState = { From 2d1216f22e3d02e960f08d26b113423996bf5f61 Mon Sep 17 00:00:00 2001 From: Duzzenn <109883788+davidanukam@users.noreply.github.com> Date: Sat, 4 Jan 2025 11:41:30 -0500 Subject: [PATCH 54/84] Create zip-two-lists.md --- .../java/array-manipulation/zip-two-lists.md | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 snippets/java/array-manipulation/zip-two-lists.md diff --git a/snippets/java/array-manipulation/zip-two-lists.md b/snippets/java/array-manipulation/zip-two-lists.md new file mode 100644 index 00000000..20abc7a2 --- /dev/null +++ b/snippets/java/array-manipulation/zip-two-lists.md @@ -0,0 +1,31 @@ +--- +title: Zip Two Lists +description: Zips two lists into a list of paired elements, combining corresponding elements from both lists. +author: davidanukam +tags: lists,java,zip,stream-api,collections +--- + +```java +import java.util.*; // Importing utility classes for List and Arrays +import java.util.stream.IntStream; // Importing IntStream for range and mapping +import java.util.stream.Collectors; // Importing Collectors for collecting stream results + +public class Main { + // Generic method to zip two lists into a list of paired elements + public static List> zip(List list1, List list2) { + // Create pairs by iterating through the indices of both lists + return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list + .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i + .collect(Collectors.toList()); // Collect the pairs into a List + } + + public static void main(String[] args) { + // Usage: + List arr1 = Arrays.asList("a", "b", "c"); + List arr2 = Arrays.asList(1, 2, 3); + List> zipped = zip(arr1, arr2); + + System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]] + } +} +``` From 37099a299f61e58a63d4dd9526d7d30bb485cf37 Mon Sep 17 00:00:00 2001 From: Duzzenn <109883788+davidanukam@users.noreply.github.com> Date: Sat, 4 Jan 2025 12:05:33 -0500 Subject: [PATCH 55/84] Update zip-two-lists.md --- snippets/java/array-manipulation/zip-two-lists.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/java/array-manipulation/zip-two-lists.md b/snippets/java/array-manipulation/zip-two-lists.md index 20abc7a2..739a21fc 100644 --- a/snippets/java/array-manipulation/zip-two-lists.md +++ b/snippets/java/array-manipulation/zip-two-lists.md @@ -2,7 +2,7 @@ title: Zip Two Lists description: Zips two lists into a list of paired elements, combining corresponding elements from both lists. author: davidanukam -tags: lists,java,zip,stream-api,collections +tags: lists,zip,stream-api,collections --- ```java From 84c58acd978def0f13242f1d47bfac955ddb70c5 Mon Sep 17 00:00:00 2001 From: Gihan Rangana Date: Sat, 4 Jan 2025 22:59:53 +0530 Subject: [PATCH 56/84] Function to convert px to rem --- snippets/scss/typography/px-to-rem-helper.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 snippets/scss/typography/px-to-rem-helper.md diff --git a/snippets/scss/typography/px-to-rem-helper.md b/snippets/scss/typography/px-to-rem-helper.md new file mode 100644 index 00000000..de1fc6ef --- /dev/null +++ b/snippets/scss/typography/px-to-rem-helper.md @@ -0,0 +1,19 @@ +--- +title: Function to convert px to rem +description: This function will convert px values to rem values. +author: gihanrangana +tags: sass,function,pixel,rem,px-to-rem,css +--- + +```scss +@function px-to-rem($px, $base: 16px) { + @return ($px / $base) * 1rem; +} + +// Usage +div { + font-size: px-to-rem(12px); // Output: 0.75rem + padding: px-to-rem(16px); // Output: 1rem + margin: px-to-rem(32px) // Output 2rem +} +``` \ No newline at end of file From 9e89a9ce7fb01d760b3ede3b615c9028dbbbf7b9 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 17:30:12 +0000 Subject: [PATCH 57/84] Update consolidated snippets --- public/consolidated/scss.json | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json index 498f3665..6a32dd82 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -167,6 +167,21 @@ "contributors": [], "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" }, + { + "title": "Function to convert px to rem", + "description": "This function will convert px values to rem values.", + "author": "gihanrangana", + "tags": [ + "sass", + "function", + "pixel", + "rem", + "px-to-rem", + "css" + ], + "contributors": [], + "code": "@function px-to-rem($px, $base: 16px) {\n @return ($px / $base) * 1rem;\n}\n\n// Usage\ndiv {\n font-size: px-to-rem(12px); // Output: 0.75rem\n padding: px-to-rem(16px); // Output: 1rem\n margin: px-to-rem(32px) // Output 2rem\n}\n" + }, { "title": "Text Gradient", "description": "Adds a gradient color effect to text.", From 203a81802e5783aff5c88c7f52e66c9bc78499d7 Mon Sep 17 00:00:00 2001 From: Gihan Rangana Date: Sat, 4 Jan 2025 23:09:57 +0530 Subject: [PATCH 58/84] update title --- snippets/scss/typography/px-to-rem-helper.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/scss/typography/px-to-rem-helper.md b/snippets/scss/typography/px-to-rem-helper.md index de1fc6ef..b292ee12 100644 --- a/snippets/scss/typography/px-to-rem-helper.md +++ b/snippets/scss/typography/px-to-rem-helper.md @@ -1,5 +1,5 @@ --- -title: Function to convert px to rem +title: PX to REM Helper description: This function will convert px values to rem values. author: gihanrangana tags: sass,function,pixel,rem,px-to-rem,css From 80e512971580b9b1f462f7139730d55ab1c493be Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 17:40:14 +0000 Subject: [PATCH 59/84] Update consolidated snippets --- public/consolidated/c.json | 2 +- public/consolidated/scss.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 1588cd69..a9258611 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] } diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json index cc336713..a7ffc666 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -157,7 +157,7 @@ "code": "@mixin line-clamp($number) {\n display: -webkit-box;\n -webkit-box-orient: vertical;\n -webkit-line-clamp: $number;\n overflow: hidden;\n}\n" }, { - "title": "Function to convert px to rem", + "title": "PX to REM Helper", "description": "This function will convert px values to rem values.", "author": "gihanrangana", "tags": [ From 90c7896c3541dc698f44106682d208872d1a58a8 Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sat, 4 Jan 2025 23:24:59 +0530 Subject: [PATCH 60/84] use language + title as layout id --- src/components/SnippetList.tsx | 2 +- src/components/SnippetModal.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index d959dc8c..0378f4f3 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -37,7 +37,7 @@ const SnippetList = () => { {fetchedSnippets.map((snippet, idx) => { - const uniqueId = `${snippet.title}-${snippet.description}`; + const uniqueId = `${language.lang}-${snippet.title}`; return ( = ({ key="modal-content" className="modal | flow" data-flow-space="lg" - layoutId={`${snippet.title}-${snippet.description}`} + layoutId={`${language}-${snippet.title}`} transition={{ type: "spring", duration: shouldReduceMotion ? 0 : 0.5 }} >
    From 9d0dc84b5b74a923a799c52c2e22ede1da6195dd Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 19:29:40 +0100 Subject: [PATCH 61/84] A bunch of JS math snippets --- public/consolidated/javascript.json | 95 ++++++++++++++++++- .../mathematical-functions/combinations.md | 24 +++++ .../mathematical-functions/cross-product.md | 23 +++++ .../mathematical-functions/dot-product.md | 19 ++++ .../mathematical-functions/error-function.md | 21 ++++ .../greatest-common-divisor.md | 2 +- .../least-common-multiple.md | 25 +++++ .../matrix-multiplication.md | 34 +++++++ .../mathematical-functions/modular-inverse.md | 33 +++++++ .../mathematical-functions/prime-number.md | 24 +++++ 10 files changed, 298 insertions(+), 2 deletions(-) create mode 100644 snippets/javascript/mathematical-functions/combinations.md create mode 100644 snippets/javascript/mathematical-functions/cross-product.md create mode 100644 snippets/javascript/mathematical-functions/dot-product.md create mode 100644 snippets/javascript/mathematical-functions/error-function.md create mode 100644 snippets/javascript/mathematical-functions/least-common-multiple.md create mode 100644 snippets/javascript/mathematical-functions/matrix-multiplication.md create mode 100644 snippets/javascript/mathematical-functions/modular-inverse.md create mode 100644 snippets/javascript/mathematical-functions/prime-number.md diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 2e8c8f97..135a8a1e 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -367,16 +367,109 @@ { "categoryName": "Mathematical Functions", "snippets": [ + { + "title": "Combinations", + "description": "Calculates the number of combinations (denoted as C(n,r) or \"n choose r\"), which determines how many ways you can select r items from n items without considering the order.", + "author": "JanluOfficial", + "tags": [ + "math", + "number-theory", + "algebra" + ], + "contributors": [], + "code": "function combinations(n, r) {\n function factorial(x) {\n if (x === 0 || x === 1) return 1;\n let result = 1;\n for (let i = 2; i <= x; i++) {\n result *= i;\n }\n return result;\n }\n return factorial(n) / (factorial(r) * factorial(n - r));\n}\n\n// Usage:\ncombinations(12,24); // Returns: 7.720248753351544e-16\ncombinations(1,22); // Returns: 8.896791392450574e-22\n" + }, + { + "title": "Cross Product", + "description": "Computes the cross product of two 3D vectors, which results in a vector perpendicular to both.", + "author": "JanluOfficial", + "tags": [ + "math", + "vector-algebra" + ], + "contributors": [], + "code": "function crossProduct(a, b) {\n if (a.length !== 3 || b.length !== 3) {\n throw new Error('Vectors must be 3-dimensional');\n }\n\n return [\n a[1] * b[2] - a[2] * b[1],\n a[2] * b[0] - a[0] * b[2],\n a[0] * b[1] - a[1] * b[0]\n ];\n}\n\n// Usage:\ncrossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3] \n" + }, + { + "title": "Dot Product", + "description": "Computes the dot product of two vectors, which is the sum of the products of corresponding elements.", + "author": "JanluOfficial", + "tags": [ + "math", + "vector-algebra" + ], + "contributors": [], + "code": "function dotProduct(a, b) {\n if (a.length !== b.length) {\n throw new Error('Vectors must be of the same length');\n }\n\n return a.reduce((sum, value, index) => sum + value * b[index], 0);\n}\n\n// Usage:\ndotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32\n" + }, + { + "title": "Error function", + "description": "Computes the error function (erf(x)) for a given input x, which is a mathematical function used frequently in probability, statistics, and partial differential equations.", + "author": "JanluOfficial", + "tags": [ + "math" + ], + "contributors": [], + "code": "function erf(x) {\n const sign = Math.sign(x);\n const absX = Math.abs(x);\n const t = 1 / (1 + 0.3275911 * absX);\n const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429;\n const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))));\n return sign * (1 - poly * Math.exp(-absX * absX));\n}\n\n// Usage:\nerf(-1); // Returns: -0.8427006897475899\nerf(1); // Returns: 0.8427006897475899\n" + }, { "title": "Greatest Common Divisor", "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.", "author": "JanluOfficial", "tags": [ "math", - "division" + "division", + "number-theory", + "algebra" ], "contributors": [], "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n" + }, + { + "title": "Least common multiple", + "description": "Computes the least common multiple (LCM) of two numbers 𝑎 and b. The LCM is the smallest positive integer that is divisible by both a and b.", + "author": "JanluOfficial", + "tags": [ + "math", + "number-theory", + "algebra" + ], + "contributors": [], + "code": "function lcm(a, b) {\n function gcd(x, y) {\n while (y !== 0) {\n const temp = y;\n y = x % y;\n x = temp;\n }\n return Math.abs(x);\n }\n return Math.abs(a * b) / gcd(a, b);\n}\n\n// Usage:\nlcm(12,16); // Returns: 48\nlcm(8,20); // Returns: 40\nlcm(16,17); // Returns: 272\n" + }, + { + "title": "Matrix Multiplication", + "description": "Multiplies two matrices, where the number of columns in the first matrix equals the number of rows in the second.", + "author": "JanluOfficial", + "tags": [ + "math", + "matrix-algebra" + ], + "contributors": [], + "code": "function matrixMultiply(A, B) {\n const rowsA = A.length;\n const colsA = A[0].length;\n const rowsB = B.length;\n const colsB = B[0].length;\n\n if (colsA !== rowsB) {\n throw new Error('Number of columns of A must equal the number of rows of B');\n }\n\n let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0));\n\n for (let i = 0; i < rowsA; i++) {\n for (let j = 0; j < colsB; j++) {\n for (let k = 0; k < colsA; k++) {\n result[i][j] += A[i][k] * B[k][j];\n }\n }\n }\n\n return result;\n}\n\n// Usage:\nmatrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]]\n" + }, + { + "title": "Modular Inverse", + "description": "Computes the modular multiplicative inverse of a number a under modulo m, which is the integer x such that (a*x) mod m=1.", + "author": "JanluOfficial", + "tags": [ + "math", + "number-theory", + "algebra" + ], + "contributors": [], + "code": "function modInverse(a, m) {\n function extendedGCD(a, b) {\n if (b === 0) {\n return { gcd: a, x: 1, y: 0 };\n }\n const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b);\n const x = y1;\n const y = x1 - Math.floor(a / b) * y1;\n return { gcd, x, y };\n }\n\n const { gcd, x } = extendedGCD(a, m);\n\n if (gcd !== 1) {\n return null;\n }\n\n return (x % m + m) % m;\n}\n\n// Usage:\nmodInverse(3, 26); // Returns: 9\nmodInverse(10, 17); // Returns: 12\nmodInverse(6, 9); // Returns: null\n" + }, + { + "title": "Prime Number", + "description": "Calculates the number of combinations (denoted as C(n,r) or \"n choose r\"), which determines how many ways you can select r items from n items without considering the order.", + "author": "JanluOfficial", + "tags": [ + "math", + "number-theory", + "algebra" + ], + "contributors": [], + "code": "function isPrime(num) {\n if (num <= 1) return false; // 0 and 1 are not prime numbers\n if (num <= 3) return true; // 2 and 3 are prime numbers\n if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3\n\n // Check divisors from 5 to √num, skipping multiples of 2 and 3\n for (let i = 5; i * i <= num; i += 6) {\n if (num % i === 0 || num % (i + 2) === 0) return false;\n }\n return true;\n}\n\n// Usage:\nisPrime(69); // Returns: false\nisPrime(17); // Returns: true\n" } ] }, diff --git a/snippets/javascript/mathematical-functions/combinations.md b/snippets/javascript/mathematical-functions/combinations.md new file mode 100644 index 00000000..0b95dccc --- /dev/null +++ b/snippets/javascript/mathematical-functions/combinations.md @@ -0,0 +1,24 @@ +--- +title: Combinations +description: Calculates the number of combinations (denoted as C(n,r) or "n choose r"), which determines how many ways you can select r items from n items without considering the order. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function combinations(n, r) { + function factorial(x) { + if (x === 0 || x === 1) return 1; + let result = 1; + for (let i = 2; i <= x; i++) { + result *= i; + } + return result; + } + return factorial(n) / (factorial(r) * factorial(n - r)); +} + +// Usage: +combinations(12,24); // Returns: 7.720248753351544e-16 +combinations(1,22); // Returns: 8.896791392450574e-22 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/cross-product.md b/snippets/javascript/mathematical-functions/cross-product.md new file mode 100644 index 00000000..4ed5404f --- /dev/null +++ b/snippets/javascript/mathematical-functions/cross-product.md @@ -0,0 +1,23 @@ +--- +title: Cross Product +description: Computes the cross product of two 3D vectors, which results in a vector perpendicular to both. +author: JanluOfficial +tags: math,vector-algebra +--- + +```js +function crossProduct(a, b) { + if (a.length !== 3 || b.length !== 3) { + throw new Error('Vectors must be 3-dimensional'); + } + + return [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0] + ]; +} + +// Usage: +crossProduct([1, 2, 3], [4, 5, 6]); // Returns: [-3, 6, -3] +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/dot-product.md b/snippets/javascript/mathematical-functions/dot-product.md new file mode 100644 index 00000000..d1b1e397 --- /dev/null +++ b/snippets/javascript/mathematical-functions/dot-product.md @@ -0,0 +1,19 @@ +--- +title: Dot Product +description: Computes the dot product of two vectors, which is the sum of the products of corresponding elements. +author: JanluOfficial +tags: math,vector-algebra +--- + +```js +function dotProduct(a, b) { + if (a.length !== b.length) { + throw new Error('Vectors must be of the same length'); + } + + return a.reduce((sum, value, index) => sum + value * b[index], 0); +} + +// Usage: +dotProduct([1, 2, 3], [4, 5, 6]); // Returns: 32 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/error-function.md b/snippets/javascript/mathematical-functions/error-function.md new file mode 100644 index 00000000..211171d8 --- /dev/null +++ b/snippets/javascript/mathematical-functions/error-function.md @@ -0,0 +1,21 @@ +--- +title: Error function +description: Computes the error function (erf(x)) for a given input x, which is a mathematical function used frequently in probability, statistics, and partial differential equations. +author: JanluOfficial +tags: math +--- + +```js +function erf(x) { + const sign = Math.sign(x); + const absX = Math.abs(x); + const t = 1 / (1 + 0.3275911 * absX); + const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741, a4 = -1.453152027, a5 = 1.061405429; + const poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5)))); + return sign * (1 - poly * Math.exp(-absX * absX)); +} + +// Usage: +erf(-1); // Returns: -0.8427006897475899 +erf(1); // Returns: 0.8427006897475899 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/greatest-common-divisor.md b/snippets/javascript/mathematical-functions/greatest-common-divisor.md index f70101e2..fec36324 100644 --- a/snippets/javascript/mathematical-functions/greatest-common-divisor.md +++ b/snippets/javascript/mathematical-functions/greatest-common-divisor.md @@ -2,7 +2,7 @@ title: Greatest Common Divisor description: Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios. author: JanluOfficial -tags: math,division +tags: math,division,number-theory,algebra --- ```js diff --git a/snippets/javascript/mathematical-functions/least-common-multiple.md b/snippets/javascript/mathematical-functions/least-common-multiple.md new file mode 100644 index 00000000..40ac9721 --- /dev/null +++ b/snippets/javascript/mathematical-functions/least-common-multiple.md @@ -0,0 +1,25 @@ +--- +title: Least common multiple +description: Computes the least common multiple (LCM) of two numbers 𝑎 and b. The LCM is the smallest positive integer that is divisible by both a and b. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function lcm(a, b) { + function gcd(x, y) { + while (y !== 0) { + const temp = y; + y = x % y; + x = temp; + } + return Math.abs(x); + } + return Math.abs(a * b) / gcd(a, b); +} + +// Usage: +lcm(12,16); // Returns: 48 +lcm(8,20); // Returns: 40 +lcm(16,17); // Returns: 272 +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/matrix-multiplication.md b/snippets/javascript/mathematical-functions/matrix-multiplication.md new file mode 100644 index 00000000..65799530 --- /dev/null +++ b/snippets/javascript/mathematical-functions/matrix-multiplication.md @@ -0,0 +1,34 @@ +--- +title: Matrix Multiplication +description: Multiplies two matrices, where the number of columns in the first matrix equals the number of rows in the second. +author: JanluOfficial +tags: math,matrix-algebra +--- + +```js +function matrixMultiply(A, B) { + const rowsA = A.length; + const colsA = A[0].length; + const rowsB = B.length; + const colsB = B[0].length; + + if (colsA !== rowsB) { + throw new Error('Number of columns of A must equal the number of rows of B'); + } + + let result = Array.from({ length: rowsA }, () => Array(colsB).fill(0)); + + for (let i = 0; i < rowsA; i++) { + for (let j = 0; j < colsB; j++) { + for (let k = 0; k < colsA; k++) { + result[i][j] += A[i][k] * B[k][j]; + } + } + } + + return result; +} + +// Usage: +matrixMultiply([[1, 2], [3, 4]], [[5, 6], [7, 8]]); // Returns: [[19, 22], [43, 50]] +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/modular-inverse.md b/snippets/javascript/mathematical-functions/modular-inverse.md new file mode 100644 index 00000000..313ab46a --- /dev/null +++ b/snippets/javascript/mathematical-functions/modular-inverse.md @@ -0,0 +1,33 @@ +--- +title: Modular Inverse +description: Computes the modular multiplicative inverse of a number a under modulo m, which is the integer x such that (a*x) mod m=1. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function modInverse(a, m) { + function extendedGCD(a, b) { + if (b === 0) { + return { gcd: a, x: 1, y: 0 }; + } + const { gcd, x: x1, y: y1 } = extendedGCD(b, a % b); + const x = y1; + const y = x1 - Math.floor(a / b) * y1; + return { gcd, x, y }; + } + + const { gcd, x } = extendedGCD(a, m); + + if (gcd !== 1) { + return null; + } + + return (x % m + m) % m; +} + +// Usage: +modInverse(3, 26); // Returns: 9 +modInverse(10, 17); // Returns: 12 +modInverse(6, 9); // Returns: null +``` \ No newline at end of file diff --git a/snippets/javascript/mathematical-functions/prime-number.md b/snippets/javascript/mathematical-functions/prime-number.md new file mode 100644 index 00000000..90e68e2a --- /dev/null +++ b/snippets/javascript/mathematical-functions/prime-number.md @@ -0,0 +1,24 @@ +--- +title: Prime Number +description: Calculates the number of combinations (denoted as C(n,r) or "n choose r"), which determines how many ways you can select r items from n items without considering the order. +author: JanluOfficial +tags: math,number-theory,algebra +--- + +```js +function isPrime(num) { + if (num <= 1) return false; // 0 and 1 are not prime numbers + if (num <= 3) return true; // 2 and 3 are prime numbers + if (num % 2 === 0 || num % 3 === 0) return false; // Exclude multiples of 2 and 3 + + // Check divisors from 5 to √num, skipping multiples of 2 and 3 + for (let i = 5; i * i <= num; i += 6) { + if (num % i === 0 || num % (i + 2) === 0) return false; + } + return true; +} + +// Usage: +isPrime(69); // Returns: false +isPrime(17); // Returns: true +``` \ No newline at end of file From a14e323e16b1d9e7d21e330589587ce5f4f23647 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 19:40:22 +0100 Subject: [PATCH 62/84] Fix cuz description was messed up --- snippets/javascript/mathematical-functions/prime-number.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snippets/javascript/mathematical-functions/prime-number.md b/snippets/javascript/mathematical-functions/prime-number.md index 90e68e2a..028b8567 100644 --- a/snippets/javascript/mathematical-functions/prime-number.md +++ b/snippets/javascript/mathematical-functions/prime-number.md @@ -1,6 +1,6 @@ --- title: Prime Number -description: Calculates the number of combinations (denoted as C(n,r) or "n choose r"), which determines how many ways you can select r items from n items without considering the order. +description: Checks if a number is a prime number or not. author: JanluOfficial tags: math,number-theory,algebra --- From 6c0959ad5b6088ba2762b45aad26a0e8836cc749 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Sat, 4 Jan 2025 19:51:58 +0100 Subject: [PATCH 63/84] Consolidate for the Prime Number Description --- public/consolidated/javascript.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 135a8a1e..2c67ae51 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -461,7 +461,7 @@ }, { "title": "Prime Number", - "description": "Calculates the number of combinations (denoted as C(n,r) or \"n choose r\"), which determines how many ways you can select r items from n items without considering the order.", + "description": "Checks if a number is a prime number or not.", "author": "JanluOfficial", "tags": [ "math", From 2d59cca5615f36b0e1dc22f5c4f14216e7fa04e7 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 18:57:19 +0000 Subject: [PATCH 64/84] Update consolidated snippets --- public/consolidated/c.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 1588cd69..a9258611 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] } From e40c8123d6480f5c196e3b3121b8b30d27c91548 Mon Sep 17 00:00:00 2001 From: ACR1209 Date: Sat, 4 Jan 2025 13:59:24 -0500 Subject: [PATCH 65/84] Rename function to transform from snake_case to PascalCase in Ruby snippet --- .../transform-from-snake-case-to-pascal-case.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md b/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md index 92a51a51..8a8ef980 100644 --- a/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md +++ b/snippets/ruby/string-manipulation/transform-from-snake-case-to-pascal-case.md @@ -6,7 +6,7 @@ tags: string,convert,snake-case,pascal-case --- ```rb -def snake_to_camel(str) +def snake_to_pascal(str) str.split('_').map.with_index { |word, index| word.capitalize }.join @@ -14,5 +14,5 @@ end # Usage: snake_case = "snake_case_to_pascal_case" -puts snake_to_camel(snake_case) # Output: "SnakeCaseToPascalCase" +puts snake_to_pascal(snake_case) # Output: "SnakeCaseToPascalCase" ``` From bebe1c7683783971b39550c49428612a321d7383 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 19:01:06 +0000 Subject: [PATCH 66/84] Update consolidated snippets --- public/consolidated/ruby.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json index 2432be6d..5d1da9f7 100644 --- a/public/consolidated/ruby.json +++ b/public/consolidated/ruby.json @@ -204,7 +204,7 @@ "pascal-case" ], "contributors": [], - "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_camel(snake_case) # Output: \"SnakeCaseToPascalCase\"\n" + "code": "def snake_to_pascal(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_pascal(snake_case) # Output: \"SnakeCaseToPascalCase\"\n" }, { "title": "Truncate String", From 0ac16f027b6589b6bb9967b04486ce2187f25b7e Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sat, 4 Jan 2025 19:04:34 +0000 Subject: [PATCH 67/84] Update consolidated snippets --- public/consolidated/c.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 1588cd69..a9258611 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] } From d3c46174b3cf93588a40abb01c160b7ec1ad36d7 Mon Sep 17 00:00:00 2001 From: Typfout <100569212+timomen@users.noreply.github.com> Date: Sat, 4 Jan 2025 20:25:43 +0100 Subject: [PATCH 68/84] changed typo debuging to debugging --- snippets/cpp/{debuging => debugging}/vector-print.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename snippets/cpp/{debuging => debugging}/vector-print.md (100%) diff --git a/snippets/cpp/debuging/vector-print.md b/snippets/cpp/debugging/vector-print.md similarity index 100% rename from snippets/cpp/debuging/vector-print.md rename to snippets/cpp/debugging/vector-print.md From a92a93f23b828e7b6a59850f2a9481e202fc84b3 Mon Sep 17 00:00:00 2001 From: christianfuttrup Date: Sat, 4 Jan 2025 20:51:23 +0100 Subject: [PATCH 69/84] Revert "Update consolidated snippets" This reverts commit 2d59cca5615f36b0e1dc22f5c4f14216e7fa04e7. --- public/consolidated/c.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/public/consolidated/c.json b/public/consolidated/c.json index a9258611..1588cd69 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" } ] } From 8f6de4d2cbb8bce5465e30d6d0c2c41f094f8c5d Mon Sep 17 00:00:00 2001 From: Duzzenn <109883788+davidanukam@users.noreply.github.com> Date: Sat, 4 Jan 2025 16:07:25 -0500 Subject: [PATCH 70/84] Update zip-two-lists.md --- .../java/array-manipulation/zip-two-lists.md | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/snippets/java/array-manipulation/zip-two-lists.md b/snippets/java/array-manipulation/zip-two-lists.md index 739a21fc..800d2ce9 100644 --- a/snippets/java/array-manipulation/zip-two-lists.md +++ b/snippets/java/array-manipulation/zip-two-lists.md @@ -10,22 +10,17 @@ import java.util.*; // Importing utility classes for List and Arrays import java.util.stream.IntStream; // Importing IntStream for range and mapping import java.util.stream.Collectors; // Importing Collectors for collecting stream results -public class Main { - // Generic method to zip two lists into a list of paired elements - public static List> zip(List list1, List list2) { - // Create pairs by iterating through the indices of both lists - return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list - .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i - .collect(Collectors.toList()); // Collect the pairs into a List - } +public List> zip(List list1, List list2) { + // Create pairs by iterating through the indices of both lists + return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list + .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i + .collect(Collectors.toList()); // Collect the pairs into a List +} - public static void main(String[] args) { - // Usage: - List arr1 = Arrays.asList("a", "b", "c"); - List arr2 = Arrays.asList(1, 2, 3); - List> zipped = zip(arr1, arr2); +// Usage: +List arr1 = Arrays.asList("a", "b", "c"); +List arr2 = Arrays.asList(1, 2, 3); +List> zipped = zip(arr1, arr2); - System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]] - } -} +System.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]] ``` From 0ef3160eca93a670eafc7e7b796a127758535020 Mon Sep 17 00:00:00 2001 From: pvictor Date: Sat, 4 Jan 2025 23:51:48 +0200 Subject: [PATCH 71/84] snippets: hex to rgb color --- public/consolidated/c.json | 2 +- public/consolidated/javascript.json | 11 +++++++++ .../color-manipulation/hex-to-rgb-color.md | 24 +++++++++++++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 snippets/javascript/color-manipulation/hex-to-rgb-color.md diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 1588cd69..a9258611 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -38,7 +38,7 @@ "numbers" ], "contributors": [], - "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // simply use printf after this to print swapped values\n" + "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] } diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 2e8c8f97..72ef536e 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -80,6 +80,17 @@ { "categoryName": "Color Manipulation", "snippets": [ + { + "title": "Hex to RGB Color", + "description": "Converts hexadecimal color code to RGB color values.", + "author": "pvictordev", + "tags": [ + "color", + "conversion" + ], + "contributors": [], + "code": "function hexToRgb(r, g, b) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n const hex = x.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n })\n .join(\"\")\n );\n},\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n" + }, { "title": "RGB to Hex Color", "description": "Converts RGB color values to hexadecimal color code.", diff --git a/snippets/javascript/color-manipulation/hex-to-rgb-color.md b/snippets/javascript/color-manipulation/hex-to-rgb-color.md new file mode 100644 index 00000000..5ff39cd5 --- /dev/null +++ b/snippets/javascript/color-manipulation/hex-to-rgb-color.md @@ -0,0 +1,24 @@ +--- +title: Hex to RGB Color +description: Converts hexadecimal color code to RGB color values. +author: pvictordev +tags: color,conversion +--- + +```js +function hexToRgb(r, g, b) { + return ( + "#" + + [r, g, b] + .map((x) => { + const hex = x.toString(16); + return hex.length === 1 ? "0" + hex : hex; + }) + .join("") + ); +}, + +// Usage: +console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 } +console.log(hexToRgb("#ffff")); // { r: 0, g: 255, b: 255 } +``` \ No newline at end of file From 4f58819a56ab07b308b9acb013e64f434c90d867 Mon Sep 17 00:00:00 2001 From: pvictor Date: Sat, 4 Jan 2025 23:53:22 +0200 Subject: [PATCH 72/84] snippets: rgb to hsl color --- public/consolidated/javascript.json | 11 +++++ .../color-manipulation/rgb-to-hsl-color.md | 42 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 snippets/javascript/color-manipulation/rgb-to-hsl-color.md diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 72ef536e..2379d9c7 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -101,6 +101,17 @@ ], "contributors": [], "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n" + }, + { + "title": "RGB to HSL Color", + "description": "Converts RGB color values to HSL color values.", + "author": "pvictordev", + "tags": [ + "color", + "conversion" + ], + "contributors": [], + "code": "function rgbToHsl(r, g, b) {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n let h, s, l;\n l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0;\n } else {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n" } ] }, diff --git a/snippets/javascript/color-manipulation/rgb-to-hsl-color.md b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md new file mode 100644 index 00000000..d333e043 --- /dev/null +++ b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md @@ -0,0 +1,42 @@ +--- +title: RGB to HSL Color +description: Converts RGB color values to HSL color values. +author: pvictordev +tags: color,conversion +--- + +```js +function rgbToHsl(r, g, b) { + r /= 255; + g /= 255; + b /= 255; + const max = Math.max(r, g, b), + min = Math.min(r, g, b); + let h, s, l; + l = (max + min) / 2; + + if (max === min) { + h = s = 0; + } else { + const d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) }; +} + +// Usage: +console.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 } +console.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 } +``` \ No newline at end of file From 5036b30fdc21d0fffe5142e9aa6dbd7b11eedbbe Mon Sep 17 00:00:00 2001 From: pvictor Date: Sun, 5 Jan 2025 00:03:49 +0200 Subject: [PATCH 73/84] snippets: hsl to rgb color --- public/consolidated/javascript.json | 11 ++++++ .../color-manipulation/hsl-to-rgb-color.md | 34 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 snippets/javascript/color-manipulation/hsl-to-rgb-color.md diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 2379d9c7..9e5ea5e6 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -91,6 +91,17 @@ "contributors": [], "code": "function hexToRgb(r, g, b) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n const hex = x.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n })\n .join(\"\")\n );\n},\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n" }, + { + "title": "HSL to RGB Color", + "description": "Converts HSL color values to RGB color values.", + "author": "pvictordev", + "tags": [ + "color", + "conversion" + ], + "contributors": [], + "code": "function hslToRgb(h, s, l) {\n s /= 100;\n l /= 100;\n const c = (1 - Math.abs(2 * l - 1)) * s;\n const x = c * (1 - Math.abs((h / 60) % 2 - 1));\n const m = l - c / 2;\n\n const [r, g, b] = \n h < 60 ? [c, x, 0] :\n h < 120 ? [x, c, 0] :\n h < 180 ? [0, c, x] :\n h < 240 ? [0, x, c] :\n h < 300 ? [x, 0, c] :\n [c, 0, x];\n\n return {\n r: Math.round((r + m) * 255),\n g: Math.round((g + m) * 255),\n b: Math.round((b + m) * 255),\n };\n}\n\n// Usage:\nconsole.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 }\nconsole.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 }\n" + }, { "title": "RGB to Hex Color", "description": "Converts RGB color values to hexadecimal color code.", diff --git a/snippets/javascript/color-manipulation/hsl-to-rgb-color.md b/snippets/javascript/color-manipulation/hsl-to-rgb-color.md new file mode 100644 index 00000000..23390237 --- /dev/null +++ b/snippets/javascript/color-manipulation/hsl-to-rgb-color.md @@ -0,0 +1,34 @@ +--- +title: HSL to RGB Color +description: Converts HSL color values to RGB color values. +author: pvictordev +tags: color,conversion +--- + +```js +function hslToRgb(h, s, l) { + s /= 100; + l /= 100; + const c = (1 - Math.abs(2 * l - 1)) * s; + const x = c * (1 - Math.abs((h / 60) % 2 - 1)); + const m = l - c / 2; + + const [r, g, b] = + h < 60 ? [c, x, 0] : + h < 120 ? [x, c, 0] : + h < 180 ? [0, c, x] : + h < 240 ? [0, x, c] : + h < 300 ? [x, 0, c] : + [c, 0, x]; + + return { + r: Math.round((r + m) * 255), + g: Math.round((g + m) * 255), + b: Math.round((b + m) * 255), + }; +} + +// Usage: +console.log(hslToRgb(14, 100, 60)); // { r: 255, g: 87, b: 51 } +console.log(hslToRgb(0, 0, 100)); // { r: 255, g: 255, b: 255 } +``` \ No newline at end of file From f71db888b37c1380cc3410e0c3cfc58c1800a57a Mon Sep 17 00:00:00 2001 From: pvictor Date: Sun, 5 Jan 2025 00:07:38 +0200 Subject: [PATCH 74/84] refactor: optimized rgb to hsl color --- public/consolidated/javascript.json | 2 +- .../color-manipulation/rgb-to-hsl-color.md | 49 +++++++++---------- 2 files changed, 23 insertions(+), 28 deletions(-) diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index 9e5ea5e6..d2293838 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -122,7 +122,7 @@ "conversion" ], "contributors": [], - "code": "function rgbToHsl(r, g, b) {\n r /= 255;\n g /= 255;\n b /= 255;\n const max = Math.max(r, g, b),\n min = Math.min(r, g, b);\n let h, s, l;\n l = (max + min) / 2;\n\n if (max === min) {\n h = s = 0;\n } else {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n" + "code": "function rgbToHsl(r, g, b) {\n [r, g, b] = [r, g, b].map((v) => v / 255);\n\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const delta = max - min;\n\n const l = (max + min) / 2;\n\n if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) };\n\n const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min);\n\n const h = \n max === r ? ((g - b) / delta + (g < b ? 6 : 0)) :\n max === g ? (b - r) / delta + 2 :\n (r - g) / delta + 4;\n\n return {\n h: Math.round(h * 60), \n s: Math.round(s * 100),\n l: Math.round(l * 100), \n };\n}\n\n// Usage:\nconsole.log(rgbToHsl(255, 87, 51)); // { h: 14, s: 100, l: 60 }\nconsole.log(rgbToHsl(255, 255, 255)); // { h: 0, s: 0, l: 100 }\n" } ] }, diff --git a/snippets/javascript/color-manipulation/rgb-to-hsl-color.md b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md index d333e043..51e29a86 100644 --- a/snippets/javascript/color-manipulation/rgb-to-hsl-color.md +++ b/snippets/javascript/color-manipulation/rgb-to-hsl-color.md @@ -7,33 +7,28 @@ tags: color,conversion ```js function rgbToHsl(r, g, b) { - r /= 255; - g /= 255; - b /= 255; - const max = Math.max(r, g, b), - min = Math.min(r, g, b); - let h, s, l; - l = (max + min) / 2; - - if (max === min) { - h = s = 0; - } else { - const d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch (max) { - case r: - h = (g - b) / d + (g < b ? 6 : 0); - break; - case g: - h = (b - r) / d + 2; - break; - case b: - h = (r - g) / d + 4; - break; - } - h /= 6; - } - return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) }; + [r, g, b] = [r, g, b].map((v) => v / 255); + + const max = Math.max(r, g, b); + const min = Math.min(r, g, b); + const delta = max - min; + + const l = (max + min) / 2; + + if (delta === 0) return { h: 0, s: 0, l: Math.round(l * 100) }; + + const s = l > 0.5 ? delta / (2 - max - min) : delta / (max + min); + + const h = + max === r ? ((g - b) / delta + (g < b ? 6 : 0)) : + max === g ? (b - r) / delta + 2 : + (r - g) / delta + 4; + + return { + h: Math.round(h * 60), + s: Math.round(s * 100), + l: Math.round(l * 100), + }; } // Usage: From 59a44e6acb86b3fa4b2674c5f484c5887e5d8746 Mon Sep 17 00:00:00 2001 From: Gihan Rangana Date: Sun, 5 Jan 2025 09:36:48 +0530 Subject: [PATCH 75/84] updated the requested changes --- .github/workflows/auto-sync.yml | 26 -------------------- snippets/scss/typography/px-to-rem-helper.md | 4 +-- 2 files changed, 2 insertions(+), 28 deletions(-) delete mode 100644 .github/workflows/auto-sync.yml diff --git a/.github/workflows/auto-sync.yml b/.github/workflows/auto-sync.yml deleted file mode 100644 index dd3fb1e7..00000000 --- a/.github/workflows/auto-sync.yml +++ /dev/null @@ -1,26 +0,0 @@ -name: Auto Sync with Main Repo - -on: - push: - branches: - - main - -jobs: - sync: - runs-on: ubuntu-latest - - steps: - - name: Checkout Target Repository - uses: actions/checkout@v2 - with: - repository: gihanrangana/quicksnip - ref: main - token: ${{ secrets.GITHUB_TOKEN }} - - - name: Sync with Main Repository - run: | - git remote add upstream https://github.com/gihanrangana/quicksnip.git - git fetch upstream - git checkout main - git merge upstream/main - git push origin main diff --git a/snippets/scss/typography/px-to-rem-helper.md b/snippets/scss/typography/px-to-rem-helper.md index b292ee12..17e154d0 100644 --- a/snippets/scss/typography/px-to-rem-helper.md +++ b/snippets/scss/typography/px-to-rem-helper.md @@ -2,7 +2,7 @@ title: PX to REM Helper description: This function will convert px values to rem values. author: gihanrangana -tags: sass,function,pixel,rem,px-to-rem,css +tags: function,pixel,rem,px-to-rem --- ```scss @@ -10,7 +10,7 @@ tags: sass,function,pixel,rem,px-to-rem,css @return ($px / $base) * 1rem; } -// Usage +// Usage: div { font-size: px-to-rem(12px); // Output: 0.75rem padding: px-to-rem(16px); // Output: 1rem From bd4f36938342bdc05be6e739aa49f453dcbc6609 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sun, 5 Jan 2025 04:07:11 +0000 Subject: [PATCH 76/84] Update consolidated snippets --- public/consolidated/scss.json | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/public/consolidated/scss.json b/public/consolidated/scss.json index a7ffc666..5a2fbeaa 100644 --- a/public/consolidated/scss.json +++ b/public/consolidated/scss.json @@ -161,15 +161,13 @@ "description": "This function will convert px values to rem values.", "author": "gihanrangana", "tags": [ - "sass", "function", "pixel", "rem", - "px-to-rem", - "css" + "px-to-rem" ], "contributors": [], - "code": "@function px-to-rem($px, $base: 16px) {\n @return ($px / $base) * 1rem;\n}\n\n// Usage\ndiv {\n font-size: px-to-rem(12px); // Output: 0.75rem\n padding: px-to-rem(16px); // Output: 1rem\n margin: px-to-rem(32px) // Output 2rem\n}\n" + "code": "@function px-to-rem($px, $base: 16px) {\n @return ($px / $base) * 1rem;\n}\n\n// Usage:\ndiv {\n font-size: px-to-rem(12px); // Output: 0.75rem\n padding: px-to-rem(16px); // Output: 1rem\n margin: px-to-rem(32px) // Output 2rem\n}\n" }, { "title": "Text Gradient", From 92f1f4f05372ff786adcd978d964b14d83230700 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Sun, 5 Jan 2025 04:08:29 +0000 Subject: [PATCH 77/84] Update consolidated snippets --- public/consolidated/cpp.json | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index 6427f04f..81eb1c04 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -32,6 +32,23 @@ } ] }, + { + "categoryName": "Debugging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "categoryName": "Debuging", "snippets": [ From 755ae1742f7a84ee6cb08adb85e9d32618fe9457 Mon Sep 17 00:00:00 2001 From: pvictor Date: Sun, 5 Jan 2025 09:19:32 +0200 Subject: [PATCH 78/84] fix: hex to rgb color --- public/consolidated/javascript.json | 2 +- .../color-manipulation/hex-to-rgb-color.md | 26 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json index d2293838..d6f23739 100644 --- a/public/consolidated/javascript.json +++ b/public/consolidated/javascript.json @@ -89,7 +89,7 @@ "conversion" ], "contributors": [], - "code": "function hexToRgb(r, g, b) {\n return (\n \"#\" +\n [r, g, b]\n .map((x) => {\n const hex = x.toString(16);\n return hex.length === 1 ? \"0\" + hex : hex;\n })\n .join(\"\")\n );\n},\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n" + "code": "function hexToRgb(hex) {\n let sanitizedHex = hex.startsWith(\"#\") ? hex.slice(1) : hex;\n\n if (sanitizedHex.length === 3) {\n sanitizedHex = [...sanitizedHex].map((char) => char + char).join(\"\");\n }\n\n const bigint = parseInt(sanitizedHex, 16);\n\n return {\n r: (bigint >> 16) & 0xff, \n g: (bigint >> 8) & 0xff, \n b: bigint & 0xff, \n };\n}\n\n// Usage:\nconsole.log(hexToRgb(\"#ff5733\")); // { r: 255, g: 87, b: 51 }\nconsole.log(hexToRgb(\"#ffff\")); // { r: 0, g: 255, b: 255 }\n" }, { "title": "HSL to RGB Color", diff --git a/snippets/javascript/color-manipulation/hex-to-rgb-color.md b/snippets/javascript/color-manipulation/hex-to-rgb-color.md index 5ff39cd5..3d0108d1 100644 --- a/snippets/javascript/color-manipulation/hex-to-rgb-color.md +++ b/snippets/javascript/color-manipulation/hex-to-rgb-color.md @@ -6,17 +6,21 @@ tags: color,conversion --- ```js -function hexToRgb(r, g, b) { - return ( - "#" + - [r, g, b] - .map((x) => { - const hex = x.toString(16); - return hex.length === 1 ? "0" + hex : hex; - }) - .join("") - ); -}, +function hexToRgb(hex) { + let sanitizedHex = hex.startsWith("#") ? hex.slice(1) : hex; + + if (sanitizedHex.length === 3) { + sanitizedHex = [...sanitizedHex].map((char) => char + char).join(""); + } + + const bigint = parseInt(sanitizedHex, 16); + + return { + r: (bigint >> 16) & 0xff, + g: (bigint >> 8) & 0xff, + b: bigint & 0xff, + }; +} // Usage: console.log(hexToRgb("#ff5733")); // { r: 255, g: 87, b: 51 } From 2a5055a8e233514392fb299b27c5a965a5222dbc Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sun, 5 Jan 2025 15:22:50 +0530 Subject: [PATCH 79/84] fixed package-lock.json --- package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package-lock.json b/package-lock.json index e45de524..66d58886 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3585,9 +3585,9 @@ "node": ">=0.4.x" } }, - "node_modules/motion/react": { + "node_modules/framer-motion": { "version": "11.15.0", - "resolved": "https://registry.npmjs.org/motion/react/-/motion/react-11.15.0.tgz", + "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.15.0.tgz", "integrity": "sha512-MLk8IvZntxOMg7lDBLw2qgTHHv664bYoYmnFTmE0Gm/FW67aOJk0WM3ctMcG+Xhcv+vh5uyyXwxvxhSeJzSe+w==", "license": "MIT", "dependencies": { @@ -4672,7 +4672,7 @@ "integrity": "sha512-iZ7dwADQJWGsqsSkBhNHdI2LyYWU+hA1Nhy357wCLZq1yHxGImgt3l7Yv0HT/WOskcYDq9nxdedyl4zUv7UFFw==", "license": "MIT", "dependencies": { - "motion/react": "^11.15.0", + "framer-motion": "^11.15.0", "tslib": "^2.4.0" }, "peerDependencies": { From 8a1352c7de47ceb7fc31565414db53621e536277 Mon Sep 17 00:00:00 2001 From: Yugveer Singh Date: Sun, 5 Jan 2025 16:00:31 +0530 Subject: [PATCH 80/84] lowered the layout animation duration and changed the easing --- src/components/SnippetList.tsx | 4 ++-- src/components/SnippetModal.tsx | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/components/SnippetList.tsx b/src/components/SnippetList.tsx index 0378f4f3..1b96925b 100644 --- a/src/components/SnippetList.tsx +++ b/src/components/SnippetList.tsx @@ -60,8 +60,8 @@ const SnippetList = () => { }, }} transition={{ - type: "spring", - duration: shouldReduceMotion ? 0 : 0.5, + ease: [0, 0.75, 0.25, 1], + duration: shouldReduceMotion ? 0 : 0.25, }} > = ({ className="modal | flow" data-flow-space="lg" layoutId={`${language}-${snippet.title}`} - transition={{ type: "spring", duration: shouldReduceMotion ? 0 : 0.5 }} + transition={{ + ease: [0, 0.75, 0.25, 1], + duration: shouldReduceMotion ? 0 : 0.3, + }} >

    {snippet.title}

    From 581ae003ac6aaed21d95fd0b328ef77f36c738b5 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Sun, 5 Jan 2025 13:51:32 +0100 Subject: [PATCH 81/84] Adding support for CRLF in the parser --- utils/snippetParser.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/utils/snippetParser.js b/utils/snippetParser.js index e7b502f8..c1180f85 100644 --- a/utils/snippetParser.js +++ b/utils/snippetParser.js @@ -27,12 +27,10 @@ function raise(issue, snippet = '') { return null; } -const crlfRegex = /\r\n/gm; const propertyRegex = /^\s+([a-zA-Z]+):\s*(.+)/; -const headerEndCodeStartRegex = /^\s*---\s*```.*\n/; +const headerEndCodeStartRegex = /^\s*---\s*```.*\r?\n/; const codeRegex = /^(.+)```/s function parseSnippet(path, name, text) { - if(crlfRegex.exec(text) !== null) return raise('Found CRLF line endings instead of LF line endings', path); let cursor = 0; const fromCursor = () => text.substring(cursor); @@ -68,7 +66,7 @@ function parseSnippet(path, name, text) { author: properties.author, tags: properties.tags.split(',').map((tag) => tag.trim()).filter((tag) => tag), contributors: 'contributors' in properties ? properties.contributors.split(',').map((contributor) => contributor.trim()).filter((contributor) => contributor) : [], - code: code, + code: code.replace(/\r\n/g, '\n'), } } From 06092c73b0c00065d412edb6c92c870293f4f5d7 Mon Sep 17 00:00:00 2001 From: Mathys-Gasnier Date: Sun, 5 Jan 2025 14:02:21 +0100 Subject: [PATCH 82/84] Removing end of line prettier config as it's not needed anymore --- .prettierrc | 1 - 1 file changed, 1 deletion(-) diff --git a/.prettierrc b/.prettierrc index 453861ee..f70b340c 100644 --- a/.prettierrc +++ b/.prettierrc @@ -7,6 +7,5 @@ "bracketSpacing": true, "bracketSameLine": false, "arrowParens": "always", - "endOfLine": "lf", "jsxSingleQuote": false } From 57cfb364c1aaca047bd0ddc5b55cb082fbf5a56e Mon Sep 17 00:00:00 2001 From: Utkarsh Konwar <91830690+utkarshkonwar@users.noreply.github.com> Date: Mon, 6 Jan 2025 19:45:11 +0530 Subject: [PATCH 83/84] Added Sorting and Search Algorithms to C (#199) --- public/consolidated/c.json | 101 +++++++++++++++++++++++++++ public/consolidated/cpp.json | 18 ++++- public/consolidated/css.json | 63 +++++++++++++++++ public/consolidated/java.json | 18 +++++ snippets/c/search/binary-search.md | 36 ++++++++++ snippets/c/search/linear-search.md | 25 +++++++ snippets/c/sorting/bubble-sort.md | 27 +++++++ snippets/c/sorting/insertion-sort.md | 30 ++++++++ snippets/c/sorting/merge-sort.md | 71 +++++++++++++++++++ snippets/c/sorting/quick-sort.md | 47 +++++++++++++ snippets/c/sorting/selection-sort.md | 33 +++++++++ 11 files changed, 468 insertions(+), 1 deletion(-) create mode 100644 snippets/c/search/binary-search.md create mode 100644 snippets/c/search/linear-search.md create mode 100644 snippets/c/sorting/bubble-sort.md create mode 100644 snippets/c/sorting/insertion-sort.md create mode 100644 snippets/c/sorting/merge-sort.md create mode 100644 snippets/c/sorting/quick-sort.md create mode 100644 snippets/c/sorting/selection-sort.md diff --git a/public/consolidated/c.json b/public/consolidated/c.json index 2343c989..91fb3e81 100644 --- a/public/consolidated/c.json +++ b/public/consolidated/c.json @@ -41,5 +41,106 @@ "code": "#include\nvoid swap(int* num1,int* num2){\n *num1 = *num1 + *num2;\n *num2 = *num1 - *num2;\n *num1 = *num1 - *num2;\n}\n\n// Usage:\nint a = 3,b = 4;\nswap(&a,&b); // swaps the values of the a and b variables\n" } ] + }, + { + "name": "Search", + "snippets": [ + { + "title": "Binary Search ", + "description": "Searches for an element in a sorted array using the Binary Search algorithm.", + "author": "0xHouss", + "tags": [ + "search", + "binarysearch", + "array", + "algorithm" + ], + "contributors": [], + "code": "int binarySearch(int arr[], int low, int high, int x) {\n while (low <= high) {\n int mid = low + (high - low) / 2;\n\n // Check if x is present at mid\n if (arr[mid] == x) {\n return mid;\n }\n\n // If x is smaller, search the left half\n if (arr[mid] > x) {\n high = mid - 1;\n } else { // If x is larger, search the right half\n low = mid + 1;\n }\n }\n return -1; // Element not found\n}\n\n// Usage:\nint arr[] = {2, 3, 4, 10, 40};\nint n = sizeof(arr) / sizeof(arr[0]);\nint x = 10;\nint result = binarySearch(arr, 0, n - 1, x);\n// result = 3 (index of the element 10)\n\n\n" + }, + { + "title": "Linear Search ", + "description": "Searches for an element in an array using the Linear Search algorithm.", + "author": "0xHouss", + "tags": [ + "search", + "linearsearch", + "array", + "algorithm" + ], + "contributors": [], + "code": "int linearSearch(int arr[], int n, int x) {\n for (int i = 0; i < n; i++) {\n if (arr[i] == x) {\n return i; // Element found at index i\n }\n }\n return -1; // Element not found\n}\n\n// Usage:\nint arr[] = {10, 20, 30, 40, 50};\nint n = sizeof(arr) / sizeof(arr[0]);\nint x = 30;\nint result = linearSearch(arr, n, x);\n// result = 2 (index of the element 30)\n\n" + } + ] + }, + { + "name": "Sorting", + "snippets": [ + { + "title": "Bubble Sort ", + "description": "Sorts an array of integers using the Bubble Sort algorithm.", + "author": "0xHouss", + "tags": [ + "sorting", + "bubblesort", + "array", + "algorithm" + ], + "contributors": [], + "code": "void bubbleSort(int arr[], int n) {\n for (int i = 0; i < n - 1; i++) {\n for (int j = 0; j < n - i - 1; j++) {\n if (arr[j] > arr[j + 1]) {\n // Swap arr[j] and arr[j + 1]\n int temp = arr[j];\n arr[j] = arr[j + 1];\n arr[j + 1] = temp;\n }\n }\n }\n}\n\n// Usage:\nint arr[] = {64, 34, 25, 12, 22, 11, 90};\nint n = sizeof(arr) / sizeof(arr[0]);\nbubbleSort(arr, n);\n// Now arr[] is sorted: {11, 12, 22, 25, 34, 64, 90}\n" + }, + { + "title": "Insertion Sort ", + "description": "Sorts an array of integers using the Insertion Sort algorithm.", + "author": "0xHouss", + "tags": [ + "sorting", + "insertionsort", + "array", + "algorithm" + ], + "contributors": [], + "code": "void insertionSort(int arr[], int n) {\n for (int i = 1; i < n; i++) {\n int key = arr[i];\n int j = i - 1;\n\n // Move elements of arr[0..i-1] that are greater than key\n // to one position ahead of their current position\n while (j >= 0 && arr[j] > key) {\n arr[j + 1] = arr[j];\n j--;\n }\n arr[j + 1] = key;\n }\n}\n\n// Usage:\nint arr[] = {12, 11, 13, 5, 6};\nint n = sizeof(arr) / sizeof(arr[0]);\ninsertionSort(arr, n);\n// Now arr[] is sorted: {5, 6, 11, 12, 13}\n\n" + }, + { + "title": "Merge Sort ", + "description": "Sorts an array of integers using the Merge Sort algorithm.", + "author": "0xHouss", + "tags": [ + "sorting", + "mergesort", + "array", + "algorithm" + ], + "contributors": [], + "code": "#include \n\nvoid merge(int arr[], int l, int m, int r) {\n int n1 = m - l + 1;\n int n2 = r - m;\n\n // Temporary arrays\n int L[n1], R[n2];\n\n // Copy data to temporary arrays L[] and R[]\n for (int i = 0; i < n1; i++)\n L[i] = arr[l + i];\n for (int j = 0; j < n2; j++)\n R[j] = arr[m + 1 + j];\n\n int i = 0, j = 0, k = l;\n\n // Merge the temporary arrays back into arr[l..r]\n while (i < n1 && j < n2) {\n if (L[i] <= R[j]) {\n arr[k] = L[i];\n i++;\n } else {\n arr[k] = R[j];\n j++;\n }\n k++;\n }\n\n // Copy remaining elements of L[], if any\n while (i < n1) {\n arr[k] = L[i];\n i++;\n k++;\n }\n\n // Copy remaining elements of R[], if any\n while (j < n2) {\n arr[k] = R[j];\n j++;\n k++;\n }\n}\n\nvoid mergeSort(int arr[], int l, int r) {\n if (l < r) {\n int m = l + (r - l) / 2;\n\n // Sort first and second halves\n mergeSort(arr, l, m);\n mergeSort(arr, m + 1, r);\n\n merge(arr, l, m, r);\n }\n}\n\n// Usage:\nint arr[] = {38, 27, 43, 3, 9, 82, 10};\nint n = sizeof(arr) / sizeof(arr[0]);\nmergeSort(arr, 0, n - 1);\n// Now arr[] is sorted: {3, 9, 10, 27, 38, 43, 82}\n\n" + }, + { + "title": "Quick Sort ", + "description": "Sorts an array of integers using the Quick Sort algorithm.", + "author": "0xHouss", + "tags": [ + "sorting", + "quicksort", + "array", + "algorithm" + ], + "contributors": [], + "code": "int partition(int arr[], int low, int high) {\n int pivot = arr[high]; // Pivot element\n int i = low - 1;\n\n for (int j = low; j < high; j++) {\n if (arr[j] < pivot) {\n i++;\n // Swap arr[i] and arr[j]\n int temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n\n // Swap arr[i + 1] and arr[high] (pivot)\n int temp = arr[i + 1];\n arr[i + 1] = arr[high];\n arr[high] = temp;\n\n return i + 1;\n}\n\nvoid quickSort(int arr[], int low, int high) {\n if (low < high) {\n int pi = partition(arr, low, high);\n\n // Recursively sort elements before and after partition\n quickSort(arr, low, pi - 1);\n quickSort(arr, pi + 1, high);\n }\n}\n\n// Usage:\nint arr[] = {10, 7, 8, 9, 1, 5};\nint n = sizeof(arr) / sizeof(arr[0]);\nquickSort(arr, 0, n - 1);\n// Now arr[] is sorted: {1, 5, 7, 8, 9, 10}\n\n" + }, + { + "title": "Selection Sort ", + "description": "Sorts an array of integers using the Selection Sort algorithm.", + "author": "0xHouss", + "tags": [ + "sorting", + "selectionsort", + "array", + "algorithm" + ], + "contributors": [], + "code": "void selectionSort(int arr[], int n) {\n for (int i = 0; i < n - 1; i++) {\n int minIdx = i;\n\n // Find the minimum element in the unsorted part of the array\n for (int j = i + 1; j < n; j++) {\n if (arr[j] < arr[minIdx]) {\n minIdx = j;\n }\n }\n\n // Swap the found minimum element with the first element of the unsorted part\n int temp = arr[minIdx];\n arr[minIdx] = arr[i];\n arr[i] = temp;\n }\n}\n\n// Usage:\nint arr[] = {64, 25, 12, 22, 11};\nint n = sizeof(arr) / sizeof(arr[0]);\nselectionSort(arr, n);\n// Now arr[] is sorted: {11, 12, 22, 25, 64}\n\n" + } + ] } ] \ No newline at end of file diff --git a/public/consolidated/cpp.json b/public/consolidated/cpp.json index fd38de1b..c121a725 100644 --- a/public/consolidated/cpp.json +++ b/public/consolidated/cpp.json @@ -33,7 +33,6 @@ ] }, { - "categoryName": "Debuging", "name": "Debugging", "snippets": [ { @@ -50,6 +49,23 @@ } ] }, + { + "name": "Debuging", + "snippets": [ + { + "title": "Vector Print", + "description": "Overloads the << operator to print the contents of a vector just like in python.", + "author": "Mohamed-faaris", + "tags": [ + "printing", + "debuging", + "vector" + ], + "contributors": [], + "code": "#include \n#include \n\ntemplate \nstd::ostream& operator<<(std::ostream& os, const std::vector& vec) {\n os << \"[\"; \n for (size_t i = 0; i < vec.size(); ++i) {\n os << vec[i]; // Print each vector element\n if (i != vec.size() - 1) {\n os << \", \"; // Add separator\n }\n }\n os << \"]\"; \n return os; // Return the stream\n}\n\n// Usage:\nstd::vector numbers = {1, 2, 3, 4, 5};\nstd::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]\n\n" + } + ] + }, { "name": "Math And Numbers", "snippets": [ diff --git a/public/consolidated/css.json b/public/consolidated/css.json index 359088c9..0f19249e 100644 --- a/public/consolidated/css.json +++ b/public/consolidated/css.json @@ -1,4 +1,67 @@ [ + { + "name": "Animations", + "snippets": [ + { + "title": "Blink Animation", + "description": "Adds an infinite blinking animation to an element", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "blink", + "infinite" + ], + "contributors": [], + "code": ".blink {\n animation: blink 1s linear infinite;\n}\n\n@keyframes blink{\n 0%{\n opacity: 0;\n }\n 50%{\n opacity: 1;\n }\n 100%{\n opacity: 0;\n }\n}\n" + }, + { + "title": "Pulse Animation", + "description": "Adds a smooth pulsing animation with opacity and scale effects", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "pulse", + "pulse-scale" + ], + "contributors": [], + "code": ".pulse {\n animation: pulse 2s ease-in-out infinite;\n}\n\n@keyframes pulse {\n 0% {\n opacity: 0.5;\n transform: scale(1);\n }\n 50% {\n opacity: 1;\n transform: scale(1.05);\n }\n 100% {\n opacity: 0.5;\n transform: scale(1);\n }\n}\n" + }, + { + "title": "Shake Animation", + "description": "Adds a shake animation ( commonly used to mark invalid fields )", + "author": "AlsoKnownAs-Ax", + "tags": [ + "shake", + "shake-horizontal" + ], + "contributors": [], + "code": ".shake {\n animation: shake .5s ease-in-out;\n}\n\n@keyframes shake {\n 0%, 100% {\n transform: translateX(0);\n }\n 25% {\n transform: translateX(-10px);\n }\n 50% {\n transform: translateX(10px);\n }\n 75% {\n transform: translateX(-10px);\n }\n}\n" + }, + { + "title": "Slide-in Animation", + "description": "Adds a slide-in from the right side of the screen", + "author": "AlsoKnownAs-Ax", + "tags": [ + "animation", + "slide-in", + "slide-right" + ], + "contributors": [], + "code": ".slide-in {\n animation: slide-in 1s ease-in-out;\n}\n\n@keyframes slide-in {\n from {\n scale: 300% 1;\n translate: 150vw 0;\n }\n\n to {\n scale: 100% 1;\n translate: 0 0;\n }\n}\n" + }, + { + "title": "Typewriter Animation", + "description": "Adds a typewriter animation + blinking cursor", + "author": "AlsoKnownAs-Ax", + "tags": [ + "blinking", + "typewriter" + ], + "contributors": [], + "code": "
    \n
    \n

    Typerwriter Animation

    \n
    \n
    \n```\n\n```css\n .typewriter{\n display: flex;\n justify-content: center;\n }\n\n .typewriter p {\n overflow: hidden;\n font-size: 1.5rem;\n font-family: monospace;\n border-right: 1px solid;\n margin-inline: auto;\n white-space: nowrap;\n /* The cursor will inherit the text's color by default */\n /* border-color: red */ \n /* Steps: number of chars (better to set directly in js)*/\n animation: typing 3s steps(21) forwards,\n blink 1s step-end infinite;\n }\n\n @keyframes typing{\n from{\n width: 0%\n }\n to{\n width: 100%\n }\n }\n\n @keyframes blink{\n 50%{\n border-color: transparent;\n }\n }\n" + } + ] + }, { "name": "Buttons", "snippets": [ diff --git a/public/consolidated/java.json b/public/consolidated/java.json index 3a36e17d..f972f5e0 100644 --- a/public/consolidated/java.json +++ b/public/consolidated/java.json @@ -1,4 +1,22 @@ [ + { + "name": "Array Manipulation", + "snippets": [ + { + "title": "Zip Two Lists", + "description": "Zips two lists into a list of paired elements, combining corresponding elements from both lists.", + "author": "davidanukam", + "tags": [ + "lists", + "zip", + "stream-api", + "collections" + ], + "contributors": [], + "code": "import java.util.*; // Importing utility classes for List and Arrays\nimport java.util.stream.IntStream; // Importing IntStream for range and mapping\nimport java.util.stream.Collectors; // Importing Collectors for collecting stream results\n\npublic List> zip(List
    list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList arr1 = Arrays.asList(\"a\", \"b\", \"c\");\nList arr2 = Arrays.asList(1, 2, 3);\nList> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n" + } + ] + }, { "name": "Basics", "snippets": [ diff --git a/snippets/c/search/binary-search.md b/snippets/c/search/binary-search.md new file mode 100644 index 00000000..7f65d37e --- /dev/null +++ b/snippets/c/search/binary-search.md @@ -0,0 +1,36 @@ +--- +title: Binary Search +description: Searches for an element in a sorted array using the Binary Search algorithm. +author: 0xHouss +tags: search,binarysearch,array,algorithm +--- + +```c +int binarySearch(int arr[], int low, int high, int x) { + while (low <= high) { + int mid = low + (high - low) / 2; + + // Check if x is present at mid + if (arr[mid] == x) { + return mid; + } + + // If x is smaller, search the left half + if (arr[mid] > x) { + high = mid - 1; + } else { // If x is larger, search the right half + low = mid + 1; + } + } + return -1; // Element not found +} + +// Usage: +int arr[] = {2, 3, 4, 10, 40}; +int n = sizeof(arr) / sizeof(arr[0]); +int x = 10; +int result = binarySearch(arr, 0, n - 1, x); +// result = 3 (index of the element 10) + + +``` \ No newline at end of file diff --git a/snippets/c/search/linear-search.md b/snippets/c/search/linear-search.md new file mode 100644 index 00000000..3e6f4f29 --- /dev/null +++ b/snippets/c/search/linear-search.md @@ -0,0 +1,25 @@ +--- +title: Linear Search +description: Searches for an element in an array using the Linear Search algorithm. +author: 0xHouss +tags: search,linearsearch,array,algorithm +--- + +```c +int linearSearch(int arr[], int n, int x) { + for (int i = 0; i < n; i++) { + if (arr[i] == x) { + return i; // Element found at index i + } + } + return -1; // Element not found +} + +// Usage: +int arr[] = {10, 20, 30, 40, 50}; +int n = sizeof(arr) / sizeof(arr[0]); +int x = 30; +int result = linearSearch(arr, n, x); +// result = 2 (index of the element 30) + +``` \ No newline at end of file diff --git a/snippets/c/sorting/bubble-sort.md b/snippets/c/sorting/bubble-sort.md new file mode 100644 index 00000000..e6c81508 --- /dev/null +++ b/snippets/c/sorting/bubble-sort.md @@ -0,0 +1,27 @@ +--- +title: Bubble Sort +description: Sorts an array of integers using the Bubble Sort algorithm. +author: 0xHouss +tags: sorting,bubblesort,array,algorithm +--- + +```c +void bubbleSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + // Swap arr[j] and arr[j + 1] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +// Usage: +int arr[] = {64, 34, 25, 12, 22, 11, 90}; +int n = sizeof(arr) / sizeof(arr[0]); +bubbleSort(arr, n); +// Now arr[] is sorted: {11, 12, 22, 25, 34, 64, 90} +``` \ No newline at end of file diff --git a/snippets/c/sorting/insertion-sort.md b/snippets/c/sorting/insertion-sort.md new file mode 100644 index 00000000..c26cf552 --- /dev/null +++ b/snippets/c/sorting/insertion-sort.md @@ -0,0 +1,30 @@ +--- +title: Insertion Sort +description: Sorts an array of integers using the Insertion Sort algorithm. +author: 0xHouss +tags: sorting,insertionsort,array,algorithm +--- + +```c +void insertionSort(int arr[], int n) { + for (int i = 1; i < n; i++) { + int key = arr[i]; + int j = i - 1; + + // Move elements of arr[0..i-1] that are greater than key + // to one position ahead of their current position + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j--; + } + arr[j + 1] = key; + } +} + +// Usage: +int arr[] = {12, 11, 13, 5, 6}; +int n = sizeof(arr) / sizeof(arr[0]); +insertionSort(arr, n); +// Now arr[] is sorted: {5, 6, 11, 12, 13} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/merge-sort.md b/snippets/c/sorting/merge-sort.md new file mode 100644 index 00000000..71fc0315 --- /dev/null +++ b/snippets/c/sorting/merge-sort.md @@ -0,0 +1,71 @@ +--- +title: Merge Sort +description: Sorts an array of integers using the Merge Sort algorithm. +author: 0xHouss +tags: sorting,mergesort,array,algorithm +--- + +```c +#include + +void merge(int arr[], int l, int m, int r) { + int n1 = m - l + 1; + int n2 = r - m; + + // Temporary arrays + int L[n1], R[n2]; + + // Copy data to temporary arrays L[] and R[] + for (int i = 0; i < n1; i++) + L[i] = arr[l + i]; + for (int j = 0; j < n2; j++) + R[j] = arr[m + 1 + j]; + + int i = 0, j = 0, k = l; + + // Merge the temporary arrays back into arr[l..r] + while (i < n1 && j < n2) { + if (L[i] <= R[j]) { + arr[k] = L[i]; + i++; + } else { + arr[k] = R[j]; + j++; + } + k++; + } + + // Copy remaining elements of L[], if any + while (i < n1) { + arr[k] = L[i]; + i++; + k++; + } + + // Copy remaining elements of R[], if any + while (j < n2) { + arr[k] = R[j]; + j++; + k++; + } +} + +void mergeSort(int arr[], int l, int r) { + if (l < r) { + int m = l + (r - l) / 2; + + // Sort first and second halves + mergeSort(arr, l, m); + mergeSort(arr, m + 1, r); + + merge(arr, l, m, r); + } +} + +// Usage: +int arr[] = {38, 27, 43, 3, 9, 82, 10}; +int n = sizeof(arr) / sizeof(arr[0]); +mergeSort(arr, 0, n - 1); +// Now arr[] is sorted: {3, 9, 10, 27, 38, 43, 82} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/quick-sort.md b/snippets/c/sorting/quick-sort.md new file mode 100644 index 00000000..be259147 --- /dev/null +++ b/snippets/c/sorting/quick-sort.md @@ -0,0 +1,47 @@ +--- +title: Quick Sort +description: Sorts an array of integers using the Quick Sort algorithm. +author: 0xHouss +tags: sorting,quicksort,array,algorithm +--- + +```c +int partition(int arr[], int low, int high) { + int pivot = arr[high]; // Pivot element + int i = low - 1; + + for (int j = low; j < high; j++) { + if (arr[j] < pivot) { + i++; + // Swap arr[i] and arr[j] + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + // Swap arr[i + 1] and arr[high] (pivot) + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + + return i + 1; +} + +void quickSort(int arr[], int low, int high) { + if (low < high) { + int pi = partition(arr, low, high); + + // Recursively sort elements before and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +// Usage: +int arr[] = {10, 7, 8, 9, 1, 5}; +int n = sizeof(arr) / sizeof(arr[0]); +quickSort(arr, 0, n - 1); +// Now arr[] is sorted: {1, 5, 7, 8, 9, 10} + +``` \ No newline at end of file diff --git a/snippets/c/sorting/selection-sort.md b/snippets/c/sorting/selection-sort.md new file mode 100644 index 00000000..3bdfda99 --- /dev/null +++ b/snippets/c/sorting/selection-sort.md @@ -0,0 +1,33 @@ +--- +title: Selection Sort +description: Sorts an array of integers using the Selection Sort algorithm. +author: 0xHouss +tags: sorting,selectionsort,array,algorithm +--- + +```c +void selectionSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + int minIdx = i; + + // Find the minimum element in the unsorted part of the array + for (int j = i + 1; j < n; j++) { + if (arr[j] < arr[minIdx]) { + minIdx = j; + } + } + + // Swap the found minimum element with the first element of the unsorted part + int temp = arr[minIdx]; + arr[minIdx] = arr[i]; + arr[i] = temp; + } +} + +// Usage: +int arr[] = {64, 25, 12, 22, 11}; +int n = sizeof(arr) / sizeof(arr[0]); +selectionSort(arr, n); +// Now arr[] is sorted: {11, 12, 22, 25, 64} + +``` \ No newline at end of file From 67f0a955a7ed7ac0d3a61c7d58cd1a869ebb6272 Mon Sep 17 00:00:00 2001 From: JanluOfficial <95766563+JanluOfficial@users.noreply.github.com> Date: Mon, 6 Jan 2025 18:06:19 +0100 Subject: [PATCH 84/84] Updated combinations.md --- .../mathematical-functions/combinations.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/snippets/javascript/mathematical-functions/combinations.md b/snippets/javascript/mathematical-functions/combinations.md index 0b95dccc..080c8fd9 100644 --- a/snippets/javascript/mathematical-functions/combinations.md +++ b/snippets/javascript/mathematical-functions/combinations.md @@ -7,6 +7,10 @@ tags: math,number-theory,algebra ```js function combinations(n, r) { + if (n < 0 || r < 0 || n < r) { + throw new Error('Invalid input: n and r must be non-negative and n must be greater than or equal to r.'); + } + function factorial(x) { if (x === 0 || x === 1) return 1; let result = 1; @@ -15,10 +19,13 @@ function combinations(n, r) { } return result; } - return factorial(n) / (factorial(r) * factorial(n - r)); + + const numerator = factorial(n); + const denominator = factorial(r) * factorial(n - r); + return numerator / denominator; } // Usage: -combinations(12,24); // Returns: 7.720248753351544e-16 -combinations(1,22); // Returns: 8.896791392450574e-22 +combinations(24,22); // Returns: 276 +combinations(5,3); // Returns: 10 ``` \ No newline at end of file