Snippets Collections
 error_log(print_r($new_date, true), 3, __DIR__ . '/../error_log');
Estructura general:

xmlelement(name libros, ...): crea un elemento XML raíz llamado <libros>.

xmlagg(...): agrega múltiples elementos XML dentro del elemento raíz.

xmlelement(name libro, xmlforest(...)): crea un elemento <libro> con varios subelementos para los campos del libro.

SELECT
  xmlelement(
    name libros,
    xmlagg(
      xmlelement(
        name libro,
        xmlforest(
          id,
          titulo,
          autor,
          anio
        )
      )
    )
  ) AS libros_xml
FROM libros;
$conn = pg_connect("host=localhost dbname=mi_base user=usuario password=clave");

$sql = "SELECT
  xmlelement(
    name libros,
    xmlagg(
      xmlelement(
        name libro,
        xmlforest(
          id,
          titulo,
          autor,
          anio
        )
      )
    )
  ) AS libros_xml
FROM libros";

$result = pg_query($conn, $sql);
$row = pg_fetch_assoc($result);

$xmlStr = $row['libros_xml'];
$xml = simplexml_load_string($xmlStr);
Cómo funciona cada uno para obtener datos:
XML es un formato de datos estructurado que puede estar almacenado en un archivo local o servido desde un servidor remoto (por ejemplo, desde una API REST).

XPath es un lenguaje para navegar y seleccionar partes específicas dentro de un documento XML.

XQuery es un lenguaje de consulta más avanzado para extraer, transformar y manipular datos XML, que puede usarse para consultar documentos XML o bases de datos XML alojadas en servidores, locales o remotos.

JSON es otro formato muy popular para transmitir datos, especialmente en APIs web modernas, y se pueden consultar y manipular fácilmente con lenguajes como JavaScript o PHP.
Un ejemplo sencillo y representativo de una base de datos XML podría ser un conjunto de documentos XML que almacenan información estructurada, como un catálogo de libros o una lista de contactos.

Aquí tienes una estructura básica de un archivo XML que simula la información en una base de datos de libros:

<?xml version="1.0" encoding="UTF-8"?>
<biblioteca>
  <libro id="1">
    <titulo>El Quijote</titulo>
    <autor>Miguel de Cervantes</autor>
    <anio>1605</anio>
    <genero>Novela</genero>
  </libro>
  <libro id="2">
    <titulo>Cien Años de Soledad</titulo>
    <autor>Gabriel García Márquez</autor>
    <anio>1967</anio>
    <genero>Realismo mágico</genero>
  </libro>
  <libro id="3">
    <titulo>La Sombra del Viento</titulo>
    <autor>Carlos Ruiz Zafón</autor>
    <anio>2001</anio>
    <genero>Novela negra</genero>
  </libro>
</biblioteca>
Base de datos PostgreSQL con datos XML

<biblioteca>
  <libro>
    <titulo>El Quijote</titulo>
    <autor>Miguel de Cervantes</autor>
  </libro>
  <libro>
    <titulo>Cien Años de Soledad</titulo>
    <autor>Gabriel García Márquez</autor>
  </libro>
</biblioteca>
json_encode(): convierte un array u objeto PHP en una cadena JSON.

json_decode(): convierte una cadena JSON en un objeto o array PHP.

// Array PHP a JSON
$array = ['nombre' => 'Juan', 'edad' => 30];
$json = json_encode($array);
echo $json; // {"nombre":"Juan","edad":30}

// JSON a array PHP
$jsonString = '{"nombre":"Ana","edad":25}';
$arrayPHP = json_decode($jsonString, true);
echo $arrayPHP['nombre']; // Ana
convertir una tabla postgres en json en yii2:
<?php
namespace app\controllers;

use yii\web\Controller;
use yii\web\Response;
use app\models\Libro; // Suponiendo que tienes un modelo Libro

class LibroController extends Controller
{
    public function actionLista()
    {
        // Obtener datos como array usando asArray()
        $libros = Libro::find()->asArray()->all();

        \Yii::$app->response->format = Response::FORMAT_JSON;

        // Devolver los datos directamente como JSON
        return $libros;
    }
}


convertir una tabla postgres en json en  laravel:
<?php

namespace App\Http\Controllers;

use App\Models\Libro;
use Illuminate\Http\JsonResponse;

class LibroController extends Controller
{
    public function lista(): JsonResponse
    {
        // Obtener todos los registros como array
        $libros = Libro::all();

        // Devolver los datos como JSON
        return response()->json($libros);
    }
}
Cómo definir la ruta para acceder a este método (en routes/web.php o routes/api.php):
use App\Http\Controllers\LibroController;
Route::get('/libro/lista', [LibroController::class, 'lista']);

javascript:
1. Con promesas (.then)
Cómo consumirlo con JavaScript sería igual que en Yii2-laravel:
fetch('/libro/lista')
  .then(response => response.json())
  .then(data => {
    data.forEach(libro => {
      console.log(libro.titulo);
    });
  });

2. Con async/await (más legible)
Cómo consumirlo en JavaScript sería igual que en Yii2-laravel:
async function obtenerLibros() {
  try {
    const response = await fetch('/libro/lista');
    const data = await response.json();
    data.forEach(libro => {
      console.log(libro.titulo);
    });
  } catch (error) {
    console.error('Error:', error);
  }
}

obtenerLibros();

3. Con callback (usando XMLHttpRequest)
Cómo consumirlo en JavaScript sería igual que en Yii2-laravel:
function obtenerLibrosConCallback(callback) {
  const xhr = new XMLHttpRequest();
  xhr.open('GET', '/libro/lista');
  xhr.onload = function() {
    if (xhr.status === 200) {
      const data = JSON.parse(xhr.responseText);
      callback(null, data);
    } else {
      callback(new Error('Error en la solicitud: ' + xhr.status));
    }
  };
  xhr.onerror = function() {
    callback(new Error('Error de red'));
  };
  xhr.send();
}

// Usando la función con callback
obtenerLibrosConCallback(function(error, data) {
  if (error) {
    console.error(error);
  } else {
    data.forEach(libro => {
      console.log(libro.titulo);
    });
  }
});

jquery:
1.-Ejemplo usando $.getJSON()

<!DOCTYPE html>
<html>
<head>
  <title>Consumir API con jQuery</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<ul id="lista-libros"></ul>

<script>
$(document).ready(function() {
  $.getJSON('/libro/lista')
    .done(function(data) {
      // data es un array de objetos libros
      $.each(data, function(index, libro) {
        $('#lista-libros').append('<li>' + libro.titulo + '</li>');
      });
    })
    .fail(function(jqxhr, textStatus, error) {
      console.error('Error al consumir la API:', textStatus, error);
    });
});
</script>

</body>
</html>

2.-Ejemplo usando $.ajax():
$.ajax({
  url: '/libro/lista',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    data.forEach(function(libro) {
      console.log(libro.titulo);
    });
  },
  error: function(jqxhr, textStatus, error) {
    console.error('Error:', error);
  }
});

laravel:
use Illuminate\Support\Facades\Http;

$response = Http::get('https://api.example.com/data');

if ($response->successful()) {
    $data = $response->json(); // decodifica JSON automáticamente a array
    // procesar $data
} else {
    // manejar error
}

yii2:
Formas comunes de consumir APIs en PHP / Yii2:
1. Usar cURL directamente (funciona en cualquier PHP)

use yii\httpclient\Client;

$client = new Client();
$response = $client->get('https://api.ejemplo.com/data')->send();

if ($response->isOk) {
    $data = $response->getData(); // Obtienes array o json decodificado automáticamente
}

2. Usar la clase yii\httpclient\Client que trae Yii2 (más moderno y elegante)
use yii\httpclient\Client;

$client = new Client();
$response = $client->get('https://api.ejemplo.com/data')->send();

if ($response->isOk) {
    $data = $response->getData(); // Obtienes array o json decodificado automáticamente
}




// Component Registry (same as before)

const ComponentRegistry = {

  // Button Component

  Button: {

    template: (props = {}) => `

          <button class="neo-brutalist bg-${props.color || 'yellow-400'} text-${props.textColor || 'black'} text-lg font-bold py-3 px-6 hover:bg-${props.color || 'yellow-400'}-600 transition-none">

            ${props.text || 'Click Me'}

          </button>

        `,

    init: (element, props) => {

      element.innerHTML = ComponentRegistry.Button.template(props);

    }

  },

​

  // Card Component

  Card: {

    template: (props = {}) => `

          <div class="neo-brutalist bg-white p-6">
body {

  font-family: 'Roboto Mono', monospace;

  background-color: #ff5f5;

  color: #1a1a1a;
5
}

.neo-brutalist {

  border: 4px solid #000;

  box-shadow: 8px 8px 0 #000;

  transition: all 0.2s ease;

  border-radius: 4px;

}

.neo-brutalist:hover {

  box-shadow: 6px 6px 0 #000;

  transform: translate(2px, 2px);

}

h1, h2, h3 {

  font-family: 'Bebas Neue', sans-serif;

  letter-spacing: 2px;

}

.component-card {

  height: 100%;
<body class="p- md:p-">

  <div class="container mx-auto">

    <h1 class="text-4xl md:text-xl mb- md:mb-8 text-center">Neo Brutalist Component Library</h1>
4
​
5
    <!-- Component Grid -->
6
    <div id="components" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-2 gap-6">

      <!-- Components will be injected here by JavaScript -->
8
    </div>

  </div>

  

  

<a target="_blank" href="https://www.rustcodeweb.com/" 

   style="position: fixed; bottom: 0.6rem; right: 0.6rem; background: #FFD6; color: #073B4C; text-decoration: none; padding: 0.5rem 1rem; border: 3px solid #073B4C; box-shadow: 3px 3px 0 #073B4C; font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; font-weight: 600; font-size: 0.875rem; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1200; border-radius: 2px; display: flex; align-items: center; gap: 0.5rem;"

   onmouseover="this.style.background='#F8F9FA'; this.style.transform='translate(-1px, -1px)'; this.style.boxShadow='4px 4px 0 #073B4C';"

   onmouseout="this.style.background='#FFD166'; this.style.transform='translate(0, 0)'; this.style.boxShadow='3px 3px 0 #073B4C';"
16
   onmousedown="this.style.transform='translate(0, 0)'; this.style.boxShadow='2px 2px 0 #073B4C';"

   onmouseup="this.style.transform='translate(-1px, -1px)'; this.style.boxShadow='4px 4px 0 #073B4C';"
<body class="p- md:p-">

  <div class="container mx-auto">

    <h1 class="text-4xl md:text-xl mb- md:mb-8 text-center">Neo Brutalist Component Library</h1>
4
​
5
    <!-- Component Grid -->
6
    <div id="components" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-2 gap-6">

      <!-- Components will be injected here by JavaScript -->
8
    </div>

  </div>

  

  

<a target="_blank" href="https://www.rustcodeweb.com/" 

   style="position: fixed; bottom: 0.6rem; right: 0.6rem; background: #FFD6; color: #073B4C; text-decoration: none; padding: 0.5rem 1rem; border: 3px solid #073B4C; box-shadow: 3px 3px 0 #073B4C; font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; font-weight: 600; font-size: 0.875rem; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); z-index: 1200; border-radius: 2px; display: flex; align-items: center; gap: 0.5rem;"

   onmouseover="this.style.background='#F8F9FA'; this.style.transform='translate(-1px, -1px)'; this.style.boxShadow='4px 4px 0 #073B4C';"

   onmouseout="this.style.background='#FFD166'; this.style.transform='translate(0, 0)'; this.style.boxShadow='3px 3px 0 #073B4C';"
16
   onmousedown="this.style.transform='translate(0, 0)'; this.style.boxShadow='2px 2px 0 #073B4C';"

   onmouseup="this.style.transform='translate(-1px, -1px)'; this.style.boxShadow='4px 4px 0 #073B4C';"
php-nativo:
php -S 192.168.1.50:9000
php -S localhost:9000
php -S 127.0.0.1:9000 //localhost

php-yii2
php -S localhost:8001 -t backend/web
php -S 172.xx.xx.xx:8081 -t backend/web

php-laravel
php artisan serve --port=8080
php -S 192.168.1.50:9000 -t public

laravel
php artisan serve
php artisan serve --host=172.xx.xx.xx:8081 --port=8000
php artisan serve --host=localhost --port=8000


yii2
php yii serve --port=8080
php yii serve --docroot="backend/web"
php yii serve --docroot="backend/web" --address=192.168.1.50 --port=9000
import json
import os
from typing import Dict

import torch
import torch.fx as fx
import torch.nn as nn
from core.frameworks.pytorch.quantization.sdk.graph_utils import ModelGraphUtils
from core.frameworks.pytorch.quantization.sdk.model_preparer import (
    _get_module_for_dotted_name,
    prepare_model,
)
from core.frameworks.pytorch.quantization.sdk.modules.fake_quantize import (
    FakeQuantize as CustomFakeQuantize,
)
from core.frameworks.pytorch.quantization.sdk.modules.module_replacement_registry import (
    ModuleReplacements,
)
from core.frameworks.pytorch.quantization.sdk.modules.quantized_modules import (
    QuantizationMixin,
)
from core.frameworks.pytorch.quantization.sdk.quantization_utils import (
    build_clean_onnx_path,
    build_onnx_path_from_torch_name,
    get_bitwidth_from_string_dtype,
    normalize_class_name,
    print_quant_summary,
)
from core.frameworks.pytorch.utils.utils import is_leaf_module
from logger.logger_registry import get_logger
from utils.config_utils import (
    get_model_configs,
    get_task_configs,
)
from utils.helpers import set_nested_attr

from .modules.function_modules import REPLACEMENTS
from .quantsim_config.quantsim_parser import QuantSimConfigParser

logger = get_logger("main")


class QuantizerEnginer:
    def __init__(
        self,
        model: torch.nn.Module,
        configs,
        device: torch.device,
    ):
        self._model: torch.nn.Module = model
        self.config = configs
        self.logger = get_logger("main")
        self.device = device
        self.task_type = (
            "qft" if self.config["qft"] else "ptq" if self.config["ptq"] else "pruning"
        )

        self.quantsim_config = QuantSimConfigParser()

    def update_model(self, model: torch.nn.Module):
        self._model = model

    def fuse_all_conv_bn(self, module):
        fusion_list = []
        module_list = list(module.named_modules())

        for (name1, mod1), (name2, mod2) in zip(module_list, module_list[1:]):
            if isinstance(mod1, torch.nn.Conv2d) and isinstance(
                mod2, torch.nn.BatchNorm2d
            ):
                fusion_list.append([name1, name2])

        if fusion_list:
            torch.ao.quantization.fuse_modules(module, fusion_list, inplace=True)

    def _check_super_groups_module(self, layer_name: str) -> bool:
        super_groups = self.quantsim_config.get_super_groups_ops()
        next_node_name = self.graphutils.get_next_non_identity_module(layer_name)
        if not next_node_name:
            return self.quantsim_config.is_default_ops_output_quantized()
        layer_name = self.graphutils.get_normalized_layer_name(layer_name)
        next_node_name = self.graphutils.get_normalized_layer_name(next_node_name)
        if next_node_name:
            next_node_name_lower = next_node_name.lower()
            node_name_lower = layer_name.lower()
            for super_group in super_groups:
                super_group_first = super_group[0].lower()
                super_group_second = super_group[1].lower()
                if (
                    node_name_lower in super_group_first
                    and next_node_name_lower in super_group_second
                ):
                    return False
                elif next_node_name_lower in super_group_second:
                    return True
        return self.quantsim_config.is_default_ops_output_quantized()

    def apply_io_quantizer_flags_to_graph(
        self, graph: torch.fx.GraphModule
    ) -> dict[str, tuple[bool, bool]]:
        """
        Iterate over all nodes in the graph and determine IO quantizer flags.

        Returns:
            A dictionary mapping node names to (add_input_quantizer, add_output_quantizer) flags.
        """
        io_flags = {}
        for node in graph.graph.nodes:
            if node.op == "call_module":
                flags = self.__get_io_quantizer_flags(graph, node, None)
                io_flags[node.name] = flags
                print(
                    f"[IO Quantizer Flags] {node.name}: Input={flags[0]}, Output={flags[1]}"
                )
                module: QuantizationMixin = _get_module_for_dotted_name(
                    graph, node.target
                )
                if not isinstance(module, QuantizationMixin):
                    continue
                if not flags[0]:
                    module.disable_input_quantization()
                if not flags[1]:
                    module.disable_output_quantization()
                if flags[0]:
                    module.enable_input_quantization()
                if flags[1]:
                    module.enable_output_quantization()

        return io_flags

    def _check_super_groups_node(
        self,
        layer_name: str,
        node: torch.fx.Node,
        next_node: torch.fx.Node,
        next_node_name: str,
    ) -> bool:
        super_groups = self.quantsim_config.get_super_groups_ops()
        for super_group in super_groups:
            if (
                layer_name in super_group[0].lower()
                and next_node
                and next_node_name in super_group[1].lower()
            ):
                print("#" * 20, layer_name, next_node_name, "#" * 20)
                return False
            elif layer_name in super_group[1].lower():
                return True
        return True

    def __is_quantizable_module(self, module: torch.nn.Module):
        return ModuleReplacements.get_replacement(module) is not None

    @classmethod
    def __is_quantized_module(cls, module: torch.nn.Module):
        return isinstance(module, QuantizationMixin)

    def _normalized_op_name(self, module: torch.nn.Module) -> str:
        """Map a module to the normalized op name used in your config."""
        return self.graphutils.get_normalized_layer_name(module)

    def _match_pattern_from(
        self,
        graph: torch.fx.GraphModule,
        start_node: torch.fx.Node,
        pattern_ops: list[str],
    ):
        """
        Try to match a supergroup pattern starting at start_node.
        Returns list of nodes if matched, else None.
        """
        if start_node.op != "call_module":
            return None

        try:
            first_module = _get_module_for_dotted_name(graph, start_node.target)
        except Exception:
            return None

        first_name = self._normalized_op_name(first_module)
        if first_name != pattern_ops[0]:
            return None

        matched_nodes = [start_node]
        curr = start_node
        for expected in pattern_ops[1:]:
            next_node = self.graphutils.get_next_non_identity_node(curr)
            if not next_node or next_node.op != "call_module":
                return None
            try:
                next_module = _get_module_for_dotted_name(graph, next_node.target)
            except Exception:
                return None
            next_name = self._normalized_op_name(next_module)
            if next_name != expected:
                return None
            matched_nodes.append(next_node)
            curr = next_node

        return matched_nodes

    def _collect_supergroup_patterns(self):
        """
        Read patterns from your quantsim config.
        Expected structure: [["Conv", "BatchNorm", "Relu"], ["MatMul", "Add"]]
        """
        cfg = self.quantsim_config.get_model_quantization_config()
        patterns = cfg.get("supergroups", [])
        cleaned = []
        for pat in patterns:
            if isinstance(pat, (list, tuple)) and len(pat) >= 2:
                cleaned.append([str(x) for x in pat])
        return cleaned

    def _apply_super_groups_config(self, graph: torch.fx.GraphModule):
        """
        Find and apply super-group quantization configuration.
        Works for groups of any length >= 2. Prevents overlaps.
        """
        patterns = self._collect_supergroup_patterns()
        self._supergroup_members = {}
        claimed = set()
        group_id = 0

        for node in graph.graph.nodes:
            if node.op != "call_module" or node in claimed:
                continue

            for pat in patterns:
                match = self._match_pattern_from(graph, node, pat)
                if not match:
                    continue
                if any(n in claimed for n in match):
                    continue

                size = len(match)
                for idx, member in enumerate(match):
                    self._supergroup_members[member] = (group_id, idx, size)
                    claimed.add(member)

                # Gather actual modules
                modules = []
                for mnode in match:
                    m = _get_module_for_dotted_name(graph, mnode.target)
                    modules.append(m)

                # Apply quantizer sharing
                self._apply_super_group_action_general(modules)

                if getattr(self, "verbose", False):
                    names = [self._normalized_op_name(m) for m in modules]
                    print(f"[SuperGroup] id={group_id} matched: {' -> '.join(names)}")

                group_id += 1
                break

    def _belongs_to_super_group(self, node: torch.fx.Node) -> bool:
        return hasattr(self, "_supergroup_members") and node in self._supergroup_members

    def _supergroup_position(self, node: torch.fx.Node):
        """Return (group_id, idx, size) if node is in a supergroup, else None."""
        if self._belongs_to_super_group(node):
            return self._supergroup_members[node]
        return None

    def _apply_super_group_action_general(self, modules: list):
        n = len(modules)
        if n < 2:
            return

        last_module = modules[-1]
        if not hasattr(last_module, "output_quantizer"):
            return

        shared_output_q = last_module.output_quantizer

        for m in modules[:-1]:
            if hasattr(m, "output_quantizer"):
                m.output_quantizer = shared_output_q

    def __get_io_quantizer_flags(
        self, graph, node: torch.fx.Node, layer_name: str | None
    ) -> tuple[bool, bool]:
        """
        Decide whether to add input/output quantizers for a node,
        respecting model IO policy and per-layer overrides.
        """
        layer_name = layer_name or self.graphutils.get_normalized_layer_name(node)
        model_quant_config = self.quantsim_config.get_model_quantization_config()

        add_input_quantizer = self.quantsim_config.is_default_ops_input_quantized()
        add_output_quantizer = self.quantsim_config.is_default_ops_output_quantized()

        if self.graphutils._is_first(node, layer_name):
            add_input_quantizer = model_quant_config.get("input_quantized", False)
        if self.graphutils._is_last(node, layer_name):
            add_output_quantizer = model_quant_config.get("output_quantized", False)

        # No need for explicit supergroup override:
        # all sharing is already handled in _apply_super_group_action_general.

        add_input_quantizer = self._apply_layer_override(
            layer_name, add_input_quantizer, is_input=True
        )
        add_output_quantizer = self._apply_layer_override(
            layer_name, add_output_quantizer, is_input=False
        )
        _module = _get_module_for_dotted_name(graph, node.target)
        return add_input_quantizer, add_output_quantizer

    def _apply_layer_override(
        self, layer_name: str, current_value: bool, is_input: bool
    ) -> bool:
        if is_input:
            if (
                layer_name
                in self.quantsim_config.get_layers_to_skip_from_input_quantizers()
            ):
                return False
            if layer_name in self.quantsim_config.get_layers_to_add_input_quantizers():
                return True
        else:
            if (
                layer_name
                in self.quantsim_config.get_layers_to_skip_from_output_quantizers()
            ):
                return False
            if layer_name in self.quantsim_config.get_layers_to_add_output_quantizers():
                return True
        return current_value

    def _add_quantization_wrappers(self, module, prefix=""):

        if self.__is_quantized_module(module):
            return
        for module_name, module_ref in module.named_children():
            full_name = f"{prefix}.{module_name}" if prefix else module_name
            self.logger.info("nn.Module found : %s", module_ref)
            print("nn.Module found : %s", module_ref)

            if self.__is_quantizable_module(module_ref) and is_leaf_module(module_ref):
                quantized_module = self._create_quantizer_module(module_ref, full_name)
                if not quantized_module:
                    self.logger.info(f"Please register {full_name}")
                    continue
                setattr(module, module_name, quantized_module)
            else:
                self._add_quantization_wrappers(module_ref, prefix=full_name)

    def _create_quantizer_module(
        self, module_to_quantize: torch.nn.Module, module_name: str
    ):

        param_per_channel = get_task_configs(
            self.config, "ptq", "parameter_per_channel", False
        )
        act_per_channel = get_task_configs(
            self.config, "ptq", "activation_per_channel", False
        )
        param_per_tensor = get_task_configs(
            self.config, "ptq", "parameter_per_tensor", True
        )
        act_per_tensor = get_task_configs(
            self.config, "ptq", "activation_per_tensor", True
        )
        param_is_symmetric = get_task_configs(
            self.config, "ptq", "parameter_is_symmetric", True
        )
        act_is_symmetric = get_task_configs(
            self.config, "ptq", "activation_is_symmetric", False
        )

        global_activation_dtype = get_task_configs(
            self.config, "ptq", "activation_dtype", "int4"
        )
        global_param_dtype = get_task_configs(
            self.config, "ptq", "parameter_dtype", "int4"
        )
        global_activation_observer = get_task_configs(
            self.config, "ptq", "activation_observer"
        )
        global_weight_observer = get_task_configs(self.config, "ptq", "weight_observer")

        quantizer = ModuleReplacements.get_replacement(module_to_quantize)

        if not quantizer:
            self.logger.info(f"Please register {type(module_to_quantize)}")
            return None

        # registering parameter and activation dtype
        setattr(module_to_quantize, "activation_dtype", global_activation_dtype)
        setattr(module_to_quantize, "parameter_dtype", global_param_dtype)
        setattr(module_to_quantize, "parameter_observer", global_weight_observer)
        setattr(module_to_quantize, "activation_observer", global_activation_observer)
        setattr(module_to_quantize, "param_per_channel", param_per_channel)
        setattr(module_to_quantize, "act_per_channel", act_per_channel)
        setattr(module_to_quantize, "param_per_tensor", param_per_tensor)
        setattr(module_to_quantize, "act_per_tensor", act_per_tensor)
        setattr(module_to_quantize, "param_is_symmetric", param_is_symmetric)
        setattr(module_to_quantize, "act_is_symmetric", act_is_symmetric)

        self.logger.info(
            f"Replacing {type(module_to_quantize)} with {quantizer.__name__} for quantization"
        )
        quantized_module = quantizer(
            _module_to_wrap=module_to_quantize,
            # add_input_quantizers=add_input_quantizers,
            # add_output_quantizers=add_output_quantizers,
        )
        return quantized_module

    def prepare(
        self,
    ):
        """
        Recursively replace every weight-bearing layer with a QuantWrapper.

        Args:
            layer_types: if provided, only wrap these types; else wrap all with 'weight'.
            model:       internal use for recursion (initially None → uses self._model).
        """
        self.logger.info("=" * 60)
        self.logger.info("Preparing model for QFT (Quantization-Aware Fine-Tuning)")
        self.logger.info("=" * 60)
        self._model.eval()
        self.fuse_all_conv_bn(self._model)

        # try:
        self.traced_graph = fx.symbolic_trace(self._model)
        self.graphutils = ModelGraphUtils(self._model, self.traced_graph)
        self._model = prepare_model(self._model)
        self.graphutils.update_model(self._model)
        self._add_quantization_wrappers(self._model)
        self.graphutils.update_graph(self._model)
        self.apply_io_quantizer_flags_to_graph(self._model)
        self.logger.info(self._model)

        # except Exception as e:
        #     print(e)
        #     self.graphutils = ModelGraphUtils(self._model, None)
        #     self.logger.info("Model is not graph tracable. Cannot replace math ops.")
        #     self._add_quantization_wrappers(self._model)

        self.logger.info("Model after preparing")
        self.logger.info(self._model)
        print_quant_summary(self._model)
        return self._model

    def convert(self, model) -> None:
        """
        Convert the model to a quantized model.
        This method is called after the training and preparation steps.
        """

        for name, child in list(model.named_children()):
            if isinstance(child, QuantizationMixin):
                self.logger.info(f"Replacing Quantized module: {name}")
                module: QuantizationMixin = child
                scale_fp = module.get_scale_fp()
                wrapped_module: nn.Module = module._module_to_wrap
                for k, v in scale_fp.items():
                    wrapped_module.register_buffer(f"{k}_scale", v["scale"])
                    wrapped_module.register_buffer(f"{k}_zero_point", v["zero_point"])
                    setattr(wrapped_module, f"{k}_scale", v["scale"])
                    setattr(wrapped_module, f"{k}_zero_point", v["zero_point"])

                setattr(model, name, wrapped_module)
                continue

            self.convert(child)

    def export_model(self, model: torch.nn.Module, task_type: str) -> None:
        """
        Export the quantized model to a format suitable for deployment.
        """
        self.model_name = get_model_configs(self.config)["name"]
        export_format = self.config["export"]["format"]
        output_dir = self.config["export"]["output_dir"] + "/" + self.model_name
        if export_format == "onnx":
            export_model = model.apply(torch.ao.quantization.disable_observer)
            export_model.cpu()
            if not os.path.exists(output_dir):
                os.makedirs(output_dir, exist_ok=True)

            param_dtype = get_task_configs(
                self.config, task_type, "parameter_dtype", "int4"
            )
            opset = get_task_configs(self.config, "export", "opset", 13)
            attribute = get_task_configs(self.config, "export", "attribute", None)
            if attribute is not None:
                if not hasattr(export_model, attribute):
                    raise ValueError(f"Model has no attribute '{attribute}' for export")
                export_model = getattr(export_model, attribute)

            onnx_file = (
                f"{self.model_name}_quantized_model_{task_type}_{param_dtype}.onnx"
            )

            output_path = os.path.join(output_dir, onnx_file)

            self.logger.info("=" * 60)
            self.logger.info("Exporting the quantized model")
            self.logger.info("=" * 60)
            self.logger.info(f"Model Name      : {self.model_name}")
            self.logger.info(f"Export Format   : {export_format}")
            self.logger.info(f"Output Path     : {output_path}")
            self.logger.info("=" * 60)
            try:
                torch.onnx.export(
                    export_model,
                    torch.randn(self._input_shape),  # type: ignore
                    output_path,
                    export_params=True,
                    opset_version=opset,
                    do_constant_folding=True,
                    input_names=["input_image"],
                    output_names=["output"],
                )
                self.logger.info("Model export completed successfully.")
            except Exception as e:
                self.logger.error("Model export failed.")
                self.logger.exception(e)

    def __extract_encoding(self, module: CustomFakeQuantize) -> Dict:
        scale = module.scale
        zero_point = module.zero_point
        quant_min = module.quant_min
        quant_max = module.quant_max
        qscheme = module.qscheme
        dtype = str(module.dtype)

        bitwidth = get_bitwidth_from_string_dtype(dtype)

        is_symmetric = qscheme in [
            torch.per_tensor_symmetric,
            torch.per_channel_symmetric,
        ]

        if is_symmetric:
            encoding_min = -scale * ((quant_max - quant_min) / 2)
            encoding_max = scale * ((quant_max - quant_min) / 2)
        else:
            encoding_min = scale * (quant_min - zero_point)
            encoding_max = scale * (quant_max - zero_point)

        base_info = {
            "bitwidth": bitwidth,
            "quant_min": quant_min,
            "quant_max": quant_max,
            "qscheme": str(qscheme),
            "dtype": dtype,
            "is_symmetric": is_symmetric,
        }

        if scale.numel() == 1:
            return {
                **base_info,
                "encodings": [
                    {
                        "scale": scale.item(),
                        "offset": zero_point.item(),
                        "min": encoding_min.item(),
                        "max": encoding_max.item(),
                    }
                ],
            }

        else:
            encodings = []
            for i in range(scale.numel()):
                encodings.append(
                    {
                        "scale": scale[i].item(),
                        "offset": zero_point[i].item(),
                        "min": encoding_min[i].item(),
                        "max": encoding_max[i].item(),
                    }
                )
        return {**base_info, "encodings": encodings}

    def __get_quant_min_max(self, dtype):
        dtype = dtype.lower()
        if dtype == "int4":
            return -8, 7, torch.qint8
        elif dtype == "uint4":
            return 0, 15, torch.quint8
        elif dtype == "int8":
            return -128, 127, torch.qint8
        elif dtype == "uint8":
            return 0, 255, torch.quint8
        elif dtype == "int16":
            return -32768, 32767, torch.qint32
        #     return 0, 65535, torch.qint32
        else:
            raise ValueError(f"Unsupported dtype: {dtype}")

    def __get_encodings_from_model(self, model, encoding_dict=None) -> Dict[str, Dict]:
        """
        Extracts quantization parameters (scale, zero_point, min, max, etc.)
        from a model prepared using torch.ao.quantization.prepare_qat.

        Returns a hierarchical dictionary of encodings per FakeQuantize module.
        """
        encoding_dict = {}

        for name, child in model.named_modules():
            if not name:
                continue
            if "quant" in name:
                continue
            onnx_path = build_onnx_path_from_torch_name(name)
            cls_name = normalize_class_name(child.__class__.__name__)
            output_name = build_clean_onnx_path(f"{onnx_path}/{cls_name}")
            output_name = output_name.replace("Quantized", "")
            if "module_" in output_name:
                output_name.replace("module_", "")
            if isinstance(child, QuantizationMixin):
                data = {}
                for sub_name, sub_module in child.named_modules():
                    if isinstance(sub_module, (CustomFakeQuantize)):
                        encoding_info = self.__extract_encoding(sub_module)
                        data[f"{sub_name.replace('_quantizers','')}"] = encoding_info
                encoding_dict[output_name] = data

        return encoding_dict

    def generate_embeddings(self, attribute):
        """
        Iterates through model modules, collects quantization encodings from QuantizationMixin modules,
        and writes them to a JSON file as a list.
        """
        output_dir = (
            self.config["export"]["output_dir"]
            + "/"
            + get_model_configs(self.config, "name")
        )
        # if attribute is not None:
        #     if not hasattr(model, attribute):
        #         raise ValueError(f"Model has no attribute '{attribute}' for export")
        #     model = getattr(model, attribute)

        all_encodings = self.__get_encodings_from_model(
            self._model
            # if  isinstance(attribute, str) and not hasattr(self._model, attribute)
            # else  isinstance(attribute, str) and getattr(self._model, attribute)
        )

        task_type = (
            "qft"
            if get_model_configs(self.config, "qft")
            else "ptq" if get_model_configs(self.config, "ptq") else "pruning"
        )
        output_path = os.path.join(
            output_dir,
            f'{get_model_configs(self.config, "name")}_{task_type}_quantization_encodings.json',
        )
        os.makedirs(output_dir, exist_ok=True)

        with open(output_path, "w") as f:
            json.dump(all_encodings, f, indent=4)

        print(f"Quantization encodings saved to: {output_path}")
Update all method according to my quantsimparse
ignore aimet
i have sent one quantsimparser class right
some methods that you have used here is wrong
South Goa is a tranquil haven for travelers seeking a blend of luxury, nature, and authentic Goan charm. Unlike the bustling beaches of the North, South Goa offers serene stretches of sand, lush coconut groves, and a more laid-back vibe — making it the ideal destination for those who prefer a peaceful and personalized vacation experience. One of the best ways to enjoy this unique region is by staying in boutique resorts, which offer a mix of exclusivity, style, and local flavor that big hotel chains often lack.

Boutique resorts in South Goa are known for their distinctive charm and personalized hospitality. These resorts are typically smaller in size but big on experience — offering beautifully designed rooms, curated wellness programs, gourmet cuisine, and easy access to quiet beaches. If you're looking for an intimate getaway, a boutique resort like Soul Vacation
 offers the perfect escape. Located near Colva Beach, Soul Vacation blends Mediterranean-inspired design with Goan warmth, making it one of the top boutique choices in the region. Whether you're on a romantic holiday or a solo retreat, this resort offers tranquility and luxury in equal measure.

What sets boutique resorts apart in South Goa is their focus on individuality and attention to detail. Many of these properties are set in heritage homes or artistically crafted villas that reflect the cultural essence of Goa. With fewer rooms and a focus on bespoke service, guests enjoy a more intimate and relaxing experience. You’ll often find yoga sessions by the beach, spa treatments using local ingredients, and home-style meals that highlight traditional Goan recipes.

Beyond the resorts themselves, South Goa offers plenty to explore — from hidden waterfalls and spice plantations to historic churches and quiet fishing villages. Staying in a boutique resort puts you closer to these unique experiences, away from the crowds, while still enjoying all the comforts of a luxury holiday. It’s not just about accommodation; it’s about creating lasting memories in an environment that feels both indulgent and authentic.

Whether you're escaping the hustle of daily life or planning a special celebration, boutique resorts in South Goa offer a soulful, immersive, and unforgettable stay.

Visit: https://soulvacation.in/resort-in-south-goa/
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: What's on in Melbourne this week! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday and hope you all had a Beautiful weekend! Please see below for what's on this week. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering:* \n\n :caramel-slice: *Sweet Treats*: Selection of cookies \n\n :coffee: *Weekly Café Special*: English Toffee Coffee"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 27th August :calendar-date-27:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n:lunch: :flag-fr: Join us for an French lunch From *12pm* in the Wominjeka breakout space! Menu in the:thread: "
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 28th August :calendar-date-28:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":breakfast: *Breakfast*: Join us for Breakfast from *8:30am - 10:30am* in the Wominjeka Breakout Space. Menu in the :thread: \n\n\n\n *What Else? :green_heart:*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": " Feedback on our Boost Offerings? We want to hear more. Let us know what you love by filling out our form <https://docs.google.com/forms/d/e/1FAIpQLScGOSeS5zUI8WXEl0K4WGoQUkmpIHzAjLlEKWBob4sMPhDXmA/viewform|here.>  \n\n Stay tuned to this channel, and make sure you're subscribed to the <https://calendar.google.com/calendar/u/0?cid=Y19xczkyMjk5ZGlsODJzMjA4aGt1b3RnM2t1MEBncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Melbourne Social Calendar*> :party-wx:"
			}
		}
	]
}
C:\Users\Ismingiz>python --version
<style>
	/* menu open */
body{
	  overflow-x: hidden;
}
body.open-menu{
	overflow: hidden;
}
#header-main{
	transition: all 0.5s;
}
.scroll-web #header-main {
	background-color: #1B101D !important;
	top: 20px;
}
#menu-menu-header .menu-item.menu-item-has-children {
    margin-top: 0;
    padding: 0 25px;
}
#menu-menu-header .menu-item.menu-item-has-children > a {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 0;
}
#menu-menu-header .menu-item.menu-item-has-children > a:first-child:after {
    content: "";
    background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOSIgaGVpZ2h0PSI1IiB2aWV3Qm94PSIwIDAgOSA1IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNNC4xNjc5NyA0Ljk0OTIyTDAgMC43ODEyNUwwLjczMDQ2OSAwLjA1MDc4MTJMMS4wOTU3IDAuNDE2MDE2TDQuMTY3OTcgMy41MDk3N0w3LjYwNTQ3IDAuMDcyMjY1Nkw4LjMzNTk0IDAuNzgxMjVMNC4xNjc5NyA0Ljk0OTIyWiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==);
    width: 8.336px;
    height: 4.898px;
    position: unset;
    display: block;
}
.menu-icon {
	width: 50px;
	height: 50px;
	background: #f15a29; 
	display: flex;
	justify-content: center;
	align-items: center;
	cursor: pointer;
	flex-direction: column;
	transition: background 0.3s ease;
}
 
.menu-icon:hover {
	background: #27b4b2; 
}
 
.menu-icon span {
	display: block;
	width: 30px;
	height: 2px;
	background: white;
	margin: 2.5px 0;
	transition: width 0.3s ease;
}
 
.menu-icon:hover span:nth-child(2) {
	width: 16px;
}
@media(min-width: 981px){
	#menu-open{
		display: none !important;
	}
}
#menu-mobile-section{
	opacity: 0;
	visibility: hidden;
	transition: all 0.5s;
}
#menu-mobile-section.active {
    opacity: 1 !important;
    visibility: visible !important;
    z-index: 1000 !important;
}
#menu-mobile-section #menu-box {
    transition: all 0.5s;
}
#menu-mobile-section.active #menu-box {
    right: 0;
}
.header-menu-custom{
		height: calc(100% - 30px);
    overflow: scroll;
	 scrollbar-width: none;
    -ms-overflow-style: none;
}
.header-menu-custom::-webkit-scrollbar{
	display: none;
}
.header-menu-custom .menu {
    list-style: none;
    padding: 0;
}
#menu-mobile-section .header-menu-custom .sub-menu {
    list-style: none;
    padding: 0 0 0 20px !important;
    display: none;
}
#menu-mobile-section .header-menu-custom .et-show-dropdown ul.sub-menu {
    display: block;
}
#menu-mobile-section .header-menu-custom .menu a {
    color: #323D62;
    font-family: Figtree;
    font-size: 18px;
    font-style: normal;
    font-weight: 500;
    line-height: 1.35;
    letter-spacing: 0.24px;
    padding: 10px;
    width: 100%;
    display: block;
    position: relative;
}
#menu-mobile-section .header-menu-custom .menu .sub-menu a {
    font-size: 16px;
    line-height: 1.2;
    padding: 8px 0;
}
#menu-mobile-section .header-menu-custom .menu .menu-item-has-children >  a:after {
    content: "";
    width: 12px;
    height: 12px;
    position: absolute;
    background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iOSIgaGVpZ2h0PSI1IiB2aWV3Qm94PSIwIDAgOSA1IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8cGF0aCBkPSJNNC4xNjc5NyA0Ljk0OTIyTDAgMC43ODEyNUwwLjczMDQ2OSAwLjA1MDc4MTJMMS4wOTU3IDAuNDE2MDE2TDQuMTY3OTcgMy41MDk3N0w3LjYwNTQ3IDAuMDcyMjY1Nkw4LjMzNTk0IDAuNzgxMjVMNC4xNjc5NyA0Ljk0OTIyWiIgZmlsbD0iIzFCMTAxRCIvPgo8L3N2Zz4K);
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;
    top: 50%;
    transform: translateY(-50%);
    right: 0;
	  transition: all 0.3s;
}
#menu-mobile-section .header-menu-custom .menu .menu-item-has-children.et-hover >  a:after{
	transform: translateY(-50%) rotate(180deg);
}
 
.close-button {
    width: 30px;
    height: 30px;
    padding: 5px;
    position: relative;
    cursor: pointer;
    margin: 0 0 0 auto;
    background: #ED5D2C;
}
.close-button span {
    position: absolute;
    width: 2px;
    height: 60%;
    background-color: #ffffff;
    top: 50%;
    left: 50%;
    transform-origin: center;
    transition: all 0.3s;
}
.close-button:hover{
	background: #32B4B8;
}
.close-button .line1 {
    transform: translate(-50%, -50%) rotate(45deg);
}
.close-button .line2 {
    transform: translate(-50%, -50%) rotate(-45deg);
}
 
@media(min-width: 982px){
	.menu-icon.menu-open {
			display: none;
	}
}
@media(min-width: 767px){
	#menu-mobile-section.active #menu-box {
			width: 80%;
      max-width: 520px;
	}
}
@media(max-width: 767px){
	.menu-icon {
    width: 40px;
    height: 40px;
	}
}
@media(max-width: 520px){
	#menu-mobile-section.active #menu-box {
			width: 100%;
	}
	.menu-icon {
    width: 40px;
    height: 40px;
	}
}
</style>
// Menu
function custom_menu_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'name' => 'Menu Header',
        ),
        $atts
    );
 
    $menu = wp_nav_menu(
        array(
            'menu'            => $atts['name'],
            'container'       => 'nav',
            'container_class' => 'header-menu-custom',
            'echo'            => false,
            'depth'           => 0,
            'fallback_cb'     => false,
        )
    );
 
    return $menu ?: '';
}
add_shortcode( 'show_menu', 'custom_menu_shortcode' );
jQuery(document).ready(function($) {
    $('.menu-icon').click(function() {
        $('#menu-mobile-section').addClass('active');
        $('body').addClass('open-menu');
    });
 
    $('.menu-close').click(function() {
        $('#menu-mobile-section').removeClass('active');
        $('body').removeClass('open-menu');
    });
 
    $(document).click(function(event) {
        if (!$(event.target).closest('#menu-box, .menu-open').length) {
            $('#menu-mobile-section').removeClass('active');
            $('body').removeClass('open-menu');
        }
    });
 
    $('.header-menu-custom .menu .menu-item-has-children > a').on('click', function(e) {
        var $this = $(this);
        var subMenu = $this.siblings('.sub-menu');
        if (subMenu.length) {
            if (!subMenu.is(':visible')) {
                e.preventDefault();
                $('.header-menu-custom .menu .sub-menu').slideUp();
                $('.header-menu-custom .menu .menu-item-has-children').removeClass('active-sub');
                subMenu.slideDown();
                $this.parent().addClass('active-sub');
            }
        }
    });
	
	$(window).scroll(function() {
        if ($(this).scrollTop() > 0) {
            $('body').addClass('scroll-web');
        } else {
            $('body').removeClass('scroll-web');
        }
    });
});
// Utility function for delay
function wait(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// Function to hit API with retries and delay
function hitApiWithRetry(url, options = {}, retries = 3, delay = 1000, callbacks = {}) {
  return new Promise(async (resolve, reject) => {
    for (let attempt = 1; attempt <= retries; attempt++) {
      try {
        console.log(`Attempt ${attempt}...`);
        let response = await fetch(url, options);

        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }

        let data = await response.json();

        // success callback
        if (callbacks.onSuccess) {
          callbacks.onSuccess(data, attempt);
        }

        return resolve(data); // resolve promise if success
      } catch (err) {
        console.error(`Error on attempt ${attempt}: ${err.message}`);

        // error callback
        if (callbacks.onError) {
          callbacks.onError(err, attempt);
        }

        if (attempt < retries) {
          console.log(`Retrying in ${delay}ms...`);
          await wait(delay);
        } else {
          return reject(`Failed after ${retries} attempts`);
        }
      }
    }
  });
}

// Usage example:
hitApiWithRetry(
  "https://jsonplaceholder.typicode.com/posts/1",
  {},
  3,  // retries
  2000, // delay (ms)
  {
    onSuccess: (data, attempt) => {
      console.log(`✅ Success on attempt ${attempt}`, data);
    },
    onError: (err, attempt) => {
      console.log(`❌ Failed on attempt ${attempt}: ${err.message}`);
    }
  }
)
.then(data => console.log("Final Data:", data))
.catch(err => console.log("Final Error:", err));
const apiserver = new Promise((resolve, reject) => {
    const user = {
        name: "tanishq dhingra",
        age: 19,
    };

    const status = 200;

    if (status === 200) {
        resolve(user);
    } else {
        reject("some error occurred here");
    }
});

apiserver
    .then((result) => {
        console.log(result);
    })
    .catch((err) => {
        console.log(err); // shows actual error message
    });
public LedgerDimensionAccount getLedgerDimensionModified(
    LedgerDimensionAccount _ledgerDimension,
    DimensionValue         _toDimTaxDeductionVal)
{
    LedgerDimensionAccount          ledgerDimension;
    DimensionDefault                defaultDimension;
    LedgerDimensionDefaultAccount   defaultAccount;

    DimensionAttribute                  dimAttr;
    DimensionAttributeValue             dimAttrValue;
    DimensionAttributeValueSetStorage   dimAttrValDimStorage;
    DimensionStorage                    dimAttrStorage;
    int                                 i;

    // Name of dimension attribute to change, example: TaxDeduction
    #define.DimAttrTaxDeductionName('TaxDeduction')
    ;

    dimAttr = DimensionAttribute::findByName(#DimAttrTaxDeductionName);

    if (_toDimTaxDeductionVal != '')
    {
        // convert to Default dimensions
        defaultDimension = DimensionStorage::getDefaultDimensionFromLedgerDimension(_ledgerDimension);
        dimAttrValDimStorage = DimensionAttributeValueSetStorage::find(defaultDimension);

        // find DimensionAttributeValue for specified display value of TaxDeduction dimension
        dimAttrValue = DimensionAttributeValue::findByDimensionAttributeAndValue(dimAttr, _toDimTaxDeductionVal);

        // add dimension value to Default dimension
        dimAttrValDimStorage.addItemValues(dimAttr.RecId, dimAttrValue.RecId, dimAttrValue.HashKey);
        defaultDimension = dimAttrValDimStorage.save();

        // combine default dimension with ledger dimension representing main account
        defaultAccount = DimensionStorage::getLedgerDefaultAccountFromLedgerDim(_ledgerDimension);
        ledgerDimension = DimensionDefaultingService::serviceCreateLedgerDimension(defaultAccount, defaultDimension);
    }
    // remove dimension from combination
    else
    {
        dimAttrStorage = DimensionStorage::findById(_ledgerDimension);
        for (i = 1; i <= dimAttrStorage.segmentCount(); i++)
        {
            if (dimAttrStorage.getAttributeIdForSegment(i) == dimAttr.RecId)
                dimAttrStorage.clearSegment(i);
        }
        ledgerDimension = dimAttrStorage.save();
    }

    return ledgerDimension;
}

// https://daxtarkowski.wordpress.com/2014/04/16/changing-value-in-ledger-dimension-combination/
(function($){
	$('body').off("click", ".qib-button").on('click','.woocommerce-mini-cart-item-info-price .qib-button',function(e){
		e.preventDefault();
		var $this	= $(this),
			$qty	= $this.parent().find('.qty'),
			$qty_val = $qty.val(),
			currentVal	= parseFloat($qty.val()),
			max			= parseFloat($qty.attr('max')),
			min			= parseFloat($qty.attr('min')),
			step		= $qty.attr('step');
		
		$(this).addClass('loading');
		// Format values
		if (!currentVal || currentVal === '' || currentVal === 'NaN') currentVal = 0;
		if (max === '' || max === 'NaN') max = '';
		if (min === '' || min === 'NaN') min = 0;
		if (step === 'any' || step === '' || step === undefined || parseFloat(step) === 'NaN') step = 1;
		
		// Change the value
		if ($this.hasClass('plus')) {
			if (max && (max == currentVal || currentVal > max)) {
				$qty_val = max;
				
			} else {
				$qty_val = currentVal + parseFloat(step);
				
				//clickThrottle = setTimeout(function() { self.quantityInputsTriggerEvents($qty); }, clickThrottleTimeout);
			}
		} else {
			if (min && (min == currentVal || currentVal < min)) {
				$qty_val = min;
				
			} else if (currentVal > 0) {
				$qty_val = currentVal - parseFloat(step);
				
				//clickThrottle = setTimeout(function() { self.quantityInputsTriggerEvents($qty); }, clickThrottleTimeout);
			}
		}
		$qty.val($qty_val);
		//console.log($qty_val);
		callChangeQTYAddToCart($qty,$qty_val);
	});
	$('body').on('added_to_cart',function(e,data) {
		$(document.body).trigger('wc_fragment_refresh').trigger('updated_cart_totals');
	});
	$(document).ajaxComplete(function () {
		//alert(1);
		/*if (cartOpen) {
		  setTimeout(function () {
			openCart();
		  }, 100);
		}
		*/
		
	  });
	$(document).on('removed_from_cart', function(event, cart_item_key) {
        console.log("Item removed with key: " + cart_item_key);
        preventRedirect = true;
		//alert(11);
		return false;
		jQuery('body').addClass('is-visible');
    });
	jQuery(document.body).on('removed_from_cart updated_cart_totals',
		function() {
			
		  	jQuery(document.body).trigger('update_checkout');
		}
	);
	jQuery('body').on('change','.woocommerce-mini-cart-item-info-price .qty',function(e){
		e.preventDefault();
		var $this	= $(this),
			$qty_val = $this.val();
		callChangeQTYAddToCart($this,$qty_val);
	})
	function callChangeQTYAddToCart($qty,$qty_val){
		var self = this;
		if (self.cartPanelAjax) {
			self.cartPanelAjax.abort();
		}
		var $cartForm = $('#nm-cart-panel-form'), 
                $cartFormNonce = $cartForm.find('#_wpnonce'),
                data = {};
		if ( ! $cartFormNonce.length ) {
			return;
		}
		data['nm_cart_panel_update'] = '1';
		data['update_cart'] = '1';
		data[$qty.attr('name')] = $qty_val;
		data['_wpnonce'] = $cartFormNonce.val();
        
		// Make call to actual form post URL.
		self.cartPanelAjax = $.ajax({
			type:     'POST',
			url:      $cartForm.attr('action'),
			data:     data,
			dataType: 'html',
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				console.log('NM: AJAX error - widgetPanelCartUpdate() - ' + errorThrown);
			},
			success:  function(response) {
				$(document.body).trigger('wc_fragment_refresh').trigger('updated_cart_totals');
				if($('body').hasClass('woocommerce-checkout'))
					jQuery(document.body).trigger('update_checkout');
			},
			complete: function() {
				self.cartPanelAjax = null; // Reset Ajax state
			}
		});
	}
})(jQuery)
jQuery(document.body).on('wc_fragment_refresh', function() {
	
    // Send AJAX to get content of minicart
    jQuery.ajax({
        url: wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
        type: 'POST',
        success: function(data) {
            if (data && data.fragments) {
                // Update element
                //debugger;
                jQuery.each(data.fragments, function(key, value) {
                    jQuery(key).replaceWith(value);
                });
             
                console.log('Minicart has been refreshed');

            }
        }
    });
	
});
function smo_add_to_cart_func($atts) {
    ob_start();
	$atts = shortcode_atts(
        array(
            'product_id' => '',
        ), 
        $atts, 
        'smo_add_to_cart'
    );
	$product_id = $atts['product_id'];
	if ( ! class_exists( 'WooCommerce' ) ) {
        return;
    }
    $product = wc_get_product( $product_id );
    if ( ! $product || ! $product->is_purchasable() || ! $product->is_in_stock() ) {
        return;
    }
	
    echo '<form action="' . esc_url( get_the_permalink($product_id) ) . '" method="post" class="cart">';
    echo '<button type="submit" name="add-to-cart" value="' . esc_attr( $product_id ) . '" class="single_add_to_cart_button button alt">Add to cart - '.$product->get_price_html().'</button>';
    echo '</form>';
?>
<?php
	$output = ob_get_contents();
    ob_end_clean();
    return $output;
}

add_shortcode('smo_add_to_cart', 'smo_add_to_cart_func');
// Tạo field trong variation
add_action( 'woocommerce_variation_options', 'add_custom_variation_field', 10, 3 );
function add_custom_variation_field( $loop, $variation_data, $variation ) {
    woocommerce_wp_text_input( array(
        'id' => '_custom_variation_field[' . $loop . ']',
        'label' => 'Custom Save Percent(%)',
        'desc_tip' => true,
        'description' => '',
        'value' => get_post_meta( $variation->ID, '_custom_variation_field', true )
    ));
}

add_action( 'woocommerce_save_product_variation', 'save_custom_variation_field', 10, 2 );
function save_custom_variation_field( $variation_id, $i ) {
	$custom_field = $_POST['_custom_variation_field'][$i];
    if ( isset( $custom_field ) ) {
        update_post_meta( $variation_id, '_custom_variation_field', esc_attr( $custom_field ) );
    }
}
add_filter( 'woocommerce_available_variation', 'bbloomer_add_custom_field_variation_data' );
function bbloomer_add_custom_field_variation_data( $variations ) {
  $variations['save_percent'] = '<span class="discount-percentage">Save ' . get_post_meta( $variations[ 'variation_id' ], '_custom_variation_field', true ) . '%</span>';
  return $variations;
}

// Tạo Save percentage trong variations
function custom_variation_price_discount( $variations ) {
    if( isset( $variations['price_html'] ) && $variations['price_html'] != '' ) {
		$discount_message = '';
		$variation = wc_get_product( $variations['variation_id'] );
		
		if ( $variation->is_on_sale() ) {
			if($variations['save_percent'] && $variations['save_percent'] == ''){
				$regular_price = $variation->get_regular_price();
				$sale_price = $variation->get_sale_price();
				if ( $regular_price > 0 && $sale_price > 0 ) {
					$percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
					$discount_message = '<span class="discount-percentage">Save ' . $percentage . '%</span>';
				}
			}else{
				$discount_message = $variations['save_percent'];
			}
		}
		
        $variations['price_html'] = '<div class="price-wrap">'. $variations['price_html'] . $discount_message  . '</div>';
    }
    return $variations;
}

add_filter( 'woocommerce_available_variation', 'custom_variation_price_discount' );
add_action( 'wp', 'bbloomer_remove_zoom_lightbox_theme_support', 99 );
  
function bbloomer_remove_zoom_lightbox_theme_support() { 
    remove_theme_support( 'wc-product-gallery-zoom' );
    remove_theme_support( 'wc-product-gallery-lightbox' );
    remove_theme_support( 'wc-product-gallery-slider' );
}
remove_action('woocommerce_mini_cart_contents', 'commercekit_minicart_order_bump', 99);
add_action( 'custom_mini_cart_order_bump', 'commercekit_minicart_order_bump', 99 );


//pluign commercegurus-commercekit
https://drive.google.com/file/d/11QZEzZt8syH3elbPZFfp6Bbu8PTqUaac/view?usp=sharing
function custom_mini_cart() {
    if ( function_exists('WC') && WC()->cart ) {
        ?>
        <div class="custom-mini-cart">
            <a class="cart-contents" href="#" title="<?php _e( 'View your shopping cart', 'text-domain' ); ?>">
				<svg xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 576 512" aria-hidden="true" class="icon icon-cart">
				 	 <title>Your cart</title><path d="M16 0H0V32H16 67.2l77.2 339.5 2.8 12.5H160 496h16V352H496 172.8l-14.5-64H496L566 64l10-32H542.5 100L95.6 12.5 92.8 0H80 16zm91.3 64H532.5l-60 192H151L107.3 64zM184 432a24 24 0 1 1 0 48 24 24 0 1 1 0-48zm0 80a56 56 0 1 0 0-112 56 56 0 1 0 0 112zm248-56a24 24 0 1 1 48 0 24 24 0 1 1 -48 0zm80 0a56 56 0 1 0 -112 0 56 56 0 1 0 112 0z"></path>
				</svg>
                <span class="cart-contents-count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
            </a>
        </div>
        <?php
    } else {
        echo '<p>' . __( 'Cart is empty.', 'text-domain' ) . '</p>';
    }
}
add_shortcode('custom_mini_cart', 'custom_mini_cart');
function custom_mini_cart_content() {
    if ( function_exists('WC') && WC()->cart ) {
        ?>
			<div class="bg_minicart_show"></div>
			<div class="minicart-wrap">
				<div class="widget_shopping_cart_heading">
					<h3>
						Your Cart
					</h3>
					<button type="button" aria-label="Close Cart" class="mni-cart-close"><img src="<?php echo get_stylesheet_directory_uri(); ?>/close.png" alt="" /></button>
				</div>
				<div class="widget_shopping_cart_content">
					<?php woocommerce_mini_cart(); ?>
				</div>
			</div>
            
        
        <?php
    } else {
        echo '<p>' . __( 'Cart is empty.', 'text-domain' ) . '</p>';
    }
}
add_shortcode('custom_mini_cart_content', 'custom_mini_cart_content');
function add_to_cart_fragment( $fragments ) {
    if ( function_exists('WC') && WC()->cart ) {
        ob_start();
        ?>
        <span class="cart-contents-count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
        <?php
        $fragments['.cart-contents-count'] = ob_get_clean();
    }
    return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'add_to_cart_fragment' );
<?php
		$product = wc_get_product(get_the_ID());
		$post_date = get_the_date('Y-m-d', get_the_ID());
		$post_date_time = strtotime($post_date);
		$current_date_time = strtotime(current_time('Y-m-d'));
		$date_diff = ($current_date_time - $post_date_time) / (60 * 60 * 24);
		if ($date_diff <= 10){
			echo '<span class="badge new-label">NEW</span>';
		}
	?>
	<?php
		$max_discount = 0;
		$output = '';

		if ($product->is_type('variable')) {
			foreach ($product->get_available_variations() as $variation) {
				$regular_price_variation = $variation['display_regular_price'];
				$sale_price_variation = $variation['display_price'];
				if ($sale_price_variation < $regular_price_variation) {
					$percentage_off = round((($regular_price_variation - $sale_price_variation) / $regular_price_variation) * 100);
					if ($percentage_off > $max_discount) {
						$max_discount = $percentage_off;
					}
				}
			}
			if ($max_discount > 0) {
				$output = '<span class="badge sale">ON SALE</span>';
			}
		} else {
			$regular_price = (float) $product->get_regular_price();
			$sale_price = (float) $product->get_sale_price();
			if ($sale_price && $sale_price < $regular_price) {
				$output = '<span class="badge sale">ON SALE</span>';
			}
		}
		if($output){
			echo $output;
		}
	?>
$('form.variations_form').on('found_variation', function(event, variation) {
				
				var imageSrc = variation.image.src;

				if(jQuery('.rst-image-product-thumb').length){
					if (imageSrc) {
						if (swiper2.activeIndex !== 0)
							swiper2.slideTo(0);
						setTimeout(function(){
							$('.product-single-image .swiper-slide-active img').attr('src',imageSrc);
						},100)
					}
				}
			});
function enable_ajax_add_to_cart_single_product() {
    if (is_product()) {
        ?>
        <script type="text/javascript">
           
			jQuery(function($){
				
				/* global wc_add_to_cart_params */
				if ( typeof wc_add_to_cart_params === 'undefined' ) {
					return false;
				}
				// Ajax add to cart on the product page
				var $warp_fragment_refresh = {
					url: woocommerce_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'get_refreshed_fragments' ),
					type: 'POST',
					success: function( data ) {
						if ( data && data.fragments ) {

							$.each( data.fragments, function( key, value ) {
								$( key ).replaceWith( value );
							});

							$( document.body ).trigger( 'wc_fragments_refreshed' );
							$('body').addClass('is-visible');
						}
					}
				};

				$('form.cart').on('submit', function (e)
				{
					e.preventDefault();
					var form = $(this),
					button = form.find('.single_add_to_cart_button');
					button.block({ 
						message: null, 
						overlayCSS: {
							
							opacity: 0 
						}
					});

					var product_url = window.location;

					$.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result)
					{
						

						// update fragments
						$.ajax($warp_fragment_refresh);

						button.unblock();

					});
				});
			});
        </script>
        <?php
   }
}
add_action('wp_footer', 'enable_ajax_add_to_cart_single_product');
function enqueue_woocommerce_ajax_add_to_cart() {
    if (is_product()) {
        wp_enqueue_script('wc-add-to-cart'); // WooCommerce Add to Cart Script
        wp_enqueue_script('woocommerce');
    }
}

add_action('wp_enqueue_scripts', 'enqueue_woocommerce_ajax_add_to_cart');
function display_product_variations_in_cart($cart_item, $cart_item_key) { 
    if (!empty($cart_item['variation'])) {
        echo '<div class="cart-item-variations">';
		
        foreach ($cart_item['variation'] as $key => $value) {
			
            $taxonomy = str_replace('attribute_', '', $key);
            $term = get_term_by('slug', $value, $taxonomy);
			
            if ($term) {
                echo '<p>' . $term->name . '</p>';
            }
        }
        echo '</div>';
    }
}
add_action('woocommerce_after_cart_item_name', 'display_product_variations_in_cart', 10, 2);
function custom_variation_price_discount( $variations ) {
    if( isset( $variations['price_html'] ) && $variations['price_html'] != '' ) {
		$discount_message = '';
		$variation = wc_get_product( $variations['variation_id'] );
		
		if ( $variation->is_on_sale() ) {
			if($variations['save_percent'] && $variations['save_percent'] == ''){
				$regular_price = $variation->get_regular_price();
				$sale_price = $variation->get_sale_price();
				if ( $regular_price > 0 && $sale_price > 0 ) {
					$percentage = round( ( ( $regular_price - $sale_price ) / $regular_price ) * 100 );
					$discount_message = '<span class="discount-percentage">Save ' . $percentage . '%</span>';
				}
			}else{
				$discount_message = $variations['save_percent'];
			}
		}
		
        $variations['price_html'] = '<div class="price-wrap">'. $variations['price_html'] . $discount_message  . '</div>';
    }
    return $variations;
}

add_filter( 'woocommerce_available_variation', 'custom_variation_price_discount' );
function smo_product_images_func2($atts) {
    ob_start();
	$atts = shortcode_atts(
        array(
            'product_id' => '',
        ), 
        $atts, 
        'smo_product_images2'
    );
	if(isset($atts['product_id']) && $atts['product_id'] != '') {
		$id = $atts['product_id'];
	}else{
		$id = get_the_ID();
	}
	$product = wc_get_product($id);
	//global $product;
	$thumbnail_size = 'woocommerce_single';
    $thumbnail_size_full = 'full';
	if ($product) {
	$post_thumbnail_id = $product->get_image_id();
	$attachment_ids = $product->get_gallery_image_ids();
	$thumbnail_src     = wp_get_attachment_image_src( $post_thumbnail_id, $thumbnail_size_full );
	$thumbnail_src2     = wp_get_attachment_image_src( $post_thumbnail_id, $thumbnail_size );
	}
?>
<div class="product--thumbnail_slider">
<div class="swiper rst-image-product-big2">
    <div class="swiper-wrapper">
		<div class="swiper-slide rst-item-image-product-big">
			<img src="<?php echo esc_url( $thumbnail_src[0] ); ?>" alt="" />
		</div>
		<?php
		if ( is_array($attachment_ids) && !empty($attachment_ids) ) {
		foreach ( $attachment_ids as $attachment_id ) {
		$gallery_src = wp_get_attachment_image_src( $attachment_id, $thumbnail_size_full );
		?>
		<div class="swiper-slide rst-item-image-product-big">
			<img src="<?php echo esc_url( $gallery_src[0] ); ?>" alt="" />
		</div>
		<?php
		}
		}
		?>
	</div> 
	<div class="swiper-pagination"></div>
</div> 
<?php
	if ( is_array($attachment_ids) && !empty($attachment_ids) ) {
?>
<div class="rst-image-product-thumb-container2">
<div class="swiper rst-image-product-thumb2">
    <div class="swiper-wrapper">
		<div class="swiper-slide rst-item-image-product-thumb">
			<div class="rst-item-image-product-thumb-img"><img src="<?php echo esc_url( $thumbnail_src2[0] ); ?>" alt="" /></div>
		</div>
		<?php
		
		foreach ( $attachment_ids as $attachment_id ) {
		$gallery_src = wp_get_attachment_image_src( $attachment_id, $thumbnail_size );
		?>
		<div class="swiper-slide rst-item-image-product-thumb">
			<div class="rst-item-image-product-thumb-img"><img src="<?php echo esc_url( $gallery_src[0] ); ?>" alt="" /></div>
		</div>
		<?php
		}
		?>
	</div>
	
</div>
	</div>
<?php
	}
?>
</div>
<?php	
	$output = ob_get_contents();
    ob_end_clean();
    return $output;
}

add_shortcode('smo_product_images2', 'smo_product_images_func2');
$(document).on('found_variation', 'form.cart', function(event, variation) {
	console.log(variation);
    if (variation.price_html) {
      $('.custom-price-box .elementor-widget-container').html(variation.price_html + variation.variation_description);
    }
});
function addCouponToMiniCart(){
?>
<div class="mini-cart-nm-coupon" style="margin-bottom: 10px;">
    <div class="nm-coupon" style="display: flex;">
       <input type="text" id="nm-coupon-code" class="input-text nm-coupon-code" name="nm_coupon_code" value="" placeholder="Discount code">
       <button type="button" id="nm-apply-coupon-btn" class="button" name="nm_apply_coupon" value="" onclick="applyCoupon(this)" style="white-space: nowrap;">Apply</button>
    </div>
    <div class="nm-coupon-notify" style="display: none; color: #FF0000;"></div>
</div>
<script type="text/javascript">
function applyCoupon(button) {
    let form = button.closest('.nm-coupon');
    let couponCode = form.querySelector(".nm-coupon-code").value;
    let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
    jQuery.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'json',
        data: 'coupon_code=' + couponCode + '&action=custom_apply_coupon',
        success: function (data) {
            if (data.status === 'success') {
                jQuery(document.body).trigger('wc_fragment_refresh');
                if (jQuery('body').hasClass('woocommerce-checkout'))
                    jQuery(document.body).trigger('update_checkout');
            } else if (data.status === 'already_used') {
                jQuery('.nm-coupon-notify').html('Coupon already used!');
                jQuery('.nm-coupon-notify').show();
            } else {
                jQuery('.nm-coupon-notify').html('Coupon is not valid!');
                jQuery('.nm-coupon-notify').show();
            }
        },
    });
}

(function($) {
    $('body').on('click', '.woocommerce-remove-coupon', function(e) {
        e.preventDefault();
        let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var coupon = $(this).data('coupon');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'remove_coupon',
                coupon: coupon,
            },
            success: function(response) {
                jQuery(document.body).trigger('wc_fragment_refresh');
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    });
})(jQuery);
</script>
<?php    
}
//add_action('woocommerce_widget_shopping_cart_before_buttons', 'addCouponToMiniCart', 20);
add_action('woocommerce_custom_checkout_counpon', 'addCouponToMiniCart', 10);

add_action('wp_ajax_custom_apply_coupon', 'custom_apply_coupon');
add_action('wp_ajax_nopriv_custom_apply_coupon', 'custom_apply_coupon');

function custom_apply_coupon() {
    $coupon_code = isset($_GET['coupon_code']) ? $_GET['coupon_code'] : '';
    $coupon_code = sanitize_text_field($coupon_code);

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        echo json_encode(array('status' => 'already_used'));
    } else {
        // Apply coupon
        $applied = WC()->cart->apply_coupon($coupon_code);
        if ($applied) {
            echo json_encode(array('status' => 'success'));
        } else {
            echo json_encode(array('status' => 'invalid'));
        }
    }
    wp_die();
}

add_action('wp_ajax_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_remove_coupon', 'remove_coupon_from_cart');

function remove_coupon_from_cart() {
    if (isset($_POST['coupon'])) {
        $coupon_code = sanitize_text_field($_POST['coupon']);
        WC()->cart->remove_coupon($coupon_code);
        wc_clear_notices(); 
        
        wp_send_json_success();
    } else {
        wp_send_json_error('Coupon code not provided.');
    }
}
remove_action( 'woocommerce_checkout_order_review', 'woocommerce_checkout_payment', 20 );
add_filter('woocommerce_checkout_fields', 'remove_postal_code_field');
function remove_postal_code_field($fields) {
    //unset($fields['billing']['kl_newsletter_checkbox']);
		//unset($fields['billing']['billing_email']);
    return $fields;
}

add_action( 'woocommerce_checkout_after_customer_details', 'woocommerce_checkout_payment', 10 );
remove_action( 'woocommerce_before_checkout_form', 'woocommerce_checkout_coupon_form', 10 );
function custom_woocommerce_place_order_button_text( $button_text ) {
    return 'Pay now';
}
add_filter( 'woocommerce_order_button_text', 'custom_woocommerce_place_order_button_text' );
function custom_checkout_privacy_policy_text( $text ) {
    return 'One or more items in your cart is a deferred or recurring purchase. By continuing with your payment, you agree that your payment method will automatically be charged at the price and frequency listed on this page until it ends or you cancel. All cancellations are subject to the <a href="" class="click-cancellation">cancellation policy</a>.';
}
add_filter( 'woocommerce_get_privacy_policy_text', 'custom_checkout_privacy_policy_text' );

function addCouponToMiniCart(){
?>
<div class="mini-cart-nm-coupon" style="margin-bottom: 10px;">
    <div class="nm-coupon" style="display: flex;">
       <input type="text" id="nm-coupon-code" class="input-text nm-coupon-code" name="nm_coupon_code" value="" placeholder="Discount code">
       <button type="button" id="nm-apply-coupon-btn" class="button" name="nm_apply_coupon" value="" onclick="applyCoupon(this)" style="white-space: nowrap;">Apply</button>
    </div>
    <div class="nm-coupon-notify" style="display: none; color: #FF0000;"></div>
</div>
<script type="text/javascript">
function applyCoupon(button) {
    let form = button.closest('.nm-coupon');
    let couponCode = form.querySelector(".nm-coupon-code").value;
    let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    
    jQuery.ajax({
        type: "GET",
        url: ajaxurl,
        dataType: 'json',
        data: 'coupon_code=' + couponCode + '&action=custom_apply_coupon',
        success: function (data) {
            if (data.status === 'success') {
                jQuery(document.body).trigger('wc_fragment_refresh');
                if (jQuery('body').hasClass('woocommerce-checkout'))
                    jQuery(document.body).trigger('update_checkout');
            } else if (data.status === 'already_used') {
                jQuery('.nm-coupon-notify').html('Coupon already used!');
                jQuery('.nm-coupon-notify').show();
            } else {
                jQuery('.nm-coupon-notify').html('Coupon is not valid!');
                jQuery('.nm-coupon-notify').show();
            }
        },
    });
}

(function($) {
    $('body').on('click', '.woocommerce-remove-coupon', function(e) {
        e.preventDefault();
        let ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
        var coupon = $(this).data('coupon');
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'remove_coupon',
                coupon: coupon,
            },
            success: function(response) {
                jQuery(document.body).trigger('wc_fragment_refresh');
            },
            error: function(error) {
                console.log('Error:', error);
            }
        });
    });
})(jQuery);
</script>
<?php    
}
//add_action('woocommerce_widget_shopping_cart_before_buttons', 'addCouponToMiniCart', 20);
add_action('woocommerce_custom_checkout_counpon', 'addCouponToMiniCart', 10);

add_action('wp_ajax_custom_apply_coupon', 'custom_apply_coupon');
add_action('wp_ajax_nopriv_custom_apply_coupon', 'custom_apply_coupon');

function custom_apply_coupon() {
    $coupon_code = isset($_GET['coupon_code']) ? $_GET['coupon_code'] : '';
    $coupon_code = sanitize_text_field($coupon_code);

    // Check if the coupon is already applied
    if (WC()->cart->has_discount($coupon_code)) {
        echo json_encode(array('status' => 'already_used'));
    } else {
        // Apply coupon
        $applied = WC()->cart->apply_coupon($coupon_code);
        if ($applied) {
            echo json_encode(array('status' => 'success'));
        } else {
            echo json_encode(array('status' => 'invalid'));
        }
    }
    wp_die();
}

add_action('wp_ajax_remove_coupon', 'remove_coupon_from_cart');
add_action('wp_ajax_nopriv_remove_coupon', 'remove_coupon_from_cart');

function remove_coupon_from_cart() {
    if (isset($_POST['coupon'])) {
        $coupon_code = sanitize_text_field($_POST['coupon']);
        WC()->cart->remove_coupon($coupon_code);
        wc_clear_notices(); 
        
        wp_send_json_success();
    } else {
        wp_send_json_error('Coupon code not provided.');
    }
}
	
sudo alternatives --config java
{% if product.metafields.custom.file2.value != blank %}
  <ul>
    {% for file in product.metafields.custom.file2.value %}
      <li>
        <a href="{{ file.url.value }}" target="new">{{ file.title }}</a>
      </li>
    {% endfor %}
  </ul>
{% else %}
  <p>No files available.</p>
{% endif %}
docker-compose down --rmi all --volumes --remove-orphans

--rmi all: elimina todas las imágenes creadas por docker-compose.
--volumes: elimina los volúmenes asociados.
--remove-orphans: elimina contenedores no definidos en el .yml actual.
# Eliminar volúmenes sin uso
docker volume prune -f

# Eliminar redes sin uso
docker network prune -f
Este comando elimina todas las imágenes de Docker del sistema (solo si no hay contenedores activos que las usen).

docker rmi $(docker images -a -q)
Estos comandos buscan todos los contenedores (activos y detenidos) y los detienen/eliminan automáticamente.

# Detener todos los contenedores
docker stop $(docker ps -a -q)

# Eliminar todos los contenedores
docker rm $(docker ps -a -q)
2. Archivo docker-compose.yml
¿Qué es un docker-compose.yml?
Es un archivo de configuración en formato YAML que permite definir y ejecutar múltiples contenedores Docker como un solo servicio, facilitando la orquestación de aplicaciones complejas.

Estructura básica de un docker-compose.yml
version: Define la versión de la sintaxis de Docker Compose.

services: Define los diferentes servicios o contenedores a levantar.

build: Ruta para construir la imagen Docker (opcional cuando se usa imagen pública).

image: Nombre de la imagen a usar.

ports: Puertos que se exponen y mapean al host.

volumes: Para montar volúmenes o carpetas locales dentro del contenedor.

environment: Variables de entorno para los contenedores.

Ejemplo básico:
version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"
    volumes:
      - .:/app
    environment:
      - NODE_ENV=development
  db:
    image: postgres:13
    environment:
      POSTGRES_USER: usuario
      POSTGRES_PASSWORD: contraseña
      POSTGRES_DB: mibase
    ports:
      - "5432:5432"
¿Cómo ejecutar un archivo docker-compose.yml?
Abrir una terminal.
Navegar a la carpeta donde está el archivo docker-compose.yml.

Ejecutar el comando:
docker-compose up
Esto creará y arrancará todos los servicios definidos en el archivo.

Para detener los servicios:
docker-compose down


Dockerfile
Qué es: Un archivo de texto que contiene una serie de instrucciones para construir una imagen Docker. Funciona como una "receta" para crear una imagen personalizada.

Para qué sirve: Define cómo se debe construir una imagen de contenedor, especificando la base del sistema operativo, las aplicaciones que se deben instalar, variables de entorno, archivos que se copian, comandos que se deben ejecutar para preparar la imagen, entre otros.

Cómo se arma: Se escribe paso a paso con comandos Docker (por ejemplo, FROM, COPY, RUN, CMD) que instruyen cómo se debe crear la imagen.

1. Dockerfile
¿Qué es un Dockerfile?
Un Dockerfile es un archivo de texto que contiene instrucciones para construir una imagen de Docker personalizada. Esta imagen luego se puede usar para crear contenedores.

Estructura básica de un Dockerfile
FROM: Define la imagen base desde la cual se construirá la nueva imagen.

WORKDIR: Define el directorio de trabajo dentro del contenedor.

COPY: Copia archivos o directorios desde tu sistema local hacia la imagen.

RUN: Ejecuta comandos en la imagen mientras se construye.

CMD: Define el comando que se ejecutará cuando se inicie un contenedor a partir de esta imagen.

Ejemplo básico:

# Imagen base
FROM node:14

# Directorio de trabajo
WORKDIR /app

# Copiar archivos al contenedor
COPY package*.json ./

# Instalar dependencias
RUN npm install

# Copiar el resto del código
COPY . .

# Puerto que se expondrá
EXPOSE 3000

# Comando para iniciar la aplicación
CMD ["npm", "start"]

¿Cómo ejecutar un Dockerfile?
Abrir una terminal.

Navegar a la carpeta donde está el Dockerfile.

Construir la imagen con el comando:
docker build -t nombre_de_la_imagen .

Ejecutar el contenedor con:
docker run -p 3000:3000 nombre_de_la_imagen
star

Thu Aug 21 2025 09:47:03 GMT+0000 (Coordinated Universal Time) https://www.i95dev.com/dynamics-erp-integration/magento-2-dynamics-365-integration/

@alexpaul

star

Thu Aug 21 2025 09:44:49 GMT+0000 (Coordinated Universal Time) https://www.i95dev.com/dynamics-erp-integration/magento-microsoft-dynamics-365-business-central-connect/

@alexpaul

star

Wed Aug 20 2025 20:26:20 GMT+0000 (Coordinated Universal Time)

@jdeveloper #php

star

Wed Aug 20 2025 17:41:01 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 17:35:40 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 17:33:07 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 17:32:22 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 17:30:15 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 17:21:47 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Wed Aug 20 2025 15:13:56 GMT+0000 (Coordinated Universal Time) https://codepen.io/rustcode/pen/YPPbxYX

@CallTheCops #undefined

star

Wed Aug 20 2025 15:13:53 GMT+0000 (Coordinated Universal Time) https://codepen.io/rustcode/pen/YPPbxYX

@CallTheCops #undefined

star

Wed Aug 20 2025 15:13:51 GMT+0000 (Coordinated Universal Time) https://codepen.io/rustcode/pen/YPPbxYX

@CallTheCops #undefined

star

Wed Aug 20 2025 15:05:47 GMT+0000 (Coordinated Universal Time) https://codepen.io/rustcode/pen/YPPbxYX

@CallTheCops #undefined

star

Wed Aug 20 2025 14:18:20 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Tue Aug 19 2025 18:40:28 GMT+0000 (Coordinated Universal Time)

@reiddd #javascript

star

Tue Aug 19 2025 16:12:49 GMT+0000 (Coordinated Universal Time) https://soulvacation.in/resort-in-south-goa/

@dagapam705

star

Tue Aug 19 2025 05:58:33 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Mon Aug 18 2025 11:43:20 GMT+0000 (Coordinated Universal Time) https://maticz.com/rummy-game-development

@austinparker #rummy #rummygame #rummygamedevelopment #rummygameapp

star

Mon Aug 18 2025 05:58:16 GMT+0000 (Coordinated Universal Time)

@Diyorbek21

star

Mon Aug 18 2025 03:31:25 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #wordpress #divi #menumobile

star

Mon Aug 18 2025 03:30:31 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #wordpress #divi #menumobile

star

Mon Aug 18 2025 03:29:48 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #wordpress #divi #menumobile

star

Sun Aug 17 2025 15:00:07 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Aug 17 2025 09:13:15 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Aug 17 2025 06:06:20 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Sat Aug 16 2025 09:09:55 GMT+0000 (Coordinated Universal Time) https://www.allassignmenthelp.com/pay-someone-to-take-my-online-class.html

@payforonline

star

Sat Aug 16 2025 02:21:12 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:20:16 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:19:57 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:18:00 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:15:26 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:12:54 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:12:09 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:11:35 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:10:56 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:09:46 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:08:41 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:07:54 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:06:00 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:05:34 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Sat Aug 16 2025 02:04:32 GMT+0000 (Coordinated Universal Time)

@vanthien

star

Fri Aug 15 2025 23:54:54 GMT+0000 (Coordinated Universal Time)

@wizyOsva #bash

star

Fri Aug 15 2025 21:33:20 GMT+0000 (Coordinated Universal Time)

@procodefinder

star

Fri Aug 15 2025 17:50:19 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Fri Aug 15 2025 17:31:01 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Fri Aug 15 2025 17:29:03 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Fri Aug 15 2025 17:28:09 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Fri Aug 15 2025 17:27:35 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

star

Fri Aug 15 2025 17:15:05 GMT+0000 (Coordinated Universal Time)

@jrg_300i #docker

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension