Snippets Collections
/////////////////datatypes summary /////////////////////

/// primitive datatype 
// 7 types : string. number, boolean , null ,  undefined , symbol , bigint 

const score = 100
const scoreValue = 100.09
const isLoggedIn = false
const outsideTemp = null

let userEmail;// undefined 

const ID = Symbol('1234')
const anotherID = Symbol('1234')
console.log(ID === anotherID );// false

const biggNumber = 2774763796237673n // bigint 


// refrenced types(non primitive datatype )
// array , object and function 

const heros = ["her0","naagraj","doga"]; //array
let myObj= { // object
    name: "hitesh",
    age: 22,
}
const myFunction = function(){
    // function
    console.log("hello wrold");
}

console.log(typeof outsideTemp); // object
console.log(typeof myFunction); // function object 
console.log(typeof ID); // SYMBOL

selector .elementor-icon-box-wrapper {
    display: flex;
    align-items: flex-start; /* Aligns the icon and title to the top */
}

selector .elementor-icon-box-icon {
    align-self: flex-start; /* Ensures the icon stays at the top */
}

selector .elementor-icon-box-title {
    margin-top: 0 !important; /* Removes any top margin on the title */
    padding-top: 0 !important; /* Removes any top padding on the title */
    line-height: 1.2em; /* Adjusts line height for a closer alignment */
}
import os
import cv2
import numpy as np
from typing import Tuple

# Definicja kolorów i etykiet
CLASS_COLORS = {
    0: {'color_rgb': (0, 0, 0), 'label': 'background'},
    1: {'color_rgb': (255, 0, 0), 'label': 'chondroosseous border'},
    2: {'color_rgb': (0, 255, 0), 'label': 'femoral head'},
    3: {'color_rgb': (0, 0, 255), 'label': 'labrum'},
    4: {'color_rgb': (255, 255, 0), 'label': 'cartilagineous roof'},
    5: {'color_rgb': (0, 255, 255), 'label': 'bony roof'},
    6: {'color_rgb': (159, 2, 250), 'label': 'bony rim'},
    7: {'color_rgb': (255, 132, 0), 'label': 'lower limb'},
    8: {'color_rgb': (255, 0, 255), 'label': 'baseline'},
    9: {'color_rgb': (66, 135, 245), 'label': 'lower limb template'},
    10: {'color_rgb': (255, 69, 0), 'label': 'lower limb - alg. v3'}
}


def visualize_masks(input_dir, output_dir):
    # Tworzenie katalogu wyjściowego, jeśli nie istnieje
    os.makedirs(output_dir, exist_ok=True)

    # Iteracja po plikach PNG w katalogu wejściowym
    for filename in os.listdir(input_dir):
        if filename.endswith(".png"):
            # Wczytywanie maski
            mask_path = os.path.join(input_dir, filename)
            mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

            # Tworzenie pustego obrazu RGB o tych samych wymiarach co maska
            color_image = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)

            # Zamiana etykiet na kolory RGB zgodnie z CLASS_COLORS
            for class_id, color_info in CLASS_COLORS.items():
                color_rgb = color_info['color_rgb']
                color_image[mask == class_id] = color_rgb

            # Znajdowanie punktów baseline
            right_point, left_point = find_baseline(mask)
            
            # Rysowanie baseline na obrazie, jeżeli punkty istnieją
            if right_point[0] is not None and left_point[0] is not None:
                cv2.line(color_image, right_point, left_point, (255, 255, 255), 1)

            # Zapisanie obrazu kolorowego do katalogu wyjściowego
            output_path = os.path.join(output_dir, filename)
            cv2.imwrite(output_path, color_image)
            print(f"Maska {filename} została zapisana w katalogu wyjściowym.")

# Przykładowe użycie
input_dir = "./Angles/dane/ta_jedna"
output_dir = "./Angles/dane/wizul"
visualize_masks(input_dir, output_dir)
WebMidi.enable(function(err) {
148
    if (err) {
149
      console.log("WebMidi kon niet worden ingeschakeld.", err);
150
    } else {
151
      console.log("WebMidi ingeschakeld!");
152
    }
153
​
154
    let inputSoftware = WebMidi.inputs[0];
155
​
156
    // Luister naar 'noteon' events op alle kanalen
157
    inputSoftware.addListener('noteon', "all", function(e) {
158
      let note = e.note.number;
159
​
160
      // Roep de corresponderende nootfunctie aan
161
      if (noteFunctions[note]) {
162
        noteFunctions[note]();
163
      }
164
    });
165
  });
    <script src="https://cdn.jsdelivr.net/npm/webmidi@latest/dist/iife/webmidi.iife.js"></script>
In the on-demand industry, food delivery apps play an important role in the sectors. Many more entrepreneurs want to adopt this business strategy into their businesses. In such respect, if you want to integrate your business idea with a food delivery business, Here, is the best solution provider for any kind of business needs. Appticz is a well-known brand in the on-demand sector, successively availing on-demand services for their clients. In that way, you can proceed your business ideas with the best food delivery application development company that will make your dreamier business ideas into reality.
import java.util.*;

import javax.swing.plaf.synth.SynthOptionPaneUI;
public class LinkedList {
    int size;
    public class Node{
        int data;
        Node next;

        Node(int data){
            this.data=data;
            this.next=null;
            size++;
        }
    }
    LinkedList(){
        size=0;
    }
    Node head;
    public void addFirst(int data){
        Node newNode=new Node(data);
        newNode.next=head;
        head=newNode;
    }
    public void addLast(int data){
        Node newNode=new Node(data);
        if(head==null){
            newNode.next=head;
            head=newNode;
        }else{
            Node curNode=head;
            while(curNode.next!=null){
                curNode=curNode.next;
            }
            curNode.next=newNode;
        }
    }
    public void removeFirst(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            val=head.data;
            head=head.next;
            System.out.println(val+" Deleted...");
            size--;
        }
    }
    public void removeLast(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            Node curNode=head;
            Node lastNode=head.next;
            while(lastNode.next!=null){
                lastNode=lastNode.next;
                curNode=curNode.next;
            }
            val=lastNode.data;
            System.out.println(val+" Deleted...");
            curNode.next=null;
            size--;
        }
    }
    public void reverseIterate(){
        if(head==null || head.next==null){
            return;
        }else{
            Node prevNode=head;
            Node curNode=head.next;
            while(curNode!=null){
                Node nextNode=curNode.next;
                curNode.next=prevNode;
                prevNode=curNode;
                curNode=nextNode;
            }
            head.next=null;
            head=prevNode;
            System.out.println("Linked List Reversed...");
        }

    }
    public void sizeOfList(){
        System.out.println("Size of List: "+size);
    }
    public void printList(){
        Node curNode=head;
        while(curNode!=null){
            System.out.print(curNode.data+"-> ");
            curNode=curNode.next;
        }System.out.println("NULL");
    }
    public static void main(String args[]){
        LinkedList list=new LinkedList();
        Scanner sc=new Scanner(System.in);
        int val=0;
        while(true){
            System.out.println("1:addFirst  2:addLast  3:removeFirst  4:removeLast  5:reverseIterate  6:sizeOfList  7:printList  8:End");
            System.out.print("Select any Option: ");
            int option=sc.nextInt();
            if(option==8){
                System.out.println("Thank You!!! ");
                break;
            }
            if(option==1 || option==2){
                System.out.print("Enter Value: ");
                val=sc.nextInt();
            }
            switch(option){
                case 1: 
                    list.addFirst(val);
                    break;
                case 2:
                    list.addLast(val);
                    break;
                case 3:
                    list.removeFirst();
                    break;
                case 4:
                    list.removeLast();
                    break;
                case 5:
                    list.reverseIterate();
                    break;
                case 6:
                    list.sizeOfList();
                    break;
                case 7:
                    list.printList();
                    break;
                default:
                    System.out.println("INVALID INPUT");
            }
        }
        
        
    }
}
/////**************comaprison***************/////////////


console.log(2 > 1);
console.log(2 >= 1);
console.log(2 < 1);
console.log(2 == 1);
console.log(2 != 1);

console.log( null > 0);//fales
console.log( null == 0);//fales
console.log( null >= 0);// true

console.log( undefined > 0);//fales
console.log( undefined == 0);//fales
console.log( undefined >= 0);// fales
 
//// strit check 
console.log(2 == "2");///it will check  value (it will give true)
console.log(2 === "2");///it will check both dataype and value (it will give false)
let value = 4
let negvalue = -value 
console.log(negvalue);

/*console.log(2+2);
console.log(2-2);
console.log(2*2);
console.log(2**2);
console.log(2/2);
console.log(2%2);*/

let str1 = "hello "
let str2 = "namastey"
let str3 = str1 + str2 
console.log(str1 + str2)

/* javascript basic tricks*/

console.log(2+"3") //23
console.log("2"+"3") //23
console.log("1"+2+2) //122
console.log(1+2+'2') //32 

/* bad performance*/
console.log(+true);//true
console.log(+"");//fales

let gamecounter = 100
gamecounter++; // post increment and pre increment gives a same answer 
console.log(gamecounter);

let score = true


console.log(score);
console.log(typeof (score));
let valueInNumber = Number(score)
console.log(typeof valueInNumber);
console.log( valueInNumber);
/* PRINTING OF
"33" = 33
"33annaa" = NaN(not a number )
true = 1
false = 0*/


let isLoggedIn = 1
/* empty will give false 
0 will give false*/
let booleanIsLoggedIn = Boolean(isLoggedIn)
console.log(booleanIsLoggedIn); //true


let somenumber = 33;
console.log(typeof somenumber);
let stringNumber = String(somenumber)
console.log(stringNumber);
console.log(typeof stringNumber);
#Boot in Safe Mode (via msconfig)
#Open Registry Editor
#Navigateto:
#HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service
#The six keys in the registry to change the values of:
#Sense
#WdBoot
#WdFilter
#WdNisDrv
#WdNisSvc
#WinDefend

# To disable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	4

#To re-enable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	2



Run actions/github-script@e69ef5462fd455e02edcaf4dd7708eda96b9eda0
2
  with:
3
    github-token: ***
4
    script: // Only perform this action with GitHub employees
5
  try {
6
    await github.rest.teams.getMembershipForUserInOrg({
7
      org: %27github%27,
8
      team_slug: %27employees%27,
9
      username: context.payload.sender.login,
10
    });
11
  } catch(err) {
12
    // An error will be thrown if the user is not a GitHub employee
13
    // If a user is not a GitHub employee, we should stop here and
14
    // Not send a notification
15
    return
16
  }
"use strict"; // treated as all new js code version 

// alert(3+3) we are using nodejs not brpwser 

console.log(3+3+3);
console.log("tansihq dhingra ");// code readibility is very important 

let name = "tanishq"
let age = 18 
let isLoggedIn = false 

/* primitive 
number = 2 ki power 53
bigint
string = " "
boolean = true/ false 
null = standalone value (value is null )
undefined = not defined 
symbbol = uniqueness in react */

// object 
console.log(typeof undefined );//undefined
console.log(typeof null);//object 
import java.util.*;

public class Graph {
    private int vertices;  // Number of vertices
    private LinkedList<Integer>[] adjList;  // Adjacency list representation
    private int time;  // Time counter for DFS

    // Constructor
    public Graph(int v) {
        vertices = v;
        adjList = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adjList[i] = new LinkedList<>();
        }
        time = 0;
    }

    // Add an edge to the graph
    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);  // Since the graph is undirected
    }

    // Articulation Point (Art) Algorithm
    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];  // Discovery time of visited vertices
        int[] low = new int[vertices];  // Lowest discovery time reachable
        int[] parent = new int[vertices];  // Parent vertices in DFS
        Arrays.fill(parent, -1);  // Initialize all parents as -1

        // Start DFS from each unvisited node
        for (int i = 0; i < vertices; i++) {
            if (!visited[i]) {
                DFSArt(i, visited, dfn, low, parent);
            }
        }
    }

    private void DFSArt(int u, boolean[] visited, int[] dfn, int[] low, int[] parent) {
        visited[u] = true;  // Mark the current node as visited
        dfn[u] = low[u] = ++time;  // Initialize discovery time and low value
        int childCount = 0;  // Count of children in DFS tree
        boolean isArticulation = false;

        for (int v : adjList[u]) {
            if (!visited[v]) {
                childCount++;
                parent[v] = u;
                DFSArt(v, visited, dfn, low, parent);

                // Check if the subtree rooted at v has a connection back to one of u's ancestors
                low[u] = Math.min(low[u], low[v]);

                // u is an articulation point in two cases:
                // (1) u is not the root and low value of one of its child is more than discovery value of u
                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                // (2) u is the root of DFS tree and has two or more children
                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                // Update low value of u for back edge
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        // If u is an articulation point, print it
        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    // Construct graph from adjacency matrix
    public static Graph createGraphFromAdjMatrix(int[][] adjMatrix) {
        int n = adjMatrix.length;
        Graph g = new Graph(n);
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {  // Undirected graph, so only check i < j
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Input the number of vertices
        System.out.print("Enter the number of vertices: ");
        int v = scanner.nextInt();

        // Input the adjacency matrix
        System.out.println("Enter the adjacency matrix:");
        int[][] adjMatrix = new int[v][v];
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                adjMatrix[i][j] = scanner.nextInt();
            }
        }

        // Create the graph from adjacency matrix
        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        // Find and print the articulation points
        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}

output1:
Enter the number of vertices: 5
Enter the adjacency matrix:
0 1 1 0 0
1 0 1 1 0
1 1 0 0 0
0 1 0 0 1
0 0 0 1 0
Articulation Points:
Articulation Point: 1
Articulation Point: 3

output2:
Enter the number of vertices: 6
Enter the adjacency matrix:
0 1 1 0 0 0
1 0 1 1 0 0
1 1 0 0 1 0
0 1 0 0 1 1
0 0 1 1 0 1
0 0 0 1 1 0
Articulation Points:
Articulation Point: 2
Articulation Point: 3
const accountID = 145242;//constant value 
let accountEmail = "dhingra@gmail.com";// variable we will use it the most 
var accountPassword = "123433";// variable we dont use var generally
accountCity = "jaipur";

accountEmail = "dhbscbbcd@g.com";
accountPassword = "132322";
accountCity = "bengaluru";
let accountState;

console.log(accountID);
console.table({ accountID, accountEmail, accountPassword, accountCity ,accountState });
import base64

sample_string = "GeeksForGeeks is the best"
sample_string_bytes = sample_string.encode("ascii")

base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")

print(f"Encoded string: {base64_string}")
tar -xf node-v20.18.0-linux-x64.tar.xz

2. Mover Node.js a un directorio adecuado
Para que Node.js esté disponible globalmente, es recomendable moverlo a /usr/local. Puedes hacerlo con el siguiente comando:

sudo mv node-v20.18.0-linux-x64 /usr/local/nodejs

3. Configurar las variables de entorno
Para que el sistema reconozca los comandos de Node.js y npm, necesitas agregar el directorio de Node.js a tu variable de entorno PATH. Abre el archivo de configuración de tu shell. Si usas bash, puedes editar el archivo .bashrc:

nano ~/.bashrc

Agrega la siguiente línea al final del archivo:

4. Aplicar los cambios
Para aplicar los cambios realizados en el archivo .bashrc, ejecuta:

source ~/.bashrc

5. Verificar la instalación
Finalmente, verifica que Node.js y npm se hayan instalado correctamente ejecutando los siguientes comandos:

node -v
npm -v

pattrens = [
    '123456',
    '6665522',
    '887799',
    '123456',
    '6665522',
    '1111222',
    '123456',
    '6665522',
    '887799',
    '123456',
    '111111'
]


def classify_pattrens(pattrens_list):
    labels = {k : [] for k in pattrens_list}
    for pattren in pattrens_list:
        labels[pattren].append(pattren)

    return labels

print(classify_pattrens(pattrens))
ejemplo de exportar modulo
// archivo: miModulo.mjs
export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

ejemplo de importar modulo
// archivo: app.mjs
import { saludar } from './miModulo.mjs';

console.log(saludar('Mundo')); // Salida: Hola, Mundo!
/mi-proyecto
├── backend
│   ├── composer.json
│   ├── index.php
│   └── miModulo.mjs
└── frontend
    ├── package.json
    └── app.mjs

codigo:

1. Archivo composer.json (Backend)
Este archivo se encuentra en la carpeta backend y define las dependencias de PHP que necesitas. Aquí hay un ejemplo básico:

{
  "require": {
    "monolog/monolog": "^2.0"
  }
}

2. Archivo index.php (Backend)
Este archivo es el punto de entrada de tu aplicación PHP. Aquí puedes manejar las solicitudes y enviar respuestas. Un ejemplo simple podría ser:

<?php
// backend/index.php

require 'vendor/autoload.php'; // Asegúrate de que el autoload de Composer esté incluido

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Crear un logger
$log = new Logger('mi_proyecto');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));

// Registrar un mensaje
$log->warning('Esto es un mensaje de advertencia');

// Enviar una respuesta simple
header('Content-Type: application/json');
echo json_encode(['message' => 'Hola desde el backend!']);

3. Archivo miModulo.mjs (Backend)
Este archivo contiene un módulo que puedes importar en otros archivos. Aquí hay un ejemplo de cómo podría verse:

// backend/miModulo.mjs

export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

4. Archivo package.json (Frontend)
Este archivo se encuentra en la carpeta frontend y define las dependencias de JavaScript que necesitas. Aquí hay un ejemplo básico:

{
  "name": "mi-proyecto-frontend",
  "version": "1.0.0",
  "dependencies": {
    "axios": "^0.21.1"
  },
  "scripts": {
    "start": "node app.mjs"
  }
}

5. Archivo app.mjs (Frontend)
Este archivo contiene el código JavaScript que se ejecutará en el lado del cliente. Aquí hay un ejemplo que utiliza axios para hacer una solicitud al backend y también importa la función saludar del módulo:

// frontend/app.mjs

import { saludar } from '../backend/miModulo.mjs'; // Importar la función del módulo

const nombre = 'Mundo';
console.log(saludar(nombre)); // Salida: Hola, Mundo!

// Hacer una solicitud al backend
axios.get('http://localhost/backend/index.php')
  .then(response => {
    console.log('Respuesta del backend:', response.data);
  })
  .catch(error => {
    console.error('Error al hacer la solicitud:', error);
  });


Conclusión
Este ejemplo proporciona una base para un proyecto que combina un backend en PHP y un frontend en JavaScript utilizando módulos ES. Puedes expandirlo según tus necesidades, añadiendo más funcionalidades y dependencias según sea necesario. Asegúrate de tener configurado un servidor para el backend y de ejecutar el script del frontend para ver la interacción entre ambos.
<script>
document.addEventListener('click', function (event) {
    if (event.target.closest('a[href*="#"]:not([aria-haspopup="true"])') && event.target.closest('.e-off-canvas[aria-hidden="false"]')) {
        const canvasTrigger = document.querySelector('[href*="off_canvas%3A"]:not([href*="%3Aopen"]');
        if (canvasTrigger) canvasTrigger.click();
    }
});
</script>
selector .menu-item .elementor-item-active {
    font-weight: 600;
}


selector .sub-menu {
    padding: 15px 20px 15px 15px;
}

selector .sub-menu li {
    padding: 5px 0;
}

selector .elementor-nav-menu--dropdown.elementor-nav-menu__container {
    padding: 20px;
}

@media only screen and (max-width: 1024px) {
selector .sub-menu.elementor-nav-menu--dropdown {
    padding: 0; 
}
selector .sub-menu.elementor-nav-menu--dropdown a {
    margin-left: -8px; 
}
selector .elementor-nav-menu--dropdown .menu-item  {
    padding: 10px 0;
}
selector .menu-item.menu-item-has-children .sub-menu .menu-item {
    padding: 0;
    padding-top: 15px;
    color: red !important;
}
selector .menu-item.menu-item-has-children .sub-menu .menu-item a {
    font-weight: 400
}
}
let phi = (1 + sqrt(5)) / 2; // Gouden ratio
<?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($user = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['id']); ?></td>
                            <td class="<?php echo ($user['is_admin'] ? 'admin-user' : 'normal-user'); ?>">
                                <?php echo htmlspecialchars($user['username']); ?>
                            </td>
                            <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($user['register_date']))); ?></td>
                            <td><?php echo ($user['is_admin'] ? 'Yes' : 'No'); ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4">No users!</td>
                    </tr>
                <?php endif; ?>
#include <iostream>
using namespace std;

// Function to merge two sorted halves of the array into a single sorted array.
void merge(int arr[], int left, int mid, int right) 
{
    int n1 = mid - left + 1;
    int n2 = right - mid;

    //temporary arrays
    int leftArr[n1], rightArr[n2];

    //copy data to temporary arrays
    for (int i = 0; i < n1; i++)
        leftArr[i] = arr[left + i];
    for (int j = 0; j < n2; j++)
        rightArr[j] = arr[mid + 1 + j];

    //merge temporary arrays back into arr[left..right]
    int i = 0, j = 0, k = left;
    while (i < n1 && j < n2) 
    {
        if (leftArr[i] <= rightArr[j]) 
        {
            arr[k] = leftArr[i];
            i++;
        } else {
            arr[k] = rightArr[j];
            j++;
        }
        k++;
    }

    //copy the remaining elements of leftArr[], if any
    while (i < n1) 
    {
        arr[k] = leftArr[i];
        i++;
        k++;
    }

    //copy the remaining elements of rightArr[], if any
    while (j < n2) 
    {
        arr[k] = rightArr[j];
        j++;
        k++;
    }
}

// Function to recursively divide the array and merge the sorted halves.
void mergeSort(int arr[], int left, int right) 
{
    if (left < right) 
    {
        int mid = left + (right - left) / 2;

        //sort first and second halves
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);

        //merge the sorted halves
        merge(arr, left, mid, right);
    }
}

// Function to initiate the merge sort process.
void processMergeSort(int arr[], int n) 
{
    if (n > 1) 
    {
        mergeSort(arr, 0, n - 1);
    }
}

void displayArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processMergeSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()

using namespace std;

// Function to merge two sorted sub-arrays in place.
void inPlaceMerge(int arr[], int left, int mid, int right) 
{
    int start2 = mid + 1;

    //if the direct merge is already sorted
    if (arr[mid] <= arr[start2]) 
    {
        return;
    }

    //two pointers to maintain start of both arrays to merge
    while (left <= mid && start2 <= right) 
    {
        //if element 1 is in right place
        if (arr[left] <= arr[start2]) 
        {
            left++;
        } 
        else 
        {
            int value = arr[start2];
            int index = start2;

            //shifting all elements between element 1 and element 2 right by 1.
            while (index != left) 
            {
                arr[index] = arr[index - 1];
                index--;
            }
            arr[left] = value;

            //update all pointers
            left++;
            mid++;
            start2++;
        }
    }
}

// Function to recursively sort the array using Merge Sort.
void inPlaceMergeSort(int arr[], int left, int right) 
{
    if (left < right) 
    {
        int mid = left + (right - left) / 2;

        //sort first and second halves
        inPlaceMergeSort(arr, left, mid);
        inPlaceMergeSort(arr, mid + 1, right);

        //merge the sorted halves
        inPlaceMerge(arr, left, mid, right);
    }
}

// Function to initiate the Merge Sort process.
void processInPlaceMergeSort(int arr[], int n) 
{
    if (n > 1) 
    {
        inPlaceMergeSort(arr, 0, n - 1);
    }
}

void displayArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processInPlaceMergeSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
mpl.rcParams.update({'font.size': 14})

# Indices to step through colormap.
x = np.linspace(0.0, 1.0, 100)

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(cmap_category, cmap_list):
    fig, axs = plt.subplots(nrows=len(cmap_list), ncols=2)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99,
                        wspace=0.05)
    fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6)

    for ax, name in zip(axs, cmap_list):

        # Get RGB values for colormap.
        rgb = mpl.colormaps[name](x)[np.newaxis, :, :3]

        # Get colormap in CAM02-UCS colorspace. We want the lightness.
        lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
        L = lab[0, :, 0]
        L = np.float32(np.vstack((L, L, L)))

        ax[0].imshow(gradient, aspect='auto', cmap=mpl.colormaps[name])
        ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.)
        pos = list(ax[0].get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axs.flat:
        ax.set_axis_off()

    plt.show()


for cmap_category, cmap_list in cmaps.items():

    plot_color_gradients(cmap_category, cmap_list)
sync && echo 3 > /proc/sys/vm/drop_caches
public boolean equals(Object obj) {
    return (this == obj);
}
import React, { useState, useEffect } from "react";
import { FaMedal } from "react-icons/fa";
import axios from "axios";
import Apis from "../../APIs";
import { useAuth } from "../Auth/AuthContext";
import { useNavigate } from "react-router-dom"; // To navigate to the dashboard

const Assessment = () => {
  const { user, setUser } = useAuth(); // Assuming setUser is available to update user data
  const navigate = useNavigate(); // To handle navigation
  const [questions, setQuestions] = useState([]);
  const [answers, setAnswers] = useState([]);
  const [score, setScore] = useState(0);
  const [result, setResult] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [assessmentRecordId, setAssessmentRecordId] = useState(null); // To store the assessment record ID
  const [redirectPage, setRedirectPage] = useState(null); // Store the page to redirect after clicking "Ok"

  const optionLabels = ["A", "B", "C", "D"];

  // Fetch questions from the API
  useEffect(() => {
    const fetchQuestions = async () => {
      try {
        const response = await axios.get(Apis.QUESTION_API);
        const fetchedQuestions = response.data;
        setQuestions(fetchedQuestions);
        setAnswers(fetchedQuestions.map(() => Array(4).fill(null)));
        setLoading(false);
      } catch (err) {
        console.error("Error fetching questions:", err);
        setError("Failed to load questions. Please try again later.");
        setLoading(false);
      }
    };

    fetchQuestions();
  }, []);

  const handleRatingSelect = (qIndex, oIndex, rating) => {
    const newAnswers = [...answers];
    newAnswers[qIndex][oIndex] = rating;
    setAnswers(newAnswers);
  };

  const handleSubmit = async () => {
    setResult(true);

    // Create the payload in the required JSON format for the POST request
    const formattedResponses = questions.map((question, qIndex) => ({
      questionId: question._id,
      ratings: answers[qIndex].map((rating) => ({ rating })),
    }));

    const userId = user._id;

    const payload = {
      userId: userId,
      responses: formattedResponses,
    };

    try {
      const response = await axios.post(Apis.ASSESSMENT_API, payload);
      console.log("Assessment submitted successfully:", response.data);
      setAssessmentRecordId(response.data._id); // Store the assessment record ID
      fetchAssessmentRecord(response.data._id); // Fetch the assessment record
    } catch (error) {
      console.error("Error submitting assessment:", error);
    }
  };

  const fetchAssessmentRecord = async (recordId) => {
    try {
      const response = await axios.get(
        `${Apis.ASSESSMENT_API}/getAssessmentRecord/${recordId}`
      );
      const optionStats = response.data.optionStats;
      determineRedirect(optionStats); // Call function to determine redirect
    } catch (error) {
      console.error("Error fetching assessment record:", error);
    }
  };

  const determineRedirect = (optionStats) => {
    const maxOption = Object.entries(optionStats).reduce(
      (acc, [key, value]) => {
        if (value[1] > acc.count) {
          return { key, count: value[1] }; // Find option with the highest count of "1"
        }
        return acc;
      },
      { key: null, count: 0 }
    );

    switch (maxOption.key) {
      case "option1":
        setRedirectPage("/PdfC"); // Set the redirect page
        break;
      case "option2":
        setRedirectPage("/PdfC");
        break;
      case "option3":
        setRedirectPage("/PdfC");
        break;
      case "option4":
        setRedirectPage("/PdfC");
        break;
      default:
        setRedirectPage("/dashboard"); // Default fallback
    }
  };

  const handleOkClick = async () => {
    // Fetch the updated user data
    const fetchUserData = async () => {
      try {
        const response = await axios.get(`${Apis.USER_API}/${user._id}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        const updatedUserData = response.data;
        setUser(updatedUserData); // Update the user data in the context
        console.log("User data refreshed:", updatedUserData);
      } catch (error) {
        console.error("Error refreshing user data:", error);
      }
    };

    await fetchUserData();
    // window.location.reload();

    navigate(redirectPage); // Navigate to the determined PDF page
  };

  if (loading) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">Loading questions...</div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">{error}</div>
      </section>
    );
  }

  return (
    <>
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center p-5">
        {result ? (
          <div className="min-h-[400px] w-80 md:w-[400px] rounded-lg bg-white p-5 flex items-center justify-center flex-col gap-5">
            <h2 className="text-3xl text-center">
              Thank you for giving the assessment
            </h2>
            <h2 className="text-3xl text-center">
              To See Your Result Click Ok
            </h2>
            <FaMedal className="text-4xl text-yellow-400" />
            {/* <h3 className="font-semibold text-4xl">{score}</h3> */}
            <button
              onClick={handleOkClick} // Handle Ok click and navigate
              className="h-10 w-full rounded-lg bg-green-500 text-white hover:bg-green-700"
            >
              Ok
            </button>
          </div>
        ) : (
          <div className="min-h-[400px] w-full max-w-screen-md rounded-lg bg-white p-5">
            <h2 className="font-bold text-xl mb-5">
              Know Your Competency (KYC) - Assessment on DGCS Leadership Style :
              -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              Please choose your rating based on your preference. Rank 1 - Most
              Agreed; 2 - Agreed; 3 - Lesser agreed; 4 - Least Agreed. -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              only one option should be given for each rank for each questions.
              For the question one - if you give rank 4 for 1st option, the same
              rank 4 cannot be given for the other 3 options. -{" "}
            </h2>
            
            {questions.map((q, qIndex) => (
              <div key={q._id} className="mb-6">
                <h3 className="font-semibold text-lg mb-3">
                  {qIndex + 1}. {q.mainQuestion}
                </h3>
                <div className="flex flex-col gap-3">
                  {q.options.map((option, oIndex) => (
                    <div
                      key={option._id}
                      className="flex items-center justify-between"
                    >
                      <span>{`(${optionLabels[oIndex]}) ${option.option}`}</span>
                      <div className="flex gap-7">
                        {[1, 2, 3, 4].map((rating) => (
                          <button
                            key={rating}
                            onClick={() =>
                              handleRatingSelect(qIndex, oIndex, rating)
                            }
                            className={`w-8 h-8 rounded-full border-2 flex items-center justify-center ${
                              answers[qIndex][oIndex] === rating
                                ? "bg-green-500 text-white"
                                : "border-gray-300"
                            }`}
                          >
                            {rating}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            <div className="mt-5 flex justify-end">
              <button
                onClick={handleSubmit}
                className="h-10 w-32 rounded-lg bg-green-500 text-white hover:bg-green-700"
              >
                Submit
              </button>
            </div>
          </div>
        )}
      </section>
    </>
  );
};

export default Assessment;
#include <iostream>
using namespace std;

// Function to sort the array using insertion sort algorithm.
void processSelectionSort(int arr[], int n) 
{
    for (int i = 0; i < n - 1; i++) 
    {
        int min_index = i;
        for (int j = i + 1; j < n; j++) 
        {
            if (arr[j] < arr[min_index]) 
            {
                min_index = j;
            }
        }
        
        if (min_index != i) 
        {
            swap(arr[min_index], arr[i]);
        }
    }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "\nUnsorted array: ";
    displayArray(arr, n);
    processSelectionSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
In today's digital era, a strong online presence is essential for business success. VFIX Technology, based in Delhi, is recognized as the best website designing company in Delhi and a leading provider of cutting-edge solutions, including app development, e-commerce websites, and website customization. Our goal is to empower businesses with tailored technology solutions that drive growth and customer satisfaction.
Expert App Development for Seamless User Experiences
At VFIX Technology, we specialize in creating intuitive and high-performance mobile apps. Whether you're looking for an app for Android or iOS, we ensure that your users have a seamless experience. From idea conceptualization to final deployment, our app development services cover all stages, offering:

    Custom app solutions for businesses of all sizes
    User-friendly interfaces designed to enhance engagement
    Robust, scalable, and secure apps

By leveraging the latest technologies, our team delivers apps that not only meet your requirements but also exceed your expectations. Whether you need a dynamic mobile presence or a customized app tailored to your industry, we’re here to help you take your mobile strategy to the next level.
#include <iostream>
using namespace std;

// Function to sort the array using insertion sort algorithm.
void processInsertionSort(int arr[], int n) 
{
  for (int i = 1; i < n; i++) 
    {
        int key = arr[i];
        int j = i - 1;
        
        while (j >= 0 && arr[j] > key) 
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processInsertionSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Boost Days: What's on in Melbourne this week!"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :halloween-coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering:* \n\n Halloween Themed Cookies and Caramel & Macadamia Slice (Gluten Free) :jack_o_lantern: \n\n *Weekly Café Special:* _ *Superfreak Halloween Blend* - expect notes of Candy Apple, Citrus, Orange Marmalade and Praline! _"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 30th October :calendar-date-30:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n* :cartoon-cannoli:* Afternoon Tea From *2pm* in the L3 kitchen \n\n:lotus: *Wellbeing - Yoga Flow*: Confirm your spot <https://docs.google.com/spreadsheets/d/1iKMQtSaawEdJluOmhdi_r_dAifeIg0JGCu7ZSPuwRbo/edit?gid=0#gid=0/|*here*>. Please note we have a maximum of 15 participants per class, a minimum notice period of 2 hours is required if you can no longer attend."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 31st October :halloween-date:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":halloween-breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am - 10:30am* in the Wominjeka Breakout Space.\n\n :meow-scary: *Haunted Hackathon Social+* A combination of Hackathon + Halloween themed! Dress up in your scariest outfit and come along for a range of activities, drinks and delicious food! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n *🎟 RSVP to our EOY Event Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_* :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":xero-unicorn: Reminder: End of Year Celebration – Registrations :xero-unicorn:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Hi Melbourne!* \n We hope you're getting excited for a night of magic! This is your friendly reminder to make sure you register to our end of year event by the 14th of November 2024! \n\n In today's post we've added in some answers to the commonly asked questions! Please read below."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"fields": [
				{
					"type": "mrkdwn",
					"text": "*📅 When:*\nThursday 28th November"
				},
				{
					"type": "mrkdwn",
					"text": "*📍 Where:*\n<https://www.google.com/maps/place/The+Timber+Yard/@-37.8331021,144.918894,17z/data=!3m1!4b1!4m6!3m5!1s0x6ad667735e56fcab:0x966480f06c58c00c!8m2!3d-37.8331021!4d144.9214743!16s/g/11gyy7sy4c?entry=ttu&g_ep=EgoyMDI0MDkxOC4xIKXMDSoASAFQAw==/|*The Timber Yard*> \n351 Plummer Street, Port Melbourne"
				},
				{
					"type": "mrkdwn",
					"text": "*⏰ Time:*\n4PM - 10PM"
				}
			]
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*:question: FAQs Fast Answers:*\n *Can I register on behalf of a colleague if they're on leave?* Yes absolutely! Just make sure you fill in their registration form with their Xero email address + personal details. \n\n *Smoking at the party?* No smoking/vaping will be permitted onsite, we will have a dedicated area outside of the venue for you to do your business! \n\n *How do we get into the event?* Simply show the security guards your email confirmation from JomaBlue for quick and easy access into the venue! "
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*🎟 RSVP Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":question:Got more questions? See the <https://docs.google.com/document/d/1iygJFHgLBRSdAffNsg3PudZCA45w6Wit7xsFxNc_wKM/edit|FAQs> doc or ask away in this thread!\n\n We can’t wait to celebrate with you! :partying_face: :xero-love:"
			}
		}
	]
}
{
  "type[currency]": "Hello, world!",
  "type[periodicity]": "Hello, world!",
  "type[price]": 1,
  "type[external_id]": "Hello, world!",
  "type[name]": "Hello, world!",
  "type[description]": "Hello, world!",
  "type[active]": true,
  "type[restriction_enabled]": true,
  "type[discharged]": true,
  "type[recurring_payment_enabled]": true,
  "type[until_year_end]": true,
  "type[enable_expire_month]": true,
  "type[expire_month]": 1,
  "type[recurring_mode]": "Hello, world!",
  "type[payment_account_id]": 1
}
for each  item in input.Items
{
	barcode = item.Barcode;
	query = Map();
	query.put("cf_barcode",barcode);
	fetch_item = invokeurl
	[
		url :"https://www.zohoapis.eu/books/v3/items?organization_id=" + organization_id
		type :GET
		parameters:query
		connection:"zoho_oauth_connection"
	];
	// 		info fetch_item;
	search_items = fetch_item.get("items");
	if(search_items.size() > 0)
	{
		////// Item found with barcode ////
		inventory_item_id = search_items.get(0).get("item_id");
		get_by_id = zoho.books.getRecordsByID("Items",organization_id,inventory_item_id,"zoho_oauth_connection");
// 		info get_by_id;
		item_details = get_by_id.get("item");
		custom_fields = item_details.get("custom_fields");
		rate = item_details.get("rate");
		for each field in custom_fields
        {
			if(field.get("label") == "Make")
			{
				make = field.get("value");
			}
			if(field.get("label") == "Model")
			{
				model = field.get("value");
			}
			if(field.get("label") == "Machine Type")
			{
				machine_type = field.get("value");
			}
			if(field.get("label") == "Shipping Class")
			{
				shipping_class = field.get("value");
			}
        } 
		item.Make = make;
		item.Model = model;
		item.Machine_Type = machine_type;
		item.Shipping_Class = shipping_class;
		item.Sales_Pric = rate;
		
	}
}
from yattag import Doc

import webbrowser

doc, tag, text = Doc().tagtext()

doc.asis('<!DOCTYPE html>')

with tag('html') as html:
    with tag('head') as head:
        with tag('title') as title:
            text('This is test web page')
    with tag('body') as body:
        with tag('h2') as h2:
            text('This is h2')

page = doc.getvalue()

f = open('page.html', 'w')
f.write(page)
f.close()

webbrowser.open('page.html')
<div class="col-xs-4" style="display: none;" id='id_estado'>
                                                    <?= $form->field($model, 'id_estado')->dropDownList(ArrayHelper::map(Estados::find()/*->where(['id_municipio'=> 2])*/->orderBy('desc_estado')->all(), 'id_estado', 'desc_estado'), ['prompt' => 'Seleccione ', 'id' => 'id-estado']); ?>
                                                </div>

                                                <div class="col-xs-4" style="display: none;" id='id_municipio'>

                                                    <?= $form->field($model, 'id_municipio')->widget(DepDrop::classname(), [
                                                        'options' => ['id' => 'id-ubicacion'],
                                                        'data' => $model->isNewRecord ? [] : ArrayHelper::map(Municipios::find()->where([ 'id_estado'=>$model->id_estado])->orderBy('desc_municipio')->asArray()->all(), 'id_municipio', 'desc_municipio'),
                                        
                                                        // ensure at least the preselected value is available
                                                        'pluginOptions' => [
                                                            'depends' => ['id-estado'],
                                                            // the id for cat attribute
                                                            'placeholder' => 'Seleccione un municipio...',
                                                            'url' => Url::to(['municipios/listar'])
                                                        ]
                                                    ]);
                                                    ?>
                                                </div>

                                                <div class="col-xs-4" style="display: none;" id='id_parroquia'>
                                                    <?= $form->field($model, 'id_parroquia')->widget(DepDrop::classname(), [
                                                        //'options'=>['id'=>'co_art_'.$regla->cod_linea.''],

                                                        'data' => $model->isNewRecord ? [] : ArrayHelper::map(Parroquias::find()->where(['id_municipio'=>$model->id_municipio])->orderBy('desc_parroquia')->asArray()->all(), 'id_parroquia', 'desc_parroquia'),
                                                        // ensure at least the preselected value is available
                                                        'pluginOptions' => [
                                                            'depends' => ['id-ubicacion'],
                                                            // the id for cat attribute
                                                            'placeholder' => 'Seleccione una parroquia...',
                                                            'url' => Url::to(['parroquias/listar'])
                                                        ]
                                                    ]);
                                                    ?>
                                                </div>

controlador municipio

public function actionListar() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $dep_id = $parents[0];
                //$hoy = date('Y-m-d');
                //$out = self::getSubCatList($cat_id);
                $out = \yii\helpers\ArrayHelper::toArray(Municipios::find()->where([ 'id_estado'=>$dep_id])->orderBy('desc_municipio')->all(), 'id_municipio', 'desc_municipio');
               
                $response = array();
                foreach ($out as $row) {
                  $arr['id'] = trim($row['id_municipio']);
                  $arr['name'] = trim($row['desc_municipio']);
                  array_push($response, $arr);
                }
                echo \yii\helpers\Json::encode(['output'=>$response, 'selected'=>'']);
                return;
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }

controlador parroquia
public function actionListar() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
    //var_dump($parents); die();
            if ($parents != null) {
                $dep_id = $parents[0];

                //para que se pueda cargar la parroquia en blanco, mientras no sea seleccionado un municipio
                if($dep_id == ""){
                          echo \yii\helpers\Json::encode(['output'=>'', 'selected'=>'']);
                          return;

                }
                //$hoy = date('Y-m-d');
                $out = yii\helpers\ArrayHelper::toArray(Parroquias::find()->where(['id_municipio'=>$dep_id])->orderBy('desc_parroquia')->all(), 'id_parroquia', 'desc_parroquia');

                $response = array();
                foreach ($out as $row) {
                  $arr['id'] = trim($row['id_parroquia']);
                  $arr['name'] = trim($row['desc_parroquia']);
                  array_push($response, $arr);
                }
                echo \yii\helpers\Json::encode(['output'=>$response, 'selected'=>'']);
                return;
            }
        }
        echo \yii\helpers\Json::encode(['output'=>'', 'selected'=>'']);
    }    

___________________otro ejemplo usando el modelo del mismo archivo este ejemplo es mas sencillo por que no hay que ponerle la condicion en data como en el ejemplo anterior
<div class="row">
        <div class="col-xs-1"></div>
        <div class="col-xs-3">
            <?= $form->field($model, 'id_estado')->dropDownList(ArrayHelper::map(Estados::find()->orderBy('desc_estado')->all(), 'id_estado', 'desc_estado'), ['prompt' => 'Seleccione un estado', 'id' => 'id-estado']); ?>
        </div>

        <div class="col-xs-3">
            <?= $form->field($model, 'id_municipio')->widget(DepDrop::classname(), [
                'options' => ['id' => 'id-municipio'],
                'data' => [$model->id_municipio => $model->municipio],
                // ensure at least the preselected value is available
                'pluginOptions' => [
                    'depends' => ['id-estado'],
                    // the id for cat attribute
                    'placeholder' => 'Seleccione un municipio...',
                    'url' => Url::to(['municipios/listar'])
                ]
            ]);
            ?>
        </div>
        <div class="col-xs-3">
            <?= $form->field($model, 'id_parroquia')->widget(DepDrop::classname(), [
                //'options'=>['id'=>'co_art_'.$regla->cod_linea.''],
            
                'data' => [$model->id_parroquia => $model->Parroquia],
                // ensure at least the preselected value is available
                'pluginOptions' => [
                    'depends' => ['id-municipio'],
                    // the id for cat attribute
                    'placeholder' => 'Seleccione una parroquia...',
                    'url' => Url::to(['parroquias/listar'])
                ]
            ]);
            ?>
        </div>
    </div>

depues colocar esto en el modelo solamente este ejemplo es mas sencillo que el anterior

public function getMunicipio(){
        if($this->id_municipio):
          $p = Municipios::findOne(['id_municipio'=>$this->id_municipio]);
          if ($p):
            $p = $p->desc_municipio;
          endif;
        else:
          $p = "";
        endif;
  
        return $p;
      }
  
       public function getParroquia(){
        if($this->id_parroquia):
          $p = Parroquias::findOne(['id_parroquia'=>$this->id_parroquia]);
          if ($p):
            $p = $p->desc_parroquia;
          endif;
        else:
          $p = "";
        endif;
  
        return $p;
      }
[acf field="field_name" post_id="123"]
add_action( 'acf/init', 'set_acf_settings' );
function set_acf_settings() {
    acf_update_setting( 'enable_shortcode', true );
}
star

Sat Oct 26 2024 17:35:13 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 17:13:37 GMT+0000 (Coordinated Universal Time)

@mrsdigital #elementor

star

Sat Oct 26 2024 15:51:58 GMT+0000 (Coordinated Universal Time) http://kikoumania.monorganisation.fr/administrator/index.php?option

@pcessac

star

Sat Oct 26 2024 15:08:37 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Sat Oct 26 2024 14:12:14 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Oct 26 2024 14:10:58 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Oct 26 2024 13:26:40 GMT+0000 (Coordinated Universal Time) https://appticz.com/food-delivery-app-development

@aditi_sharma_

star

Sat Oct 26 2024 13:20:44 GMT+0000 (Coordinated Universal Time)

@sukumar #java

star

Sat Oct 26 2024 11:58:12 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 11:54:31 GMT+0000 (Coordinated Universal Time) https://uiball.com/ldrs/

@Rishi1808

star

Sat Oct 26 2024 11:48:33 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 10:03:40 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:35:20 GMT+0000 (Coordinated Universal Time) https://lazyadmin.nl/win-11/turn-off-windows-defender-windows-11-permanently/

@Curable1600 #windows

star

Sat Oct 26 2024 09:31:43 GMT+0000 (Coordinated Universal Time) https://github.com/orgs/community/discussions/139005

@Ashsebahay0323_

star

Sat Oct 26 2024 09:28:15 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:01:51 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 26 2024 08:26:18 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 06:34:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/p2p-cryptocurrency-exchange-development

@jamielucas #nodejs

star

Sat Oct 26 2024 03:23:34 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/blog/new-in-devtools-130/?utm_source

@Ashsebahay0323_

star

Sat Oct 26 2024 01:44:49 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/encoding-and-decoding-base64-strings-in-python/

@jrb9000 #python

star

Fri Oct 25 2024 20:59:03 GMT+0000 (Coordinated Universal Time) https://www.go2bank.com/?utm_medium

@Ashsebahay0323_

star

Fri Oct 25 2024 19:12:59 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Oct 25 2024 18:31:19 GMT+0000 (Coordinated Universal Time) https://element.how/elementor-close-off-canvas-on-anchor-link-click/

@webisko #javascript

star

Fri Oct 25 2024 13:30:04 GMT+0000 (Coordinated Universal Time)

@banch3v

star

Fri Oct 25 2024 12:21:57 GMT+0000 (Coordinated Universal Time) https://editor.p5js.org/

@seb_prjcts_be

star

Fri Oct 25 2024 09:17:55 GMT+0000 (Coordinated Universal Time)

@SVELTRON #php

star

Fri Oct 25 2024 07:44:53 GMT+0000 (Coordinated Universal Time) https://myaccount.google.com/apppasswords?pli

@jwhitlow5

star

Fri Oct 25 2024 06:57:58 GMT+0000 (Coordinated Universal Time) https://innosoft-group.com/sports-betting-software-development/

@johnstone #sportsbetting app developers #bettingapp development company #sportsbetting app development

star

Fri Oct 25 2024 05:50:03 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Fri Oct 25 2024 05:20:41 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Fri Oct 25 2024 02:11:21 GMT+0000 (Coordinated Universal Time) https://matplotlib.org/stable/users/explain/colors/colormaps.html

@theshyxin

star

Fri Oct 25 2024 00:33:07 GMT+0000 (Coordinated Universal Time) https://eda-ai-lab.tistory.com/580

@wheedo

star

Thu Oct 24 2024 16:10:33 GMT+0000 (Coordinated Universal Time) undefined

@kirexmak

star

Thu Oct 24 2024 13:38:52 GMT+0000 (Coordinated Universal Time) https://www.dabapps.com/insights/api-performance-profiling-django-rest-framework/

@fearless

star

Thu Oct 24 2024 10:11:01 GMT+0000 (Coordinated Universal Time)

@sarathkishore

star

Thu Oct 24 2024 08:18:16 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Oct 24 2024 07:16:08 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Oct 24 2024 07:10:49 GMT+0000 (Coordinated Universal Time) https://www.bestwebsite.com

@Webvfix #laravel

star

Thu Oct 24 2024 06:12:32 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Oct 24 2024 05:26:18 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Thu Oct 24 2024 04:21:20 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Oct 24 2024 02:19:44 GMT+0000 (Coordinated Universal Time) https://hivebrite.com/documentation/api/admin

@acassell

star

Wed Oct 23 2024 21:55:14 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Wed Oct 23 2024 19:52:13 GMT+0000 (Coordinated Universal Time)

@freepythoncode ##python #coding #python #programming

star

Wed Oct 23 2024 14:23:07 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Wed Oct 23 2024 13:09:45 GMT+0000 (Coordinated Universal Time)

@webisko

star

Wed Oct 23 2024 12:55:49 GMT+0000 (Coordinated Universal Time)

@webisko #php

Save snippets that work with our extensions

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