Snippets Collections
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
video {
  width: 100%;
  height: auto;
}
</style>
</head>
<body>
​
<video width="400" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>
​
<p>Resize the browser window to see how the size of the video player will scale.</p>
​
</body>
</html>
​
​
​
node* sortList (node* head) {
  int zeroCount = 0;
  int oneCount = 0;
  int twoCount = 0;
  node* temp = head;
  while (temp != NULL) {
    if (temp -> data == 0) {
      zeroCount++;
    }
    else if (temp -> data == 0) {
      oneCount++;
    }
    else if (temp -> data == 0) {
      twoCount++;
    }
    temp = temp -> next;
  }
  temp = head;
  while (temp != NULL) {
    if (zeroCount != 0) {
      temp -> data = 0;
      zeroCount--;
    }
    else if (oneCount != 0) {
      temp -> data = 1;
      oneCount--;
    }
    else if (twoCount != 0) {
      temp -> data = 2;
      twoCount--;
    }
    temp = temp -> next;
  }
  return temp;
}
void removeLoop(node *head) {
  if (head == NULL) {
    return;
  }
  node *startOfLoop = getStartingNode(head);
  node *temp = startOfLoop;
  while (temp->next != startOfLoop) {
    temp = temp->next;
  }
  temp->next = NULL;
  cout << "loop is removed " << endl;
}
node *floyedDetectionLoop(node *head) {
  if (head == NULL) {
    return NULL;
  }
  node *fast = head;
  node *slow = head;
  while (fast != NULL && slow != NULL) {
    fast = fast->next;
    if (fast->next != NULL) {
      fast = fast->next;
    }
    slow = slow->next;
    if (fast == slow) {
      return slow;
    }
  }
  return NULL;
}

node *getStartingNode(node *head) {
  if (head == NULL) {
    return NULL;
  }
  node *intersection = floyedDetectionLoop(head);
  node *slow = head;
  while (slow != intersection) {
    slow = slow->next;
    intersection = intersection->next;
  }
  return slow;
}
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Tools')
      .addItem('Remove Blank Rows', 'removeBlankRows')
      .addToUi();
}

function removeBlankRows() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = sheet.getDataRange();
  var values = range.getValues();
  var rowsToDelete = [];

  // Loop through all rows and check for blank rows
  for (var i = values.length - 1; i >= 0; i--) {
    var isBlank = values[i].every(function(cell) { return cell === ''; });
    if (isBlank) {
      rowsToDelete.push(i + 1);
    }
  }

  // Delete rows in reverse order to avoid shifting indices
  for (var j = 0; j < rowsToDelete.length; j++) {
    sheet.deleteRow(rowsToDelete[j]);
  }
}
/**
 * Create the test data, ideally run 1 by 1 to prevent govenor limits
 * Run accounts and contacts first. Cases and opportunities require both
 */
upsertAccounts(0,10);
upsertContacts(0,10,0,10);
upsertCases(0,10,0,10);
upsertOpportunities(0,10,0,10);

/**
 * @description Method to create Basic Test Contacts
 */
public void upsertAccounts(Integer accountOffset, Integer numberOfAccounts){
    
    // List to store the new cases
    Account[] accounts = new Account[]{};

    // Loop for to create all top level accounts
    for (Integer i = accountOffset; i < numberOfAccounts; i++) {
    
        // A postfix to keep track of what item we're dealing with
        String postfix = String.valueOf(i+1).leftPad(4,'0');
        
        // Create a new account
        accounts.add(new Account(
            Name           = 'LWT - Test - Account - ' + postfix,
            UUID__c        = UUID.randomUUID().toString(),
            External_Id__c = 'ACC - ' + postfix
        ));
    }
    upsert accounts External_Id__c;
}


/**
 * @description Method to create Basic Test Contacts
 */
public void upsertContacts(Integer accountOffset, Integer numberOfAccounts, Integer contactOffset,Integer numberOfContacts){
    
    // Get the account and contact data
    Account[] accounts = [SELECT Id FROM Account WHERE Name LIKE 'LWT - Test - %' ORDER BY Name ASC LIMIT :numberOfAccounts];
    
    // Basic error handling
    if(numberOfAccounts != accounts.size()){throw new StringException('Number of accounts does not match number returned by the query');}
    
    // List to store the new contacts
    Contact[] contacts = new Contact[]{};

    // Iterate the top level accounts
    for(Integer i=accountOffset; i<numberOfAccounts; i++){
        
        // Create a number of contacts for each account
        for(Integer j=contactOffset; j < numberOfContacts; j++){
        
            // Postfix to keep track of where we are
            String postfix = String.valueOf(i+1).leftPad(4,'0') + ' - ' + String.valueOf(j+1).leftPad(4,'0');
            
            // Add a new contact to the list
            contacts.add(new Contact(
                AccountId      = accounts[i].Id,
                FirstName      = 'LWT - Test - ' + postfix,
                LastName       = 'Contact - ' + postfix,
                UUID__c        = UUID.randomUUID().toString(),
                External_Id__c = 'CON - ' + postfix
            ));
        }
    }
    upsert contacts External_Id__c;
}


/**
 * @description Method to create Basic Test Cases
 */
public void upsertCases(Integer offset, Integer numberOfAccounts, Integer contactOffset, Integer numberOfContacts){

    // Get the account and contact data
    Account[] accounts = [SELECT Id FROM Account WHERE Name LIKE 'LWT - Test - %' ORDER BY Name ASC LIMIT :numberOfAccounts];
    Contact[] contacts = [SELECT Id FROM Contact WHERE Name LIKE 'LWT - Test - %' ORDER BY Name ASC LIMIT :numberOfContacts];

    // Basic error handling
    if(numberOfAccounts != accounts.size()){throw new StringException('Number of accounts does not match number returned by the query');}
    if(numberOfContacts != contacts.size()){throw new StringException('Number of contacts does not match number returned by the query');}

    // List to store the new cases
    Case[] cases = new Case[]{};

    // Iterate the top level accounts
    for(Integer i=offset; i<numberOfAccounts; i++){
        
        // Create a case for each contact in the account
        for(Integer j=offset; j<numberOfContacts; j++){
        
            // Postfix to keep track of where we are
            String postfix = String.valueOf(i+1).leftPad(4,'0') + ' - ' + String.valueOf(j+1).leftPad(4,'0');
            
            // Add a new case
            cases.add(new Case(
                AccountId      = accounts[i].Id,
                ContactId      = contacts[j].Id,
                Subject        = 'LWT - Test - Case - ' + postfix,
                UUID__c        = UUID.randomUUID().toString(),
                External_Id__c = 'CSE - ' + postfix
            ));
        }
    }
    upsert cases External_Id__c;
}


/**
 * @description Method to create Basic Test Opportunities
 */
public void upsertOpportunities(Integer offset, Integer numberOfAccounts, Integer contactOffset, Integer numberOfContacts){
    
    // Get the account and contact data
    Account[] accounts = [SELECT Id FROM Account WHERE Name LIKE 'LWT - Test - %' ORDER BY Name ASC LIMIT :numberOfAccounts];
    Contact[] contacts = [SELECT Id FROM Contact WHERE Name LIKE 'LWT - Test - %' ORDER BY Name ASC LIMIT :numberOfContacts];

    // Basic error handling
    if(numberOfAccounts != accounts.size()){throw new StringException('Number of accounts does not match number returned by the query');}
    if(numberOfContacts != contacts.size()){throw new StringException('Number of contacts does not match number returned by the query');}
    
    // List to store the new cases
    Opportunity[] opportunities = new Opportunity[]{};

    // Iterate the top level accounts
    for(Integer i=offset; i<numberOfAccounts; i++){
        
        // Create an opportunity for each contact in the account
        for(Integer j=offset; j<numberOfContacts; j++){
        
            // Postfix to keep track of where we are
            String postfix = String.valueOf(i+1).leftPad(4,'0') + ' - ' + String.valueOf(j+1).leftPad(4,'0');
            
            // Add a new opportunity to the list
            opportunities.add(new Opportunity(
                AccountId      = accounts[i].Id,
                ContactId      = contacts[j].Id,
                Name           = 'LWT - Test - Opportunity - ' + postfix,
                StageName      = (Math.mod(j,2) == 0) ? 'New' : 'Closed/Won',
                CloseDate      = Date.today().addDays(j),
                UUID__c        = UUID.randomUUID().toString(),
                External_Id__c = 'OPP - ' + postfix
            ));
        }
    }
    upsert opportunities External_Id__c;
}
#include<stdio.h>
void interchange(int a[],int i,int j){
	int p=a[i];
	a[i]=a[j];
	a[j]=p;
}

int partition(int a[],int m,int p){
	int v=a[m],i=m,j=p;
	
	do{
		do{
			i=i+1;
		}while(a[i] < v);
		do{
			j=j-1;
		}while(a[j] > v);

		if(i<j){
			interchange(a,i,j);
		}
	}while(i < j);
	a[m]=a[j];
	a[j]=v;
	return j;
}



void QuickSort(int a[],int p,int q){
	if(p<q){
		int j=partition(a,p,q+1);
		QuickSort(a,p,j-1);
		QuickSort(a,j+1,q);
	}
}

int main(){
	int n;
	printf("Enter the size of array : ");
	scanf(" %d",&n);

	int a[n];
	for(int i=0;i<n;i++){
		printf("Enter the element %d : ",(i+1));
		scanf(" %d",&a[i]);		
	}

	QuickSort(a,0,n-1);
	printf("Sorted array is ");
	for(int i=0;i<n;i++){
		printf(" %d",a[i]);
	}

return 0;}
export const handleCacheListHolterBeats = async (studyId, profileId, timeRanges, ecgDataMap = []) => {
  try {
    if (!timeRanges || !timeRanges.length) return;

    const listHolterBeatsFilter = {
      studyId,
      profileId,
      timeRanges,
      ecgDataMap,
    };

    let listHolterBeats = [];

    for (const timeRange of timeRanges) {
      const { start, stop } = timeRange;
      if (!start || !stop) continue;

      const momentObject = {
        startMoment: start,
        stopMoment: stop,
      };

      // Await the result of checkAndProcessBeatData if it returns a promise
      const data = await checkAndProcessBeatData({
        ecgDataMap,
        momentObject,
      });

      listHolterBeats = listHolterBeats.concat(data);
    }

    // if (!listHolterBeats.length) {
    //   // Await the result of fetchListHolterBeats if it returns a promise
    //   listHolterBeats = await fetchListHolterBeats(listHolterBeatsFilter, KEY_CANCEL.API_HOLTER_AI);
    // }

    console.log('listHolterBeats: ', timeRanges, listHolterBeats);

    const client = await createClient();

    for (const item of listHolterBeats) {
      await client.writeQuery({
        query: HOLTER_BEAT_QUERY,
        data: {
          holterBeats: {
            isSuccess: true,
            message: null,
            beats: item.beats,
            hesBeatStatus: item.hesBeatStatus,
            beatChannels: item.beatChannels,
          },
        },
        variables: {
          filter: {
            studyId,
            profileId,
            start: item.start,
            stop: item.stop,
          },
        },
      });
    }

    console.log('Final Holter Beats Data:', listHolterBeats);
  } catch (error) {
    logError('Failed to cache list holter beats: ', error);
  }
};
bool floyedDetectionLoop (node* head) {
  if (head == NULL) {
    return false;
  }
  node* fast = head;
  node* slow = head;
  while (fast != NULL && slow != NULL) {
    fast = fast -> next;
    if (fast -> next == NULL) {
      fast = fast -> next;
    }
    slow = slow -> next;
    if (fast == slow) {
      return true;
    }
    
  }
  return false;
}
🖌️ 3D Artist & Developer of Zombie Rush! 🧟‍♂️
💬 Messages are open to everyone. Feel free to ask questions, make suggestions or let me know about bugs in Zombie Rush!

🛒 Shop my UGC! 👉 www.roblox.com/catalog/?Category=11&CreatorName=FracturedSkies
🖌️ 3D Artist & Developer of Zombie Rush! 🧟‍♂️
💬 Messages are open to everyone. Feel free to ask questions, make suggestions or let me know about bugs in Zombie Rush!

🛒 Shop my UGC! 👉 www.roblox.com/catalog/?Category=11&CreatorName=FracturedSkies
bool detectLoop (node* head) {
  if (head == NULL) {
    return false;
  }
  map <node*, bool> visited;
  node* temp = head;
  while (temp != NULL) {
    if (visited[temp] == true) {
      return true;
    }
    visited[temp] = true;
    temp = temp -> next;
  }
  return false;
}
// check if a linked list is circular or not
bool isCircular (node* head) {
  if (head == NULL) {
    return true;
  }
  node* temp = head -> next;
  while (temp != NULL && temp != head) {
    temp = temp -> next;
  }
  if (temp == head) {
    return true;
  }
  return false;
}
node* kReverse (node* head, int k) {
  // base case
  if (head == NULL) {
    return NULL;
  }

  // step 1: reverse first k nodes
  node* forward = NULL;
  node* curr = head;
  node* prev = NULL;
  int cnt = 0;
  while (curr != NULL && cnt < k) {
    forward = curr -> next;
    curr -> next = prev;
    prev = curr;
    curr = forward;
    cnt++;
    
  }
  // step 2: recursion
  if (forward != NULL) {
    head -> next = kReverse(forward, k);
    
  }
  // step 3: return head of the modified list
  return prev;
}
function generateButtons(buttons) {
    // get the dataset value
    let uniqueCategories = [...new Set()];

    buttons.forEach((button) => {
      const category = button.dataset.category;
      uniqueCategories.push(category);
    });

    uniqueCategories = uniqueCategories.filter(function (item, pos) {
      return uniqueCategories.indexOf(item) == pos;
    });

    uniqueCategories.unshift("All");

    console.log(uniqueCategories);

    // return ` <button type="button" class="filter-btn" data-id="${category}">${category}</button>`;
  }
Diversie dashboards, analyses en rapportages werkbladen obv. het dagelijks ververste Proactis datamodel. 
int getLength (node* head) {
  int length = 0;
  node* temp = head;
  while (temp != NULL) {
    length++;
    temp = temp -> next;
  }
  return length;
}

node* middleNode (node* head) {
  int length = getLength(head);
  int mid = (length/2) + 1;
  int cnt = 1;
  node* temp = head;
  while (cnt < mid) {
    temp = temp -> next;
    cnt++;
  }
  return temp;
}
node* reverseLinkedList (node* & head) {
  //empty list or single node
  if (head == NULL || head -> next == NULL) {
    return head;
  }
  node* prev = NULL;
  node* curr = head;
  node* forword = NULL;
  while (curr != NULL) {
    forword = curr -> next;
    curr -> next = prev;
    prev = curr;
    curr = forword;
  }
  return prev;
}
// it will return the head of the reversed linked list
node* reverse1 (node* head) {
  // base case
  if (head == NULL || head -> next == NULL) {
    return head;
  }
  node* chotaHead = reverse1(head -> next) {
    head -> next -> next = head;
    head -> next = NULL;

    return chotaHead;
  }
}
node* reverseLinkedList (node* head) {
  // empty  list 
	if (head == NULL || head -> next == NULL) {
	return head;
	}
  node* prev = NULL;
  node* curr = head;
  node* forword = NULL;
  
  while (curr != NULL) {
	forword = curr -> next;
    curr -> next = prev;
    prev = curr;
    curr = forword;
  }
  return prev;
}
.more-less .e-n-accordion-item span.mniej {
    display: none;
}

.more-less.elementor-widget-n-accordion .e-n-accordion-item[open] .e-n-accordion-item-title span.more {
    display: none;
}
.more-less.elementor-widget-n-accordion .e-n-accordion-item[open] .e-n-accordion-item-title span.less {
    display: inline;
}
function sum(...numbers) {
  // The rest operator is three dots followed by the variable name; by convention, it is typically called 'rest'
  // The rest operator must be the last parameter in the function definition
  return numbers.reduce((acc, val) => acc + val, 0);
}   // The reduce method is used to sum all the numbers in the array
dataGridView1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Rows.Add("test" + Environment.NewLine + "test");
Optimize your business operations with distinctively designed smart contract solutions specially crafted for every industry. Maticz is a leading smart contract development agency that helps businesses automate transactions when certain criteria are fulfilled. 
As the smart contract uses blockchain technology, data is secured from hacking attempts. We are experts at designing customized solutions for the business, for the specific business requirements. Collaborate with our trusted solutions, to build a transparent and secure system.
<img src="your-image.jpg" alt="description" class="responsive-image">
  //1st way
.responsive-image {
  max-width: 100%;
  height: auto;
}
//2nd way
.responsive-image {
  width: 100%;
  height: auto;
}

<div class="responsive-background"></div>
//3rd way
  .responsive-background {
  width: 100%;
  height: 300px; /* Or any desired height */
  background: url('your-image.jpg') no-repeat center center;
  background-size: cover;
}

//4th way
<picture>
  <source srcset="small.jpg" media="(max-width: 600px)">
  <source srcset="medium.jpg" media="(max-width: 1200px)">
  <img src="large.jpg" alt="description" class="responsive-image">
</picture>
.responsive-image {
  width: 100%;
  height: auto;
}
/**
 * Method to test Fernando's F' map trick
 */

// Query a 1000 records
Account[] records = [SELECT Id,Name FROM Account WHERE Name LIKE 'Test Account - %' LIMIT 1000];

// Use Fernando's MapCreator Method to 
Integer fst = Limits.getCpuTime();
Map<String, SObject> fMap = (Map<String, SObject>) MapCreator.createMapByIndex(records, 'Name' );
Integer fet = Limits.getCpuTime();
System.debug('"Fernanados" method: ' + (fet-fst) + 'ms - Number of records:' + fMap.size());


// Use a traditional for loop
Integer tst = Limits.getCpuTime();
Map<String, SObject> tMap = new Map<String, SObject>();
for(Integer i=0,max=records.size();i<max;i++){
    tMap.put(records[i].name,records[i]);
}
Integer tet = Limits.getCpuTime();
System.debug('"Traditional" method: ' + (tet-tst) + 'ms - Number of records:' + tMap.size());



/**
 * https://learnsf.wordpress.com/2014/12/29/trick-how-to-obtain-a-map-indexed-by-any-field-not-just-id-faster-and-without-loops/
 */
public class MapCreator {
    
    public static Map<String, SObject> createMapByIndex(List<SObject> aList, String indexField ) {
    
        // get the list in JSON format
        String jsonList = JSON.serialize( aList );
        
        // remove enclosing []
        jsonList = jsonList.substring( 1, jsonList.length() - 1 );
        
        // copy the indexField value in front of each
        // {} group using RegEx substitution
        // example result: value:{…"indexField":"value"…}
        jsonList = '{' + jsonList.replaceAll('(\\{.*?"' + indexField + '":"(.*?)"(,".*?")*\\},?)', '"$2":$1' ) + '}';
        
        // create map from the modified JSON
        Map<String, SObject> changedMap = (Map<String, SObject>) JSON.deserialize( jsonList, Map<String, SObject>.class );
        
        return changedMap;
    }
}
public class Palindrome {
    public static void main(String[] args) {
     String str="abcdcba";
        System.out.println(isPalindrome(str));
        System.out.println(str.length()/2);

    }
   static boolean isPalindrome(String str) {
        str = str.toLowerCase();
        for (int i = 0; i < str.length() / 2; i++) {
          char start=str.charAt(i);
          char end=str.charAt(str.length() - i -  1);

          if (start != end) {
              return false;
          }
        }
        return true;
   }
}
public class RichestCustomerWealth  {
    public static void main(String[] args) {
        int[][] accounts = {
                {1,2,3},
                {4,5,6},
                {7,8,9}
        };
        System.out.println(CustomerWealth(accounts));

    }
    public static int CustomerWealth(int[][] accounts) {
        //person =ro
        //account=col
        int ans=Integer.MIN_VALUE;

        for (int person = 0; person < accounts.length; person++) {
            //when you start a new col ,take a new row
            int sum=0;
            for (int account = 0; account < accounts[person].length; account++) {
                sum = sum + accounts[person][account];
            }
            //now we have sum of accounts of person
            //check overall ans
            if (sum > ans) {
                ans = sum;
            }
        }
        return ans;
    }

}
public class SearchIn2DArr {
    public static void main(String[] args) {
       int[][] num=new int[][]{
               {1,2,3},
               {4,5,6,33,45,52},
               {7,8,9,23,11,12,13},
               {122,33}

       } ;
        System.out.println(max(num));
        System.out.println(even(num));
//        int target=23;
//        int[] ans=search(num,target);
//        System.out.println(ans);
    }
//    static int[] search(int[][] arr, int target) {
//        for(int i=0;i<arr.length;i++) {
//            for(int j=0;j<arr[i].length;j++) {
//                if(arr[i][j] == target) {
//                    return new int[]{i,j};
//
//                }
//            }
//        }
//        return new int[]{-1,-1};
//    }
static int max(int[][] arr) {
     int max=arr[0][0];
    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < arr[i].length; j++) {
            if (arr[i][j]>max) {
                max=arr[i][j];
            }
        }
    }
    return max;
}
    static int[] even(int[][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j]%2==0) {
                    System.out.println("It is even number"+arr[i][j]);
                }
                if(arr[i][j]%2!=0){
                    System.out.println("It is odd number"+arr[i][j]);
                }

            }
        }
        return null;
    }

}


public class SearchInRange {
    public static void main(String[] args) {
        //arr=[18,12,-7,3,14,28]
        //search for 3 in the range of index[1,4]

        int[] nums={1,2,3,4,5,6,7,78,89};
        int target=5;
        System.out.println(search(nums,target,2,7));


    }
    static int search(int[] arr, int target,int start,int end) {
        if (arr.length == 0) {
            return -1;
        }
//check for a element at every index if it is =target
        for (int index = start; index < end; index++) {
            int element = arr[index];
            if (element == target) {
                return index;
            }
        }
        return -1;
    }
}
import java.util.Arrays;

public class Swap {
    public static void main(String[] args) {
        int[] arr={1,2,3,4,5,6,7,8,9};
        reverse(arr);
//        swap(arr,0,1);
        System.out.println(Arrays.toString(arr));
    }
    static void swap(int[] arr,int a,int b){
        int temp=arr[a];
        arr[a]=arr[b];
        arr[b]=temp;
    }

    static void reverse(int[] arr) {
        int start=0;
        int end=arr.length-1;
        while(start<end){
            swap(arr,start,end);
            start++;
            end--;
        }
    }

}

public class Problem1 {
    //Celing of a number:

        public static void main(String[] args) {
            int[] arr={2,3,5,9,14,16,18};
            int ans=binarySearch(arr,15  );
            System.out.println(ans);

        }

        //return The index
        //return -1 it doesnot exist
        static int binarySearch(int[] arr,int target){
            int start=0;
            int end=arr.length-1;

            while(start<=end){
//    int mid=(start+end)/2; might be possible that start + end exceeds the range of int
                int mid=start+(end-start)/2;
                if(arr[mid]>target){
                    end=mid-1;
                }
                if(arr[mid]<target){
                    start=mid+1;
                }
                if(arr[mid]==target){
                    //ans found
                    return mid;
                }
            }
            return end;
        }

    }


import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) {
      int arr[]={5,4,3,2,1};
      insertion(arr);
      System.out.println(Arrays.toString(arr));
    }


    static void insertion(int[] arr){
        for(int i=0;i<=arr.length-2;i++){
            for(int j=i+1;j>0;j--){
                if(arr[j]<arr[j-1]){
                    swap(arr,j,j-1);
                }
                else{
                   break;
                }


            }
        }
    }
    static void selection(int[] arr){
        for(int i=0;i<arr.length;i++){
            //find the max item in the remaining array and swap with correct index
             int last=arr.length-i-1;
             int maxindex=getMaxIndex(arr,0,last);
             swap(arr,maxindex,last);
        }

    }

    static void swap(int[]arr,int first,int second){
        int temp=arr[first];
        arr[first]=arr[second];
        arr[second]=temp;
    }

    static int getMaxIndex(int[] arr, int start, int end) {
        int max=start;

        for(int index=start;index<=end;index++){
            if(arr[index]>arr[max]){
                max=index;
            }
        }
        return max;
    }

}
import java.util.LinkedList;

public class LL {
    private Node head;
    private Node tail;
    private int size;
    public LL(){
        this.size=0;
    }

    public void insertFront(int value){
        Node newNode = new Node(value);
        newNode.next = head;
        head = newNode;

       if(tail==null){
           tail = head;
       }
       size+=1;
    }

     public void insert(int value,int index){
        if(index==0){
            insertFront(value);
        }
        if(index==size){
            insertBack(value);
        }

        Node temp=head;
        for(int i=1;i<index;i++){
            temp=temp.next;

        }
        Node newNode = new Node(value);
        newNode.next = temp.next;
        temp.next = newNode;
     }

    public void insertBack(int value){
        if(tail==null){
            insertFront(value);
        }
        Node newNode = new Node(value);
        tail.next=newNode;
        tail = newNode;
        size+=1;


    }

    public int deleteFirst(){
        int val=head.value;
        head=head.next;
        if(head==null){
            tail=null;
        }
        size-=1;
        return val;
    }

    public int deleteLast(){
        if(size<=1){
            return deleteFirst();
        }
         Node secondlast=get(size-2);
         int val=tail.value;
         tail=secondlast;
         tail.next=null;
         return val;
    }

    public int deleteAtIndex(int index){
        if(index==0){
            return deleteFirst();
        }
        if(index==size-1){
            return deleteLast();
        }
        Node prev=get(index-1);
        int val=prev.next.value;
        prev.next=prev.next.next;
        return val;
    }
    public Node get(int index){
        Node node=head;
        for(int i=0;i<index;i++){
            node=node.next;
        }
        return node;
    }

    public Node find(int value){
        Node node=head;
        while(node!=null){
            if(node.value==value){
                return node;
            }
            node=node.next;
        }
        return null;
    }



    public void display(){
        Node temp=head;
        while(temp!=null){
            System.out.println(temp.value+"->");
            temp=temp.next;
        }
        System.out.println("END");
    }
    private class Node{
        private int value;
        private Node next;

        public Node(int value){
            this.value = value;
        }
        public Node(int value, Node next){
            this.value = value;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        LL list=new LL();
        list.insertFront(3);
        list.insertFront(5);
        list.insertFront(7);
        list.insertFront(9);
        System.out.println(list.find(5));
//        list.insertBack(10);
//        list.insert(11,2);
//        System.out.println(list.deleteFirst());
//        System.out.println(list.deleteLast());
        list.display();

//        System.out.println(list.deleteAtIndex(2));
    }
}
<?php

class Product_Search_Widget extends \Elementor\Widget_Base
{
    public function get_name()
    {
        return 'product-search-widget';
    }

    public function get_title()
    {
        return __('Product Search Widget', 'text-domain');
    }

    public function get_icon()
    {
        return 'eicon-search'; 
    }

    public function get_categories()
    {
        return ['general'];
    }

    protected function render()
    {
        ?>

        <form class="pp-search-form" role="search" action="<?php echo esc_url(home_url('/')); ?>" method="get" aria-label="Search form">
            <div class="pp-search-form__toggle">
                <i class="fa fa-search" aria-hidden="true"></i>
            </div>
            <div class="pp-search-form__container pp-search-form--lightbox">
                <div class="search-form">
                    <label class="pp-screen-reader-text" for="pp-search-form__input-<?php echo esc_attr($this->get_id()); ?>">
                        Search our products
                    </label>
                    <input id="pp-search-form__input-<?php echo esc_attr($this->get_id()); ?>" class="pp-search-form__input" type="search" name="s" title="Search" value="">
                </div>
                <button type="submit" class="pp-search-form__button">
                    <span class="pp-icon-search" aria-hidden="true">
                        <i class="fa fa-search" aria-hidden="true"></i>
                    </span>
                </button>
                <input type="hidden" name="post_type" value="product"> 
                <div class="pp-search-form--lightbox-close">
                    <span class="pp-icon-close" aria-hidden="true">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"><path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/></svg>
                    </span>
                </div>
            </div>
        </form>
        
        <?php
    }
}

\Elementor\Plugin::instance()->widgets_manager->register_widget_type(new Product_Search_Widget());



import java.util.Arrays;

public class CyclicSort {
    public static void main(String[] args) {
       int[] arr={3,5,2,1,4};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }
     static void sort(int arr[]){
        int i=0;
        while(i<arr.length){
            int correct=arr[i]-1;
            if(arr[i]!=arr[correct]){
                swap(arr,i,correct);
            }
            else{
                i++;
            }
        }
     }

    static void swap(int[]arr,int first,int second){
        int temp=arr[first];
        arr[first]=arr[second];
        arr[second]=temp;
    }



}

import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr={5,4,3,2,1};
        bubble(arr);
        System.out.println(Arrays.toString(arr));
    }

    static void bubble(int[] arr){
        //run the steps n-1 times
        boolean swapped;
        for(int i=0; i<arr.length; i++){
            swapped = false;
            //for each step ,max item will come at the last respective index
            for(int j=1; j<arr.length-i; j++){

            //swap if the item is smaller than the previous item
             if(arr[j]<arr[j-1]){
                 int temp = arr[j];
                 arr[j] = arr[j-1];
                 arr[j-1] = temp;
                 swapped = true;
             }
            }

            //if you did not swap for a particular value of i , it means the array is sorted hence stop the program
            if(!swapped){
                break;
            }
        }
    }
}
---Understand the problem---

To gain clarity and understanding of the problem, write it down on paper, reword it in plain English until it makes sense to you, and draw diagrams if that helps. When you can explain the problem to someone else in plain English, you understand it.


---Plan---
  
Now that you know what you’re aiming to solve, don’t jump into coding just yet. It’s time to plan out how you’re going to solve it first. Some of the questions you should answer at this stage of the process:

Does your program have a user interface? What will it look like? What functionality will the interface have? Sketch this out on paper.
What inputs will your program have? Will the user enter data or will you get input from somewhere else?
What’s the desired output?
Given your inputs, what are the steps necessary to return the desired output?
  
  
---Pseudocode---
  
Pseudocode is writing out the logic for your program in natural language instead of code. It helps you slow down and think through the steps your program will have to go through to solve the problem.

Here’s an example of what the pseudocode for a program that prints all numbers up to an inputted number might look like:

When the user inputs a number
Initialize a counter variable and set its value to zero
While counter is smaller than user inputted number increment the counter by one
Print the value of the counter variable


---Divide and conquer---
  
From your planning, you should have identified some subproblems of the big problem you’re solving. Each of the steps in the algorithm we wrote out in the last section are subproblems. Pick the smallest or simplest one and start there with coding.
JS

$('#ceremonial').change(function () {
    var ceremonial_id = $(this).val();
    $('#responsible_ceremonial_name').empty().append('<option value=""></option>');
    $('#responsible_ceremonial_phone').val('');

    if (ceremonial_id) {
      $.ajax({
        url: BASE_URL + 'Ajax/getResponsibleCeremonialName',
        type: 'POST',
        data: { ceremonial_id: ceremonial_id },
        dataType: 'json',
        success: function (data) {
          $('#responsible_ceremonial_name').append('<option value="new">Novo</option>');
          $.each(data, function (index, responsible_ceremonial) {
            $('#responsible_ceremonial_name').append('<option value="' + responsible_ceremonial.id + '">' + responsible_ceremonial.name + '</option>');
          });


        },
        error: function (jqXHR, textStatus, errorThrown) {
          console.error('Erro ao buscar responsavel pelo cerimonial: ' + textStatus);
        }
      });
    }
  });


HTML - Primeiro Select normal preenchido pelo BD

<div id="select_ceremonial" class="col-lg-3 col-md-8">
                                            <!-- <label for="">Informações do Local do evento:</label> -->
                                            <div class="input-group mb-3">
                                                <div class="input-group-prepend">
                                                    <!-- <label class="input-group-text" for="ceremonial">Local</label> -->
                                                </div>
                                                <select class="custom-select" id="ceremonial" name="ceremonial">
                                                    <option value="" selected></option>
                                                    <option value="0">Novo</option>
                                                    <?php foreach ($ceremonials as $ceremonial) : ?>
                                                        <?php if (isset($info_event)) : ?> <!-- verificando se o form é create ou edit -->
                                                            <option value="<?= $ceremonial['id'] ?>" <?= ($info_event['ceremonial_id'] == $ceremonial['id']) ? 'selected' : '' ?>><?= $ceremonial['name'] ?></option>
                                                        <?php else : ?>
                                                            <option value="<?= $ceremonial['id'] ?>"><?= $ceremonial['name'] ?></option>
                                                        <?php endif; ?> <!-- fim da verificação create edit -->
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>


O SELECT A SER PREENCHIDO
<div class="col-lg-2 col-md-6 responsible-ceremonial-name">
                                            <div class="input-group mb-3">
                                                <!-- select controlado por js -->
                                                <select class="custom-select" name="responsible_ceremonial_name" id="responsible_ceremonial_name">

                                                    <option value="" selected></option>

                                                </select>

                                                <!-- fim select controlado -->
                                            </div>
                                        </div>
db.comments.find({_id: {$gt: ObjectId("5272e0f00000000000000000")}})
configurations.all {
    resolutionStrategy {
        eachDependency {
            if ((requested.group == "org.jetbrains.kotlin") && (requested.name.startsWith("kotlin-stdlib"))) {
                useVersion("1.8.0")
            }
        }
    }
}
using av_motion_api.Data;
using av_motion_api.Factory;
using av_motion_api.Models;
using av_motion_api.Interfaces;
using av_motion_api.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;

var builder = WebApplication.CreateBuilder(args);

// Configure the app environment
ConfigurationManager configuration = builder.Configuration;

builder.Configuration.SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: false);

builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    config.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true);
});

// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// CORS
if (builder.Environment.IsDevelopment())
{
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", policy =>
        {
            policy.AllowAnyOrigin()
                  .AllowAnyHeader()
                  .AllowAnyMethod();
        });
    });
}

// Add services to the container
builder.Services.AddControllers();

// SQL
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IRepository, Repository>();

builder.Services.AddIdentity<User, Role>(options =>
                {
                    options.Password.RequireUppercase = false;
                    options.Password.RequireLowercase = false;
                    options.Password.RequireNonAlphanumeric = false;
                    options.Password.RequireDigit = true;
                    options.User.RequireUniqueEmail = true;
                })
                .AddRoles<Role>()
                .AddEntityFrameworkStores<AppDbContext>()
                .AddDefaultTokenProviders();

builder.Services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddCookie()
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = builder.Configuration["Tokens:Issuer"],
                        ValidAudience = builder.Configuration["Tokens:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Tokens:Key"]))
                    };
                });

// Configure FormOptions for file uploads
builder.Services.Configure<FormOptions>(o =>
{
    o.ValueLengthLimit = int.MaxValue;
    o.MultipartBodyLengthLimit = int.MaxValue;
    o.MemoryBufferThreshold = int.MaxValue;
});

builder.Services.AddScoped<IUserClaimsPrincipalFactory<User>, AppUserClaimsPrincipalFactory>();

builder.Services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(3));

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Use CORS
app.UseCors("AllowAll");

app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Use(async (context, next) =>
{
    var logger = app.Services.GetRequiredService<ILogger<Program>>();
    logger.LogInformation("Handling request: " + context.Request.Path);
    await next.Invoke();
    logger.LogInformation("Finished handling request.");
});

app.Run();
import pandas as pd

# Cargar el archivo CSV
input_file = 'input.csv'  # Reemplaza con el nombre de tu archivo CSV
output_file = 'filtered_output.csv'

# Leer el CSV en un DataFrame
df = pd.read_csv(input_file)

# Primer filtro: conservar filas donde 'orden' aparece más de una vez y 'item' contiene la palabra "Tip"
filtered_df = df.groupby('orden').filter(lambda x: (x['item'].str.contains('Tip', case=False, na=False).any()))

# Segundo filtro: eliminar filas donde el campo 'metodo' está vacío
filtered_df = filtered_df[filtered_df['metodo'].notna()]

# Eliminar la columna 'item'
filtered_df = filtered_df.drop(columns=['item'])

# Guardar el DataFrame filtrado en un nuevo archivo CSV
filtered_df.to_csv(output_file, index=False)

print(f'Filtrado completado. Archivo guardado como {output_file}')
#include<iostream>
using namespace std;

int main(){
  
  int n;
  cin>>n;
  for(int j=1;j<+n;i++){
  for( int i=1;j<=n+1-i;j++){
      cout<<j<<" ";
  }
    cout<<endl;
    
    return 0;
  }
using av_motion_api.Data;
using av_motion_api.Models;
using av_motion_api.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Cors;
using System.Text.RegularExpressions;
using SendGrid.Helpers.Mail;
using SendGrid;

namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAll")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly IUserClaimsPrincipalFactory<User> _claimsPrincipalFactory;
        private readonly IConfiguration _configuration;
        private readonly AppDbContext _appDbContext;
        private readonly RoleManager<Role> _roleManager;
        private readonly ILogger<UserController> _logger;

        public UserController(AppDbContext context, UserManager<User> userManager, IUserClaimsPrincipalFactory<User> claimsPrincipalFactory, IConfiguration configuration, RoleManager<Role> roleManager, ILogger<UserController> logger)
        {
            _appDbContext = context;
            _userManager = userManager;
            _claimsPrincipalFactory = claimsPrincipalFactory;
            _configuration = configuration;
            _roleManager = roleManager;
            _logger = logger;
        }

        ////addUser
        //[HttpPost]
        //[Route("Register")]
        //public async Task<IActionResult> Register(UserViewModel uvm)
        //{
        //    var user = await _userManager.FindByEmailAsync(uvm.Email);
        //    int lastUserID = _appDbContext.Users
        //                     .OrderByDescending(u => u.User_ID)
        //                     .Select(u => u.User_ID)
        //                     .FirstOrDefault();

        //    if (user == null)
        //    {
        //        user = new User
        //        {
        //            User_ID = lastUserID + 1,
        //            Name = uvm.Name,
        //            Surname = uvm.Surname,
        //            UserName = uvm.Email,
        //            Email = uvm.Email,
        //            PasswordHash = uvm.Password,
        //            User_Status_ID = uvm.User_Status_ID,
        //            User_Type_ID = uvm.User_Type_ID,
        //            PhoneNumber = uvm.PhoneNumber,
        //            Date_of_Birth = uvm.Date_of_Birth,
        //            ID_Number = uvm.Id_Number,
        //            Physical_Address = uvm.Physical_Address,
        //            Photo = uvm.Photo
        //        };

        //        IdentityResult result = await _userManager.CreateAsync(user, uvm.Password);

        //        if (result.Succeeded)
        //        {
        //            // Assign role based on User_Type_ID
        //            string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
        //            if (!string.IsNullOrEmpty(roleName))
        //            {
        //                var roleResult = await _userManager.AddToRoleAsync(user, roleName);
        //                if (!roleResult.Succeeded)
        //                {
        //                    return BadRequest(roleResult.Errors);
        //                }
        //            }
        //        }
        //        else
        //        {
        //            return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
        //        }
        //    }
        //    else
        //    {
        //        return Forbid("Account already exists.");
        //    }

        //    return Ok();
        //}

        //private string GetRoleNameByUserType(int userTypeId)
        //{
        //    return userTypeId switch
        //    {
        //        1 => "Administrator",
        //        2 => "Employee",
        //        3 => "Member",
        //        _ => string.Empty,
        //    };
        //}

        //addUser
        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("Register")]
        public async Task<IActionResult> Register([FromForm] UserViewModel uvm)
        {
            try
            {
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

                var user = await _userManager.FindByEmailAsync(uvm.Email);
                int lastUserID = _appDbContext.Users
                                 .OrderByDescending(u => u.User_ID)
                                 .Select(u => u.User_ID)
                                 .FirstOrDefault();

                // Validate Phone Number Pattern
                var phoneNumberPattern = @"^\d{10}$";

                bool isValidPhoneNumber = Regex.IsMatch(uvm.PhoneNumber, phoneNumberPattern);

                if (!isValidPhoneNumber) return BadRequest("Enter valid 10-digit phone number.");

                // Validate South African ID number
                if (!IsValidSouthAfricanIDNumber(uvm.Id_Number, uvm.Date_of_Birth))
                {
                    return BadRequest("Enter a valid South African ID number.");
                }

                if (user == null)
                {
                    if (photo != null && photo.Length > 0)
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            await photo.CopyToAsync(memoryStream);
                            var fileBytes = memoryStream.ToArray();
                            string base64Image = Convert.ToBase64String(fileBytes);

                            user = new User
                            {
                                User_ID = lastUserID + 1,
                                Name = uvm.Name,
                                Surname = uvm.Surname,
                                UserName = uvm.Email,
                                Email = uvm.Email,
                                PasswordHash = _userManager.PasswordHasher.HashPassword(null, uvm.Password),
                                User_Status_ID = uvm.User_Status_ID,
                                User_Type_ID = uvm.User_Type_ID,
                                PhoneNumber = uvm.PhoneNumber,
                                Date_of_Birth = uvm.Date_of_Birth,
                                ID_Number = uvm.Id_Number,
                                Physical_Address = uvm.Physical_Address,
                                Photo = base64Image // Store the base64 string of the photo
                            };

                            IdentityResult result = await _userManager.CreateAsync(user);

                            if (result.Succeeded)
                            {
                                // Assign role based on User_Type_ID
                                string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
                                if (!string.IsNullOrEmpty(roleName))
                                {
                                    var roleResult = await _userManager.AddToRoleAsync(user, roleName);
                                    if (!roleResult.Succeeded)
                                    {
                                        return BadRequest(new { Status = "Error", Errors = roleResult.Errors });
                                    }
                                }


                                return Ok(new { Status = "Success", Message = "Your profile has been created successfully!" });
                            }
                            else
                            {
                                return StatusCode(StatusCodes.Status500InternalServerError, result.Errors.FirstOrDefault()?.Description);
                            }
                        }
                    }
                    else
                    {
                        return BadRequest("Photo is required.");
                    }
                }
                else
                {
                    return Forbid("User already exists.");
                }
            }
            catch (DbUpdateException dbEx)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, dbEx.InnerException?.Message ?? "An error occurred while processing your request.");
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
            }
        }

        // Method to validate South African ID number
        private bool IsValidSouthAfricanIDNumber(string idNumber, DateTime dateOfBirth)
        {
            // Check if the ID number is exactly 13 digits long
            if (idNumber.Length != 13 || !long.TryParse(idNumber, out _))
            {
                return false;
            }

            // Validate date of birth (first six digits)
            string dateOfBirthPart = idNumber.Substring(0, 6);
            if (!DateTime.TryParseExact(dateOfBirthPart, "yyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
            {
                return false;
            }

            // Check if the last two digits of the ID number match the last two digits of the year of birth
            if (parsedDate.Year % 100 != dateOfBirth.Year % 100)
            {
                return false;
            }

            // If it passes the length, date of birth, and year checks, it is considered valid
            return true;
        }


        private string GetRoleNameByUserType(int userTypeId)
        {
            return userTypeId switch
            {
                1 => "Administrator",
                2 => "Employee",
                3 => "Member",
                _ => string.Empty,
            };
        }

        [HttpPost]
        [Route("Login")]
        public async Task<ActionResult> Login(LoginViewModel lv)
        {
            var user = await _userManager.FindByNameAsync(lv.Email);

            if (user != null && await _userManager.CheckPasswordAsync(user, lv.Password))
            {
                try
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);
                    return await GenerateJWTToken(user);
                }
                catch (Exception)
                {

                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            else
            {
                return NotFound("Incorrect email or password, Please Try Again");
            }
        }

        [HttpGet]
        private async Task<ActionResult> GenerateJWTToken(User user)
        {
            var role = await _userManager.GetRolesAsync(user);
            IdentityOptions _identityOptions = new IdentityOptions();
            // Create JWT Token
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                // Add user ID claim
                new Claim("userId", user.Id.ToString()),

                new Claim("User_Type_ID", user.User_Type_ID.ToString()),

            };

            if (role.Count() > 0)
            {
                claims.Add(new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
               issuer:  _configuration["Tokens:Issuer"],
               audience: _configuration["Tokens:Audience"],
               claims: claims,
               signingCredentials: credentials,
               expires: DateTime.UtcNow.AddHours(3)
            );

            return Created("", new
            {

                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = user.UserName,

                userTypeId = user.User_Type_ID,
                // Include user ID in the response
                userId = user.Id
            });
        }

        [HttpPost]
        [Route("ChangePassword")]
        public async Task<IActionResult> ChangePassword(int id, ChangePasswordViewModel cpvm)
        {
            var user = await _userManager.FindByIdAsync(id.ToString());
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ChangePasswordAsync(user, cpvm.CurrentPassword, cpvm.NewPassword);
            if (result.Succeeded)
            {
                return Ok("Password changed successfully.");
            }
            else
            {
                return BadRequest(result.Errors);
            }
        }

        [HttpPut]
        [Route("editUser/{id}")]
        public async Task<IActionResult> EditUser(int id, [FromForm] UpdateUserViewModel uv)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                // Read the form data to get the photo file
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

                user.Name = uv.Name;
                user.Surname = uv.Surname;
                user.Email = uv.Email;
                user.Physical_Address = uv.Physical_Address;
                user.PhoneNumber = uv.PhoneNumber;

                if (photo != null && photo.Length > 0)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await photo.CopyToAsync(memoryStream);
                        var fileBytes = memoryStream.ToArray();
                        string base64Image = Convert.ToBase64String(fileBytes);

                        user.Photo = base64Image; // Store the base64 string of the photo
                    }
                }

                // Update the user
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return Ok("User updated successfully.");
                }
                else
                {
                    return BadRequest(result.Errors);
                }
            }
            catch (Exception)
            {
                return BadRequest("An Error Occurred, Please Try Again");
            }
        }


        [HttpDelete]
        [Route("deleteUser/{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                var result = await _userManager.DeleteAsync(user);

                if (result.Succeeded)
                {
                    return Ok();
                }
                else
                {
                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getAllUsers")]
        public IActionResult GetAllUsers()
        {
            try
            {
                var users = _userManager.Users.ToList();


                if (users == null || users.Count == 0)
                {
                    return NotFound("No users found.");
                }

                return Ok(users);
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getUserById/{id}")]
        public async Task<IActionResult> GetUserById(int id)
        {
            try
            {
                var u = await _appDbContext.Users
                                .Include(u => u.User_Status)
                                .Include(u => u.User_Type)
                                .FirstOrDefaultAsync(u => u.Id == id);

                var user = new
                {
                    u.Id,
                    u.Name,
                    u.Surname,
                    u.Email,
                    u.Physical_Address,
                    u.PhoneNumber,
                    u.Date_of_Birth,
                    UserStatus = u.User_Status.User_Status_Description,
                    UserType = u.User_Type.User_Type_Name,
                    u.Photo,
                    u.ID_Number
                };

                return Ok(user);
            }
            catch (Exception ex)
            {
                // Log the exception for debugging
                Console.WriteLine(ex.Message);
                return BadRequest("An error occurred while fetching user details.");
            }
        }


        [HttpGet("GetMemberByUserId/{userId}")]
        public async Task<ActionResult<Member>> GetMemberByUserId(int userId)
        {
            var member = await _appDbContext.Members.FirstOrDefaultAsync(m => m.User_ID == userId);
            if (member == null)
            {
                return NotFound();
            }
            return Ok(member);
        }

        [HttpGet("employee")]
        public async Task<ActionResult<IEnumerable<EmployeeViewModel>>> GetEmployees()
        {
            var query = await( from e in _appDbContext.Employees
                        join u in _appDbContext.Users on e.User_ID equals u.User_ID
                        select new EmployeeViewModel
                        {
                            employee_ID = e.Employee_ID,
                            employee_name = u.Name
                        }).ToListAsync();

            return query;

        }
        //Roles

        [HttpPost]
        [Route("CreateRole")]
        public async Task<IActionResult> CreateRole(string roleName)
        {
            var role = await _roleManager.FindByNameAsync(roleName);
            if (role == null)
            {
                role = new Role
                {
                    Name = roleName,
                    NormalizedName = roleName.ToUpper(),
                    isEditable = true,
                };

                var result = await _roleManager.CreateAsync(role);
                if (!result.Succeeded) return BadRequest(result.Errors);
            }
            else
            {
                return Forbid("Role already exists.");
            }

            return Ok();
        }

        [HttpPost]
        [Route("AssignRole")]
        public async Task<IActionResult> AssignRole(string emailAddress, string roleName)
        {
            var user = await _userManager.FindByEmailAsync(emailAddress);
            if (user == null) return NotFound();

            var result = await _userManager.AddToRoleAsync(user, roleName);
            if (result.Succeeded) return Ok();

            return BadRequest(result.Errors);
        }


        [HttpPost("ForgotPassword")]
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    return BadRequest("Email is required.");
                }

                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    return Ok("User does not exist.");
                }

                var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                var resetLink = Url.Action("ResetPassword", "User",
                                           new { token, email = user.Email },
                                           protocol: HttpContext.Request.Scheme);

                await SendResetPasswordEmail(model.Email, resetLink);

                return Ok("Please check your email for password reset instructions.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                return StatusCode(StatusCodes.Status500InternalServerError, "Error sending reset password email.");
            }
        }

        [HttpPost("ResetPassword")]
        public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("Invalid data.");
            }

            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
            if (result.Succeeded)
            {
                return Ok("Password has been reset successfully.");
            }

            return BadRequest("Error while resetting the password.");
        }

        private async Task SendResetPasswordEmail(string email, string resetLink)
        {
            try
            {
                var apiKey = _configuration["SendGrid:ApiKey"];
                var client = new SendGridClient(apiKey);
                var from = new EmailAddress(_configuration["SendGrid:FromEmail"], _configuration["SendGrid:FromName"]);
                var to = new EmailAddress(email);
                var subject = "Reset Password";
                var htmlContent = $"<h4>Reset your password by <a href='{resetLink}'>clicking here</a></h4>";
                var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);

                var response = await client.SendEmailAsync(msg);
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new Exception($"Failed to send email. Status code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                throw;
            }
        }
    }
}
star

Fri Jul 19 2024 15:09:10 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/css/tryit.asp?filename

@ElyasAkbari #undefined

star

Fri Jul 19 2024 12:48:09 GMT+0000 (Coordinated Universal Time) https://youtu.be/ogmBt6f9hw8?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha ##c++ ##dsa ##linkedlist ##circular ##loop #floyd'sloopdetection ##algorithm

star

Fri Jul 19 2024 11:08:49 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Fri Jul 19 2024 11:01:38 GMT+0000 (Coordinated Universal Time)

@Justus

star

Fri Jul 19 2024 10:44:34 GMT+0000 (Coordinated Universal Time) https://www.blockchainappfactory.com/crypto-marketing-agency

@albertpeter

star

Fri Jul 19 2024 09:52:03 GMT+0000 (Coordinated Universal Time)

@signup

star

Fri Jul 19 2024 09:31:12 GMT+0000 (Coordinated Universal Time)

@khainguyenhm #javascript

star

Fri Jul 19 2024 06:42:54 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/users/13540173/profile

@Vitinlonlon73

star

Fri Jul 19 2024 06:42:38 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/users/13540173/profile

@Vitinlonlon73

star

Fri Jul 19 2024 06:37:38 GMT+0000 (Coordinated Universal Time) https://youtu.be/VxOFflTXlXo?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha ##c++ ##dsa ##linkedlist ##circular ##loop

star

Fri Jul 19 2024 06:27:21 GMT+0000 (Coordinated Universal Time) https://youtu.be/fi2vh0nQLi0?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist #recursion #circular

star

Fri Jul 19 2024 06:09:29 GMT+0000 (Coordinated Universal Time) https://youtu.be/fi2vh0nQLi0?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist #recursion

star

Fri Jul 19 2024 06:03:42 GMT+0000 (Coordinated Universal Time)

@davidmchale #function #filter

star

Fri Jul 19 2024 04:43:42 GMT+0000 (Coordinated Universal Time)

@bogeyboogaard

star

Fri Jul 19 2024 04:14:41 GMT+0000 (Coordinated Universal Time) https://youtu.be/vqS1nVQdCJM

@vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist #recursion

star

Fri Jul 19 2024 04:13:46 GMT+0000 (Coordinated Universal Time) https://youtu.be/vqS1nVQdCJM

@vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist #recursion

star

Thu Jul 18 2024 17:17:04 GMT+0000 (Coordinated Universal Time) https://youtu.be/vqS1nVQdCJM

@vishnu_jha #c++ #dsa #linkedlist #reverselinkedlist

star

Thu Jul 18 2024 17:12:19 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=IzvCG7v1KHg

@webisko #css

star

Thu Jul 18 2024 16:18:58 GMT+0000 (Coordinated Universal Time)

@destinyChuck #html #css #javascript

star

Thu Jul 18 2024 14:55:38 GMT+0000 (Coordinated Universal Time) https://sweetalert2.github.io/

@poramet128

star

Thu Jul 18 2024 14:55:32 GMT+0000 (Coordinated Universal Time) https://sweetalert2.github.io/

@poramet128

star

Thu Jul 18 2024 13:38:05 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/1706454/c-multiline-text-in-datagridview-control

@javicinhio

star

Thu Jul 18 2024 12:52:40 GMT+0000 (Coordinated Universal Time) https://maticz.com/smart-contract-development

@carolinemax ##maticz ##usa #smart_contract #smart_contract_development

star

Thu Jul 18 2024 09:52:09 GMT+0000 (Coordinated Universal Time)

@ishwarpatel100 #css #images

star

Thu Jul 18 2024 09:33:49 GMT+0000 (Coordinated Universal Time)

@Justus

star

Thu Jul 18 2024 08:22:46 GMT+0000 (Coordinated Universal Time) https://ocr.space/copyfish/welcome?b

@rozzanxettri

star

Thu Jul 18 2024 08:06:25 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:05:58 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:05:19 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:04:26 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:03:50 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:03:05 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:02:05 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 08:00:45 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 07:36:53 GMT+0000 (Coordinated Universal Time)

@quanganh141220 #php #single #product

star

Thu Jul 18 2024 06:58:30 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 06:55:58 GMT+0000 (Coordinated Universal Time)

@Mohanish

star

Thu Jul 18 2024 00:17:44 GMT+0000 (Coordinated Universal Time)

@NoFox420

star

Wed Jul 17 2024 22:54:24 GMT+0000 (Coordinated Universal Time)

@jdeveloper #php #jquery

star

Wed Jul 17 2024 22:36:32 GMT+0000 (Coordinated Universal Time) https://steveridout.com/mongo-object-time/

@JasonB

star

Wed Jul 17 2024 20:10:13 GMT+0000 (Coordinated Universal Time) https://github.com/flutter/flutter/issues/119247

@zemax_c4

star

Wed Jul 17 2024 20:01:15 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Jul 17 2024 19:00:57 GMT+0000 (Coordinated Universal Time)

@vjg #python

star

Wed Jul 17 2024 16:49:12 GMT+0000 (Coordinated Universal Time) code

@9315256437

star

Wed Jul 17 2024 16:47:03 GMT+0000 (Coordinated Universal Time)

@9315256437

star

Wed Jul 17 2024 16:17:23 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

Save snippets that work with our extensions

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