Snippets Collections
import random
import string

def serial_code(length):
    letters = string.hexdigits
    result_str = ''.join(random.choice(letters) for i in range(length))
    print("Your serial code is:-", result_str, '.')
from sys import path
import os
path.append(os.path.realpath('../'))
add_filter( 'woocommerce_product_export_column_names', 'add_slug_export_column' );
add_filter( 'woocommerce_product_export_product_default_columns', 'add_slug_export_column' );

function add_slug_export_column( $columns ) {
	$columns['slug'] = 'Slug';
 
	return $columns;
}

add_filter( 'woocommerce_product_export_product_column_slug'  , 'add_export_data_slug', 10, 2 );
function add_export_data_slug( $value, $product ) {
    $value = $product->get_slug();
	
    return $value;
}

add_filter( 'woocommerce_csv_product_import_mapping_options', 'add_slug_import_option' );
function add_slug_import_option( $options ) {
  $options['slug'] = 'Slug';
 
  return $options;
}

add_filter( 'woocommerce_csv_product_import_mapping_default_columns', 'add_default_slug_column_mapping' );
function add_default_slug_column_mapping( $columns ) {
  $columns['Slug'] = 'slug';
 
  return $columns;
} 

add_filter( 'woocommerce_product_import_pre_insert_product_object', 'process_import_product_slug_column', 10, 2 );
function process_import_product_slug_column( $object, $data ) {
  if ( !empty( $data['slug'] ) ) {
    $object->set_slug( $data['slug'] );
  }
 
  return $object;
}
Run df -h to verify your root partition is full (100%)
Run lsblk and then lsblk -f to get block device details
sudo mount -o size=10M,rw,nodev,nosuid -t tmpfs tmpfs /tmp
sudo growpart /dev/DEVICE_ID PARTITION_NUMBER ex /dev/nvme0n1 1
lsblk to verify partition has expanded 
sudo resize2fs /dev/DEVICE_IDPARTITION_NUMBER ex /dev/nvme0n1p1
Run df -h to verify your resized disk
sudo umount /tmp
/**************************************
Hide the horizontal overflow sf.digital
Use freely in your CSS. Do not re-post.
**************************************/
html { overflow-x: hidden; }
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
import java.util.Scanner;

public class javaBasics {
    public static void main(String args[]) {
     
        Scanner scan = new Scanner(System.in);
        int a = scan.nextInt();
        int b = scan.nextInt();
        int sum = a + b;
       
        System.out.println(sum);
   
    }
}

#include <stdio.h>

int N;
int main() {
    
    printf("Entrer le nombre N :");
    scanf("%d", &N);
    
    N / 2;
    
    if(N % 2 == 0){
        printf("Le nombre %d est paire.", N);
    }else{
        printf("Le nombre %d est impaire.", N);
    }
    
    return 0;
}
FastLED.clear(); //Clear the LED Array

 //A heart displays and beats across the Laser Stems
for (int i = 0; i < NUM_LEDS; i++){ // Cycle through each LED on the matrix
if (heart_small[i] == 1) {
leds[i] += CRGB::Red;
}
}

FastLED.show();
delay(500);

FastLED.clear(); //Clear the LED Array

for (int i = 0; i < NUM_LEDS; i++){ // Cycle through each LED on the matrix
if (heart_large[i] == 1) {
leds[i] += CRGB::Red;
}
}
FastLED.show();
delay(500);
// Array for the Small Heart Image
static uint8_t heart_small[NUM_LEDS] ={
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};

// Array for the Largest Heart Image
static uint8_t heart_large[NUM_LEDS] = {
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 1, 1, 1, 1, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
};
SimplePatternList gPatterns = { rainbow, rainbowWithGlitter, confetti, chasing, juggle, twinkle, bpm, animatedHeart };
FastLED.clear(); //Clear the LED Array

 //A heart displays and beats across the Laser Stems
for (int i = 0; i < NUM_LEDS; i++){ // Cycle through each LED on the matrix
if (heart_small[i] == 1) {
leds[i] += CRGB::Red;
}
}

FastLED.show();
delay(500);

FastLED.clear(); //Clear the LED Array

for (int i = 0; i < NUM_LEDS; i++){ // Cycle through each LED on the matrix
if (heart_large[i] == 1) {
leds[i] += CRGB::Red;
}
}
FastLED.show();
delay(500);
import java.util.Scanner; 
class HelloWorld {
    public static void main(String[] args) {
        
        int a[]=new int[5];
        Scanner r = new Scanner(System.in);
        System.out.print("Enter elements of arrays");
        
        for(int i=0;i<a.length;i++)
        {
            a[i]=r.nextInt();
        }
        System.out.println (" arrays");
        for(int i=0;i<a.length;i++)
        {
            System.out.print(a[i]+" ");
        }
        System.out.println ("reverse  arrays");
        for(int i=a.length-1;i>=0;i--)
        {
             System.out.print(a[i]+" ");
        }
    }
}
Follow this to hide the formulaes so its not obvious 
import java.util.Arrays; 
class HelloWorld {
    public static void main(String[] args) {
        
        String a[]={"learn","coding","Keypoints"};
        System.out.println(Arrays.toString(a));
        System.out.println(Arrays.asList(a));
        
        int b[][]={{10,20},{30,40}};
        System.out.println(Arrays.deepToString(b));
        
    }
}
# Ngrok for localhost:8000
ngrok http 8000

# Ngrok for aliased localhost e.g., a test domain added to the /etc/hosts file
ngrok http 8000 --host-header=merchant-1.kamadashboard.test

# Also works for VMs like Homestead
ngrok http 192.168.56.56:80 --host-header=milipot.appp
ffmpeg -i input.mp4 -b:v 500k -c:a aac -strict experimental -y output.mp4
# input.txt
file 'file1.mp4'
file 'file2.mp4'
file 'file3.mp4'

# terminal
ffmpeg -f concat -safe 0 -i input.txt -c copy output.mp4
function getGoldPrices($apiKey, $symbol, $curr, $date = "") {
    $myHeaders = array(
        'x-access-token: ' . $apiKey,
        'Content-Type: application/json'
    );

    $curl = curl_init();
    $url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => $myHeaders
    ));

    $response = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);

    if ($error) {
        // handle the error
        echo 'Error: ' . $error;
        return null;
    } else {
        $data = json_decode($response, true);

        if ($data !== null) {
            // Create an associative array to store the gold prices
            $goldPrices = array(
                'price_gram_24k' => $data['price_gram_24k'],
                'price_gram_22k' => $data['price_gram_22k'],
                'price_gram_21k' => $data['price_gram_21k'],
                'price_gram_20k' => $data['price_gram_20k'],
                'price_gram_18k' => $data['price_gram_18k'],
                'price_gram_16k' => $data['price_gram_16k'],
                'price_gram_14k' => $data['price_gram_14k'],
                'price_gram_10k' => $data['price_gram_10k'],
            );

            // Add the timestamp to the array
            $goldPrices['timestamp'] = $data['timestamp'];

            return $goldPrices;
        }

        return null;
    }
}

function getLastButOneRecord($apiKey, $symbol, $curr, $date = "") {
    $myHeaders = array(
        'x-access-token: ' . $apiKey,
        'Content-Type: application/json'
    );

    $curl = curl_init();
    $url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => $myHeaders
    ));

    $response = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);

    if ($error) {
        echo 'Error: ' . $error;
        return null;
    } else {
        $data = json_decode($response, true);

        if ($data !== null) {
            $goldPrices = array(
                'price_gram_24k' => $data['price_gram_24k'],
                'price_gram_22k' => $data['price_gram_22k'],
                'price_gram_21k' => $data['price_gram_21k'],
                'price_gram_20k' => $data['price_gram_20k'],
                'price_gram_18k' => $data['price_gram_18k'],
                'price_gram_16k' => $data['price_gram_16k'],
                'price_gram_14k' => $data['price_gram_14k'],
                'price_gram_10k' => $data['price_gram_10k'],
            );

            $goldPrices['timestamp'] = $data['timestamp'];

            $keys = array_keys($goldPrices);
            $secondToLastKey = $keys[count($keys) - 2];
            $secondToLastValue = $goldPrices[$secondToLastKey];

            return $secondToLastValue;
        }

        return null;
    }
}
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Alexandria:wght@300&display=swap" rel="stylesheet">

<style>
    i.fas.fa-arrow-down {
        color: red;
    }

    i.fas.fa-arrow-up {
        color: yellowgreen;
    }

    i.fas.fa-circle {
        color: yellow;
    }

    po {
        color: white;
        font-size: 14px;
        font-family: 'Alexandria', sans-serif;
    }
    .fa-solid, .fas {
    font-family: "Font Awesome 6 Free" !important;
    font-weight: 900;
}
</style>
<div class="navbar" id="navGold">
    <?php
	
	function getGoldPrice($apiKey,$symbol) {
  
    $curr = "USD";
    $date = "";

    $url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

    $myHeaders = array(
        'x-access-token: ' . $apiKey,
        'Content-Type: application/json'
    );

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => $myHeaders
    ));

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    if ($error) {
        return 'Error: ' . $error;
    } else {
        $data = json_decode($response, true);

        // Check if the response contains a 'price' key
        if (isset($data['price'])) {
            return $data['price'];
        } 
    }
}
	
	function fetchDataAndInsertIntoDatabase($pdo)
	{
		$apiKey = "goldapi-xxd2ktl4miz8nf-io";
		$symbol = "XAU";
		$curr = "SAR";
		$date = "";
		$myHeaders = array(
		'x-access-token: ' . $apiKey,
		'Content-Type: application/json'
		);

		$curl = curl_init();
		$url = "https://www.goldapi.io/api/{$symbol}/{$curr}{$date}";

		curl_setopt_array($curl, array(
		CURLOPT_URL => $url,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_FOLLOWLOCATION => true,
		CURLOPT_HTTPHEADER => $myHeaders
		));
		$response = curl_exec($curl);
		$error = curl_error($curl);
		curl_close($curl);

		if ($error) {
		//	echo 'Error: ' . $error;
		} else {
			$data = json_decode($response, true);
			if ($data !== null) {
				$price_gram_24k = $data['price_gram_24k'];
				$price_gram_22k = $data['price_gram_22k'];
				$price_gram_21k = $data['price_gram_21k'];
				$price_gram_20k = $data['price_gram_20k'];
				$price_gram_18k = $data['price_gram_18k'];
				$price_gram_16k = $data['price_gram_16k'];
				$price_gram_14k = $data['price_gram_14k'];
				$price_gram_10k = $data['price_gram_10k'];
				$timestamp = $data['timestamp'];
				$goldPrice = getGoldPrice($apiKey,$symbol);

				try {
					$stmt = $pdo->prepare("INSERT INTO gold (price_gram_24k, price_gram_22k, price_gram_21k, price_gram_20k, price_gram_18k, price_gram_16k, price_gram_14k, price_gram_10k, timestamp,price) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)");

				// 	$stmt->execute([$price_gram_24k,$price_gram_22k, $price_gram_21k, $price_gram_20k, $price_gram_18k, $price_gram_16k,$price_gram_14k,$price_gram_10k, $timestamp,$goldPrice]);
					$stmt->execute([rand(100000,200000),rand(100000,200000), rand(100000,200000), rand(100000,200000), rand(100000,200000), rand(100000,200000),rand(100000,200000),rand(100000,200000), $timestamp,$goldPrice]);

					// echo 'Data inserted successfully!';
				} catch (PDOException $e) {
				//	echo 'Error: ' . $e->getMessage();
				} finally {
					$pdo = null;
				}
			} else {
			//	echo 'Error decoding JSON';
			}
		}
	}



	function getLastButOneRecord($pdo)
	{
		try {
			$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$sql = "SELECT * FROM gold ORDER BY id DESC LIMIT 1 OFFSET 1";
			$statement = $pdo->query($sql);
			$result = $statement->fetch(PDO::FETCH_ASSOC);
			$pdo = null;
			return $result;
		} catch (PDOException $e) {
		}
	}
	function icon($current_price, $previous_price)
	{
		$icon = '';

		if ($current_price > $previous_price) {
			$icon = 'fas fa-arrow-up';
		} elseif ($current_price < $previous_price) {
			$icon = 'fas fa-arrow-down';
		} else {
			$icon = 'fas fa-circle';
		}
		return $icon;
	}
	function display_price_status($current_price, $previous_price, $string)
	{
		$icon=icon($current_price,$previous_price);  // سيحتوي على النص الناتج
		return     $result = sprintf(
		"<a href='#'><i class=%s>&nbsp;&nbsp;<po>%s</po> : %s</i></a>",
		$string,
		$current_price
		);// تعديل النص الناتج حسب الحالة
	}
	$host = 'localhost';
	$dbname = 'bahrgold_aa';
	$username = 'bahrgold_aa';
	$password = 'm-rScfOBs39u';
	try {
// 		$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
// 		$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// 		fetchDataAndInsertIntoDatabase($pdo);
		$sqlLatest = "SELECT * FROM gold ORDER BY id DESC LIMIT 1";
		$stmtLatest = $pdo->query($sqlLatest);
// 		$rowLatest = $stmtLatest->fetch();
         $rowLatest=array();
         $rowLatest['price_gram_24k'] = '';
         $rowLatest['price_gram_22k'] = '';
         $rowLatest['price_gram_21k'] = '';
         $rowLatest['price_gram_20k'] = '';
         $rowLatest['price_gram_18k'] = '';
         $rowLatest['price_gram_16k'] = '';
         $rowLatest['price_gram_14k'] = '';
         $rowLatest['price_gram_10k'] = '';
		$currentFilePath = __FILE__;
		$currentFilePath;
		if ($rowLatest['price_gram_10k'] !== '') {
// 			$id = $rowLatest['id'];
			$price_gram_24k_latest = $rowLatest['price_gram_24k'];
			$price_gram_22k_latest = $rowLatest['price_gram_22k'];
			$price_gram_21k_latest = $rowLatest['price_gram_21k'];
			$price_gram_20k_latest = $rowLatest['price_gram_20k'];
			$price_gram_18k_latest = $rowLatest['price_gram_18k'];
			$price_gram_16k_latest = $rowLatest['price_gram_16k'];
			$price_gram_14k_latest = $rowLatest['price_gram_14k'];
			$price_gram_10k_latest = $rowLatest['price_gram_10k'];
			$timestamp_latest = $rowLatest['timestamp'];
	        $price = $rowLatest['price'];
			$rowPrevious=getLastButOneRecord($pdo);
			$price_gram_24k_previous = $rowPrevious['price_gram_24k'];
			$price_gram_22k_previous = $rowPrevious['price_gram_22k'];
			$price_gram_21k_previous = $rowPrevious['price_gram_21k'];
			$price_gram_20k_previous = $rowPrevious['price_gram_20k'];
			$price_gram_18k_previous = $rowPrevious['price_gram_18k'];
			$price_gram_16k_previous = $rowPrevious['price_gram_16k'];
			$price_gram_14k_previous = $rowPrevious['price_gram_14k'];
			$price_gram_10k_previous = $rowPrevious['price_gram_10k'];
			$timestamp_previous = $rowPrevious['timestamp'];
            $price_previous = $rowPrevious['price'];
			function displayPriceChange($latestPrice, $previousPrice, $caliber)
			{
				if ($latestPrice > $previousPrice) {
					$icon = 'fas fa-arrow-up';
				} elseif ($latestPrice < $previousPrice) {
					$icon = 'fas fa-arrow-down';
				} else {
					$icon = 'fas fa-arrow-up';
				}
				$latestPrice=round($latestPrice,2);
				echo sprintf(
				"<a href='#'>  &nbsp;<i class='%s'>&nbsp;&nbsp;<po>%s</po> : %s  </i> &nbsp;ريال   &nbsp;</a>",
				$icon,
				$caliber,
				$latestPrice,
				);
			}
		function displayPriceChange__($latestPrice, $previousPrice, $caliber)
			{
				if ($latestPrice > $previousPrice) {
					$icon = 'fas fa-arrow-up';
				} elseif ($latestPrice < $previousPrice) {
					$icon = 'fas fa-arrow-down';
				} else {
					$icon = 'fas fa-arrow-up';
				}
				$latestPrice=round($latestPrice,2);
				echo sprintf(
				"<a href='#'>  &nbsp;<i class='%s'>&nbsp;&nbsp;<po>%s</po> : %s  </i> </a>",
				$icon,
				$caliber,
				$latestPrice,
				);
			}
			displayPriceChange($price_gram_24k_latest, $price_gram_24k_previous, " عيار 24");
            displayPriceChange($price_gram_22k_latest, $price_gram_22k_previous, " عيار 22");
			displayPriceChange($price_gram_21k_latest, $price_gram_21k_previous, " عيار 21");
			displayPriceChange($price_gram_18k_latest, $price_gram_18k_previous, " عيار 18");
			displayPriceChange__($price, $price_previous, "الاونصة" );




		} else {
	//		echo "لم يتم العثور على سجلات";
		}

	} catch (PDOException $e) {
		// التعامل مع الأخطاء في حالة حدوث أي استثناء
	//	echo "خطأ في الاتصال بقاعدة البيانات: " . $e->getMessage();
	}
	?>
</div>
table 50075 "Sharepoint Documents"
{
    Caption = 'Sharepoint Documents';
    DataClassification = ToBeClassified;

    fields
    {
        field(1; "No."; Code[25])
        {
            DataClassification = ToBeClassified;

        }
        field(2; "Line No."; Integer)
        {
            DataClassification = ToBeClassified;
        }
        field(3; "SharePoint URL"; Text[2048])
        {
            DataClassification = ToBeClassified;
        }
        field(4; "File Name"; Text[250])
        {
            DataClassification = ToBeClassified;

        }
        field(5; "File Extension"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        field(6; "Table Id"; Integer)
        {
            DataClassification = ToBeClassified;
        }
        // field(7; "Document Type"; Option)
        // {
        //     OptionMembers = Quote,Order,Invoice,"Credit Memo","Blanket Order","Return Order";
        // }
        field(8; ID; Integer)
        {
            DataClassification = ToBeClassified;
            AutoIncrement = true;
        }
        field(9; "Document Code"; Code[20])
        {
            DataClassification = ToBeClassified;
        }
        field(10; "No. Series"; Code[20])
        {
            DataClassification = ToBeClassified;
        }
        field(11; "Document Type"; Option)
        {
            OptionMembers = Quote,Order,Invoice,"Credit Memo","Blanket Order","Return Order";
        }
        field(12; "Service Instruction Sheet"; boolean)
        {
            DataClassification = ToBeClassified;
        }
        field(13; "Exchange Rate Doc"; boolean)
        {
            DataClassification = ToBeClassified;
        }
        field(14; "Moved To Spoint"; Boolean)
        {
            DataClassification = ToBeClassified;
        }
        field(15; "Spoint Folder Relative Url"; Text[2048])
        {
            DataClassification = ToBeClassified;
        }

    }

    keys
    {
        key(Key1; "No.", "Line No.", "Table Id", ID, "Document Code")
        {
            Clustered = true;
        }
    }

    var
        CuNoSriemgmt: Codeunit NoSeriesManagement;

}


page 50159 "Sharepoint Documents1"
{
    PageType = List;
    ApplicationArea = All;
    UsageCategory = Lists;
    SourceTable = "Sharepoint Documents";


    layout
    {

        area(Content)
        {
            repeater(GroupName)
            {
                field("No."; "No.")
                {
                    ApplicationArea = All;

                }
                field("SharePoint URL"; "SharePoint URL")
                {
                    Editable = false;

                }
                field("File Name"; "File Name")
                {
                    trigger OnDrillDown()
                    var

                    begin
                        UploadDocumentForTheRecord("Table ID", "No.", "Document Code");
                    end;
                }
                field("File Extension"; "File Extension")
                {

                }
            }

        }
        area(Factboxes)
        {

        }
    }



    actions
    {
        area(processing)
        {
            action("View Document")
            {
                ApplicationArea = All;
                Image = Document;
                Promoted = true;
                PromotedCategory = Process;
                trigger OnAction();
                begin
                    Hyperlink("SharePoint URL");
                end;
            }
            action("Download Document")
            {
                ApplicationArea = All;
                Image = Download;
                Promoted = true;
                PromotedCategory = Process;
                trigger OnAction();
                var
                    ObjICTSetup: Record "ICT Setup";
                    CuDocMgt: Codeunit "SharePoint Integration Handler";
                    bas64String: Text;
                    BcInstream: InStream;
                    BcOutStream: OutStream;
                    DialogTitle: Label 'Download File';
                    Cubase64: Codeunit "Base64 Convert";
                    Cutemplob: Codeunit "Temp Blob";
                    tofileName: Text;
                    tofolder: Label 'C:\';
                    toFilter: Label 'All Files (*.*)|*.*';
                begin
                    ObjICTSetup.Get();
                    if ObjICTSetup."Use Sharepoint" then begin
                        bas64String := CuDocMgt.fnDownloadDocument("Spoint Folder Relative Url", "File Name");
                        bas64String := DelChr(bas64String, '<', '"');
                        bas64String := DelChr(bas64String, '>', '"');
                        tofileName := "File Name";
                        Cutemplob.CreateOutStream(BcOutStream);
                        Cubase64.FromBase64(bas64String, BcOutStream);
                        Cutemplob.CreateInStream(BcInstream);
                        DownloadFromStream(BcInstream, DialogTitle, tofolder, toFilter, tofileName);
                    end;
                end;
            }
            action("Delete Document")
            {
                ApplicationArea = All;
                Image = Delete;
                Promoted = true;
                PromotedCategory = Process;
                ToolTip = 'Delete Document From Sharepoint';
                trigger OnAction();
                var
                    ObjICTSetup: Record "ICT Setup";
                    CuDocMgt: Codeunit "SharePoint Integration Handler";
                    res: text;
                begin
                    ObjICTSetup.Get();
                    if ObjICTSetup."Use Sharepoint" then begin
                        res := CuDocMgt.fnDeleteDocument("Spoint Folder Relative Url", "File Name");
                    end;
                    if res = '200' then begin
                        if Delete(true) then begin
                            Message('Document Deleted Successfully');
                        end;
                    end;
                    Commit();
                    CurrPage.Update();
                end;
            }

        }
    }

    trigger OnNewRecord(BelowxRec: Boolean)
    var

    begin
        "File Name" := SelectFileTxt;
    end;

    trigger OnAfterGetRecord()
    begin

    end;

    procedure UploadDocumentForTheRecord(TableId: Integer; RecordNo: code[25]; DocCode: Code[25])
    var
        FieldRef: FieldRef;
        DocType: Option;
        LineNo: Integer;
        ColumnPropertArray: array[6] of Text[250];
        i: Integer;
        ObjPurchInvHeader: Record "Purch. Inv. Header";
        ObjPurchRcptHeader: Record "Purch. Rcpt. Header";
        ObjPurchCrMemoHdr: Record "Purch. Cr. Memo Hdr.";
        ObjSalesHeader: Record "Sales Header";
        ObjBankAccRecon: Record "Bank Acc. Reconciliation";
        ObjEft: Record "EFT Generator";
        FoldersArray: array[5] of Text[250];
    begin
        ObjcompInfo.get;
        ObjSpStp.Reset();
        ObjSpStp.SetRange(ObjSpStp."Table Id", TableId);
        if ObjSpStp.FindFirst() then begin
            case
                TableId of
                Database::"Purchase Header":
                    begin
                        ObjPurchHeader.get(RecordNo);
                        FoldersArray[1] := ObjSpStp.Folder;
                        FoldersArray[2] := ObjSpStp.Module;
                        FoldersArray[3] := ObjSpStp."Financial Year";
                        FoldersArray[4] := Format(ObjPurchHeader."Document Type");
                        FoldersArray[5] := RecordNo;
                        ParseTheDocumentToSharepointHandler(FoldersArray);
                    end;               
            end;
        end;
    end;

    procedure ParseTheDocumentToSharepointHandler(FolderArray: array[5] of Text[250])
    var
        ServerFileName: Text[250];
        ObjIctSetup: Record "ICT Setup";
        ClientPath: Text[250];
        clientFileName: Text[250];
        TempFileName: Text[250];
        cuTemplob: Codeunit "Temp Blob";
        DialogTitle: Label 'Select File';
        base64String: Text;
        cuBase64: Codeunit "Base64 Convert";
        fromFilter: label 'All Files (*.*)|*.*';
        BcInstream: InStream;
        bcOutStream: OutStream;
        BcFile: File;
        Exfilter: label '(*.*)|*.*';
        FromFolder: label 'C:\';
        filename: Text[250];
    begin
        Commit();

        ObjIctSetup.Get();
        File.UploadIntoStream(DialogTitle, FromFolder, FromFilter, clientFileName, BcInstream);
        base64String := cuBase64.ToBase64(BcInstream);
        filename := FileManagement.GetFileName(clientFileName);
        "SharePoint URL" := CuDocMgmt.fnuploadDocument(base64String, FolderArray, filename);
        "File Name" := filename;
        "File Extension" := FileManagement.GetExtension(filename);
        "Spoint Folder Relative Url" := '/' + FolderArray[1] + '/' + FolderArray[2] + '/' + FolderArray[3] + '/' + FolderArray[4] + '/' + FolderArray[5];
    end;

    procedure OpenForRecReference(RecRef: RecordRef)

    var
        FieldRef: FieldRef;
        RecNo: Code[20];
        RecNo2: Code[20];
        DocType: Option;
        LineNo: Integer;
        DoCNo: Code[25];

    begin
        Reset();
        FromRecRef := RecRef;
        SetRange("Table ID", RecRef.Number);       
        CASE RecRef.NUMBER OF
            DATABASE::"Sales Header",
            DATABASE::"Sales Line",
            DATABASE::"Purchase Header",
            DATABASE::"Purchase Line":
                BEGIN
                    FieldRef := RecRef.FIELD(1);
                    DocType := FieldRef.VALUE;
                    SETRANGE("Document Type", DocType);

                    FieldRef := RecRef.FIELD(3);
                    RecNo := FieldRef.VALUE;
                    SETRANGE("No.", RecNo);

                    FlowFieldsEditable := FALSE;
                END;
        END;
        
    end;

    var
        FromRecRef: RecordRef;
        UrlText: Text[250];
        GLAccount: Record "G/L Account";
        SalesDocumentFlow: Boolean;
        PurchaseDocumentFlow: Boolean;
        FlowFieldsEditable: Boolean;
        ObjIctStupRec: Record "ICT Setup";

        Attachment: Page "Document Attachment Details";
        SelectFileTxt: TextConst ENU = 'Select File...';
        TbUserSetup: Record "User Setup";
        ObjSpStp: Record "Sharepoint Setup";
        CuDocMgmt: Codeunit "SharePoint Integration Handler";
        ObjcompInfo: Record "Company Information";
        ObjPayments: Record Payments;
        ObjPaylines: Record "Payment Lines";
        ObjPurchHeader: Record "Purchase Header";
        ObjStaffAdvance: Record Payments;
        storereq: Record "Store Requistion Header";
        prepaymentsheader: Record "Prepayments Header";
        ObjProposedBudget: Record "Proposed Budget Header";
        objBudgReallocation: Record "Budget Reallocation";
        ObjBudget: Record "Budget Approval Header";
        FileManagement: Codeunit "File Management";
        FileName: Text;
        ImportTxt: label 'Attach a document.';
        FileDialogTxt: TextConst ENU = 'Attachments (%1)|%1';
        FilterTxt: TextConst ENU = '*.jpg;*.jpeg;*.bmp;*.png;*.gif;*.tiff;*.tif;*.pdf;*.docx;*.doc;*.xlsx;*.xls;*.pptx;*.ppt;*.msg;*.xml;*.*';
        FolderArray: array[5] of Text[250];
        i: Integer;
}

table 50076 "Sharepoint Setup"
{
    Caption = 'Sharepoint Setup';
    DataClassification = ToBeClassified;

    fields
    {
        field(1; No; Integer)
        {
            DataClassification = ToBeClassified;

        }

        field(2; "Shortcut Dimension 2 Code"; Code[20])
        {
            CaptionClass = '1,1,2';
            TableRelation = "Dimension Value".Code WHERE("Global Dimension No." = CONST(2));

            trigger OnValidate()
            begin
            end;
        }
        field(3; "Sharepoint Url"; text[250])
        {
            DataClassification = ToBeClassified;
        }

        // field(4; "Document Type"; Enum "Sharepoint Document types")
        // {
        //     DataClassification = ToBeClassified;
        // }
        field(5; "Library"; Text[150])
        {
            DataClassification = ToBeClassified;
        }
        field(6; "Folder"; Text[150])
        {
            DataClassification = ToBeClassified;
        }
        field(7; "Financial Year"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        field(8; "Quarter"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        //Module
        field(9; "Module"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        //Sub-Module By
        field(10; "Sub-Module By"; Option)
        {
            DataClassification = ToBeClassified;
            OptionMembers = "Payment Type/Document Type",None;
        }
        //Sub-Module
        field(11; "Sub-Module"; Text[50])
        {
            DataClassification = ToBeClassified;
        }
        //table Id
        field(12; "Table Id"; Integer)
        {
            DataClassification = ToBeClassified;
            TableRelation = AllObjWithCaption."Object ID" where("Object Type" = CONST(Table));
            trigger OnValidate()
            var
                ObjAllObjWithCaption: Record "AllObjWithCaption";
            begin
                ObjAllObjWithCaption.Reset();
                ObjAllObjWithCaption.SetRange("Object ID", "Table Id");
                ObjAllObjWithCaption.SetRange("Object Type", ObjAllObjWithCaption."Object Type"::Table);
                if ObjAllObjWithCaption.FindFirst() then
                    "Table Name" := ObjAllObjWithCaption."Object Name";

            end;
        }
        //table Name
        field(13; "Table Name"; Text[50])
        {
            DataClassification = ToBeClassified;
        }

    }

    keys
    {
        key(Key1; No)
        {
            Clustered = true;
        }
    }

    var
        myInt: Integer;

    trigger OnInsert()
    begin

    end;

    trigger OnModify()
    begin

    end;

    trigger OnDelete()
    begin

    end;

    trigger OnRename()
    begin

    end;

}
    procedure fnuploadDocument(docToUpload: Text; foldersArray: array[5] of Text; docName: Text): Text
    var
        httpClient: HttpClient;
        httpContent: HttpContent;
        httpResponseMessage: HttpResponseMessage;
        httpContentHeaders: HttpHeaders;
        HttpRequestMessage: HttpRequestMessage;
        apiUrl: Text;
        Responsetxt: Text;
        JSonRequest: JsonObject;
        FolderTxt: Text;
        RequestmesgTxt: Text;
        RequestBody: Text;
        RequestType: Enum "Http Requests Enum";
        JsonResp: JsonObject;
        fileUrl: Text;
        JsonToken: JsonToken;
        JsonArray: JsonArray;
        statustxt: Text;
    begin
        ObjIctSetup.GET;
        apiUrl := ObjIctSetup."Sharepoint Integrat. Base URL" + 'sharepoint/file';
        FolderTxt := '/' + foldersArray[1] + '/' + foldersArray[2] + '/' + foldersArray[3] + '/' + foldersArray[4] + '/' + foldersArray[5];
        RequestBody += '{';
        RequestBody += '"fileName":"' + docName + '",';
        RequestBody += '"fileContent":"' + doctoupload + '",';
        RequestBody += '"folderName":"' + folderTxt + '"';
        RequestBody += '}';
        Responsetxt := CallService(apiUrl, RequestType::post, RequestBody, '', '', ObjIctSetup."Sharepoint Api Key");
        JsonResp.ReadFrom(Responsetxt);
        JsonResp.Get('status', JsonToken);
        statustxt := JsonToken.AsValue().AsText();
        if statustxt = '200' then begin
            JsonResp.Get('data', JsonToken);
            JsonResp := JsonToken.AsObject();
            JsonResp.Get('fileUrl', JsonToken);
            fileUrl := JsonToken.AsValue().AsText();
            exit(fileUrl);
        end else begin
            Error('Error uploading document');
        end;
    end;

    procedure fnDownloadDocument(folderRelativeUrl: Text; docName: Text): Text
    var
        httpClient: HttpClient;
        httpContent: HttpContent;
        httpResponseMessage: HttpResponseMessage;
        httpContentHeaders: HttpHeaders;
        HttpRequestMessage: HttpRequestMessage;
        apiUrl: Text;
        Responsetxt: Text;
        JSonRequest: JsonObject;
        FolderTxt: Text;
        RequestmesgTxt: Text;
        CuRest: Codeunit "Web Service Management";
        RequestBody: Text;
        RequestType: Enum "Http Requests Enum";
        JsonResp: JsonObject;
        fileUrl: Text;
        JsonToken: JsonToken;
        JsonArray: JsonArray;
        doctoupload: Text;
        statustxt: Text;
    begin
        ObjIctSetup.GET;
        apiUrl := ObjIctSetup."Sharepoint Integrat. Base URL" + 'sharepoint/download';
        RequestBody += '{';
        RequestBody += '"fileName":"' + docName + '",';
        RequestBody += '"fileContent":"' + doctoupload + '",';
        RequestBody += '"folderName":"' + folderRelativeUrl + '"';
        RequestBody += '}';
        Responsetxt := CallService(apiUrl, RequestType::post, RequestBody, '', '', ObjIctSetup."Sharepoint Api Key");
        if Responsetxt <> '' then begin
            exit(Responsetxt);
        end else begin
            Error('Error downloading document');
        end;
    end;

    procedure fnDeleteDocument(folderRelativeUrl: Text; docName: Text): Text
    var
        httpClient: HttpClient;
        httpContent: HttpContent;
        httpResponseMessage: HttpResponseMessage;
        httpContentHeaders: HttpHeaders;
        HttpRequestMessage: HttpRequestMessage;
        apiUrl: Text;
        Responsetxt: Text;
        JSonRequest: JsonObject;
        FolderTxt: Text;
        RequestmesgTxt: Text;
        CuRest: Codeunit "Web Service Management";
        RequestBody: Text;
        RequestType: Enum "Http Requests Enum";
        JsonResp: JsonObject;
        fileUrl: Text;
        JsonToken: JsonToken;
        JsonArray: JsonArray;
        doctoupload: Text;
    begin
        ObjIctSetup.GET;
        apiUrl := ObjIctSetup."Sharepoint Integrat. Base URL" + 'sharepoint/file:delete';
        RequestBody += '{';
        RequestBody += '"fileName":"' + docName + '",';
        RequestBody += '"fileContent":"' + doctoupload + '",';
        RequestBody += '"folderName":"' + folderRelativeUrl + '"';
        RequestBody += '}';
        Responsetxt := CallService(apiUrl, RequestType::post, RequestBody, '', '', ObjIctSetup."Sharepoint Api Key");
        JsonResp.ReadFrom(Responsetxt);
        JsonResp.Get('status', JsonToken);
        exit(JsonToken.AsValue().AsText()); 
    end;
enum 50005 "Http Requests Enum"
{
    Extensible = true;
    value(0; Get) { }
    value(1; patch) { }
    value(2; post) { }
    value(3; delete) { }
}



procedure CallWebService(RequestUrl: Text; RequestType: Enum "Http Requests Enum"; payload: Text; Username: Text; Password: Text; ApiKey: text): Text
    var
        Client: HttpClient;
        RequestHeaders: HttpHeaders;
        RequestContent: HttpContent;
        ResponseMessage: HttpResponseMessage;
        RequestMessage: HttpRequestMessage;
        ResponseText: Text;
        contentHeaders: HttpHeaders;
        folderName: Text;
        FileName: Text;
        fielcontent: Text;
    begin
        RequestHeaders := Client.DefaultRequestHeaders();

        case RequestType of
            RequestType::Get:
                begin
                    RequestContent.WriteFrom(payload);

                    RequestContent.GetHeaders(contentHeaders);
                    contentHeaders.Clear();
                    contentHeaders.Add('Content-Type', 'application/json');
                    if ApiKey <> '' then
                        contentHeaders.Add('XApiKey', ApiKey);
                    RequestMessage.Content := RequestContent;
                    RequestMessage.SetRequestUri(RequestURL);
                    RequestMessage.Method := 'GET';

                    Client.send(RequestMessage, ResponseMessage);
                end;
            // Client.Get(RequestURL, ResponseMessage);
            RequestType::patch:
                begin
                    RequestContent.WriteFrom(payload);

                    RequestContent.GetHeaders(contentHeaders);
                    contentHeaders.Clear();
                    contentHeaders.Add('Content-Type', 'application/json-patch+json');
                    if ApiKey <> '' then
                        contentHeaders.Add('XApiKey', ApiKey);

                    RequestMessage.Content := RequestContent;

                    RequestMessage.SetRequestUri(RequestURL);
                    RequestMessage.Method := 'PATCH';

                    client.Send(RequestMessage, ResponseMessage);
                end;
            RequestType::post:
                begin
                    RequestContent.WriteFrom(payload);

                    RequestContent.GetHeaders(contentHeaders);
                    contentHeaders.Clear();
                    contentHeaders.Add('Content-Type', 'application/json');
                    if ApiKey <> '' then
                        contentHeaders.Add('XApiKey', ApiKey);

                    Client.Post(RequestURL, RequestContent, ResponseMessage);
                end;
            RequestType::delete:
                Client.Delete(RequestURL, ResponseMessage);
        end;
        ResponseMessage.Content().ReadAs(ResponseText);
        exit(ResponseText);
    end;


}
namespace SharepointOnlineIntegration.Middleware
{
    public class ApiKeyMiddleware
    {
        private readonly RequestDelegate _next;
        private
        const string APIKEY = "XApiKey";
        public ApiKeyMiddleware(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (!context.Request.Headers.TryGetValue(APIKEY, out
                    var extractedApiKey))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Api Key was not provided ");
                return;
            }
            var appSettings = context.RequestServices.GetRequiredService<IConfiguration>();
            var apiKey = appSettings.GetValue<string>(APIKEY);
            if (!apiKey.Equals(extractedApiKey))
            {
                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Unauthorized client");
                return;
            }
            await _next(context);
        }
    }
}
    //delete file
    [HttpPost("file:delete")]
    public async Task<IActionResult> DeleteFile([FromBody] FileUpload Upload)
    {
        Config.DefaultResponse response = new Config.DefaultResponse();
        try
        {
            string siteUrl = "";
            var relativeFilePath = "/sites/YourSiteName/YourLibraryName" + Upload.FolderName + "/" + Upload.FileName;
            var apiUrl = $"{siteUrl}/_api/web/GetFileByServerRelativePath(decodedurl='{relativeFilePath}')";

            var accessTokenResult = await GetAccessToken();

            if (accessTokenResult is ObjectResult accessTokenObjectResult && accessTokenObjectResult.Value is string accessToken)
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // Send HTTP DELETE request to delete the file
                    var deleteResponse = await httpClient.DeleteAsync(apiUrl);

                    if (deleteResponse.IsSuccessStatusCode)
                    {
                        var responseText = await deleteResponse.Content.ReadAsStringAsync();
                        response = new Config.DefaultResponse(200, "Success", "File deleted successfully");
                        return Ok(response);
                    }
                    else
                    {
                        var responseText = await deleteResponse.Content.ReadAsStringAsync();
                        response = new Config.DefaultResponse(500, "Failed to delete file", responseText);
                        return BadRequest(response);
                    }
                }
            }
            else
            {
                response = new Config.DefaultResponse(500, "Failed", "Something wrong occurred");
                return BadRequest(response);
            }
        }
        catch
        {
            response = new Config.DefaultResponse(500, "Failed", "Something wrong occurred");
            return BadRequest(response);
        }
    }
    //Downdload file
    [HttpPost("download")]
    public async Task<IActionResult> DownloadFile([FromBody] FileUpload Upload)
    {
        Config.DefaultResponse response = new Config.DefaultResponse();
        try
        {
            string siteUrl = "";
            var RelativeFilePath = "/sites/YourSiteName/YourLibraryName" + Upload.FolderName + "/" + Upload.FileName;
            var apiUrl = $"{siteUrl}/_api/web/GetFileByServerRelativePath(decodedurl='{RelativeFilePath}')/$value";

            var accessTokenResult = await GetAccessToken();

            if (accessTokenResult is ObjectResult accessTokenObjectResult && accessTokenObjectResult.Value is string accessToken)
            {
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var downloadResponse = await httpClient.GetAsync(apiUrl);
                    var responseText = downloadResponse.Content.ReadAsStringAsync();

                    if (downloadResponse.IsSuccessStatusCode)
                    {
                        var filecontent = await downloadResponse.Content.ReadAsByteArrayAsync();
                        return Ok(filecontent);
                    }
                    else
                    {
                         
                        response = new Config.DefaultResponse(500, "Failed to download", responseText);
                        return BadRequest(response);
                    }

                }

            }
            else
            {
                response = new Config.DefaultResponse(500, "Failed", "Something Wrong occured");
                return BadRequest(response);
            }
        }
        catch
        {
            response = new Config.DefaultResponse(500, "Failed", "Something Wrong occured");
            return BadRequest(response);
        }
    }
using System;
using Newtonsoft.Json.Linq;

namespace SharepointOnlineIntegration
{
    public class Config
    {
        public struct DefaultResponse
        {
            public int status { get; set; }
            public string message { get; set; }
            public object data { get; set; }





            public DefaultResponse(int status, string message, object data = null)
            {
                this.status = status;
                this.message = message;
                this.data = data;                
            }
            public struct JSONArrayResponse
            {
                public int status { get; set; }
                public JArray response { get; set; }



                public JSONArrayResponse(int status, JArray message)
                {
                    this.status = status;
                    this.response = message;
                }
            }
        }
    }
}
    [HttpPost("file")]
    public async Task<IActionResult> UploadFile([FromBody] FileUpload Upload)
    {
        Config.DefaultResponse response = new Config.DefaultResponse();
        try
        {
            string siteUrl = "";

            var accessTokenResult = await GetAccessToken();

            if (accessTokenResult is ObjectResult accessTokenObjectResult && accessTokenObjectResult.Value is string accessToken)
            {
                string libraryName = "Shared Documents";
                string folderPath = Upload.FolderName;

                string[] folders = folderPath.Trim('/').Split('/');
                var firstFolderPathSet = folders[0] + "/" + folders[1];
                var firstFolderUrl = $"{siteUrl}/_api/web/getfolderbyserverrelativeurl('{libraryName}/{firstFolderPathSet}')/Exists";
                var secondFolderPathSet = folders[0] + "/" + folders[1] + "/" + folders[2];
                var secondFolderUrl = $"{siteUrl}/_api/web/getfolderbyserverrelativeurl('{libraryName}/{secondFolderPathSet}')/Exists";
                var thirdFolderPathSet = folders[0] + "/" + folders[1] + "/" + folders[2] + "/" + folders[3];
                var thirdFolderUrl = $"{siteUrl}/_api/web/getfolderbyserverrelativeurl('{libraryName}/{thirdFolderPathSet}')/Exists";
                var fourthFolderPathSet = folders[0] + "/" + folders[1] + "/" + folders[2] + "/" + folders[3] + "/" + folders[4];
                var fourthFolderUrl = $"{siteUrl}/_api/web/getfolderbyserverrelativeurl('{libraryName}/{fourthFolderPathSet}')/Exists";

                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var checkResponse = await httpClient.GetAsync(firstFolderUrl);
                    if (checkResponse.IsSuccessStatusCode)
                    {
                        var responseText = await checkResponse.Content.ReadAsStringAsync();
                        JObject jsonResponse = JObject.Parse(responseText);
                        bool extractedValue = jsonResponse["value"].Value<bool>();
                        if (!extractedValue)
                        {
                            var createFolderUrl = $"{siteUrl}/_api/web/folders/add('{libraryName}/{firstFolderPathSet}')";
                            using (var createResponse = await httpClient.PostAsync(createFolderUrl, null))
                            {
                                if (!createResponse.IsSuccessStatusCode)
                                {
                                    response = new Config.DefaultResponse(500,"Failed to create folder", "Failed to create folder");
                                    return BadRequest(response);
                                }
                            }
                        }
                    }
                    else
                    {
                        response = new Config.DefaultResponse(500,"Failed", "Failed to check if folder exists");
                        return BadRequest(response);
                    }
                }
                //second folder
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var checkResponse = await httpClient.GetAsync(secondFolderUrl);
                    if (checkResponse.IsSuccessStatusCode)
                    {
                        var responseText = await checkResponse.Content.ReadAsStringAsync();
                        JObject jsonResponse = JObject.Parse(responseText);
                        bool extractedValue = jsonResponse["value"].Value<bool>();
                        if (!extractedValue)
                        {
                            var createFolderUrl = $"{siteUrl}/_api/web/folders/add('{libraryName}/{secondFolderPathSet}')";
                            using (var createResponse = await httpClient.PostAsync(createFolderUrl, null))
                            {
                                if (!createResponse.IsSuccessStatusCode)
                                {
                                    response = new Config.DefaultResponse(500,"Failed to create folder", "Failed to create folder");
                                    return BadRequest(response);
                                }
                            }
                        }
                    }
                    else
                    {
                        response = new Config.DefaultResponse(500,"Failed", "Failed to check if folder exists");
                        return BadRequest(response);
                    }
                }
                //third folder
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var checkResponse = await httpClient.GetAsync(thirdFolderUrl);
                    if (checkResponse.IsSuccessStatusCode)
                    {
                        var responseText = await checkResponse.Content.ReadAsStringAsync();
                        JObject jsonResponse = JObject.Parse(responseText);
                        bool extractedValue = jsonResponse["value"].Value<bool>();
                        if (!extractedValue)
                        {
                            var createFolderUrl = $"{siteUrl}/_api/web/folders/add('{libraryName}/{thirdFolderPathSet}')";
                            using (var createResponse = await httpClient.PostAsync(createFolderUrl, null))
                            {
                                if (!createResponse.IsSuccessStatusCode)
                                {
                                    response = new Config.DefaultResponse(500,"Failed to create folder", "Failed to create folder");
                                    return BadRequest(response);
                                }
                            }
                        }
                    }
                    else
                    {
                        response = new Config.DefaultResponse(500,"Failed", "Failed to check if folder exists");
                        return BadRequest(response);
                    }
                }
                //fourth folder
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var checkResponse = await httpClient.GetAsync(fourthFolderUrl);
                    if (checkResponse.IsSuccessStatusCode)
                    {
                        var responseText = await checkResponse.Content.ReadAsStringAsync();
                        JObject jsonResponse = JObject.Parse(responseText);
                        bool extractedValue = jsonResponse["value"].Value<bool>();
                        if (!extractedValue)
                        {
                            var createFolderUrl = $"{siteUrl}/_api/web/folders/add('{libraryName}/{fourthFolderPathSet}')";
                            using (var createResponse = await httpClient.PostAsync(createFolderUrl, null))
                            {
                                if (!createResponse.IsSuccessStatusCode)
                                {
                                    response = new Config.DefaultResponse(500,"Failed to create folder", "Failed to create folder");
                                    return BadRequest(response);
                                }
                            }
                        }
                    }
                    else
                    {
                        response = new Config.DefaultResponse(500,"Failed", "Failed to check if folder exists");
                        return BadRequest(response);
                    }
                }
                    string fileName = Upload.FileName;
                //var uploadUrl = $"{currentFolderUrl}/files/add(url='{fileName}',overwrite=true)";
                var uploadUrl = $"{siteUrl}/_api/web/getfolderbyserverrelativeurl('{libraryName}{folderPath}')/files/add(overwrite=true,url='{fileName}')";

                //Write filecontent to local file


                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    byte[] fileBytes = Convert.FromBase64String(Upload.FileContent);

                    ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
                    fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                    using (var httpResponse = await httpClient.PostAsync(uploadUrl, fileContent))
                    {
                        var responseText = await httpResponse.Content.ReadAsStringAsync();

                        if (httpResponse.IsSuccessStatusCode)
                        {

                            var fileUrl= siteUrl + "/" + libraryName +folderPath + "/" + fileName;
                            var myData = new
                            {
                                Name = fileName,
                                fileUrl = fileUrl
                            };
                            response = new Config.DefaultResponse(200, "Success", myData);
                            return Ok(response);
                        }
                        else
                        {
                            response = new Config.DefaultResponse(500,"Failed to upload file", responseText);
                            return BadRequest(response);
                        }
                    }
                }
            }
            else
            {
                return BadRequest("Failed to obtain access token");
            }
        }
        catch (Exception ex)
        {
           var exceptionResponse = new Config.DefaultResponse(500,"Failed to upload file", ex.Message);
            return StatusCode(500, exceptionResponse);
        }
    }
    [HttpPost("token")]
    public async Task<IActionResult> GetAccessToken()
    {
        Config.DefaultResponse response = new Config.DefaultResponse();
       

        try
        {
            
            var grantType = "client_credentials";
            var clientId = "";
            var clientSecret = "";
            var resource = "";
            var tenantId = "";
           var url = $"https://accounts.accesscontrol.windows.net/{tenantId}/tokens/OAuth/2";

            using (var httpClient = new HttpClient())
            {
                var requestContent = $"grant_type={grantType}&client_id={clientId}&client_secret={clientSecret}&resource={resource}";

                using (var httpContent = new StringContent(requestContent))
                {
                    httpContent.Headers.Clear();
                    httpContent.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

                    using (var httpResponse = await httpClient.PostAsync(url, httpContent))
                    {
                        var responseText = await httpResponse.Content.ReadAsStringAsync();
                        //get as Json
                        string decodedString = System.Text.RegularExpressions.Regex.Unescape(responseText);
                        AccessTokenResponse responseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(decodedString);
                        



                        if (httpResponse.IsSuccessStatusCode)
                        {
                           


                            return Ok(responseObject?.AccessToken);
                        }
                        else
                        {
                            response = new Config.DefaultResponse(500,"Failed to fetch token", responseObject);

                            return BadRequest(response);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            var exceptionResponse = new AccessTokenResponse
            {
               
            };

            return StatusCode(500, exceptionResponse);
        }
    }
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        
        int n,r;
        Scanner ref = new Scanner(System.in);
        System.out.println("enter you value !");
        n=ref.nextInt();
        
        while(n>0)
        {
            r=n%10;
            System.out.print(r);
            n=n/10;
        }
        
    }
class MethodOverloadDriver{
 public static void main(String args[]){
 MethodOverload obj=new MethodOverload();
 obj.add(5,10);
 obj.add(5,10,15);
 obj.add(10,12.5);
}
}
class MethodOverload{
 void add(int a,int b){
 System.out.println("Sum = "+(a+b));
 }
 void add(int a,int b,int c){
 System.out.println("Sum = "+(a+b+c));
 }
 void add(int a,double b){
 System.out.println("Sum = "+(a+b));
}
}
import java.util.Scanner;
class MatrixSum
{
public static void main(string args[])
{
Scanner sc=new.Sacnner(System.in);
int a[][]=new.int[3][3];
System.out.println("enter the values");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
a[i][j]=sc.nextInt();
}
}
int sum=0;
for(int x[]:a)
{
for(int y:x)
{
sum+=y;
}
}
System.out.println("sum="+sum);
}
}
class Employee{
 private int eno;
 private String name,designation;
 Employee(){
 this.eno=0;
 this.name=this.designation="";
 }
 Employee(int eno,String name,String designation){
 this.eno=eno;
 this.name=name;
 this.designation=designation;
 }
 void setEno(int eno){
 this.eno=eno; 
 }
 void setName(String name){
  this.name=name;
 }
 void setDesignation(String designation){
  this.designation=designation;
 }
 int getEno(){return this.eno;}
 String getName(){return this.name;}
 String getDesignation(){return this.designation;}
}
import java.util.Scanner;
class EmployeeDriver{
 public static void main(String args[]){
 Scanner sc=new Scanner(System.in);
 Employee e1=new Employee();
 System.out.println("Enter Employee 1 Details : ");
 System.out.print("Enter ID : ");
 e1.setEno(sc.nextInt());
 System.out.print("Enter Name : ");
 e1.setName(sc.next());
 System.out.print("Enter Designation : ");
 e1.setDesignation(sc.next());
 System.out.println("Enter Employee 2 Details : ");
 System.out.print("Enter ID : ");
 int e=sc.nextInt();
 System.out.print("Enter Name : ");
 String name=sc.next();
 System.out.print("Enter Designation : ");
 String designation=sc.next();
 Employee e2=new Employee(e,name,designation);
 System.out.println("Employee 1 Details : ");
 System.out.println(e1.getEno()+" "+e1.getName()+" "+e1.getDesignation());
 System.out.println("Employee 2 Details : ");
 System.out.println(e2.getEno()+" "+e2.getName()+" "+e2.getDesignation());
 }
}
function ajax_price()
{


    $product_id = $_GET['product_id'];
    $weight = $_GET['weight'];

    $gold_price_karats = get_post_meta($product_id, 'gold_price_karats', true);
    $extra_fee = get_post_meta($product_id, 'gold_price_product_fee', true);
    $extra_fee = empty($extra_fee) ? 0 : $extra_fee;
    $latest_id = get_latest_id_from_gold_table();
    $record_last = get_gold_record_by_id($latest_id);
    if ($record_last) {

        $weight = empty($weight) ? 1 : $weight;

        $id = $record_last['id'];
        $price_gram_24k = $record_last['price_gram_24k'] * $weight + $extra_fee;
        $price_gram_22k = $record_last['price_gram_22k'] * $weight + $extra_fee;
        $price_gram_21k = $record_last['price_gram_21k'] * $weight + $extra_fee;
        $price_gram_20k = $record_last['price_gram_20k'] * $weight + $extra_fee;
        $price_gram_18k = $record_last['price_gram_18k'] * $weight + $extra_fee;
        $price_gram_16k = $record_last['price_gram_16k'] * $weight + $extra_fee;
        $price_gram_14k = $record_last['price_gram_14k'] * $weight + $extra_fee;
        $price_gram_10k = $record_last['price_gram_10k'] * $weight + $extra_fee;
        $timestamp = $record_last['timestamp'];
        $gold_price_karats = get_post_meta($product_id, 'gold_price_karats', true);
    }

    if ($gold_price_karats == "14k") {
     
        $response = array('price' => $price_gram_14k);
        wp_send_json_success($response);


echo $price_gram_14k;
        // update_post_meta($product_id, 'custom_price_field', $price_gram_14k);


    } elseif ($gold_price_karats == "18k") {
       
        $response = array('price' => $price_gram_18k . " " . "ريال");
        wp_send_json_success($response);

    } elseif ($gold_price_karats == "22k") {

        $response = array('price' => $price_gram_22k . " " . "ريال");
        wp_send_json_success($response);
    } elseif ($gold_price_karats == "24k") {

        $response = array('price' => $price_gram_24k . " " . "ريال");
        wp_send_json_success($response);
    } elseif ($gold_price_karats == "21k") {
 
    $response = array('price' => $price_gram_21k . " " . "ريال");
        wp_send_json_success($response);
    } elseif ($gold_price_karats == "20k") {
  
    $response = array('price' => $price_gram_20k . " " . "ريال");
        wp_send_json_success($response);
    } elseif ($gold_price_karats == "18k") {

 $response = array('price' => $price_gram_18k . " " . "ريال");
        wp_send_json_success($response);
    } elseif ($gold_price_karats == "16k") {
        
 $response = array('price' => $price_gram_16k . " " . "ريال");
        wp_send_json_success($response);
  
    } elseif ($gold_price_karats == "10k") {

$response = array('price' => $price_gram_10k . " " . "ريال");
        wp_send_json_success($response);
    }else{
        $response = array('price' => 0 . " " . "ريال");
        wp_send_json_success($response);
        
        
    }

    wp_die(); // Always use wp_die() after echoing the response.


}
  stroke(0);
  strokeWeight(0.5);
  noFill();
  rect(-width/2+100,-height/2+100,width-200,height-200);
<button onclick="alert('hello')">Click ME</button>
// Online C compiler to run C program online
#include <stdio.h>

int i, j, N;
int T[20];
int main() {

    printf("Entrer la taille du tableau :");
    scanf("%d",&N);

    for(i=0; i<N; i++){
        printf("Entrer l'element T[%d] du tableau :",i);
        scanf("%d",&T[i]);
    }
    
    for(i=0; i<N-1; i++){
        if(T[i+1] != T[i]+1){
        printf("Le tableau ne contient pas des elements consecutifs.");
        return 0;
        }
    }
    
printf("Le tableau a des valeurs consecutifs.");
return 0;
}
use Illuminate\Support\Facades\Schema;
 
/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Schema::defaultStringLength(191);
}
#include <bits/stdc++.h> 
#define int long long
using namespace std;

vector<int> g[100010];
vector<int> vis(1001);

void dfs(int node){
    if(vis[node]) return;
    vis[node] = 1;
    cout << node <<  " ";
    for(int i = 0;i<v[node].size();i++){
        dfs(v[node][i]);
    }
}

int32_t main(){
    int n;
    cin >> n;
    for(int i = 1;i<=n;i++){
        int x,y;
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    dfs(5);
}
LY Sales 2 =

CALCULATE( 
	[Total Sales],
	SAMEPERIODLASTYEAR( 'Calendar'[Date] )
	)
LY Sales 1 =

SUMX ( 
	SAMEPERIODLASTYEAR( ' Calendar'[Date] ),
	[Total Sales]
	)
function(config) { 
   config.defaultGridViewOptions = { 
      footer: false } 
return config; } 
@Composable
fun KeyboardHandlingDemo1() {
  var text by remember { mutableStateOf(TextFieldValue()) }
  Column(
    modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Bottom
  ) {
    Box(
      modifier = Modifier
        .padding(16.dp)
        .fillMaxSize()
        .background(color = MaterialTheme.colors.primary)
        .weight(1.0F),
      contentAlignment = Alignment.BottomCenter
    ) {
      Text(
        modifier = Modifier.padding(bottom = 16.dp),
        text = stringResource(id = R.string.app_name),
        color = MaterialTheme.colors.onPrimary,
        style = MaterialTheme.typography.h5
      )
    }
    TextField(modifier = Modifier.padding(bottom = 16.dp),
      value = text,
      onValueChange = {
        text = it
      })
  }
}
import java.util.Scanner;
class HelloWorld {
    public static void main(String[] args) {
        int month ;
        Scanner r=new Scanner(System.in);
        System.out.println("input month");
        month=r.nextInt();
        
        switch(month)
        {
            case 1:System.out.print("january and days 31");
            break;
            case 2:System.out.print("febuary and days 28");
            break;
            case 3:System.out.println("march and days 31");
            break;
            case 4:System.out.println("april and days 30");
            break;
            case 5:System.out.println("may and days 31");
            break;
            case 6:System.out.println("june and days 30");
            break;
            case 7:System.out.println("july and days 31");
            break;
            case 8:System.out.println("august and days 31");
            break;
            case 9:System.out.println("september and days 30");
            break;
            case 10:System.out.println("october and days 31");
            break;
            case 11:System.out.println("november and days 30");
            break;
            case 12:System.out.println("december and days 31");
            break;
            
            
        }
        
        
        
    }
    
    
}
star

Wed Jan 03 2024 08:37:01 GMT+0000 (Coordinated Universal Time)

@gzmer

star

Wed Jan 03 2024 07:55:22 GMT+0000 (Coordinated Universal Time)

@mricca78 #python #pandas #businesanalytics

star

Wed Jan 03 2024 05:51:05 GMT+0000 (Coordinated Universal Time)

@Alihaan #php

star

Wed Jan 03 2024 05:06:30 GMT+0000 (Coordinated Universal Time)

@agung #aws #ec2 #volume

star

Wed Jan 03 2024 04:23:03 GMT+0000 (Coordinated Universal Time) https://sf.digital/squarespace-solutions/top-css-tweaks-for-squarespace-71

@camikunu14

star

Wed Jan 03 2024 02:30:01 GMT+0000 (Coordinated Universal Time) https://getbootstrap.com/docs/5.0/components/modal/

@misibini13

star

Tue Jan 02 2024 23:29:08 GMT+0000 (Coordinated Universal Time)

@Ravi_solanki

star

Tue Jan 02 2024 22:37:21 GMT+0000 (Coordinated Universal Time)

@elOuahabiKarim

star

Tue Jan 02 2024 18:59:38 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:58:53 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:57:23 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:56:20 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:52:04 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:49:58 GMT+0000 (Coordinated Universal Time)

@TechBox

star

Tue Jan 02 2024 18:01:33 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151 #java

star

Tue Jan 02 2024 15:23:13 GMT+0000 (Coordinated Universal Time) https://trumpexcel.com/hide-formulas-excel/

@darshcode #excel

star

Tue Jan 02 2024 10:46:09 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151 #java

star

Tue Jan 02 2024 09:43:02 GMT+0000 (Coordinated Universal Time)

@eneki #ngrok

star

Tue Jan 02 2024 04:02:11 GMT+0000 (Coordinated Universal Time)

@vs #bash

star

Tue Jan 02 2024 03:58:54 GMT+0000 (Coordinated Universal Time)

@vs #bash

star

Tue Jan 02 2024 00:37:16 GMT+0000 (Coordinated Universal Time)

@mebean

star

Mon Jan 01 2024 23:01:18 GMT+0000 (Coordinated Universal Time)

@mebean #اشعارات

star

Mon Jan 01 2024 22:58:24 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #al

star

Mon Jan 01 2024 22:46:36 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #al

star

Mon Jan 01 2024 22:33:59 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #al

star

Mon Jan 01 2024 22:20:13 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 22:00:19 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 21:55:58 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 21:46:00 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 21:21:29 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 20:27:40 GMT+0000 (Coordinated Universal Time)

@MuriungiMartin #c#

star

Mon Jan 01 2024 19:48:53 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151 #java

star

Mon Jan 01 2024 19:39:37 GMT+0000 (Coordinated Universal Time)

@javaA

star

Mon Jan 01 2024 19:38:49 GMT+0000 (Coordinated Universal Time)

@javaA

star

Mon Jan 01 2024 19:37:37 GMT+0000 (Coordinated Universal Time)

@javaA

star

Mon Jan 01 2024 19:34:29 GMT+0000 (Coordinated Universal Time)

@javaA

star

Mon Jan 01 2024 19:33:33 GMT+0000 (Coordinated Universal Time)

@javaA

star

Mon Jan 01 2024 19:26:49 GMT+0000 (Coordinated Universal Time)

@mebean #اشعارات

star

Mon Jan 01 2024 14:22:39 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Mon Jan 01 2024 14:12:35 GMT+0000 (Coordinated Universal Time)

@bhushan

star

Mon Jan 01 2024 11:34:31 GMT+0000 (Coordinated Universal Time)

@elOuahabiKarim

star

Mon Jan 01 2024 11:07:25 GMT+0000 (Coordinated Universal Time) https://laravel.com/docs/10.x/migrations

@hirsch

star

Mon Jan 01 2024 11:02:28 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@drynor

star

Mon Jan 01 2024 11:01:33 GMT+0000 (Coordinated Universal Time) https://www.programiz.com/cpp-programming/online-compiler/

@drynor

star

Mon Jan 01 2024 08:27:48 GMT+0000 (Coordinated Universal Time)

@Reemhel #sql

star

Mon Jan 01 2024 03:28:44 GMT+0000 (Coordinated Universal Time) https://dev.to/tkuenneth/keyboard-handling-in-jetpack-compose-2593

@iamjasonli

star

Mon Jan 01 2024 00:55:02 GMT+0000 (Coordinated Universal Time) https://www.ip2location.io/#ipl

@etg1 #json

star

Sun Dec 31 2023 22:44:04 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151 #java

Save snippets that work with our extensions

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