menu

Search By Label

Magic Numbers are literal numeric values that are used directly in code without a clear explanation of their meaning.
For example:
function calculatePrice(total) {
  if (total > 1000) {
    return total * 0.9; // 0.9 is a magic number
  } else {
    return total * 0.95; // 0.95 is another magic number
  }
}


In this example, the numbers 0.9 and 0.95 are magic numbers because their meaning is not clear. If someone else reads this code in the future, it will be difficult to understand their significance without additional context.
Similarly, Magic Strings are literal string values that are used directly in code without a clear explanation. 
For example:
function getErrorMessage(code) {
  switch (code) {
    case "ERR001":
      return "Connection Error"; // "ERR001" is a magic string
    case "ERR002":
      return "Authentication Error"; // "ERR002" is another magic string
    default:
      return "Unknown Error";
  }
}

Resources: 
https://softwareengineering.stackexchange.com/questions/365339/what-is-wrong-with-magic-strings
https://dev.to/ruben_alapont/magic-numbers-and-magic-strings-its-time-to-talk-about-it-ci2
I use polymorphic routes for readability purposes. This is useful to make the lines of code a bit shorter like this:

<%= button_to "Delete", [quote, line_item_date] %>
<%= button_to "Delete", quote_line_item_date_path(quote, line_item_date) %>

It is also possible to use them in controllers. For example, the two following lines for code are equivalent:

redirect_to @quote
redirect_to quote_path(@quote)


If you want to learn more about them, here is a link to the documentation.

A Foundation Model in AI is a large, powerful neural network trained on a massive dataset of text, code, images, or other forms of data. Here are some key points to understand them:
  • Large and General: These models are typically very large, containing billions or even trillions of parameters. This allows them to learn complex patterns and relationships within the data.
  • Broadly Applicable: Foundation models are trained in a way that allows them to be applied to a wide range of tasks. They can be fine-tuned for specific purposes like generating text, translating languages, or recognizing objects in images.
  • Platform for AI Applications: They act as a foundation upon which other AI applications can be built. By fine-tuning a foundation model for a specific task, developers can create powerful AI tools without needing to train a massive model from scratch.

Think of them as pre-trained brains:

  • Imagine a child learning from a vast amount of information (books, videos, experiences). Foundation models are like these "child brains" in the AI world, having learned from a huge dataset.
  • While the child might not be an expert in any specific field, it can use this knowledge as a base to learn new things quickly. Similarly, foundation models can be adapted (fine-tuned) to perform various tasks effectively.

Lambda functions are anonymous functions in Python. They allow you to define a small, one-line function without the need for a formal def keyword and a function name.

Example:
Imagine you want to double a number. Here's how you can do it with a regular function:
def double(x):
  """Doubles a number."""
  return x * 2

result = double(5)
print(result)  # Output: 10

This defines a function named double that takes a number (x) as input and returns its double.
Here's how you can achieve the same functionality using a Lambda function:
# Lambda function to double a number
double_lambda = lambda x: x * 2

result = double_lambda(5)
print(result)  # Output: 10

Use Cases:
  • Passing small functions as arguments to other functions.
  • Sorting or filtering data based on a simple criterion.
  • Creating throwaway functions used only once.
Syntactic sugar refers to the little bit of ✨ magic ✨ Ruby provides you in writing easier to read and more concise code. In Ruby this means leaving out certain symbols, and spaces or writing some expression with a helper of some kind one of these possibilities is the sandwich method, we look more at it here: 

It is common when we begin to handle an array in a each to do it specific actions thing like that:
array = [1, 2, 3, 4]
new_array = []
array.each do |element|
  new_array << element * 2
end
new_array
# => [2, 4, 6, 8]

Today I learned how simplified it is to handle this type of interaction by thinking about this magic we talked about before. the first thing that is important here is to remember that the use of each handle and return the same array and for this reason, it is necessary to create a new_array variable to inject the new values of the product to element * 2

Most of the time, if you have to use the sandwich method, there is probably a higher-level iterator that you could use that will allow you to perform the function on the array or hash without using the sandwich method. In this case, your best bet would be map :

array = [1, 2, 3, 4]
array.map do |element|
  element * 2
end
# => [2, 4, 6, 8]


GET requests are designed to retrieve data from a server, similar to fetching a document from a library catalog.
Since you're "getting" info, a body (like a new book) wouldn't be appropriate. Params (like search terms) are used to filter or specify the data you want.
This design keeps GET requests simple and avoids ambiguity.

The .strip() method in Python is used to remove leading and trailing characters from a string. It's a versatile method with various applications for string manipulation.

Example:
data = "  Hello, world!   "  # String with leading and trailing spaces

stripped_data = data.strip()

print(stripped_data)  # Output: "Hello, world!" (whitespace removed)
Or
data = "**Hello, world!**"  # String with leading and trailing asterisks

stripped_data = data.strip("*")

print(stripped_data)  # Output: "Hello, world!" (asterisks removed)

you can debug any Python app (>3.7 version) by adding the method breakpoint()  to any line.

Here the actions you can use:
h: help
w: where
n: next
s: step (steps into function)
c: continue
p: print
l: list
q: quit

Source: https://www.youtube.com/watch?v=aZJnGOwzHtU&ab_channel=PatrickLoeber
We can use the following method to ensure a variable value is between a specific range

# Ensure between 1 and 100
111.clamp(1, 100)
# => 100
-1.clamp(1, 100)
We can use the following methods to ensure a variable is always min or max value:

# Ensure the value is one or more
[value, 1].min

# Ensure the value is 100 or less
[value, 100].max
The docker system prune command is a shortcut that prunes images, containers, and networks.

docker system prune
It is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.

//example
const double = (x) => x * 2;
const square = (x) => x * x;

var output1 = double(2);
var output2 = square(output1);
console.log(output2);

var output_final = square(double(2));
console.log(output_final);
Lambdas in Python are a concise way to define anonymous functions. They are useful for short, inline functions that are used only once or in situations where a full function definition would be cumbersome.

# Syntax
lambda arguments: expression

# Example of use
add = lambda x, y: x + y  # Defines a lambda function that adds two numbers
result = add(5, 3)  # Calls the lambda function with arguments 5 and 3
print(result)  # Output: 8
Recently, I became interested in Rails' Action Mailbox, and I read several articles including the official documentation. One article from Prograils (https://prograils.com/real-life-examples-adding-action-mailbox-to-a-rails-6-app) particularly caught my attention due to its discussion on using the simple_command gem (https://github.com/nebulab/simple_command). This article shows how the gem can help you avoid repeating the way you invoke your services or classes. It allows you to structure classes like this:

# define a command class
class AuthenticateUser
  prepend SimpleCommand

  # optional, initialize the command with some arguments
  def initialize(email, password)
    @email = email
    @password = password
  end

  # mandatory: define a #call method. its return value will be available
  #            through #result
  def call
    if user = User.find_by(email: @email)&.authenticate(@password)
    ...
end

So you can invoke it like this
AuthenticateUser.call(session_params[:email], session_params[:password])

And I wondered how the SimpleCommand module might be structured. Additionally, I considered how it could support keyword arguments in the form of:
def my_method(value:, second_value:)
  puts "value #{value}, second_value #{second_value}"
end
my_method(value: 'value one', second_value: 'value two')

In fact, it is quite simple. Let’s define it in two different ways without using any additional dependencies:

Using class_eval and self for defining a class method

module SimpleCommand
  def self.included(klass)
    klass.class_eval do 
      def self.call(*args, **kwargs)
        puts "args #{args}"
        new(*args, **kwargs).call
      end
    end
  end
end

or

Using extend to define the methods as class methods

module SimpleCommand
  def self.included(klass)
    klass.extend(ClassMethods)
  end
  
  module ClassMethods
    def call(*args, **kwargs)
      new(*args, **kwargs).call
    end
  end
end

And here is how you can use it after that
class NamedArguments
  include SimpleCommand
  def initialize(value: , second:)
    @value = value
    @second = second
  end

  def call
    puts "the method in myClass @value: #{@value}, @second #{@second}"
  end
end

NamedArguments.call(value: 'the value', second: 'from second')

Or using positional arguments

class SimpleArguments
  include SimpleCommand
  def initialize(valueOne, valueTwo)
    @valueOne = valueOne
    @valueTwo = valueTwo
  end

  def call
    puts "the method in myClass @value: #{@valueOne}, @second #{@valueTwo}"
  end
end

SimpleArguments.call('arg one', 'arg two')

There you have it!

from functools import lru_cache
@lru_cache(maxsize= 128) #cache can save up to 128 entries and optimize execution
def fib_with_cache(n): 
   if n < 2: 
       return n 
   return fib_with_cache(n-1)+ fib_with_cache(n-2)