Relevannsi - Search title only

// Relevannsi - Search title only.
// Rebuild index after adding function.
add_filter( 'relevanssi_index_content', '__return_false' );

blog_article

Tu es un expert en rénovation de biens immobiliers et consommation énergétique des logements.
Rédige un article de blog sur [TOPIC] en français, entre 600 et 1500 mots.
L'article devrait notamment traiter des sujets suivants [TOPICS].
L'article doit comporter un titre dans une balise h2 et un sous-titre dans une balise h3.
L'article doit comporter entre 3 et 7 chapitres.
L'article doit être généré sous forme de document html.
Le document html doit notamment contenir deux balises meta :
- une bal

Catching async/await

function getUserInfo() {
     return new Promise((resolve, reject) => {
         setTimeout(() => {
             reject('request exception')
         }, 1000)
     })
}


// 1) Try-catch
async function loggedIn() {
     try {
         let userInfo = await getUserInfo()
         // Execution interrupt
         let pageInfo = await getPageInfo(userInfo?.userId)
     } catch(e) {
         console.warn(e)
     }
}


// 2 direct catch
async function loggedIn() {
   let userInfo

database_optimization

https://www.linkedin.com/posts/aashish-kumar-30698b145_database-optimisation-in-django-activity-7177904694957146112-sPCA?utm_source=share&utm_medium=member_desktop https://www.linkedin.com/posts/aashish-kumar-30698b145_database-optimisation-in-django-activity-7178271669017276416-xvAw?utm_source=share&utm_medium=member_desktop https://www.linkedin.com/posts/aashish-kumar-30698b145_database-optimisation-in-django-activity-7178609891538821122-ZxyK?utm_source=share&utm_medium=member_desktop https://www.linkedin.com/posts/aashish-kumar-30698b145_database-optimisation-in-django-activity-7178991109350547456-zWvE?utm_source=share&utm_medium=member_desktop https://www.linkedin.com/posts/aashish-kumar-30698b145_difference-between-aggregate-vs-annotate-activity-7179351235609710592-c7z5?utm_source=share&utm_medium=member_desktop
from .models import LargeData, SomeData

# * 1 iterator()

data = LargeData.objects.all()

# Iterate over queryset using iterator
# The iterator() method is used to retrieve query results one at a time, rather than loading all results into memory at once
for obj in data.iterator(chunk_size=100):
  # process each object
  print(obj)

# * 2 explain()
queryset = SomeData.objects.filter(is_active=True, is_published=False)
explanation = queryset.query.explain()
print(explanation)

memoize

from functools import wraps

def memoize(func):
    cache = {}

    @wraps(func)
    def wrapper(*args):
        print("** 'memoize' decorator :")
        if args in cache:
            return cache[args]
        else:
            result = func(*args)
            cache[args] = result
        print(f"{func.__name__} returned: {result}")
        print()
        return result

    return wrapper

debug

from functools import wraps

def debug(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("** 'debug' decorator :")
        print(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        print()
        return result

    return wrapper

base_model

from django.db import models


class BaseModel(models.Model):
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name="created_at",
        help_text="Date et heure de création",
    )
    updated_at = models.DateTimeField(
        auto_now=True,
        verbose_name="updated_at",
        help_text="Date et heure de la dernière modification",
    )
    is_being_deleted = models.BooleanField(
        default=False,
        verbose_name="is_being_dele

class_dataclass

https://medium.com/@pouyahallaj/python-data-classes-the-key-to-clean-maintainable-code-a76a740d9884 https://stackoverflow.com/questions/47955263/what-are-data-classes-and-how-are-they-different-from-common-classes
from dataclasses import dataclass

# dataclass is a shortcut to avoid writing __init__ __repr__ __eq__ and __hash__ methods

@dataclass
class Product:
  name: str
  price: float
  quantity: int = 0
  
  def total_cost(self) -> float:
    return self.price * self.quantity

# Usage
p1 = Product(name="Laptop", price=1000.0, quantity=3)
p2 = Product(name="Laptop", price=1000.0, quantity=3)
p3 = Product(name="Smartphone", price=500.0, quantity=2)

print(p1) # Product(name="Laptop", price=1000.0, quan

class_classmethod

https://youtu.be/JgxCY-tbWHA?si=r-sFxCm2goCdyBUU
# It transforms the 1st implicit parameter to be the name or instance of the class not the individual object

class Person:
  species = "Homo sapiens"
  
  @classmethod
  def get_species(cls):
    return cls.species

# Usage
print(Person.get_species()) # Homo sapiens

class_staticmethod

https://youtu.be/JgxCY-tbWHA?si=NcPU3PPV1IXj1N74
# staticmethod is used to denote a method inside of a class as static
# ie method belongs to the class, not to the instance of a class

class Math:
  @staticmethod
  def add(x, y):
    return x + y
  
  @staticmethod
  def multiply(x, y):
    return x * y

# Usage
print(Math.add(5, 7)) # 12
print(Math.multiply(3, 4)) # 12

class_property

https://youtu.be/JgxCY-tbWHA?si=wAZ0Q_eUtWcLSOCs
class Circle:
  def __init__(self, radius):
    self._radius = radius
  
  @property
  def radius(self):
    """Get the radius of the circle"""
    print("called me")
    return self._radius
  
  @radius.setter
  def radius(self, value):
    """Set the radius of the circle. Must be positive."""
    if value >=0:
      self._radius = value
    else:
      raise ValueError("Radius must be positive")
  
  @radius.deleter
  def radius(self):
    print("deleted")
    del self._radius
  
  # Usage
  c

on_exit_2

https://github.com/federicoazzu/five_decorators/ https://youtu.be/3_P-dxrNCq8?si=Znfh3SA2YtIEGYzg
import atexit
import sqlite3

cxn = sqlite3.connect("db.sqlite3")


def init_db():
    cxn.execute("CREATE TABLE IF NOT EXISTS memes (id INTEGER PRIMARY KEY, meme TEXT)")
    print("Database initialised!")


@atexit.register
def exit_handler():
    cxn.commit()
    cxn.close()
    print("Closed database!")


if __name__ == "__main__":
    init_db()
    1 / 0
    ...

on_exit_1

https://github.com/federicoazzu/five_decorators/ https://youtu.be/3_P-dxrNCq8?si=Znfh3SA2YtIEGYzg
import atexit


@atexit.register
def exit_handler() -> None:
    print("We're exiting now!")


def main() -> None:
    for i in range(10):
        print(2**i)


if __name__ == "__main__":
    main()
    atexit.unregister(exit_handler)
    1 / 0

deprecated

https://github.com/federicoazzu/five_decorators/ https://youtu.be/3_P-dxrNCq8?si=Znfh3SA2YtIEGYzg
# XXX
# XXX TALK ABOUT PEP 702
# XXX https://peps.python.org/pep-0702
# XXX

from deprecated import deprecated


@deprecated("Adding ain't cool no more", version="1.0.0")
def add(x: int, y: int) -> int:
    return x + y


if __name__ == "__main__":
    print(add(5, 7))

timing

https://github.com/federicoazzu/five_decorators/ https://youtu.be/3_P-dxrNCq8?si=Znfh3SA2YtIEGYzg
import time
from time import perf_counter, sleep
from functools import wraps
from typing import Callable, Any


def get_time(func: Callable) -> Callable:
    @wraps(func)
    def wrapper(*args, **kwargs) -> Any:

        # Note that timing your code once isn't the most reliable option
        # for timing your code. Look into the timeit module for more accurate
        # timing.
        start_time: float = perf_counter()
        result: Any = func(*args, **kwargs)
        end_time