Snippets Collections
#Get all pods
kubectl get pods

#Get logs 
kubectl logs atlasai-control-plane-api-549dfcd85b-677zv 

#Delete pod
kubectl delete deployment atlasai-control-plane-api

#Applly local deployment 
kubectl apply -f local_deploy/atlasai-control-plane-api-deployment.yaml
import java.util.Scanner;

public class Main {

    public static int prim(int[][] cost, int n) {
        int[] near = new int[n]; // Tracks the nearest vertices
        int[][] t = new int[n - 1][2]; // Array to store the edges of the minimum spanning tree
        int minCost = 0;

        // Step 1: Find the edge with minimum cost
        int k = -1, l = -1;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (cost[i][j] < min) {
                    min = cost[i][j];
                    k = i;
                    l = j;
                }
            }
        }

        // Initialize the minimum cost and the first edge of the MST
        minCost += min;
        t[0][0] = k;
        t[0][1] = l;

        // Initialize the near array
        for (int i = 0; i < n; i++) {
            near[i] = (cost[i][l] < cost[i][k]) ? l : k;
        }
        near[k] = near[l] = -1; // Mark these vertices as part of the MST

        // Step 2: Find n - 2 edges to complete the MST
        for (int i = 1; i < n - 1; i++) {
            min = Integer.MAX_VALUE;
            int j = -1;

            // Find the vertex j with the minimum cost to add to the MST
            for (int m = 0; m < n; m++) {
                if (near[m] != -1 && cost[m][near[m]] < min) {
                    min = cost[m][near[m]];
                    j = m;
                }
            }

            // Add the edge to the MST
            t[i][0] = j;
            t[i][1] = near[j];
            minCost += cost[j][near[j]];
            near[j] = -1; // Mark j as included in the MST

            // Update the near array
            for (int m = 0; m < n; m++) {
                if (near[m] != -1 && cost[m][near[m]] > cost[m][j]) {
                    near[m] = j;
                }
            }
        }

        // Print the MST edges
        System.out.println("Edges in the Minimum Spanning Tree:");
        for (int i = 0; i < n - 1; i++) {
            System.out.println("(" + t[i][0] + ", " + t[i][1] + ")");
        }

        return minCost;
    }

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

        // Take the number of vertices as input
        System.out.print("Enter the number of vertices: ");
        int n = sc.nextInt();

        // Create the adjacency matrix (cost) based on user input
        int[][] cost = new int[n][n];
        System.out.println("Enter the adjacency matrix (-1 for no edge):");

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j) {
                    cost[i][j] = Integer.MAX_VALUE; // No self-loops
                } else {
                    System.out.print("Cost of edge between " + i + " and " + j + ": ");
                    int input = sc.nextInt();
                    cost[i][j] = (input == -1) ? Integer.MAX_VALUE : input;
                }
            }
        }

        // Calculate the minimum spanning tree
        int minCost = prim(cost, n);

        // Output the minimum cost of the MST
        System.out.println("Minimum Cost of the MST: " + minCost);
        sc.close();
    }
}

/*
Enter the number of vertices: 4
Enter the adjacency matrix (-1 for no edge):
Cost of edge between 0 and 1: 1
Cost of edge between 0 and 2: 3
Cost of edge between 0 and 3: -1
Cost of edge between 1 and 2: 1
Cost of edge between 1 and 3: 4
Cost of edge between 2 and 3: 2
Edges in the Minimum Spanning Tree:
(0, 1)
(1, 2)
(2, 3)
Minimum Cost of the MST: 4*/




 
Algorithm Prim(E, cost, n, t)
// E is the set of edges in G. cost[1 : n, 1 : n] is the cost
// adjacency matrix of an n vertex graph such that cost[i, j] is
// either a positive real number or ∞ if no edge (i, j) exists.
// A minimum spanning tree is computed and stored as a set of
// edges in the array t[1 : n − 1, 1 : 2]. (t[i, 1], t[i, 2]) is an edge in
// the minimum-cost spanning tree. The final cost is returned.
 
css
Copy code
Let (k, l) be an edge of minimum cost in E;  
mincost := cost[k, l];  
t[1, 1] := k; t[1, 2] := l;  
for i := 1 to n do  // Initialize near.  
{  
    if (cost[i, l] < cost[i, k]) then near[i] := l;  
    else near[i] := k;  
}  
near[k] := near[l] := 0;  
for i := 2 to n − 1 do  
{  
    // Find n − 2 additional edges for t.  
    Let j be an index such that near[j] ≠ 0 and  
    cost[j, near[j]] is minimum;  
    t[i, 1] := j; t[i, 2] := near[j];  
    mincost := mincost + cost[j, near[j]];  
    near[j] := 0;  
    for k := 1 to n do  // Update near[ ].  
    {  
        if ((near[k] ≠ 0) and (cost[k, near[k]] > cost[k, j]))  
            then near[k] := j;  
    }  
}  
return mincost;
import java.util.Arrays;
import java.util.Scanner;

// Job class to hold information about each job.
class Job {
    int id;       // Job ID
    int profit;   // Profit of the job
    int deadline; // Deadline of the job
    
    // Constructor to initialize job details
    public Job(int id, int profit, int deadline) {
        this.id = id;
        this.profit = profit;
        this.deadline = deadline;
    }
}

// Comparator to sort jobs based on profit in descending order
class JobComparator implements java.util.Comparator<Job> {
    @Override
    public int compare(Job job1, Job job2) {
        return job2.profit - job1.profit; // Sorting in descending order of profit
    }
}

public class Main {

    // Function to perform Job Sequencing with Deadlines
    public static void jobSequencing(Job[] jobs, int n) {
        // Sort the jobs based on profit in descending order
        Arrays.sort(jobs, new JobComparator());
        
        // Find the maximum deadline to determine the size of the result array
        int maxDeadline = 0;
        for (int i = 0; i < n; i++) {
            if (jobs[i].deadline > maxDeadline) {
                maxDeadline = jobs[i].deadline;
            }
        }
        
        // Array to store the result (sequenced jobs)
        int[] result = new int[maxDeadline];
        
        // Initialize all slots as empty (-1 means no job is scheduled)
        Arrays.fill(result, -1);
        
        // Variable to track total profit
        int totalProfit = 0;
        
        // Iterate over all jobs
        for (int i = 0; i < n; i++) {
            // Find a free slot for the job (starting from the latest available slot)
            for (int j = jobs[i].deadline - 1; j >= 0; j--) {
                if (result[j] == -1) { // If the slot is free
                    result[j] = jobs[i].id; // Schedule the job
                    totalProfit += jobs[i].profit; // Add profit
                    break;
                }
            }
        }
        
        // Print the scheduled jobs and total profit
        System.out.println("Jobs scheduled in the sequence are:");
        for (int i = 0; i < maxDeadline; i++) {
            if (result[i] != -1) {
                System.out.print("Job " + result[i] + " ");
            }
        }
        System.out.println();
        System.out.println("Total Profit = " + totalProfit);
    }

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

        // Take input for number of jobs
        System.out.print("Enter number of jobs: ");
        int n = scanner.nextInt();

        // Create an array of jobs
        Job[] jobs = new Job[n];

        // Take input for jobs (id, profit, deadline)
        System.out.println("Enter job details (ID Profit Deadline):");
        for (int i = 0; i < n; i++) {
            System.out.print("Job " + (i + 1) + ": ");
            int id = scanner.nextInt();
            int profit = scanner.nextInt();
            int deadline = scanner.nextInt();
            jobs[i] = new Job(id, profit, deadline);
        }

        // Call the job sequencing function
        jobSequencing(jobs, n);

        scanner.close();
    }
}




 GreedyJob(d, J, n)
{
    // J is the set of jobs that can be completed by their deadlines.
    J := {1};  // Start with the first job

    for i := 2 to n do
    {
        // Check if adding job i to the set J allows all jobs in J to be completed by their deadlines.
        if (all jobs in J ∪ {i} can be completed by their deadlines) then
        {
            J := J ∪ {i};  // Add job i to the set
        }
    }
}



 Algorithm JS(d, p, n)
// d[i] > 1, 1 ≤ i ≤ n are the deadlines, n > 1.
// The jobs are ordered such that p[1] > p[2] > ... > p[n].
// J[i] is the ith job in the optimal solution, 1 ≤ i ≤ k.
// At termination, d[J[i]] < d[J[i+1]], 1 ≤ i < k.
{
    rf[0] := J[0] := 0;  // Initialize.
    J[1] := 1;           // Include job 1 in the solution.
    k := 1;

    for i := 2 to n do
    {
        // Consider jobs in non-increasing order of profit p[i].
        // Find position for job i and check feasibility of insertion.
        r := k;

        while ((d[J[r]] > d[i]) and (d[J[r]] ≠ r)) do
        {
            r := r - 1;
        }

        if ((d[J[r]] < d[i]) and (d[i] > r)) then
        {
            // Insert job i into J[].
            for q := k to (r + 1) step -1 do
            {
                J[q + 1] := J[q];
            }
            J[r + 1] := i;
            k := k + 1;
        }
    }
    return k;
}
import java.util.*;

public class Graph {
    private int vertices;
    private LinkedList<Integer>[] adjList;
    private int time;

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

    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);
    }

    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];
        int[] low = new int[vertices];
        int[] parent = new int[vertices];
        Arrays.fill(parent, -1);

        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;
        dfn[u] = low[u] = ++time;
        int childCount = 0;
        boolean isArticulation = false;

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

                low[u] = Math.min(low[u], low[v]);

                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    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++) {
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

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

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

        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();
            }
        }

        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}





AlgorithmArt(u, v)
// u: Start vertex for Depth First Search (DFS)
// v: Parent of u in the DFS tree (if any)
// dfn: Global array initialized to 0, storing discovery times of vertices
// L: Global array to store the lowest discovery time reachable from each vertex
// num: Global variable initialized to 1, represents the discovery order
// n: Number of vertices in the graph

{
    dfn[u] := num;           // Assign discovery time for u
    L[u] := num;             // Initialize lowest discovery time for u
    num := num + 1;          // Increment discovery counter

    for each vertex w adjacent to u do
    {
        if (dfn[w] = 0) then  // If w is unvisited
        {
            Art(w, u);        // Recursively visit w
            L[u] := min(L[u], L[w]);  // Update the lowest discovery time for u
        }
        elseif (w ≠ v) then   // If w is not the parent of u
        {
            L[u] := min(L[u], dfn[w]); // Update the lowest discovery time
        }
    }
}
 AlgorithmBiComp(u, v)
// u: Start vertex for Depth First Search (DFS)
// v: Parent of u in the DFS tree (if any)
// dfn: Global array initialized to 0, storing discovery times of vertices
// L: Global array to store the lowest discovery time reachable from each vertex
// num: Global variable initialized to 1, represents the discovery order
// s: Stack to store edges
// n: Number of vertices in the graph

{
    dfn[u] := num;           // Assign discovery time for u
    L[u] := num;             // Initialize lowest discovery time for u
    num := num + 1;          // Increment discovery counter

    for each vertex w adjacent to u do
    {
        // Push edge (u, w) onto the stack if it exists and w is not the parent
        if ((w ≠ v) and (dfn[w] < dfn[u])) then
            Add edge (u, w) to the top of the stack s;

        if (dfn[w] = 0) then  // If w is unvisited
        {
            BiComp(w, u);     // Recursively apply BiComp on w

            if (L[w] > dfn[u]) then  // Found a new biconnected component
            {
                write("New biconnected component:");
                repeat
                {
                    Delete an edge from the top of stack s;
                    Let this edge be (x, y);
                    write(x, y);   // Output the edges in the component
                } until (((x, y) = (u, w)) or ((x, y) = (w, u))); 
            }

            L[u] := min(L[u], L[w]);  // Update the lowest discovery time for u
        }
        elseif (w ≠ v) then
        {
            L[u] := min(L[u], dfn[w]);  // Update the lowest discovery time if w is already visited
        }
    }
}
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of keys (n):");
        int n = sc.nextInt();
        double[] p = new double[n+1];
        double[] q = new double[n+1];
        
       System.out.println("Enter probabilities of successful searches for keys (p):");
        for(int i=1;i<=n;i++){
            p[i] = sc.nextDouble();
        }
        
       System.out.println("Enter probabilities of unsuccessful searches (q):");
        for(int i=0;i<=n;i++){
            q[i] = sc.nextDouble();
        }
        obst(p,q,n);
    }
    public static void obst(double[] p,double[] q,int n){
        double[][] w = new double[n+1][n+1];
        double[][] c = new double[n+1][n+1];
        int[][] r = new int[n+1][n+1];
        for(int i=0;i<=n;i++){
            w[i][i] = q[i];
            c[i][i] = 0;
            r[i][i] = 0;
        }
        for(int m = 1;m<=n;m++){
            for(int i=0;i<=n-m;i++){
                int j = i+m;
                w[i][j] = w[i][j-1] + p[j]+q[j];
                double mincost = Double.MAX_VALUE;
                int root = -1;
                for(int k=i+1;k<=j;k++){
                    double cost = c[i][k-1]+c[k][j]+w[i][j];
                    if(cost < mincost){
                        mincost = cost;
                        root = k;
                    }
                }
                c[i][j] = mincost;
                r[i][j] = root;
            }
        }
        System.out.println("Cost = "+c[0][n]);
        System.out.println("Weight = "+w[0][n]);
    }
}






ALGORITHM:
// Algorithm OBST(p, q, n)
// Given n distinct identifiers a1 < a2 < ... < an and probabilities
// p[i], 1 ≤ i ≤ n, and q[i], 0 ≤ i ≤ n, this algorithm computes
// the cost c[i, j] of optimal binary search trees tij for identifiers
// a[i+1],...,a[j]. It also computes r[i, j], the root of tij.
// w[i, j] is the weight of tij.
 
for i := 0 to n - 1 do
{
    // Initialize.
    w[i, i] := q[i]; r[i, i] := 0; c[i, i] := 0.0;
    // Optimal trees with one node
    w[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
    r[i, i + 1] := i + 1;
    c[i, i + 1] := q[i] + q[i + 1] + p[i + 1];
}
w[n, n] := q[n]; r[n, n] := 0; c[n, n] := 0.0;
for m := 2 to n do // Find optimal trees with m nodes.
    for i := 0 to n - m do
    {
        j := i + m;
        w[i, j] := w[i, j - 1] + p[j] + q[j];
        // Solve 5.12 using Knuth's result.
        k := Find(c, r, i, j);
        // A value of l in the range r[i, j - 1] ≤ l ≤ r[i + 1, j] that minimizes c[i, l - 1] + c[l, j];
        c[i, j] := w[i, j] + c[i, k - 1] + c[k, j];
        r[i, j] := k;
    }
write (c[0, n], w[0, n], r[0, n]);
 
// Algorithm Find(c, r, i, j)
min := ∞;
for m := r[i, j - 1] to r[i + 1, j] do
    if (c[i, m - 1] + c[m, j]) < min then
    {
        min := c[i, m - 1] + c[m, j];
        l := m;
    }
return l;
import java.util.Scanner;

public class QuickSort {
    
    // Method to swap two elements in an array
    public static void interchange(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    
    // Partition method to select the pivot and arrange the array
    public static int partition(int[] a, int p, int q) {
        int v = a[p];  // pivot element
        int i = p, j = q + 1;
        
        do {
            // Move i to the right as long as the element is less than the pivot
            do {
                i = i + 1;
            } while (i <= q && a[i] < v);
            
            // Move j to the left as long as the element is greater than the pivot
            do {
                j = j - 1;
            } while (a[j] > v && j >= p);
            
            // If i < j, swap the elements
            if (i < j) {
                interchange(a, i, j);
            }
        } while (i < j);
        
        // Swap the pivot with the element at j
        interchange(a, p, j);
        
        return j;  // Return the index of the pivot element
    }
    
    // QuickSort method to recursively sort the subarrays
    public static void quickSort(int[] a, int p, int q) {
        if (p < q) {
            int j = partition(a, p, q);  // Partition the array
            quickSort(a, p, j - 1);       // Sort the left subarray
            quickSort(a, j + 1, q);       // Sort the right subarray
        }
    }

    // Main method to accept input and run the quickSort
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Input size of the array
        System.out.print("Enter Size: ");
        int n = scanner.nextInt();
        
        int[] a = new int[n];  // Array initialization
        
        // Input array elements
        System.out.println("Enter elements: ");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }
        
        // Perform QuickSort
        quickSort(a, 0, n - 1);
        
        // Output the sorted array
        System.out.print("Sorted Array: ");
        for (int i = 0; i < n; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        
        scanner.close();  // Close the scanner to avoid memory leaks
    }
}




 
Algorithm Partition(a, m, p)
Within a[m], a[m+1],...,a[p-1] the elements are rearranged in such a manner that if initially t = a[m],
then after completion a[q] = t for some q between m and p-1, a[k] < t for m ≤ k < q, and a[k] ≥ t for q < k < p. q is returned. Set a[p] = ∞.
v := a[m]; i := m; j := p;
repeat
    repeat
        i := i + 1;
    until (a[i] ≥ v);
    repeat
        j := j - 1;
    until (a[j] < v);
    if (i < j) then
        Interchange(a, i, j);
} until (i ≥ j);
 
a[m] := a[j]; a[j] := v;
return j;
 
Algorithm Interchange(a, i, j)
// Exchange a[i] with a[j].
temp := a[i];
a[i] := a[j];
a[j] := temp;
 
 
Algorithm: QuickSort (p, q)
 
// Sorts the elements in the array a[p : q] in non-decreasing order.
 
if (p < q) then // If there is more than one element
{
    // Divide the array into two subproblems.
    j := Partition(a, p, q + 1);
    // 'j' is the position of the partitioning element.
 
    QuickSort(p, j - 1); // Sort the left subarray.
    QuickSort(j + 1, q); // Sort the right subarray.
def dfs(adj, V, vis, i, curr):
    vis[curr] = 1
    for x in adj[curr]:
        if x != i and not vis[x]:
            dfs(adj, V, vis, i, x)

def AP(adj, V):
    for i in range(1, V + 1):
        components = 0
        vis = [0] * (V + 1)
        for j in range(1, V + 1):
            if j != i:
                if not vis[j]:
                    components += 1
                    dfs(adj, V, vis, i, j)
        if components > 1:
            print(i)

def addEdge(adj, u, v):
    adj[u].append(v)
    adj[v].append(u)

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    adj = [[] for _ in range(V + 1)]
    print("Enter each edge as 'u v' (space-separated):")
    for _ in range(E):
        u, v = map(int, input().split())
        addEdge(adj, u, v)
    print("Articulation points in the graph:")
    AP(adj, V)
class Job:
    def __init__(self, id, profit, deadline):
        self.id = id
        self.profit = profit
        self.deadline = deadline

def job_sequencing(jobs, n):
    jobs.sort(key=lambda x: x.profit, reverse=True)
    result = [None] * n
    slot = [False] * n
    total_profit = 0

    for job in jobs:
        for j in range(min(n, job.deadline) - 1, -1, -1):
            if not slot[j]:
                result[j] = job.id
                slot[j] = True
                total_profit += job.profit
                break

    print("Job sequence:", result)
    print("Total profit:", total_profit)

if __name__ == "__main__":
    n = int(input("Enter number of jobs: "))
    jobs = []
    for _ in range(n):
        id, profit, deadline = map(int, input("Enter id, profit, deadline: ").split())
        jobs.append(Job(id, profit, deadline))
    
    job_sequencing(jobs, n)
class Item:
    def __init__(self, cost, weight):
        self.cost = cost
        self.weight = weight
        self.ratio = cost / weight

def fractional_knapsack(capacity, items):
    items.sort(key=lambda item: item.ratio, reverse=True)

    total_cost = 0
    for item in items:
        if capacity <= 0:
            break

        if item.weight <= capacity:
            total_cost += item.cost
            capacity -= item.weight
        else:
            total_cost += item.cost * (capacity / item.weight)
            capacity = 0

    return total_cost

if __name__ == "__main__":
    n = int(input("Enter the number of items: "))
    capacity = int(input("Enter the capacity of the knapsack: "))
    
    items = []
    for _ in range(n):
        cost, weight = map(int, input("Enter cost and weight of item (cost weight): ").split())
        items.append(Item(cost, weight))
    
    result = fractional_knapsack(capacity, items)
    print(f"The maximum cost that can be obtained: {result}")
import heapq

def dijkstra(V, edges, start):
    adj = [[] for _ in range(V)]
    for u, v, wt in edges:
        adj[u].append((v, wt))
        adj[v].append((u, wt))

    pq = []
    distances = [float('inf')] * V
    visited = [False] * V

    distances[start] = 0
    heapq.heappush(pq, (0, start))

    while pq:
        current_distance, u = heapq.heappop(pq)
        if visited[u]:
            continue
        visited[u] = True

        for v, weight in adj[u]:
            if not visited[v] and current_distance + weight < distances[v]:
                distances[v] = current_distance + weight
                heapq.heappush(pq, (distances[v], v))

    return distances

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    edges = []

    print("Enter each edge as 'u v weight':")
    for _ in range(E):
        u, v, wt = map(int, input().split())
        edges.append((u, v, wt))

    start = int(input("Enter the starting vertex: "))
    result = dijkstra(V, edges, start)
    print("The shortest distances from the starting vertex are:")
    for i, d in enumerate(result):
        print(f"Vertex {i}: {d}")
import heapq

def tree(V, E, edges):
    adj = [[] for _ in range(V)]
    for i in range(E):
        u, v, wt = edges[i]
        adj[u].append((v, wt))
        adj[v].append((u, wt))

    pq = []
    visited = [False] * V
    res = 0
    heapq.heappush(pq, (0, 0))

    while pq:
        wt, u = heapq.heappop(pq)
        if visited[u]:
            continue
        res += wt
        visited[u] = True
        for v, weight in adj[u]:
            if not visited[v]:
                heapq.heappush(pq, (weight, v))

    return res

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    edges = []

    print("Enter each edge as 'u v weight':")
    for _ in range(E):
        u, v, wt = map(int, input().split())
        edges.append([u, v, wt])

    result = tree(V, E, edges)
    print("The total weight of the Minimum Spanning Tree is:", result)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# Make predictions
y_pred = rf.predict(X_test)
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
Partition(a, m, p)
    v = a[m]
    i = m
    j = p
    repeat
        repeat
            i = i + 1
        until a[i] > v
        repeat
            j = j - 1
        until a[j] < v
        if i < j then
            Interchange(a, i, j)
    until i > j
    a[m] = a[j]
    a[j] = v
    return j


Interchange(a, i, j)
    temp = a[i]
    a[i] = a[j]
    a[j] = temp


QuickSort(a, p, q)
    if p < q then
        j = Partition(a, p, q + 1)
        QuickSort(a, p, j - 1)
        QuickSort(a, j + 1, q)
MERGE-SORT(A, low, high)
If low < high
    mid = (low + high) / 2
    MERGE-SORT(A, low, mid)       // Sort first half
    MERGE-SORT(A, mid + 1, high)  // Sort second half
    MERGE(A, low, mid, high)      // Merge the sorted halves










MERGE(low, mid, high)
{
    h = low        // Pointer for the first subarray (a[low : mid])
    i = low        // Pointer for the auxiliary array (b[])
    j = mid + 1    // Pointer for the second subarray (a[mid + 1 : high])

    // Merge the two sorted subarrays into b[]
    while (h <= mid) and (j <= high) do
    {
        if (a[h] <= a[j]) then
        {
            b[i] = a[h]
            h = h + 1
        }
        else
        {
            b[i] = a[j]
            j = j + 1
        }
        i = i + 1
    }

    // Copy remaining elements from the first subarray, if any
    if (h > mid) then
        for k = j to high do
        {
            b[i] = a[k]
            i = i + 1
        }
    else
        for k = h to mid do
        {
            b[i] = a[k]
            i = i + 1
        }

    // Copy merged elements back to the original array
    for k = low to high do
        a[k] = b[k]
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://fh-kit.com/buttons/v2/?color=8B4514" type="text/css" media="screen" />
<script type="text/javascript">
  jQuery(document).ready(function($){
    fhScript= document.createElement('script');
    fhScript.src = "https://fareharbor.com/embeds/api/v1/?autolightframe=yes";
    $('body').append(fhScript);
    $('body').append('<a href="https://fareharbor.com/embeds/book/cuevalafaraona/?full-items=yes" style="font-weight: bold !important; font-family:Montserrat, sans-serif !important; box-shadow:none !important; padding: .2em 2em !important; "class="fh-hide--mobile fh-button-true-flat-color fh-shape--round fh-fixed--bottom fh-icon--cal">Reserva</a>');
    $('body').append('<a href="https://fareharbor.com/embeds/book/cuevalafaraona/?full-items=yes" style="font-size: 1.2em !important; font-weight: bold !important; font-family:Montserrat, sans-serif !important; box-shadow:none !important;" class="fh-hide--desktop fh-size--small fh-button-true-flat-color fh-shape--round fh-fixed--bottom fh-icon--cal">Reserva</a>');
  });
</script>
#include <stdio.h>

void printSolutionVector(int* x, int k) {
    printf("Solution Vector: ");
    for (int i = 0; i <= k; i++) {
        printf("%d ", x[i]);
    }
    printf("\n");
}

void sumOfSub(int* weights, int* x, int s, int k, int r, int m, int n) {
    // Include the current element
    x[k] = 1;
    if (s + weights[k] == m) {
        // If the sum matches the target, print the solution vector
        printSolutionVector(x, k);
    } 
    // Check if including the current element and the next one keeps the sum within bounds
    else if (k + 1 < n && s + weights[k] + weights[k + 1] <= m) {
        sumOfSub(weights, x, s + weights[k], k + 1, r - weights[k], m, n);
    }

    // Exclude the current element and check if further exploration is valid
    if ((s + r - weights[k] >= m) && (k + 1 < n && s + weights[k + 1] <= m)) {
        x[k] = 0;
        sumOfSub(weights, x, s, k + 1, r - weights[k], m, n);
    }
}

int main() {
    int n;
    printf("Enter the number of elements in the set: ");
    scanf("%d", &n);

    int weights[n];
    printf("Enter the elements of the set (in non-decreasing order): ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &weights[i]);
    }

    int m;
    printf("Enter the target sum (m): ");
    scanf("%d", &m);

    int x[n];
    int r = 0;
    for (int i = 0; i < n; i++) {
        r += weights[i];
    }

    printf("Solution Vectors with sum %d:\n", m);
    sumOfSub(weights, x, 0, 0, r, m, n);

    return 0;
}
import java.util.Scanner;

public class MergeSort {

    // Global array `a` and auxiliary array `b`
    private static int[] a;
    private static int[] b;

    // MergeSort function
    public static void mergeSort(int low, int high) {
        if (low < high) {
            // Divide step: find the midpoint
            int mid = (low + high) / 2;

            // Solve subproblems by recursively calling mergeSort on each half
            mergeSort(low, mid);
            mergeSort(mid + 1, high);

            // Combine step: merge the two halves
            merge(low, mid, high);
        }
    }

    // Merge function to combine two sorted subarrays a[low:mid] and a[mid+1:high]
    public static void merge(int low, int mid, int high) {
        int h = low;  // Start index for first subarray
        int i = low;  // Index to place merged elements in the auxiliary array
        int j = mid + 1;  // Start index for second subarray

        // Copy the elements to the auxiliary array `b`
        b = new int[a.length];
        
        // Merge the two subarrays
        while (h <= mid && j <= high) {
            if (a[h] <= a[j]) {
                b[i] = a[h];
                h++;
            } else {
                b[i] = a[j];
                j++;
            }
            i++;
        }

        // Copy remaining elements of the first subarray (if any)
        while (h <= mid) {
            b[i] = a[h];
            h++;
            i++;
        }

        // Copy remaining elements of the second subarray (if any)
        while (j <= high) {
            b[i] = a[j];
            j++;
            i++;
        }

        // Copy the sorted elements back to the original array
        for (int k = low; k <= high; k++) {
            a[k] = b[k];
        }
    }

    // Helper method to print the array
    public static void printArray() {
        for (int element : a) {
            System.out.print(element + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // Create a scanner object for taking input from the user
        Scanner scanner = new Scanner(System.in);

        // Ask the user for the size of the array
        System.out.println("Enter the number of elements in the array:");
        int n = scanner.nextInt();

        // Initialize the global array `a` with the user-provided size
        a = new int[n];

        // Take input from the user for the array elements
        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }

        // Display the original array
        System.out.println("Original array:");
        printArray();

        // Sort the array using mergeSort
        mergeSort(0, a.length - 1);

        // Display the sorted array
        System.out.println("Sorted array:");
        printArray();

        // Close the scanner
        scanner.close();
    }
}



Algorithm:
 
 
 
Algorithm MergeSort(low, high)
    // a[low : high] is a global array to be sorted.
    // Small(P) is true if there is only one element to sort.
    // In this case, the list is already sorted.
 
    if (low < high) then  
        // Step 1: Divide the problem into subproblems
    {
        mid := ⌊(low + high) / 2⌋;  // Find where to split the set
        
        // Step 2: Solve the subproblems
        MergeSort(low, mid);
        MergeSort(mid + 1, high);
 
        // Step 3: Combine the solutions
        Merge(low, mid, high);
    }
}
 
 
 
Algorithm Merge (low, mid, high)
k := low; i := low; j := mid + 1;  
while ((i ≤ mid) and (j ≤ high)) do  
    if (a[i] ≤ a[j]) then  
    {  
        b[k] := a[i]; i := i + 1;  
    }  
    else  
    {  
        b[k] := a[j]; j := j + 1;  
    }  
    k := k + 1;  
}
 
if (i > mid) then  
    for k := j to high do  
    {  
        b[k] := a[k]; i := i + 1;  
    }  
else  
    for k := i to mid do  
    {  
        b[k] := a[k]; i := i + 1;  
    }  
 
for k := low to high do a[k] := b[k];  
 
 
 
OUTPUT:
Enter the size of the array: 5
Enter 5 elements:
10
3
6
2
9
Original array:
10 3 6 2 9 
Sorted array:
2 3 6 9 10 
import java.util.Scanner;

public class NQueens {

    static void printSolution(int[][] board, int n) {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print((board[i][j] == 1 ? "Q " : ". "));
            }
            System.out.println();
        }
        System.out.println();
    }

    static boolean isSafe(int[][] board, int row, int col, int n) {
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 1) return false;
        }
        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1) return false;
        }
        for (int i = row, j = col; i >= 0 && j < n; i--, j++) {
            if (board[i][j] == 1) return false;
        }
        return true;
    }

    static boolean solveNQueens(int[][] board, int row, int n) {
        if (row == n) {
            printSolution(board, n);
            return true;
        }

        boolean result = false;
        for (int col = 0; col < n; col++) {
            if (isSafe(board, row, col, n)) {
                board[row][col] = 1;
                result = solveNQueens(board, row + 1, n) || result;
                board[row][col] = 0;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the value of N: ");
        int n = sc.nextInt();

        int[][] board = new int[n][n];
        System.out.println("Solutions to the " + n + "-Queens problem:");
        if (!solveNQueens(board, 0, n)) {
            System.out.println("No solution exists.");
        }
    }
}
import pandas as pd

# Sample DataFrame
data = {
    'Name': ['Alice', 'Bob', None, 'David'],
    'Age': [24, None, 32, 28],
    'City': ['New York', 'Los Angeles', 'Chicago', None]
}
df = pd.DataFrame(data)

# Checking for missing values
print(df.isnull())  # True where there are missing values
print(df.isnull().sum())  # Total number of missing values per column

# Drop rows with any missing values
df_dropped_rows = df.dropna()
print("Rows with missing values dropped:\n", df_dropped_rows)

# Drop columns with any missing values
df_dropped_cols = df.dropna(axis=1)
print("Columns with missing values dropped:\n", df_dropped_cols)

# Fill with a specific value (e.g., 0)
df_filled_zeros = df.fillna(0)
print("Missing values filled with 0:\n", df_filled_zeros)

# Fill with the mean (useful for numeric data)
df['Age'] = df['Age'].fillna(df['Age'].mean())
print("Age column with missing values filled by mean:\n", df)

# Fill with the median
df['Age'] = df['Age'].fillna(df['Age'].median())
print("Age column with missing values filled by median:\n", df)

# Fill with the mode (useful for categorical data)
df['City'] = df['City'].fillna(df['City'].mode()[0])
print("City column with missing values filled by mode:\n", df)

# Forward fill (fills using the last valid observation)
df_ffill = df.ffill()
print("Forward fill (missing values filled using last valid observation):\n", df_ffill)

# Backward fill (fills using the next valid observation)
df_bfill = df.bfill()
print("Backward fill (missing values filled using next valid observation):\n", df_bfill)
import pandas as pd
import matplotlib.pyplot as plt

# Create the DataFrame
data = {
    'Feature1': [10, 20, 30, 40, 50],
    'Feature2': [100, 200, 300, 400, 500]
}
df = pd.DataFrame(data)

# Calculate the sum of each feature for pie chart visualization
sizes = [df['Feature1'].sum(), df['Feature2'].sum()]

# Labels for the pie chart
labels = ['Feature1', 'Feature2']

# Plotting the Pie Chart
plt.pie(sizes, labels=labels)
plt.title("Proportion of Feature1 and Feature2")
plt.show()
import pandas as pd

# Step 1.1: Convert the dictionary to a DataFrame
data = {
    'Category': ['A', 'B', 'A', 'C', 'B']
}
df = pd.DataFrame(data)

# Step 1.2: Apply One-Hot Encoding
df_encoded = pd.get_dummies(df, columns=['Category'])

# Step 1.3: Print the DataFrame with One-Hot Encoding
print(df_encoded)
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score

# Step 1.1: Convert dictionary to DataFrame
data = {
    'Feature1': [1, 2, np.nan, 4, 5],
    'Feature2': [5, np.nan, np.nan, 8, 9]
}

df = pd.DataFrame(data)


df['Feature1'].fillna(df['Feature1'].mean(), inplace=True)

# Step 1.4: Fill missing values in 'Feature2' with median
df['Feature2'].fillna(df['Feature2'].median(), inplace=True)





df['Target'] = [0, 1, 0, 1, 0]  # Example target values for classification


X = df.drop(columns=['Target'])  # Features (without 'Target')
y = df['Target']  # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Load Decision Tree Classifier
clf = DecisionTreeClassifier(random_state=42)

# Step 4: Train the model
clf.fit(X_train, y_train)

# Step 5: Make predictions
y_pred = clf.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nDecision Tree Classifier Accuracy: {accuracy * 100:.2f}%")

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
 
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score,confusion_matrix
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
 
# Load the Iris dataset
iris = pd.read_csv('/content/iris.csv')
X = iris.drop(columns=["Species"]) # Features
y = iris["Species"]  # Labels
 
 
 
# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
 
# Train the SVC model with a linear kernel
model = SVC(kernel='linear', random_state=42)
model.fit(X_train, y_train)
 
# Make predictions
y_pred = model.predict(X_test)
 
# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.2f}")
 
conf_matrix = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(conf_matrix)
import java.util.Scanner;

public class GFG 
{
    static int optCost(int freq[], int i, int j)
    {
       if (j < i)
         return 0;
       if (j == i)
         return freq[i];
      
       int fsum = sum(freq, i, j);
       int min = Integer.MAX_VALUE;
      
       for (int r = i; r <= j; ++r)
       {
           int cost = optCost(freq, i, r-1) + 
                          optCost(freq, r+1, j);
           if (cost < min)
              min = cost;
       }
       return min + fsum;
    }

    static int optimalSearchTree(int keys[], int freq[], int n)
    {
         return optCost(freq, 0, n-1);
    }

    static int sum(int freq[], int i, int j)
    {
        int s = 0;
        for (int k = i; k <= j; k++)
           s += freq[k];
        return s;
    }

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

        // User input for the number of keys
        System.out.print("Enter the number of keys: ");
        int n = scanner.nextInt();

        // User input for keys
        int keys[] = new int[n];
        System.out.println("Enter the keys:");
        for (int i = 0; i < n; i++) {
            keys[i] = scanner.nextInt();
        }

        // User input for frequencies
        int freq[] = new int[n];
        System.out.println("Enter the frequencies:");
        for (int i = 0; i < n; i++) {
            freq[i] = scanner.nextInt();
        }

        // Calculating and printing the cost of Optimal BST
        System.out.println("Cost of Optimal BST is " +
                           optimalSearchTree(keys, freq, n));
    }
}
import java.util.*;

public class Knapsack {
    public static double greedyKnapSack(ItemValue[] arr, int capacity) {
        // Sort items based on their profit-to-weight ratio in descending order
        Arrays.sort(arr, new Comparator<ItemValue>() {
            public int compare(ItemValue item1, ItemValue item2) {
                double cpr1 = (double) item1.profit / item1.weight;
                double cpr2 = (double) item2.profit / item2.weight;
                if (cpr1 < cpr2)
                    return 1;
                else
                    return -1;
            }
        });

        double total = 0;

        for (ItemValue i : arr) {
            if ((capacity - i.weight) >= 0) {
                // If the item can be fully taken
                capacity -= i.weight;
                total += i.profit;
            } else {
                // Take the fraction of the item
                double fract = (double) capacity / (double) i.weight;
                total += fract * (i.profit);
                capacity = 0;
                break;
            }
        }

        return total;
    }

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

        System.out.println("Enter the number of items: ");
        int n = sc.nextInt();
        ItemValue[] arr = new ItemValue[n];

        System.out.println("Enter weight, profit of each item: ");
        for (int i = 0; i < n; i++) {
            arr[i] = new ItemValue(sc.nextInt(), sc.nextInt());
        }

        System.out.println("Enter capacity: ");
        int m = sc.nextInt();

        double pro = greedyKnapSack(arr, m);
        System.out.println("Maximum profit: " + pro);
    }
}

class ItemValue {
    public int weight;
    public int profit;

    public ItemValue(int weight, int profit) {
        this.weight = weight;
        this.profit = profit;
    }
}



Procedure GREEDY_KNAPSACK (P, W, M, X, n):

 and  contain the profits and weights respectively of the  objects arranged so that .

 is the knapsack size, and  is the solution vector.


real P(1:n), W(1:n), X(1:n), M, cu;  
integer i, n;  

X ← 0  // Initialize solution to zero  
cu ← M  // cu = remaining knapsack capacity  

for i ← 1 to n do  
    if W(i) > cu then exit endif  
    X(i) ← 1  
    cu ← cu - W(i)  
repeat  

if i ≤ n then X(i) ← cu/W(i) endif  

end GREEDY_KNAPSACK
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of keys (n):");
        int n = sc.nextInt();
        double[] p = new double[n+1];
        double[] q = new double[n+1];
        
       System.out.println("Enter probabilities of successful searches for keys (p):");
        for(int i=1;i<=n;i++){
            p[i] = sc.nextDouble();
        }
        
       System.out.println("Enter probabilities of unsuccessful searches (q):");
        for(int i=0;i<=n;i++){
            q[i] = sc.nextDouble();
        }
        obst(p,q,n);
    }
    public static void obst(double[] p,double[] q,int n){
        double[][] w = new double[n+1][n+1];
        double[][] c = new double[n+1][n+1];
        int[][] r = new int[n+1][n+1];
        for(int i=0;i<=n;i++){
            w[i][i] = q[i];
            c[i][i] = 0;
            r[i][i] = 0;
        }
        for(int m = 1;m<=n;m++){
            for(int i=0;i<=n-m;i++){
                int j = i+m;
                w[i][j] = w[i][j-1] + p[j]+q[j];
                double mincost = Double.MAX_VALUE;
                int root = -1;
                for(int k=i+1;k<=j;k++){
                    double cost = c[i][k-1]+c[k][j]+w[i][j];
                    if(cost < mincost){
                        mincost = cost;
                        root = k;
                    }
                }
                c[i][j] = mincost;
                r[i][j] = root;
            }
        }
        System.out.println("Cost = "+c[0][n]);
        System.out.println("Weight = "+w[0][n]);
    }
}
# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Sample Dataset (replace this with your actual dataset)
# Let's assume we have a dataset with features: 'height', 'weight', and 'experience'
data = {
    'height': [150, 160, 170, 180, 190],
    'weight': [50, 60, 70, 80, 90],
    'experience': [2, 3, 4, 5, 6],
    'age': [25, 28, 30, 35, 40]  # This is the target variable
}

# Create a DataFrame
df = pd.DataFrame(data)



# Step 2: Data Preprocessing
# Define features (X) and target (y)
X = df[['height', 'weight', 'experience']]  # Independent variables
y = df['age']  # Dependent variable (age)

# Step 3: Train-Test Split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Train the Regression Model (Linear Regression)
model = LinearRegression()
model.fit(X_train, y_train)

# Step 5: Make Predictions
y_pred = model.predict(X_test)

# Step 6: Model Evaluation
# Calculate Mean Squared Error (MSE)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")

# Calculate R-squared (R²) value
r2 = r2_score(y_test, y_pred)
print(f"R-squared value: {r2}")

# Import necessary libraries
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report

# Step 1: Load the dataset
df = pd.read_csv('Iris.csv')  # Replace with the correct path if needed

# Step 1.1: Data Exploration
print("Dataset Preview:")
print(df.head())

# Data Overview
print("\nDataset Information:")
print(df.info())

# Step 1.2: Verify Missing Values
print("\nMissing Values:")
print(df.isnull().sum())

# Step 1.3: Verify Duplicates
print("\nDuplicate Rows:")
print(df.duplicated().sum())

# Step 1.4: Detect and Remove Outliers using IQR method
# IQR method to detect outliers
Q1 = df.select_dtypes(include=[np.number]).quantile(0.25)
Q3 = df.select_dtypes(include=[np.number]).quantile(0.75)
IQR = Q3 - Q1

# Outliers are those outside the range (Q1 - 1.5*IQR) and (Q3 + 1.5*IQR)
outliers_iqr = ((df.select_dtypes(include=[np.number]) < (Q1 - 1.5 * IQR)) | 
                (df.select_dtypes(include=[np.number]) > (Q3 + 1.5 * IQR))).any(axis=1)

# Removing outliers
df_no_outliers_iqr = df[~outliers_iqr]
print(f"\nShape after removing outliers: {df_no_outliers_iqr.shape}")

# Step 1.5: Split Dataset and Perform Naive Bayes Classification
# Define features (X) and target (y)
X = df_no_outliers_iqr.drop(['Id', 'Species'], axis=1)  # Drop 'Id' and 'Species'
y = df_no_outliers_iqr['Species']

# Split the data into training and testing sets (70% training, 30% testing)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Initialize Naive Bayes classifier (GaussianNB for continuous data)
nb_classifier = GaussianNB()

# Train the model
nb_classifier.fit(X_train, y_train)

# Make predictions on the test set
y_pred = nb_classifier.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
print(f"\nAccuracy of the Naive Bayes model: {accuracy * 100:.2f}%")
print("\nClassification Report:")
print(classification_report(y_test, y_pred))

# Optional: Visualize the distribution of data and outliers
plt.figure(figsize=(10, 6))
sns.boxplot(data=df_no_outliers_iqr.drop(['Id', 'Species'], axis=1))
plt.title('Boxplot to Visualize Outliers After Removal')
plt.show()
import React, { useContext } from "react";
import Link from "next/link";
import { ChevronRightIcon } from "@heroicons/react/24/outline";
import { AuthContext } from "@/context/AuthContext";
import { CurrentObjectContext } from "@/context/CurrentObjectContext";

export const getPreviousPaths = (index: number, pathname: string): string => {
  return index === 0
    ? "/dashboard"
    : pathname
        .split("/")
        .filter((_, idx) => idx <= index)
        .join("/");
};

const hasDatePattern = (str: string): boolean => {
  if (typeof str !== "string" || str.length < 11) return false;
  const pattern = /\s\d{4}\s\d{2}\s\d{2}$/; // " #### ## ##" # = digit
  return pattern.test(str);
};

const removeDatePattern = (str: string): string => {
  if (hasDatePattern(str)) {
    return str.slice(0, -11);
  }
  return str;
};

export default function BreadCrumbs({
  pathname,
  breadcrumbs,
}: {
  pathname: string;
  breadcrumbs: string[];
}) {
  const { isSuperAdmin } = useContext(AuthContext);
  const { object } = useContext(CurrentObjectContext);

  const handleIdNumber = (
    pathname: string,
    id: string | number
  ): string | number => {
    const split = pathname.split("/").filter((str) => str !== "");

    // if date pattern exists at the end of the string, remove it
    if (typeof id === "string") {
      id = removeDatePattern(id);
    }
    if (
      split.length === 3 &&
      (split[1] === "organizations" ||
        split[1] === "my-competitions" ||
        split[1] === "competitions")
    ) {
      return object.hasOwnProperty("name") && object.name;
    }
    if (object && split.length === 3 && split[1] === "users") {
      return object.first_name + " " + object.last_name || id;
    }
    return id;
  };

  const handleIdOnThird = (
    pathname: string,
    id: string | number
  ): string | number => {
    const split = pathname.split("/").filter((str) => str !== "");
    // if date pattern exists at the end of the string, remove it
    if (typeof id === "string") {
      id = removeDatePattern(id);
    }

    if (
      split.length === 4 &&
      (split[1] === "organizations" ||
        split[1] === "my-competitions" ||
        split[1] === "competitions")
    ) {
      return object.hasOwnProperty("name") && object.name;
    }
    if (object && split.length === 3 && split[1] === "users") {
      return object.first_name + " " + object.last_name || id;
    }
    return id;
  };

  return (
    <nav className="flex p-4" aria-label="Breadcrumb">
      <ol role="list" className="flex items-center space-x-4">
        {pathname === "/dashboard/" ? (
          <li key={1} className="flex items-center">
            <p className="text-xs font-medium text-gray-400">Dashboard</p>
          </li>
        ) : breadcrumbs.length > 1 ? (
          breadcrumbs.map((crumb, index) =>
            index < breadcrumbs.length - 1 ? (
              <li key={crumb} className="flex items-center">
                {crumb === "Organizations" ? (
                  <Link
                    className="text-xs font-medium text-gray-400 hover:text-gray-200"
                    href={getPreviousPaths(index + 1, pathname)}
                  >
                    {crumb === "Organizations" ? "Clubs" : crumb}
                  </Link>
                ) : crumb === "Organization" && !isSuperAdmin ? (
                  <li
                    key={crumb}
                    className="flex items-center text-xs font-medium text-gray-400"
                  >
                    {crumb}
                  </li>
                ) : index === breadcrumbs.length - 2 &&
                  breadcrumbs.length > 3 ? (
                  <Link
                    key={crumb}
                    className={`flex items-center text-xs font-medium text-gray-400 hover:text-gray-200 ${
                      pathname.split("/").filter((p) => p !== "")[1] !== "users"
                        ? "capitalize"
                        : ""
                    }`}
                    href={pathname.split("/").splice(0, 4).join("/")}
                  >
                    {handleIdOnThird(pathname, crumb)}
                  </Link>
                ) : (
                  <Link
                    className="text-xs font-medium text-gray-400 hover:text-gray-200"
                    href={getPreviousPaths(index + 1, pathname)}
                  >
                    {crumb}
                  </Link>
                )}
                <ChevronRightIcon
                  className="w-4 ml-4 text-gray-500"
                  aria-hidden="true"
                />
              </li>
            ) : (
              <Link
                key={crumb}
                className={`flex items-center text-xs font-medium text-gray-400 hover:text-gray-200 ${
                  pathname.split("/").filter((p) => p !== "")[1] !== "users"
                    ? "capitalize"
                    : ""
                }`}
                href={pathname}
              >
                {handleIdNumber(
                  pathname,
                  crumb === "Organizations" ? "Clubs" : crumb
                )}
              </Link>
            )
          )
        ) : (
          <li
            key={1}
            className="flex items-center text-xs font-medium text-gray-400"
          >
            Dashboard
          </li>
        )}
      </ol>
    </nav>
  );
}
# Import necessary libraries
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Step 1: Create a dataset (sample data for house rentals)
data = {
    'Size (sq ft)': [850, 900, 1200, 1500, 1800, 2000, 2300, 2500, 2700, 3000],
    'Bedrooms': [2, 2, 3, 3, 4, 4, 5, 5, 5, 6],
    'Age (years)': [5, 10, 3, 20, 15, 10, 8, 12, 30, 20],
    'Location Score': [8, 7, 9, 6, 8, 8, 9, 9, 7, 6],
    'Rental Price (USD)': [1500, 1700, 2500, 3000, 3500, 3700, 4200, 4500, 4700, 5000]
}

df = pd.DataFrame(data)

# Step 2: Split the data into features (X) and target (y)
X = df[['Size (sq ft)', 'Bedrooms', 'Age (years)', 'Location Score']]
y = df['Rental Price (USD)']

# Step 3: Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Step 4: Train the Multiple Linear Regression model
model = LinearRegression()
model.fit(X_train, y_train)

# Step 5: Make predictions on the test set
y_pred = model.predict(X_test)

# Step 6: Evaluate the model
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)

print("Model Evaluation:")
print(f"Mean Squared Error (MSE): {mse:.2f}")
print(f"R² Score: {r2:.2f}")
# Import necessary libraries
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
import matplotlib.pyplot as plt

# Step 1: Create the DataFrame
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace', 'Hannah', 'Ian', 'Jane'],
    'score': [85, 92, 88, 74, 95, 67, 78, 81, 89, 90],
    'sport': ['Basketball', 'Soccer', 'Tennis', 'Cricket', 'Baseball', 'Swimming', 'Soccer', 'Basketball', 'Tennis', 'Cricket'],
    'sex': ['F', 'M', 'M', 'M', 'F', 'M', 'F', 'F', 'M', 'F']
}

df = pd.DataFrame(data)
print("Original DataFrame:\n", df)

# Step 2: Add extra columns (gender and age)
df['gender'] = df['sex'].map({'F': 'Female', 'M': 'Male'})  # Map 'F' to 'Female' and 'M' to 'Male'
df['age'] = [20, 22, 19, 21, 23, 18, 22, 20, 24, 21]  # Adding age column
print("\nDataFrame after adding gender and age columns:\n", df)

# Step 3: Create custom index
df.index = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
print("\nDataFrame with custom index:\n", df)

# Step 4: Apply Label Encoding on 'gender' column
label_encoder = LabelEncoder()
df['gender_encoded'] = label_encoder.fit_transform(df['gender'])
print("\nDataFrame after Label Encoding:\n", df)

# Step 5: Apply One Hot Encoding using OneHotEncoder on 'sport' column
one_hot_encoder = OneHotEncoder(sparse_output=False)  # Use sparse=False to get a dense array
sport_encoded = one_hot_encoder.fit_transform(df[['sport']])  # Fit and transform 'sport' column

# Create a DataFrame for the encoded data
sport_encoded_df = pd.DataFrame(sport_encoded, columns=one_hot_encoder.get_feature_names_out(['sport']), index=df.index)

# Combine with the original DataFrame
df = pd.concat([df, sport_encoded_df], axis=1)
print("\nDataFrame after One Hot Encoding using OneHotEncoder:\n", df)

# Step 6: Bar Plot for Categorical Data
# Count the occurrences of each sport
sport_counts = df['sport'].value_counts()

# Plot the bar chart
plt.figure(figsize=(8, 6))
sport_counts.plot(kind='bar', color='skyblue')
plt.title('Frequency of Sports Participation')
plt.xlabel('Sport')
plt.ylabel('Frequency')


plt.show()
https://bennettfeely.com/clippy/
# Import necessary libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score

# Load the dataset
data = pd.read_csv('/content/Soybean (1).csv')  # Replace 'soybean.csv' with your actual file name

# Split the data into features (X) and target (y)
X = data.drop(columns=['Class'])  # 'Class' is the target column
y = data['Class']

# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Create and train the Decision Tree model
model = DecisionTreeClassifier(random_state=42)
model.fit(X_train, y_train)

# Predict on the test set
y_pred = model.predict(X_test)

# Calculate and print the accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy of the Decision Tree model: {accuracy * 100:.2f}%")
# Import required libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.cluster import KMeans

# Given Data
data = {
    'Feature1': [10, 20, 30, 40, 50],
    'Feature2': [100, 200, 300, 400, 500]
}

# Step 1: Create a DataFrame
df = pd.DataFrame(data)

# Step 1.1: Apply Standard Scaler
scaler_standard = StandardScaler()
df_standard = scaler_standard.fit_transform(df)

# Step 1.2: Apply Min-Max Scaler
scaler_minmax = MinMaxScaler()
df_minmax = scaler_minmax.fit_transform(df)

# Step 2: Apply KMeans Clustering (2 clusters for demonstration)
kmeans = KMeans(n_clusters=2, random_state=42)

# Fitting KMeans on both scaled datasets
kmeans_standard = kmeans.fit_predict(df_standard)
kmeans_minmax = kmeans.fit_predict(df_minmax)

# Step 3: Pie Chart Visualization for KMeans (using standard scaled data as an example)
# Count the occurrences of each cluster
labels_standard = pd.Series(kmeans_standard).value_counts()

# Plot the pie chart
plt.figure(figsize=(6, 6))
plt.pie(labels_standard, labels=[f"Cluster {i}" for i in labels_standard.index], autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart of KMeans Clusters (Standard Scaled Data)')
plt.show()
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
 
# Load the Iris dataset
data = load_iris()
X = data.data  # Features
 
# Initialize the KMeans model with 3 clusters (since there are 3 species in the Iris dataset)
kmeans = KMeans(n_clusters=3, random_state=42)
 
# Fit the model to the data
kmeans.fit(X)
 
# Predict the cluster labels
y_pred = kmeans.predict(X)
 
# Create a DataFrame for visualization
df = pd.DataFrame(X, columns=data.feature_names)
df['Cluster'] = y_pred
 
# Plot the clusters (using only the first two features for simplicity)
plt.figure(figsize=(8, 6))
sns.scatterplot(data=df, x=data.feature_names[0], y=data.feature_names[1], hue='Cluster')#, palette='viridis', s=100)
plt.title('K-Means Clustering on Iris Dataset (2D)')
plt.xlabel(data.feature_names[0])
plt.ylabel(data.feature_names[1])
plt.show()
 
# Print the cluster centers
print("Cluster Centers (Centroids):")
print(kmeans.cluster_centers_)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix,classification_report

# Step 1: Load Iris dataset
file_path = "/content/iris.csv"  # Replace with the actual file path
iris_data = pd.read_csv(file_path)

# Separate features (X) and target (y)
X = iris_data.drop(["Species"], axis=1)  # Drop unnecessary columns
y = iris_data["Species"]

# Step 2: Split the dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Apply StandardScaler
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)

# Step 4: Load KNN model
knn = KNeighborsClassifier(n_neighbors=5)  # Default k=5

# Step 5: Train the model and make predictions
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)

# Step 6: Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
classification_report=classification_report(y_test,y_pred)

# Display results
print("Accuracy Score:", accuracy)
print("Confusion Matrix:\n", conf_matrix)
print("Confusion Matrix:\n", classification_report)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    static boolean flag = false;

    static void printSubsetSum(int i, int n, int[] set, int targetSum, List<Integer> subset) {
        if (targetSum == 0) {
            flag = true;
            System.out.print("[ ");
            for (int j = 0; j < subset.size(); j++) {
                System.out.print(subset.get(j) + " ");
            }
            System.out.print("]");
            return;
        }

        if (i == n) {
            return;
        }

        printSubsetSum(i + 1, n, set, targetSum, subset);   

        if (set[i] <= targetSum) {
            subset.add(set[i]);
            printSubsetSum(i + 1, n, set, targetSum - set[i], subset);
            subset.remove(subset.size() - 1);
        }
    }

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

        System.out.print("Enter the number of elements in the set: ");
        int n = sc.nextInt();

        int[] set = new int[n];
        System.out.println("Enter the elements of the set:");
        for (int i = 0; i < n; i++) {
            set[i] = sc.nextInt();
        }

        System.out.print("Enter the target sum: ");
        int targetSum = sc.nextInt();

        List<Integer> subset = new ArrayList<>();
        System.out.println("Subsets with the given sum:");
        printSubsetSum(0, n, set, targetSum, subset);

        if (!flag) {
            System.out.println("No subset with the given sum exists.");
        }
    }
}
import java.sql.*;

public class ScrollableResultSetExample {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/your_database";
        String username = "root"; 
        String password = "your_password";

        try {
            Connection connection = DriverManager.getConnection(url, username, password);

            String query = "SELECT * FROM your_table";
            Statement statement = connection.createStatement(
                    ResultSet.TYPE_SCROLL_INSENSITIVE, 
                    ResultSet.CONCUR_READ_ONLY);
            
            ResultSet resultSet = statement.executeQuery(query);
            
            if (resultSet.last()) {
                System.out.println(resultSet.getString("column_name"));
            }

            if (resultSet.first()) {
                System.out.println(resultSet.getString("column_name"));
            }

            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
import java.util.*;

public class SumOfSubsets {

    // Function to find all subsets whose sum equals the target sum
    public static void findSubsets(int[] set, int n, int targetSum) {
        List<Integer> currentSubset = new ArrayList<>();
        backtrack(set, n, targetSum, 0, currentSubset);
    }

    // Backtracking function to find the subsets
    private static void backtrack(int[] set, int n, int targetSum, int index, List<Integer> currentSubset) {
        // Base case: if we've considered all elements
        if (index == n) {
            int sum = 0;
            for (int num : currentSubset) {
                sum += num;
            }

            // If the sum of the current subset equals the target, print it
            if (sum == targetSum) {
                System.out.println(currentSubset);
            }
            return;
        }

        // Include the current element
        currentSubset.add(set[index]);
        // Recur with the element included
        backtrack(set, n, targetSum, index + 1, currentSubset);

        // Exclude the current element
        currentSubset.remove(currentSubset.size() - 1);
        // Recur with the element excluded
        backtrack(set, n, targetSum, index + 1, currentSubset);
    }

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

        // Input the number of elements in the set and the target sum
        System.out.print("Enter the number of elements in the set: ");
        int n = scanner.nextInt();

        int[] set = new int[n];
        
        System.out.println("Enter the elements of the set: ");
        for (int i = 0; i < n; i++) {
            set[i] = scanner.nextInt();
        }

        System.out.print("Enter the target sum: ");
        int targetSum = scanner.nextInt();

        // Find and print the subsets whose sum equals the target sum
        System.out.println("Subsets whose sum equals " + targetSum + ":");
        findSubsets(set, n, targetSum);

        scanner.close();
    }
}
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
import org.xml.sax.helpers.DefaultHandler;

public class XMLValidation {
    public static void main(String[] args) {
        try {
            // Prompt user for XML file name
            System.out.println("Enter the XML file name:");
            String filename = new BufferedReader(new InputStreamReader(System.in)).readLine();
            File file = new File(filename);

            // Check if the file exists
            if (file.exists()) {
                validateXML(file);
            } else {
                System.out.println("File not found.");
            }
        } catch (IOException e) {
            System.out.println("Error reading input: " + e.getMessage());
        }
    }

    private static void validateXML(File file) {
        try {
            // Initialize the SAX parser
            SAXParserFactory.newInstance().newSAXParser().parse(file, new DefaultHandler());
            System.out.println(file.getName() + " is valid XML.");
        } catch (Exception e) {
            System.out.println(file.getName() + " is not valid XML.");
        }
    }
}


hello.xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book>
        <title>Java Programming</title>
        <author>John Doe</author>
    </book>
    <book>
        <title>XML Development</title>
        <author>Jane Smith</author>
    </book>
</library>
import java.util.Scanner;
 
class PrimsAlgorithm {
    private static int V;
 
    int minKey(int key[], boolean mstSet[]) {
        int min = Integer.MAX_VALUE, minIndex = -1;
        for (int v = 0; v < V; v++) {
            if (!mstSet[v] && key[v] < min) {
                min = key[v];
                minIndex = v;
            }
        }
        return minIndex;
    }
 
    void printMST(int parent[], int graph[][]) {
        int totalCost = 0;
        System.out.println("Edge \tWeight");
        for (int i = 1; i < V; i++) {
            System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]);
            totalCost += graph[i][parent[i]];
        }
        System.out.println("Total cost of the MST: " + totalCost);
    }
 
    void primMST(int graph[][]) {
        int parent[] = new int[V];
        int key[] = new int[V];
        boolean mstSet[] = new boolean[V];
 
        for (int i = 0; i < V; i++) {
            key[i] = Integer.MAX_VALUE;
            mstSet[i] = false;
        }
 
        key[0] = 0;
        parent[0] = -1;
 
        for (int count = 0; count < V - 1; count++) {
            int u = minKey(key, mstSet);
            mstSet[u] = true;
 
            for (int v = 0; v < V; v++) {
                if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
                    parent[v] = u;
                    key[v] = graph[u][v];
                }
            }
        }
 
        printMST(parent, graph);
    }
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter the number of vertices: ");
        V = scanner.nextInt();
 
        int[][] graph = new int[V][V];
 
        System.out.println("Enter the adjacency matrix (enter 0 if there is no edge between two vertices):");
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                graph[i][j] = scanner.nextInt();
            }
        }
 
        PrimsAlgorithm t = new PrimsAlgorithm();
        t.primMST(graph);
 
        scanner.close();
    }
}
/*2 0 6 0
2 0 3 8 5
0 3 0 0 7
6 8 0 0 9
0 5 7 9 0
Edge 	Weight
0 - 1	2
1 - 2	3
0 - 3	6
1 - 4	5
Total cost of the MST: 16
public class QuickSort {

    // Function to perform quick sort
    public static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            // Find the pivot element such that elements smaller than pivot are on the left
            // and elements greater than pivot are on the right
            int pivotIndex = partition(array, low, high);
            
            // Recursively sort the elements on the left of the pivot
            quickSort(array, low, pivotIndex - 1);
            
            // Recursively sort the elements on the right of the pivot
            quickSort(array, pivotIndex + 1, high);
        }
    }

    // Partition the array and return the pivot index
    public static int partition(int[] array, int low, int high) {
        int pivot = array[high]; // Choosing the pivot element
        int i = (low - 1);       // Index of the smaller element

        for (int j = low; j < high; j++) {
            // If the current element is smaller than or equal to the pivot
            if (array[j] <= pivot) {
                i++;
                // Swap array[i] and array[j]
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }

        // Swap array[i + 1] and array[high] (or pivot)
        int temp = array[i + 1];
        array[i + 1] = array[high];
        array[high] = temp;

        return i + 1;
    }

    public static void main(String[] args) {
        int[] array = { 10, 7, 8, 9, 1, 5 };
        int n = array.length;

        quickSort(array, 0, n - 1);

        System.out.println("Sorted array:");
        for (int value : array) {
            System.out.print(value + " ");
        }
    }
}
import java.util.Scanner;
 
public class SumOfSubsets {
 
    static void sumOfSub(int[] weights, int[] x, int s, int k, int r, int m) {
    // Include the current element
    x[k] = 1;
    if (s + weights[k] == m) {
        // If the sum matches the target, print the solution vector
        printSolutionVector(x, k);
    } 
    // Check if including the current element and the next one keeps the sum within bounds
    else if (k + 1 < weights.length && s + weights[k] + weights[k + 1] <= m) {
        sumOfSub(weights, x, s + weights[k], k + 1, r - weights[k], m);
    }

    // Exclude the current element and check if further exploration is valid
    if ((s + r - weights[k] >= m) && (k + 1 < weights.length && s + weights[k + 1] <= m)) {
        x[k] = 0;
        sumOfSub(weights, x, s, k + 1, r - weights[k], m);
    }
}

 
    static void printSolutionVector(int[] x, int k) {
        System.out.print("Solution Vector: ");
        for (int i = 0; i <=k; i++) {
            System.out.print(x[i] + " ");
        }
        System.out.println();
    }
 
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
 
        System.out.print("Enter the number of elements in the set: ");
        int n = scanner.nextInt();
 
        int[] weights = new int[n];
 
        System.out.println("Enter the elements of the set (in non-decreasing order): ");
        for (int i = 0; i < n; i++) {
            weights[i] = scanner.nextInt();
        }
 
        System.out.print("Enter the target sum (m): ");
        int m = scanner.nextInt();
 
        int[] x = new int[n];
        int r = 0;
        for (int weight : weights) {
            r += weight;
        }
 
        System.out.println("Solution Vectors with sum " + m + ":");
        sumOfSub(weights, x, 0, 0, r, m);
 
        scanner.close();
    }
}
import java.util.Scanner;

public class OptimalBSTUserInput {

    // Function to construct and return the cost of the optimal BST
    public static int optimalBST(int[] keys, int[] freq, int n) {
        int[][] cost = new int[n][n];

        // Base case: cost when the tree contains only one key
        for (int i = 0; i < n; i++) {
            cost[i][i] = freq[i];
        }

        // Compute the cost for chains of length 2 to n
        for (int length = 2; length <= n; length++) {
            for (int i = 0; i <= n - length; i++) {
                int j = i + length - 1;
                cost[i][j] = Integer.MAX_VALUE;

                // Try making each key in keys[i...j] the root
                for (int r = i; r <= j; r++) {
                    int leftCost = (r > i) ? cost[i][r - 1] : 0;
                    int rightCost = (r < j) ? cost[r + 1][j] : 0;
                    int rootCost = leftCost + rightCost + sum(freq, i, j);

                    if (rootCost < cost[i][j]) {
                        cost[i][j] = rootCost;
                    }
                }
            }
        }
        return cost[0][n - 1];
    }

    // Utility function to calculate the sum of frequencies from i to j
    private static int sum(int[] freq, int i, int j) {
        int total = 0;
        for (int k = i; k <= j; k++) {
            total += freq[k];
        }
        return total;
    }

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

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

        // Input keys
        int[] keys = new int[n];
        System.out.println("Enter the keys in sorted order:");
        for (int i = 0; i < n; i++) {
            keys[i] = scanner.nextInt();
        }

        // Input frequencies
        int[] freq = new int[n];
        System.out.println("Enter the frequencies of the keys:");
        for (int i = 0; i < n; i++) {
            freq[i] = scanner.nextInt();
        }

        // Calculate and print the cost of the optimal BST
        int cost = optimalBST(keys, freq, n);
        System.out.println("Cost of Optimal BST: " + cost);

        scanner.close();
    }
}
import java.util.Scanner;

public class SumOfSubsets {

    static void sumOfSub(int[] weights, int[] x, int s, int k, int r, int m) {
        x[k] = 1;
        if (s + weights[k] == m) {
            printSolutionVector(x, k);
        } else if (s + weights[k] + (k + 1 < weights.length ? weights[k + 1] : 0) <= m) {
            sumOfSub(weights, x, s + weights[k], k + 1, r - weights[k], m);
        }

        if ((s + r - weights[k] >= m) && (s + (k + 1 < weights.length ? weights[k + 1] : 0) <= m)) {
            x[k] = 0;
            sumOfSub(weights, x, s, k + 1, r - weights[k], m);
        }
    }

    static void printSolutionVector(int[] x, int k) {
        System.out.print("Solution Vector: ");
        for (int i = 0; i <= k; i++) {
            System.out.print(x[i] + " ");
        }
        System.out.println();
    }

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

        System.out.print("Enter the number of elements in the set: ");
        int n = scanner.nextInt();

        int[] weights = new int[n];

        System.out.println("Enter the elements of the set (in non-decreasing order): ");
        for (int i = 0; i < n; i++) {
            weights[i] = scanner.nextInt();
        }

        System.out.print("Enter the target sum (m): ");
        int m = scanner.nextInt();

        int[] x = new int[n];
        int r = 0;
        for (int weight : weights) {
            r += weight;
        }

        System.out.println("Solution Vectors with sum " + m + ":");
        sumOfSub(weights, x, 0, 0, r, m);

        scanner.close();
    }
}







SumOfSub(s, k, r)
{
    // Generate left child
    x[k] = 1
    if (s + w[k] == m) then
        write(x[1 : k]) // Subset found
    else if (s + w[k] + w[k + 1] <= m) then
        SumOfSub(s + w[k], k + 1, r - w[k])
 
    // Generate right child and evaluate conditions
    if ((s + r - w[k] >= m) and (s + w[k + 1] <= m)) then
    {
        x[k] = 0
        SumOfSub(s, k + 1, r - w[k])
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{   
    public float speed;
    public Vector3 moveOffset;
    private Vector3 targetPos;
    private Vector3 startPos;

    // Start is called before the first frame update
    void Start()
    {
        startPos = transform.position;
        targetPos = startPos;
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector3.MoveTowards(transform.position, targetPos, speed * Time.deltaTime);

        if(transform.position == targetPos)
        {
            if(targetPos == startPos)
            {
                targetPos = startPos + moveOffset;
            }
            else
            {
                targetPos = startPos;
            }
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{   
    public Transform target;
    public Vector3 offset;
    // Update is called once per frame
    void Update()
    {
        transform.position = target.position + offset;
    }
}
[ {
    "$match" : {
      "startDate" : {
        "$gte" : {
          "$date" : "2024-09-10T07:14:37.02Z"
        },
        "$lte" : {
          "$date" : "2024-10-10T07:14:37.02Z"
        }
      }
    }
  }, {
    "$lookup" : {
      "from" : "participant",
      "localField" : "userId",
      "foreignField" : "_id",
      "as" : "participantData"
    }
  }, {
    "$unwind" : "$participantData"
  }, {
    "$match" : {
      "participantData.userStatus" : {
        "$ne" : "TEST"
      }
    }
  }, {
    "$match" : {
      "$and" : [ {
        "participantData.email" : {
          "$not" : {
            "$regularExpression" : {
              "pattern" : "deleted",
              "options" : ""
            }
          }
        }
      }, {
        "participantData.email" : {
          "$not" : {
            "$regularExpression" : {
              "pattern" : "@smit\\.fit$",
              "options" : ""
            }
          }
        }
      } ]
    }
  }, {
    "$lookup" : {
      "from" : "participantBaselineAndFollowupData",
      "localField" : "userId",
      "foreignField" : "participantId",
      "as" : "baselineData"
    }
  }, {
    "$unwind" : "$baselineData"
  }, {
    "$project" : {
      "subscriptionId" : "$_id",
      "programEndDate" : "$endDate",
      "baselineId" : "$baselineData._id",
      "userId" : 1,
      "startDate" : 1,
      "programStartDate" : "$baselineData.programStartDate",
      "planCode1" : "$subscriptionPlan.programCode",
      "journeyStatus" : "$journeyTrackerObject.status",
      "planCode2" : "$baselineData.programCode",
      "followUps" : "$baselineData.followUps"
    }
  }, {
    "$match" : {
      "$and" : [ {
        "$expr" : {
          "$and" : [ {
            "$eq" : [ "$planCode1", "$planCode2" ]
          }, {
            "$eq" : [ "$startDate", "$programStartDate" ]
          } ]
        }
      } ]
    }
  }, {
    "$group" : {
      "_id" : {
        "userId" : "$userId",
        "startDate" : "$startDate",
        "planCode1" : "$planCode1"
      },
      "programEndDate" : {
        "$last" : "$programEndDate"
      },
      "userId" : {
        "$last" : "$userId"
      },
      "baselineId" : {
        "$last" : "$baselineId"
      },
      "programStartDate" : {
        "$last" : "$programStartDate"
      },
      "subscriptionId" : {
        "$last" : "$subscriptionId"
      },
      "journeyStatus" : {
        "$last" : "$journeyStatus"
      },
      "followUps" : {
        "$last" : "$followUps"
      }
    }
  } ]
import re

def extract_nf_data(text,pattern):
  match = re.search(pattern, text)
  if match:
    return match.groups()
  else:
    return 'not found'

text = _json.message_body
pattern_keys = r"ccm=(\d+)&nf=(\d+)&cod=([\w\d]+)"
pattern_provider=r"Razão Social: (.*)\n"

ccm,nf,cod=extract_nf_data(text,pattern_keys)
provider=extract_nf_data(text,pattern_provider)[0]

response = {'ccm':ccm,'nf':nf,'cod':cod,'provider':provider}

return response
function delayPromise(ms) {
  return new Promise(
    (resolve) => setTimeout(resolve, ms)
  );
}
star

Mon Nov 18 2024 14:14:46 GMT+0000 (Coordinated Universal Time)

@CarlosR

star

Mon Nov 18 2024 14:01:12 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:59:25 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:56:17 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:55:27 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:53:23 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 13:44:36 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:40:02 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:37:20 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:22:53 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:09:10 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 13:00:55 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Mon Nov 18 2024 13:00:20 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:51:23 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:38:24 GMT+0000 (Coordinated Universal Time)

@Shira

star

Mon Nov 18 2024 12:27:30 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:26:57 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 12:15:59 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 12:13:41 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 12:02:44 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:55:56 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:51:25 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:47:55 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:46:55 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 11:42:57 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 11:37:37 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:32:31 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:29:52 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 11:18:31 GMT+0000 (Coordinated Universal Time)

@nick

star

Mon Nov 18 2024 10:35:24 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 10:27:32 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 10:25:14 GMT+0000 (Coordinated Universal Time)

@Huzaifa

star

Mon Nov 18 2024 10:20:34 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 10:09:45 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 10:07:41 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 09:57:34 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 09:39:20 GMT+0000 (Coordinated Universal Time)

@badram123

star

Mon Nov 18 2024 09:13:16 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Nov 18 2024 07:30:21 GMT+0000 (Coordinated Universal Time)

@signup1

star

Mon Nov 18 2024 06:57:20 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 06:48:23 GMT+0000 (Coordinated Universal Time)

@signup1

star

Mon Nov 18 2024 06:44:55 GMT+0000 (Coordinated Universal Time)

@wtlab

star

Mon Nov 18 2024 06:44:40 GMT+0000 (Coordinated Universal Time)

@signup1

star

Mon Nov 18 2024 06:38:31 GMT+0000 (Coordinated Universal Time)

@login123

star

Mon Nov 18 2024 04:30:21 GMT+0000 (Coordinated Universal Time)

@iliavial #c#

star

Mon Nov 18 2024 04:11:06 GMT+0000 (Coordinated Universal Time)

@iliavial #c#

star

Mon Nov 18 2024 03:21:51 GMT+0000 (Coordinated Universal Time)

@CodeWithSachin #aggregation

star

Mon Nov 18 2024 00:18:47 GMT+0000 (Coordinated Universal Time)

@jmbenedetto #python #regex

star

Sun Nov 17 2024 22:04:09 GMT+0000 (Coordinated Universal Time)

@kanatov

Save snippets that work with our extensions

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