Snippets Collections
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey London!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days program is extended through March 2025! With your input, we’ve refined Boost Days to focus on the experiences that bring our Xeros the most enjoyment. To maximise what you love, we’re saying farewell to Afternoon Tea and Wellbeing activities. But don't worry - our awesome Wellbeing team and Wellbeing Champions in each region will continue to offer and promote these initiatives.\n\n*From the week of the 25th of November, here’s what’s changing—and what’s here to stay:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ Same Delicious Meals, Same Great Connections*\nOur Boost Days will continue to offer two meals each week, giving you two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style. Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "cafe-partnership",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Café Partnership*\nContinue to enjoy your favourite café-style beverages from _Vinyl Coffee_, located at 6a Tileyard Rd, London N7 9AH. Simply bring your Xero ID to claim your free beverage. Whether it's a latte, tea, or a hot chocolate, it's the perfect pick-me-up to power through your Boost day!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates.\n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey San Mateo!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days program is extended through March 2025! With your input, we’ve refined Boost Days to focus on the experiences that bring our Xeros the most enjoyment. To maximize what you love, we’re saying farewell to Afternoon Tea and Wellbeing activities. But don't worry - our awesome Wellbeing team and Wellbeing Champions in each region will continue to offer and promote these initiatives.\n\n*From the week of the 25th of November, here’s what’s changing:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ More Meals, More Connections*\nWe’re adding more deliciousness to the menu!\nGet ready for both a breakfast and a light lunch each week.\nNow you'll have two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style. Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "cafe-partnership",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Café Partnership*\nEnjoy Café-style beverages with _The Vineyard Café_ located on the first floor of the 1825 S Grant Building. Grab a latte, tea, or even a hot chocolate to power through your day!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates.\n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "boost_days_heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "boost_days_intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Canberra! \n\nWe’re thrilled to share that Boost Days are here to stay through March 2025! \nThanks to your feedback, we’ll be continuing the Boost Day experience that you’ve enjoyed so far, giving you time to recharge and connect with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "whats_staying",
			"text": {
				"type": "mrkdwn",
				"text": "*You'll Still Enjoy:*\n\n🍽️ *Weekly Meals*: Your Boost Day Lunch will continue as usual, giving you the opportunity to come together for delicious food and great company."
			}
		},
		{
			"type": "section",
			"block_id": "boost_days_impact",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days are all about creating moments to recharge and reconnect, and we’re excited to keep bringing you this experience."
			}
		},
		{
			"type": "section",
			"block_id": "closing_message",
			"text": {
				"type": "mrkdwn",
				"text": "See you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
function slick_cdn_enqueue_scripts(){
    wp_enqueue_style( 'slick-style', '//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css' );
    wp_enqueue_script( 'slick-script', '//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js', array(), null, true );
}
add_action( 'wp_enqueue_scripts', 'slick_cdn_enqueue_scripts' );
<div class="short-desc"><?php the_excerpt(); ?></div>
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":xero-unicorn: Reminder: End of Year Celebration – Registrations :xero-unicorn:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Hi Melbourne!* \n This is your friendly reminder that today is the last day to RSVP for our End of Year event that's only *2 WEEKS AWAY!* If you need a little motivation to RSVP, here's some things we have to look forward to :eyes:"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "plain_text",
				"text": ":saxophone: Entertainment Line Up: We have locked in the INCREDIBLE Ashley James on Saxophone and DJ Jodilly \n\n :cocktail: Enjoy our super shimmery Unicorn Cocktail/Mocktail on entry! \n\n :golf: We'll have LED Mini Golf set up at the venue for some friendly competition \n\n :blinky_stars: Get into the theme and bedazzle yourself with our Self Service Glitter Station! As apart of our sustainablility goals, we've made sure all of the body glitter is biodegradable :sustainability-at-xero:\n\n :pretzel: Help yourselves to the pretzel station set up at the bar! \n\n :icecream: Enjoy a delicious dessert from one of our favourite Xero Customers - 7 Apples Gelato! \n\n :homer_drool: We will have a delectable menu on offer throughout the entire night to keep you fuelled for the dancefloor. \n\n + Soooo much more, we won't spoil the rest :wink:",
				"emoji": true
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"fields": [
				{
					"type": "mrkdwn",
					"text": "*📅 When:*\nThursday 28th November"
				},
				{
					"type": "mrkdwn",
					"text": "*📍 Where:*\n<https://www.google.com/maps/place/The+Timber+Yard/@-37.8331021,144.918894,17z/data=!3m1!4b1!4m6!3m5!1s0x6ad667735e56fcab:0x966480f06c58c00c!8m2!3d-37.8331021!4d144.9214743!16s/g/11gyy7sy4c?entry=ttu&g_ep=EgoyMDI0MDkxOC4xIKXMDSoASAFQAw==/|*The Timber Yard*> \n351 Plummer Street, Port Melbourne"
				},
				{
					"type": "mrkdwn",
					"text": "*⏰ Time:*\n4PM - 10PM"
				}
			]
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*🎟 RSVP Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":question:Got more questions? See the <https://docs.google.com/document/d/1iygJFHgLBRSdAffNsg3PudZCA45w6Wit7xsFxNc_wKM/edit|FAQs> doc or ask away in this thread!\n\n We can’t wait to celebrate with you! :partying_face: :xero-love:"
			}
		}
	]
}
#include <stdio.h> 
#include <unistd.h> // For sleep function 
#include <stdlib.h> 
#define BUCKET_CAPACITY 10 // Maximum capacity of the bucket 
#define LEAK_RATE 1         
second) 
typedef struct { 
// Rate at which the bucket leaks (units per 
int currentWater; // Current amount of water in the bucket 
} LeakyBucket; 
// Initialize the leaky bucket 
void initBucket(LeakyBucket *bucket) { 
bucket->currentWater = 0; 
} 
// Add data to the bucket 
int addWater(LeakyBucket *bucket, int water) { 
if (bucket->currentWater + water > BUCKET_CAPACITY) { 
printf("Bucket overflow! Excess water discarded.\n"); 
return 0; // Overflow occurred 
} 
bucket->currentWater += water; 
printf("Added %d units of water. Current level: %d\n", water, bucket
>currentWater); 
return 1; // Successfully added water 
} 
// Leak water from the bucket 
void leakWater(LeakyBucket *bucket) { 
if (bucket->currentWater > 0) { 
bucket->currentWater -= LEAK_RATE; 
if (bucket->currentWater < 0) { 
bucket->currentWater = 0; // Prevent negative water level 
} 
printf("Leaked 1 unit of water. Current level: %d\n", bucket
>currentWater); 
} 
} 
int main() { 
LeakyBucket bucket; 
initBucket(&bucket); 
// Simulate adding water and leaking over time 
for (int i = 0; i < 15; i++) { 
printf("\nCycle %d:\n", i + 1); 
// Add a random amount of water (1-5 units) 
int waterToAdd = rand() % 5 + 1; 
addWater(&bucket, waterToAdd); 
// Leak water 
leakWater(&bucket); 
// Sleep for 1 second to simulate time passing 
sleep(1); 
} 
return 0; 
} 
Output: 
Cycle 1: 
Added 3 units of water. Current level: 3 
Leaked 1 unit of water. Current level: 2 
Cycle 2: 
Added 1 units of water. Current level: 3 
Leaked 1 unit of water. Current level: 2 
Cycle 3: 
Added 4 units of water. Current level: 6 
Leaked 1 unit of water. Current level: 5 
... 
Cycle 15: 
Added 2 units of water. Current level: 9 
Leaked 1 unit of water. Current level: 8 
#include <stdio.h> #include<stdlib.h> #include<string.h> 
//Functiontoconvertdecimalnumberto8-bitbinarystring 
voiddecimalToBinary(unsignedintdecimal,char*binaryResult){ int i; 
for(i= 7;i>= 0;--i) { 
binaryResult[i]=(decimal%2)+'0'; decimal /= 2; 
} 
binaryResult[8]='\0'; //Null-terminatethebinarystring 
} 
//FunctiontoconvertIPv4addresstobinary void ipToBinary(char *ipAddress) { 
char*token; int octet; 
charbinaryResult[33]; //Buffertostore fullbinaryIP address 
charbinaryOctet[9];//Buffer 
printf("Binary IP address: "); 
tostoreeachoctet's 
binaryrepresentation 
//TokenizetheIPaddressusingstrtok token = strtok(ipAddress, "."); 
while(token!=NULL){ 
octet=atoi(token);//Converttokentointeger if (octet < 0 || octet > 255) { 
printf("InvalidIPaddressformat.\n"); return; 
} 
decimalToBinary(octet, 
binaryOctet); 
// 
Convert 
octet 
strcat(binaryResult,binaryOctet);//Appendbinaryoctettoresult 
strcat(binaryResult, ""); // Add space for readability 
token=strtok(NULL,"."); 
} 
binaryResult[strlen(binaryResult)-1]='\0';//Removelastspace 
binaryResult); // Print the binary IP address 
} 
intmain(){ 
charipAddress[20];//Buffer forIPv4addressinput 
//InputIPv4addressfromuser 
to 
binary 
printf("%s\n", 
printf("EnteranIPv4address(e.g.,300.522.1.203):"); scanf("%19s", ipAddress); 
//CallfunctiontoconvertIPv4 addresstobinary ipToBinary(ipAddress); 
return0; 
} 
Output: 
EnteranIPv4address:300.522.1.203 
BinaryIPaddress:100101100.100001010.00000001.11001011
#include<stdio.h> 
#include<string.h> 
int main() 
{ 
int a[20],b[30],i,j,k,count,n; 
printf("Enter frame size (Example: 8):"); 
scanf("%d",&n); 
printf("Enter the frame in the form of 0 and 1 :"); 
    for(i=0; i<n; i++) 
        scanf("%d",&a[i]); 
    i=0; 
    count=1; 
    j=0; 
    while(i<n) 
    { 
        if(a[i]==1) 
        { 
            b[j]=a[i]; 
            for(k=i+1; a[k]==1 && k<n && count<5; k++) 
            { 
                j++; 
                b[j]=a[k]; 
                count++; 
                if(count==5) 
                { 
                    j++; 
                    b[j]=0; 
                } 
                i=k; 
            } 
        } 
        else 
        { 
            b[j]=a[i]; 
        } 
i++; 
j++; 
} 
printf("After Bit Stuffing :"); 
for(i=0; i<j; i++) 
printf("%d",b[i]); 
return 0; 
} 
Output: Enter frame size (Example: 8):12 
Enter the frame in the form of 0 and 1 :0 1 0 1 1 1 1 1 1 0 0 1 
After Bit Stuffing :0101111101001 
#include<stdio.h> 
int main () 
{ 
char str[100]; 
int n,i,j,c=0,count=0; 
printf ("Enter the String:"); 
scanf ("$s",str); 
printf ("Enter the number of frames:"); 
scanf ("gd",&n); 
int frames [n]; 
printf ("Enter the frames size of the frames:in"); 
for (i=0;i<n;itt) 
{ 
printf ("Frame d:"i); 
scanf ("&d" &frames [i]): 
} 
printf("Frame sd:",i); 
scanf ("&d",&frames[i]); 
} 
printf ("InThe number of frames sd\n",n); 
for (i=0;i<n;itt) 
{ 
printf ("The content of the frame $d:",i); 
j=0; 
while(c<strlen(str) && j<frames[i]) 
{ 
printf("sc",str[c]); 
if(str[c]!="I0") 
{ 
Count ++; 
} 
c=c+1; 
j=j+1; 
} 
printf("InSize of frame &d : &d\n\n",i,count); 
count=0; 
} 
} 
OUTPUT 
Enter the frames size of the frames : 
Frame 0:5 
Frame 1:5 
Frame 2:5 
The number of frames : 
3 
The content of the frame 0:10010 
Size of frame 0 
5 
The content of the frame 1:10101 
Size of frame 1 
5 
The content of the frame 2:01 
Size of frame 2 2    
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
//Functiontoconvertbinarytooctalfor 
a 
binaryToOctalForOctet(int binaryNumber) { 
int octalNumber=0,decimalNumber=0,i=0; 
single 
//Convertbinarytodecimal while(binaryNumber!=0){ 
decimalNumber+=(binaryNumber%10)*(1<<i); 
++i; 
binaryNumber/= 10; 
} 
i= 1; 
// Convert decimal to octal while(decimalNumber!=0){ 
octet(8bits) 
octalNumber+=(decimalNumber%8)*i; decimalNumber /= 8; 
i*=10; 
} 
returnoctalNumber; 
} 
//FunctiontoconvertbinaryIPaddresstooctal 
void 
int 
binaryIPToOctal(char 
binaryIP[]) { 
inti,octet,octal; char *ptr; 
//SplitbinaryIP intooctetsandconverteachoctet printf("Octal IP address: "); 
for(i= 0;i<32;i+= 8) { 
octet = strtol(binaryIP + i, &ptr, 2); octal=binaryToOctalForOctet(octet); 
printf("%d", octal); 
if (i < 24) { printf("."); 
} 
} 
printf("\n"); 
} 
intmain(){ 
charbinaryIP[33];//Assuming IPv4addressinbinaryform 
// Input binary IP address from user printf("EnterabinaryIPv4address(32bits):"); 
scanf("%32s", binaryIP); 
//CallfunctiontoconvertbinaryIPtooctal binaryIPToOctal(binaryIP); 
return0; 
} 
Output: 
EnterabinaryIPv4address(32bits):11000000101010000000000100000011   
Octal IP address: 300.522.1.203
{
"key": "run",
"url": "https://manager.qualifio.com/library/stefano_0/images/2023/runner-adidas2.png",
"type": "image",
"width": 1140,
"config": {
"yoyo": false,
"repeat": -1,
"frameRate": 10
},
"height": 382,
"frameNumber": 4,
"percentPropHeightCompareToBG": 0.27,
"percentPropWidthCompareToGameWidth": 0.27
},
#update
sudo apt-get update || true && sudo apt-get upgrade -y || true

#dependencies 
sudo apt-get install gnupg1

#add webmin repo
echo "deb http://download.webmin.com/download/repository sarge contrib" | sudo tee /etc/apt/sources.list.d/webmin.list

#add pgp key
sudo mkdir -p /etc/apt/keyrings
wget -qO- http://www.webmin.com/jcameron-key.asc | gpg --dearmor | sudo tee /etc/apt/keyrings/webmin.gpg > /dev/null

echo "deb [signed-by=/etc/apt/keyrings/webmin.gpg] http://download.webmin.com/download/repository sarge contrib" | sudo tee /etc/apt/sources.list.d/webmin.list


#install Webmin
sudo apt-get update || true && sudo apt-get upgrade -y || true
sudo apt-get install webmin -y || true

#enable firewall
sudo ufw allow 10000

#to use webman navigate to https://your_server_ip:10000 in web browser 
#replace "your_server_ip" with servers ip. 
<!-- RANGESLIDER SCRIPT-->

<script>
/*! rangeslider.js - v0.3.7 | (c) 2014 @andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */ ! function(a) {
    "use strict";
    "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery)
}(function(a) {
    "use strict";

    function b() {
        var a = document.createElement("input");
        return a.setAttribute("type", "range"), "text" !== a.type
    }

    function c(a, b) {
        var c = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function() {
            return a.apply(null, c)
        }, b)
    }

    function d(a, b) {
        return b = b || 100,
            function() {
                if (!a.debouncing) {
                    var c = Array.prototype.slice.apply(arguments);
                    a.lastReturnVal = a.apply(window, c), a.debouncing = !0
                }
                return clearTimeout(a.debounceTimeout), a.debounceTimeout = setTimeout(function() {
                    a.debouncing = !1
                }, b), a.lastReturnVal
            }
    }

    function e(a) {
        return 0 !== a.offsetWidth || 0 !== a.offsetHeight ? !1 : !0
    }

    function f(a) {
        for (var b = [], c = a.parentNode; e(c);) b.push(c), c = c.parentNode;
        return b
    }

    function g(a, b) {
        var c = f(a),
            d = c.length,
            e = [],
            g = a[b];
        if (d) {
            for (var h = 0; d > h; h++) e[h] = c[h].style.display, c[h].style.display = "block", c[h].style.height = "0", c[h].style.overflow = "hidden", c[h].style.visibility = "hidden";
            g = a[b];
            for (var i = 0; d > i; i++) c[i].style.display = e[i], c[i].style.height = "", c[i].style.overflow = "", c[i].style.visibility = ""
        }
        return g
    }

    function h(b, e) {
        if (this.$window = a(window), this.$document = a(document), this.$element = a(b), this.options = a.extend({}, m, e), this._defaults = m, this._name = i, this.startEvent = this.options.startEvent.join("." + i + " ") + "." + i, this.moveEvent = this.options.moveEvent.join("." + i + " ") + "." + i, this.endEvent = this.options.endEvent.join("." + i + " ") + "." + i, this.polyfill = this.options.polyfill, this.onInit = this.options.onInit, this.onSlide = this.options.onSlide, this.onSlideEnd = this.options.onSlideEnd, this.polyfill && l) return !1;
        this.identifier = "js-" + i + "-" + k++, this.min = parseFloat(this.$element[0].getAttribute("min") || 0), this.max = parseFloat(this.$element[0].getAttribute("max") || 100), this.value = parseFloat(this.$element[0].value || this.min + (this.max - this.min) / 2), this.step = parseFloat(this.$element[0].getAttribute("step") || 1), this.toFixed = (this.step + "").replace(".", "").length - 1, this.$fill = a('<div class="' + this.options.fillClass + '" />'), this.$handle = a('<div class="' + this.options.handleClass + '" />'), this.$range = a('<div class="' + this.options.rangeClass + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle), this.$element.css({
            position: "absolute",
            width: "1px",
            height: "1px",
            overflow: "hidden",
            opacity: "0"
        }), this.handleDown = a.proxy(this.handleDown, this), this.handleMove = a.proxy(this.handleMove, this), this.handleEnd = a.proxy(this.handleEnd, this), this.init();
        var f = this;
        this.$window.on("resize." + i, d(function() {
            c(function() {
                f.update()
            }, 300)
        }, 20)), this.$document.on(this.startEvent, "#" + this.identifier + ":not(." + this.options.disabledClass + ")", this.handleDown), this.$element.on("change." + i, function(a, b) {
            if (!b || b.origin !== i) {
                var c = a.target.value,
                    d = f.getPositionFromValue(c);
                f.setPosition(d)
            }
        })
    }
    var i = "rangeslider",
        j = [],
        k = 0,
        l = b(),
        m = {
            polyfill: !0,
            rangeClass: "rangeslider",
            disabledClass: "rangeslider--disabled",
            fillClass: "rangeslider__fill",
            handleClass: "rangeslider__handle",
            startEvent: ["mousedown", "touchstart", "pointerdown"],
            moveEvent: ["mousemove", "touchmove", "pointermove"],
            endEvent: ["mouseup", "touchend", "pointerup"]
        };
    h.prototype.init = function() {
        this.onInit && "function" == typeof this.onInit && this.onInit(), this.update()
    }, h.prototype.update = function() {
        this.handleWidth = g(this.$handle[0], "offsetWidth"), this.rangeWidth = g(this.$range[0], "offsetWidth"), this.maxHandleX = this.rangeWidth - this.handleWidth, this.grabX = this.handleWidth / 2, this.position = this.getPositionFromValue(this.value), this.$element[0].disabled ? this.$range.addClass(this.options.disabledClass) : this.$range.removeClass(this.options.disabledClass), this.setPosition(this.position)
    }, h.prototype.handleDown = function(a) {
        if (a.preventDefault(), this.$document.on(this.moveEvent, this.handleMove), this.$document.on(this.endEvent, this.handleEnd), !((" " + a.target.className + " ").replace(/[\n\t]/g, " ").indexOf(this.options.handleClass) > -1)) {
            var b = this.getRelativePosition(a),
                c = this.$range[0].getBoundingClientRect().left,
                d = this.getPositionFromNode(this.$handle[0]) - c;
            this.setPosition(b - this.grabX), b >= d && b < d + this.handleWidth && (this.grabX = b - d)
        }
    }, h.prototype.handleMove = function(a) {
        a.preventDefault();
        var b = this.getRelativePosition(a);
        this.setPosition(b - this.grabX)
    }, h.prototype.handleEnd = function(a) {
        a.preventDefault(), this.$document.off(this.moveEvent, this.handleMove), this.$document.off(this.endEvent, this.handleEnd), this.onSlideEnd && "function" == typeof this.onSlideEnd && this.onSlideEnd(this.position, this.value)
    }, h.prototype.cap = function(a, b, c) {
        return b > a ? b : a > c ? c : a
    }, h.prototype.setPosition = function(a) {
        var b, c;
        b = this.getValueFromPosition(this.cap(a, 0, this.maxHandleX)), c = this.getPositionFromValue(b), this.$fill[0].style.width = c + this.grabX + "px", this.$handle[0].style.left = c + "px", this.setValue(b), this.position = c, this.value = b, this.onSlide && "function" == typeof this.onSlide && this.onSlide(c, b)
    }, h.prototype.getPositionFromNode = function(a) {
        for (var b = 0; null !== a;) b += a.offsetLeft, a = a.offsetParent;
        return b
    }, h.prototype.getRelativePosition = function(a) {
        var b = this.$range[0].getBoundingClientRect().left,
            c = 0;
        return "undefined" != typeof a.pageX ? c = a.pageX : "undefined" != typeof a.originalEvent.clientX ? c = a.originalEvent.clientX : a.originalEvent.touches && a.originalEvent.touches[0] && "undefined" != typeof a.originalEvent.touches[0].clientX ? c = a.originalEvent.touches[0].clientX : a.currentPoint && "undefined" != typeof a.currentPoint.x && (c = a.currentPoint.x), c - b
    }, h.prototype.getPositionFromValue = function(a) {
        var b, c;
        return b = (a - this.min) / (this.max - this.min), c = b * this.maxHandleX
    }, h.prototype.getValueFromPosition = function(a) {
        var b, c;
        return b = a / (this.maxHandleX || 1), c = this.step * Math.round(b * (this.max - this.min) / this.step) + this.min, Number(c.toFixed(this.toFixed))
    }, h.prototype.setValue = function(a) {
        a !== this.value && this.$element.val(a).trigger("change", {
            origin: i
        })
    }, h.prototype.destroy = function() {
        this.$document.off(this.startEvent, "#" + this.identifier, this.handleDown), this.$element.off("." + i).removeAttr("style").removeData("plugin_" + i), this.$range && this.$range.length && this.$range[0].parentNode.removeChild(this.$range[0]), j.splice(j.indexOf(this.$element[0]), 1), j.length || this.$window.off("." + i)
    }, a.fn[i] = function(b) {
        return this.each(function() {
            var c = a(this),
                d = c.data("plugin_" + i);
            d || (c.data("plugin_" + i, d = new h(this, b)), j.push(this)), "string" == typeof b && d[b]()
        })
    }
});
</script>

<!-- EDIT SLIDER PARAMETERS-->

<script>
    $('#ranger').change(function(){
        console.log($('#ranger').val());
        if($('#ranger').val() === '1'){
            $('.pricing-card').removeClass('active-1 active-2 active-3 display-hidden');
            $('.pricing-card').addClass('active-1');
        } else if($('#ranger').val() === '2'){
            $('.pricing-card').removeClass('active-1 active-2 active-3');
            $('.pricing-card').addClass('active-2 display-hidden');
        } else if($('#ranger').val() === '3'){
            $('.pricing-card').removeClass('active-1 active-2 active-3');
            $('.pricing-card').addClass('active-3 display-hidden');
        }
    })
    
    
  $( document ).ready(function() {
  // Handler for .ready() called.
    $('.slide').removeClass('active');
  });
  $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle',
      onInit: function() {

      },
      onSlide: function(position, value) {
          $('.rangeslider__handle').attr('data-content', value);
          $('.done').removeClass('active');
          $('.slide').addClass('active');
      },
      onSlideEnd: function(position, value) {
        $('.done').addClass('active');
        $('.slide').removeClass('active');
      }
  });
  
  </script>
  
<!-- Set the initial value for the range input element -->
<input id="ranger" type="range" min="1" max="3" step="1" value="2">

<script>
  $(document).ready(function() {
    // Set the default slider position to 2nd point
    $('#ranger').val(2).change(); // This sets the handle to the value '2' on load
    
    // Initialize the rangeslider plugin
    $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle',
      onInit: function() {
        // Sync initial handle position
        $('.rangeslider__handle').attr('data-content', $('#ranger').val());
      },
      onSlide: function(position, value) {
        $('.rangeslider__handle').attr('data-content', value);
        $('.done').removeClass('active');
        $('.slide').addClass('active');
      },
      onSlideEnd: function(position, value) {
        $('.done').addClass('active');
        $('.slide').removeClass('active');
      }
    });
  });
</script>
code --extensions-dir <dir>
    Set the root path for extensions.
code --list-extensions
    List the installed extensions.
code --show-versions
    Show versions of installed extensions, when using --list-extension.
code --install-extension (<extension-id> | <extension-vsix-path>)
    Installs an extension.
code --uninstall-extension (<extension-id> | <extension-vsix-path>)
    Uninstalls an extension.
code --enable-proposed-api (<extension-id>)
    Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.

Copy
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/auth/domains/models/auth_model.dart';
import 'package:rrispat_app/src/shared/shared_views.dart';
import 'package:rrispat_app/src/shared/widgets/rr_header.dart';

import '../../controllers/auth_controller.dart';

class AddUserWidget extends ConsumerStatefulWidget {
  const AddUserWidget({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AddUserPageState();
}

class _AddUserPageState extends ConsumerState<AddUserWidget> {
  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController fullNameController = TextEditingController();
  final _gKey = GlobalKey<FormState>();
  String code = "";

  AuthModel authModel = AuthModel(
    uid: "",
    fcmToken: "",
    phoneNumber: "",
    fullName: "",
    division: "",
    department: "",
    isActive: true,
    isDefaultPin: true,
    isSuperAdmin: false,
    devices: const [],
    deviceHistory: const [],
    apps: const [],
    createdAt: DateTime.now(),
    updatedAt: DateTime.now(),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const RRHeader(),
      body: Padding(
        padding: const EdgeInsets.all(5.0),
        child: Form(
          key: _gKey,
          child: ListView(
            children: [
              const SizedBox(
                height: 10,
              ),
              fullNameWidget(),
              const SizedBox(
                height: 10,
              ),
              phoneWidget(),
              FilledButton(
                onPressed: () {
                  if (_gKey.currentState!.validate()) {
                    createUser(
                      context,
                      authModel.copyWith(
                        fullName: fullNameController.text,
                        phoneNumber: code + phoneNumberController.text,
                      ),
                    );
                  }
                },
                child: const Text("Submit"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget fullNameWidget() {
    return TextFormField(
      controller: fullNameController,
      keyboardType: TextInputType.text,
      style: Theme.of(context).textTheme.titleMedium,
      textCapitalization: TextCapitalization.words,
      decoration: InputDecoration(
        hintText: "Enter Full Name",
        label: const Text("Full Name"),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return "Enter Full Name";
        }
        return null;
      },
    );
  }

  Widget phoneWidget() {
    return TextFormField(
      controller: phoneNumberController,
      keyboardType: TextInputType.phone,
      maxLength: 10,
      style: Theme.of(context).textTheme.titleMedium,
      decoration: InputDecoration(
        prefix: const Text("+91"),
        hintText: "Enter Phone Number",
        label: const Text("Phone Number"),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return "Enter a valid PhoneNumber";
        } else if (value.length < 10) {
          return "Phone Number length must be 10";
        }
        return null;
      },
    );
  }

  Future<void> createUser(BuildContext context, AuthModel auth) async {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("Confirm User",
              style: Theme.of(context).textTheme.titleLarge),
          content: SizedBox(
            height: 100,
            child: Column(
              children: [
                const SizedBox(
                  height: 10,
                ),
                Table(
                  children: [
                    TableRow(children: [
                      TableCell(
                          child: Text("Full Name",
                              style: Theme.of(context).textTheme.labelLarge)),
                      TableCell(
                          child: Text(auth.fullName,
                              style: Theme.of(context).textTheme.bodyMedium)),
                    ]),
                    TableRow(children: [
                      TableCell(
                          child: Text("Phone Number",
                              style: Theme.of(context).textTheme.labelLarge)),
                      TableCell(
                          child: Text(auth.phoneNumber,
                              style: Theme.of(context).textTheme.bodyMedium)),
                    ]),
                  ],
                ),
                const SizedBox(
                  height: 30,
                ),
              ],
            ),
          ),
          actions: [
            OutlinedButton(
                onPressed: () {
                  context.pop(true);
                },
                child: Text("Cancel",
                    style: Theme.of(context).textTheme.titleMedium)),
            ElevatedButton(
                onPressed: () {
                  ref.read(authControllerProvider).createUser(ref, auth);
                  context.goNamed(HomeView.routeName);
                },
                child: Text("Confirm",
                    style: Theme.of(context).textTheme.titleMedium))
          ],
        );
      },
    );
  }
}
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { HttpService, } from '@nestjs/axios';
import * as dayjs from 'dayjs';
import { AxiosResponse } from 'axios';
import { log } from 'console';
import * as https from 'https'; 

@Injectable()
export class DailyEquityService {
  private readonly spotwareApiUrl: string;
  private readonly apiToken: string;
  private readonly xanoEquityUrl: string;
  private readonly logger = new Logger(DailyEquityService.name);
  private lastFetchedData: any[] = [];

  constructor(private readonly httpService: HttpService) {
    this.spotwareApiUrl = process.env.SPOTWARE_API_URL;
    this.apiToken = process.env.SPOTWARE_API_TOKEN;
    this.xanoEquityUrl = process.env.XANO_API_EQUITYURL;
  
  this.httpService.axiosRef.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false });
  }
  // Fetch daily equity data from external service
  async fetchDailyEquityData(fromDate: string, toDate: string) {
    this.logger.log(`Fetching daily equity data from Spotware for date range ${fromDate} to ${toDate}`);

    try {
      const response: AxiosResponse = await this.httpService
        .get(`${this.spotwareApiUrl}/v2/webserv/traders/`, {
          params: {
            from: fromDate,
            to: toDate,
            fields: 'login,balance,minEquityDaily,maxEquityDaily',
            token: this.apiToken,
          },
        })
        .toPromise();

      if (response.status !== 200) {
        throw new Error(`Unexpected status code: ${response.status}`);
      }

      const mappedData = response.data.trader.map((trader) => ({
        account: trader.login,
        starting_daily_equity: trader.balance.toString(),
        sde_date: dayjs().format('YYYY-MM-DD'),
        gmt_date: dayjs().toISOString(),
        created_at: dayjs().toISOString(),
        status: 'pending',
        trading_days: '0',
        challenge_begins: dayjs().subtract(30, 'days').format('YYYY-MM-DD'),
        new_status: 'pending',
      }));

      this.logger.log('Successfully fetched and mapped daily equity data');
      return mappedData;
    } catch (error) {
      this.logger.error(`Error fetching daily equity data: ${error.message}`);
      throw new HttpException(`Failed to fetch daily equity data: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // Check if data exists in Xano, and then update or create as needed
  async checkAndUpdateDailyEquityInXano(equityData: any[]) {
    this.logger.log('Starting Xano data check and update process');

    // Log to check the equityData content
    this.logger.debug(`Received equityData: ${JSON.stringify(equityData)}`);
    
    const results = [];

    if (!equityData || equityData.length === 0) {
        this.logger.warn('No equity data to process. Exiting function.');
        return results; // Return early if there is no data
    }

    for (const data of equityData) {
      try {
        this.logger.debug(`Processing account: ${data.account}`);
        console.log(`${this.xanoEquityUrl}/${data.account}/`,"hyhy");
        const existingDataResponse = await this.httpService
          .get(`${this.xanoEquityUrl}/${data.account}/`, {
            headers: { 'Content-Type': 'application/json' },
          })
          .toPromise();
        
        this.logger.debug(`Received response for account ${data.account}: ${JSON.stringify(existingDataResponse.data)}`);

        if (existingDataResponse.status === 200) {
          this.logger.log(`Account ${data.account} exists in Xano, updating record`);

          const updateResponse = await this.httpService
            .patch(`${this.xanoEquityUrl}/${data.account}`, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Update response for account ${data.account}: ${JSON.stringify(updateResponse.data)}`);
          results.push(updateResponse.data);
        } else {
          this.logger.log(`Account ${data.account} does not exist, creating new record`);

          const createResponse = await this.httpService
            .post(this.xanoEquityUrl, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Create response for account ${data.account}: ${JSON.stringify(createResponse.data)}`);
          results.push(createResponse.data);
        }
      } catch (error) {
        if (error.response?.status === 404) {
          this.logger.log(`Account ${data.account} not found in Xano, creating new record`);

          const createResponse = await this.httpService
            .post(this.xanoEquityUrl, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Create response for account ${data.account}: ${JSON.stringify(createResponse.data)}`);
          results.push(createResponse.data);
        } else {
          this.logger.error(`Failed to process account ${data.account}: ${error.message}`);
          throw new HttpException(`Failed to process account ${data.account}: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
    }

    this.logger.log('Completed Xano data check and update process');
    return results;
  }


  // Update the equity for traders daily
  async updateDailyEquityForTraders() {
    const fromDate = dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS');
    const toDate = dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS');

    this.logger.log(`Starting daily equity update for traders from ${fromDate} to ${toDate}`);

    try {
      const equityData = await this.fetchDailyEquityData(fromDate, toDate);

      if (this.hasDataChanged(equityData)) {
        this.logger.log('Data has changed; proceeding with update');
        const result = await this.checkAndUpdateDailyEquityInXano(equityData);
        this.lastFetchedData = equityData;  // Update the cache
        return result;
      } else {
        this.logger.log('No changes in data; skipping Xano update');
        return { message: 'No changes detected; update skipped.' };
      }
    } catch (error) {
      this.logger.error(`Failed to update daily equity for traders: ${error.message}`);
      throw new HttpException(`Failed to update daily equity for traders: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  private hasDataChanged(newData: any[]): boolean {
    return JSON.stringify(this.lastFetchedData) !== JSON.stringify(newData);
  }
}
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
insmod part_gpt
insmod part_msdos
if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="0"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_gpt
insmod ext2
search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=3840x2160,auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=en_US
  insmod gettext
fi
terminal_input console
terminal_output gfxterm
insmod part_gpt
insmod ext2
search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
insmod gfxmenu
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_12.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_14.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_16.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_24.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_32.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_48.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-12.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-14.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-16.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-18.pf2
insmod jpeg
insmod png
set theme=($root)/usr/share/grub/themes/stylish/theme.txt
export theme
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Arch GNU Plus Linux' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-b9549161-95f2-47de-a863-c97513774fe7' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
        echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
        GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
        echo    'Loading initial ramdisk ...'
        initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface.img
}
submenu 'Advanced options for Arch GNU Plus Linux' $menuentry_id_option 'gnulinux-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux-surface' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-surface-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux-surface (fallback initramfs)' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-surface-fallback-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface-fallback.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux (fallback initramfs)' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-fallback-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-fallback.img
        }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/30_uefi-firmware ###
if [ "$grub_platform" = "efi" ]; then
        fwsetup --is-supported
        if [ "$?" = 0 ]; then
                menuentry 'UEFI Firmware Settings' $menuentry_id_option 'uefi-firmware' {
                        fwsetup
                }
        fi
fi
### END /etc/grub.d/30_uefi-firmware ###

### BEGIN /etc/grub.d/35_fwupd ###
### END /etc/grub.d/35_fwupd ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg
fi
### END /etc/grub.d/41_custom ###

### BEGIN /etc/grub.d/60_memtest86+-efi ###
if [ "${grub_platform}" == "efi" ]; then
    menuentry "Memory Tester (memtest86+)" --class memtest86 --class gnu --class tool {
        if loadfont unicode ; then
            set gfxmode=1024x768,800x600,auto
            set gfxpayload=800x600,1024x768
            terminal_output gfxterm
        fi
        search --fs-uuid --no-floppy --set=root  b9549161-95f2-47de-a863-c97513774fe7
        GNU Plus Linux /boot/memtest86+/memtest.efi 
    }
fi
### END /etc/grub.d/60_memtest86+-efi ###
 public NW_GeneralResponse CreatePartialInvoice(PurchId PurchId, ProductReceiptId PackingSlipId, Num InvoiceNum, TransDate InvoiceDate)
 {
     VendPackingSlipJour vendPackingSlipJour;
     PurchFormLetter purchFormLetter;
     PurchTable  purchTable;
     PurchLine purchLine;
     VendPackingSlipTrans vendPackingSlipTrans;

     VendInvoiceInfoTable vendInvoiceInfoTable, vendInvoiceInfoTable2, vendInvoiceInfoTable3;
     VendInvoiceInfoLine vendInvoiceInfoLine;
     VendInvoiceInfoSubTable vendInvoiceInfoSubTable;
     VendInvoiceInfoSubLine vendInvoiceInfoSubLine;

     InvoiceId invoiceId;
     TransDate _invoiceDate;

     VendInvoiceJour vendInvoiceJour;
     InventTrans inventTransQty;
     str Log;
     boolean Result;
     List Errors;
     NW_GeneralResponse Response = new NW_GeneralResponse();

     ;
     changecompany('shc')
     {
        
         select vendPackingSlipJour 
             where vendPackingSlipJour.PurchId == PurchId
             && vendPackingSlipJour.PackingSlipId == PackingSlipId;

         while select vendInvoiceInfoTable2
             where vendInvoiceInfoTable2.InvoiceAccount == vendPackingSlipJour.InvoiceAccount
             && vendInvoiceInfoTable2.PurchId == PurchId
         {
             if(vendInvoiceInfoTable2.packingSlipId(vendInvoiceInfoTable2) == PackingSlipId)
             {
                 Result = false;
                 Response.ParmResult(Result);
                 Response.ParmMsg("You have already Invoice with this Product Receipt.");
                 Response.ParmErrors(Errors);
                 return Response;
             }
         }


         ttsBegin;
         if(vendPackingSlipJour.PackingSlipId)
         {
             invoiceId = InvoiceNum; //strFmt("INV-%1", vendPackingSlipJour.PackingSlipId);

             _invoiceDate = InvoiceDate;//DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());

             purchTable = vendPackingSlipJour.purchTable();
             //Generate Pending Invoice Header
             vendInvoiceInfoTable.clear();
             vendInvoiceInfoTable.initValue();
             vendInvoiceInfoTable.initFromPurchTable(purchTable);

             vendInvoiceInfoTable.ParmId = FormletterParmData::getNewParmId();

             vendInvoiceInfoTable.DocumentOrigin = DocumentOrigin::Manual;
             vendInvoiceInfoTable.CurrencyCode = purchTable.CurrencyCode;
             vendInvoiceInfoTable.DeliveryName = purchTable.DeliveryName;
             vendInvoiceInfoTable.Num = invoiceId;
             vendInvoiceInfoTable.PurchName = purchTable.PurchName;
             vendInvoiceInfoTable.VendInvoiceSaveStatus = VendInvoiceSaveStatus::Pending;
             vendInvoiceInfoTable.TransDate = _invoiceDate;
             vendInvoiceInfoTable.DocumentDate = _invoiceDate;
             vendInvoiceInfoTable.LastMatchVariance = LastMatchVarianceOptions::OK;
             vendInvoiceInfoTable.ParmJobStatus = ParmJobStatus::Waiting;

             vendInvoiceInfoTable.DefaultDimension = vendInvoiceInfoTable.copyDimension(purchTable.DefaultDimension);
             vendInvoiceInfoTable.defaultRow(purchTable);
             vendInvoiceInfoTable.insert();

             //Generate Vend Invoice Info reference
             if(vendInvoiceInfoTable)
             {
                 vendInvoiceInfoSubTable.clear();
                 vendInvoiceInfoSubTable.initValue();
                 vendInvoiceInfoSubTable.defaultRow();

                 vendInvoiceInfoSubTable.ParmId = vendInvoiceInfoTable.ParmId;
                 vendInvoiceInfoSubTable.OrigPurchId = vendInvoiceInfoTable.PurchId;
                 vendInvoiceInfoSubTable.PurchName = vendInvoiceInfoTable.PurchName;
                 vendInvoiceInfoSubTable.TableRefId = vendInvoiceInfoTable.TableRefId;

                 vendInvoiceInfoSubTable.insert();
             }

             //select all packing slip line
             while select vendPackingSlipTrans
                 where vendPackingSlipTrans.PackingSlipId == vendPackingSlipJour.PackingSlipId
                 && vendPackingSlipTrans.VendPackingSlipJour == vendPackingSlipJour.RecId
             {
                 //Generate Pending Invoice Line
                 purchLine = vendPackingSlipTrans.purchLine();
                 vendInvoiceInfoLine.clear();
                 vendInvoiceInfoLine.initValue();
                 // vendInvoiceInfoLine.defaultRow(null,purchLine);
                 vendInvoiceInfoLine.initFromPurchLine(purchLine);

                 vendInvoiceInfoLine.DeliveryName = vendInvoiceInfoTable.DeliveryName;
                 vendInvoiceInfoLine.ParmId = vendInvoiceInfoTable.ParmId;
                 vendInvoiceInfoLine.TableRefId = vendInvoiceInfoTable.TableRefId;
                 vendInvoiceInfoLine.currencyCode = vendInvoiceInfoTable.CurrencyCode;
                 vendInvoiceInfoLine.LineNum = any2int(purchLine.LineNumber);

                 vendInvoiceInfoLine.InvoiceAccount = vendInvoiceInfoTable.InvoiceAccount;
                 vendInvoiceInfoLine.InventDimId = vendPackingSlipTrans.InventDimId;
                 vendInvoiceInfoLine.OrderAccount = vendInvoiceInfoTable.OrderAccount;
                 vendInvoiceInfoLine.ItemId = vendPackingSlipTrans.ItemId;
                 vendInvoiceInfoLine.InventTransId = vendPackingSlipTrans.InventTransId;

                 vendInvoiceInfoLine.DocumentOrigin = DocumentOrigin::Manual;
                 vendInvoiceInfoLine.ReceiveNow = vendPackingSlipTrans.Qty;

                 vendInvoiceInfoLine.modifiedReceiveNow();

                 vendInvoiceInfoLine.PurchPrice = purchLine.PurchPrice;
                 vendInvoiceInfoLine.InventNow = vendInvoiceInfoLine.ReceiveNow;
                 if(purchLine.PurchQty != 0)
                 {
                     vendInvoiceInfoLine.LineAmount = (purchLine.LineAmount / purchLine.PurchQty) * vendInvoiceInfoLine.ReceiveNow;
                 }

                 vendInvoiceInfoLine.DefaultDimension = purchLine.DefaultDimension;

                 vendInvoiceInfoLine.insert();

                 //Generate Vend Invoice Info reference from packing slip
                 if(vendInvoiceInfoLine.RecId)
                 {
                     vendInvoiceInfoSubLine.clear();
                     vendInvoiceInfoSubLine.initValue();
                     vendInvoiceInfoSubLine.defaultRow();
                     vendInvoiceInfoSubLine.ParmId = vendInvoiceInfoTable.ParmId;
                     vendInvoiceInfoSubLine.LineRefRecId = vendInvoiceInfoLine.RecId;
                     vendInvoiceInfoSubLine.ReceiveNow = vendInvoiceInfoLine.ReceiveNow;
                     vendInvoiceInfoSubLine.InventNow = vendInvoiceInfoLine.InventNow ;
                     vendInvoiceInfoSubLine.JournalRefRecId = vendPackingSlipTrans.RecId;
                     vendInvoiceInfoSubLine.JournalRefTableId = vendPackingSlipTrans.TableId;
                     vendInvoiceInfoSubLine.DocumentId = vendPackingSlipTrans.PackingSlipId;
                     vendInvoiceInfoSubLine.insert();
                 }
             }
             ttsCommit;
             Response.ParmResult(true);
             Response.ParmMsg(strFmt("Invoice %1 has been Created for Purchase order %2 with Product Receipt %3",invoiceId, purchTable.PurchId, PackingSlipId));
             //Posting pending invoice invoice
             //purchFormLetter = PurchFormLetter_Invoice::newFromSavedInvoice(vendInvoiceInfoTable);
             //purchFormLetter.update(vendInvoiceInfoTable.purchTable(),vendInvoiceInfoTable.Num);
         }
         else
         {
             Response.ParmResult(false);
             Response.ParmMsg(strFmt("Can't found Product Receipt %1", PackingSlipId));
         }

         
         return Response;
     }
 }
var GroupUtil = Class.create();
GroupUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    //To check unique name of group
    isGroupNameUnique: function() {
        var g_name = this.getParameter('sysparam_gname');
        var grname = new GlideRecord('sys_user_group');
        grname.addQuery('name', g_name);
        grname.query();

        if (grname.next())
            return true;
    },


    //Update Support Group auto populate details
    GroupAutoPopulateDetails: function() {

        var result = this.newItem("result");
        var group_name = this.getParameter('sysparm_group');
        var grname = group_name.toString();
        var gr_detail = new GlideRecord('sys_user_group');
        gr_detail.addQuery('sys_id', grname);
        gr_detail.query();
        if (gr_detail.next()) {
            return gr_detail.name + ';' + gr_detail.description + ';' + gr_detail.parent + ';' + gr_detail.manager + ';' + gr_detail.u_manager_backup + ';' + gr_detail.type + ';' + gr_detail.email + ';' + gr_detail.u_notifications_when_tickets_assigned + ';' + gr_detail.u_is_on_call + ';' + gr_detail.u_on_call_phone_no + ';' + gr_detail.u_hours_when_on_call + ';' + gr_detail.u_day_when_on_call + ';' + gr_detail.u_region + ';' + gr_detail.u_is_support_group + ';' + gr_detail.u_phone_number + ';' + gr_detail.u_phone_no_justification;
        }
    },

    //get members from group auto populate;
    GetMembersFromGroup: function(grp) {
        var group_id = this.getParameter('sysparm_grp');
        var member = [];
        var gp = grp;
        var grUser = new GlideRecord('sys_user_grmember');
        grUser.addQuery('group', group_id);
        grUser.query();
        while (grUser.next()) {
            member.push(grUser.getValue('user').toString());
        }
        return member.join(',');
    },

    //Update SG Supported CI Auto Populate
    ToGetSupportedCI: function() {

        var group_id = this.getParameter('sysparm_grp');
        var CI = [];
        var grUser = new GlideRecord('cmdb_ci');
        grUser.addQuery('managed_by_group', group_id);
        grUser.query();
        while (grUser.next()) {
            CI.push(grUser.getValue('sys_id').toString());
        }
        return CI.join(',');
    },

    //get row count
    GetRowCount: function() {
        var group_id = this.getParameter('sysparm_grp');
        var grtask = new GlideAggregate('task');
        grtask.addQuery('assignment_group', group_id);
        grtask.addQuery('active', true);
        grtask.addAggregate('COUNT');
        grtask.query();
        var task = 0;
        if (grtask.next()) {
            task = grtask.getAggregate('COUNT');
            gs.log('Active task count: ' + task);
        }
        return task;
    },

    //To Check user membership and Primary group
    checkprimarygroup: function() {

        var groupID = this.getParameter('sysparm_gp');
        var usrID = gs.getUserID(); //Get current user ID	
        var returnval = 0;


        var groupGr = new GlideRecord('sys_user_group');
        if (groupGr.get(groupID)) {
            var isSupportGroup = groupGr.u_is_support_group;
        }

        if (isSupportGroup) {
            var grmember = new GlideRecord('sys_user_grmember');
            grmember.addQuery('group', groupID);
            grmember.addQuery('user', usrID);
            grmember.query();
            gs.log('Test99 ' + grmember.getRowCount());
            if (grmember.getRowCount() > 0) {
                returnval = 6; //not mem not primary
            } else {
                gs.log('Test100');
                var user = GlideRecord('sys_user');
                user.addQuery('sys_id', usrID);
                user.query();
                if (user.next())
                    if (user.u_primary_group == groupID) {
                        returnval = 1; //meber and primary
                    } else {
                        returnval = 2; //member but not primary
                    }
            }

            return returnval;

        } else {
            var grm = new GlideRecord('sys_user_grmember');
            grm.addQuery('group', groupID);
            grm.addQuery('user', usrID);
            grm.query();
            gs.log('group12');
            if (grm.getRowCount() > 0) {
                returnval = 5; //not mem not primary
            } else {
                var usr = GlideRecord('sys_user');
                usr.addQuery('sys_id', usrID);
                usr.query();
                if (usr.next())
                    if (usr.u_primary_group == groupID) {
                        returnval = 3; //meber and primary
                    } else {
                        returnval = 4; //member but not primary
                    }
            }
            return returnval;

        }
    },

    //users Current Groups Auto Populate in variable set
    getusersGroup: function() {

        var uID = this.getParameter('sysparm_gp');
        var supportgroup = 0;

        var grmember = new GlideRecord('sys_user_grmember');
        grmember.addQuery('user', uID);
        grmember.addQuery('group.active', true);
        grmember.addQuery('group.u_is_support_group', true);

        grmember.query();

        var groupArray = [];
        var groupJSON = {};

        while (grmember.next()) {
            var primarygroup = grmember.user.u_primary_group.getDisplayValue();
            var isprimarygroup = false;
            if (primarygroup == grmember.getDisplayValue('group'))
                isprimarygroup = true;

            var groupGr = new GlideRecord('sys_user_group');
            groupGr.addQuery('sys_id', grmember.group.sys_id);
            groupGr.query();
            while (groupGr.next()) {
                if (groupGr.u_is_support_group == true) {
                    supportgroup = true;
                } else {
                    supportgroup = false;
                }

                groupJSON.relationship = {
                        issupport: supportgroup ? 'Yes' : 'No',
                        group: grmember.getDisplayValue('group'),
                        isprimary: isprimarygroup ? 'Yes' : 'No'
                    },
                    groupArray.push(groupJSON.relationship);
            }
        }
        return JSON.stringify(groupArray);
    },


    //Remove Normal groups that user is already member and Remove Primary Group from group list Manage my subscription catalog

    removenormalgroups: function() {
        var userId = gs.getUserID();
        var excludeIds = [];

        var userGr = new GlideRecord('sys_user');
        userGr.get(gs.getUserID());
        var primaryGroup = userGr.u_primary_group.toString();

        var grtype = new GlideRecord('sys_user_group');
        grtype.addEncodedQuery('u_is_support_group=false^ORactive=false');
        grtype.query();
        while (grtype.next()) {
            excludeIds.push(grtype.sys_id.toString());
        }

        var memberGr = new GlideRecord('sys_user_grmember');
        memberGr.addQuery('user', userId);
        memberGr.addQuery('group.u_is_support_group', false);
        memberGr.query();
        while (memberGr.next()) {
            excludeIds.push(memberGr.getValue('group'));
        }
        excludeIds.push(primaryGroup);

        return 'sys_id NOT IN' + excludeIds;

    },

    type: 'GroupUtil'
});



Client Script : Populate group members

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
	
    g_form.clearValue('new_group_members');
    g_form.clearValue('old_group_members');
      return;
   }

		
var group_name = g_form.getValue('select_support_group');
	
	var grmember = new GlideAjax('GroupUtil');
	grmember.addParam('sysparm_name','GetMembersFromGroup');
	grmember.addParam('sysparm_grp',group_name);
	grmember.getXML(ajaxResponse);
	
	function ajaxResponse(response){
		var resp = (response.responseXML.documentElement.getAttribute('answer'));
    resp = resp.toString();
		
		
	g_form.setValue('new_group_members', resp);
    g_form.setValue('old_group_members', resp);
		
	}
	
}
mkdir backend
cd backend

mkdir config
New-Item -ItemType File -Path ./config/db.js

mkdir controllers
New-Item -ItemType File -Path ./controllers/authController.js

mkdir models
New-Item -ItemType File -Path ./models/User.js

mkdir routes
New-Item -ItemType File -Path ./routes/authRoutes.js

mkdir middleware
New-Item -ItemType File -Path ./middleware/authMiddleware.js

New-Item -ItemType File -Path ./server.js
New-Item -ItemType File -Path ./package.json
New-Item -ItemType File -Path ./.env







echo ".env" >> .gitignore
import type {NextApiRequest, NextApiResponse} from "next";
import * as XLSX from "xlsx";

// Handle file upload and parse Excel data
export const handleFileUpload = async (file: File) => {
  const reader = new FileReader();
  return new Promise<{
    managerRecords: { imo: string; manager: string }[];
  }>((resolve) => {
    reader.onload = (e) => {
      const data = e.target?.result;
      const workbook = XLSX.read(data, { type: "binary" });
      const managerWorksheet = workbook.Sheets["Recent Changes (EffControl)"];

      // Extract IMO and EffectiveControl columns dynamically by header name
      const managerData = XLSX.utils.sheet_to_json<any>(managerWorksheet, {
        header: 1,
      });
      const headers = managerData[0];
      const imoIndex = headers.findIndex(
        (header: string) => header === "IMONumber",
      );
      const managerIndex = headers.findIndex(
        (header: string) => header === "EffectiveControl",
      );

      const managerRecords = managerData
        .slice(1)
        .map((row: any) => ({
          imo: row[imoIndex],
          manager: row[managerIndex],
        }))
        .filter((record) => record.imo && record.manager); // Filter out empty rows

      resolve({ managerRecords });
    };
    reader.readAsBinaryString(file);
  });
};

// API handler for menteithUpdate
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  switch (req.method) {
    case "POST":
      if (req.body.action === "previewData") {
        try {
          const file = req.body.file;
          const { managerRecords } = await handleFileUpload(file);
          return res.status(200).json({ success: true, managerRecords });
        } catch (error) {
          return res
            .status(500)
            .json({ success: false, error: (error as Error).message });
        }
      }
      return res.status(400).json({ success: false, error: "Invalid action" });

    default:
      res.setHeader("Allow", ["POST"]);
      return res
        .status(405)
        .send(`Method ${req.method ?? "Undefined"} Not Allowed`);
  }
}
import React, { useState } from "react";
import { useDropzone } from "react-dropzone";
import { UpdateManager } from "@/types/vessel";

interface ManagerAndCoatingFormProps {
  onManagerDataUpdate: (data: UpdateManager[]) => void;
}

const ManagerAndCoatingForm: React.FC<ManagerAndCoatingFormProps> = ({
  onManagerDataUpdate,
}) => {
  const [file, setFile] = useState<File | null>(null);
  const [managerData, setManagerData] = useState<UpdateManager[]>([]);

  const onDrop = async (acceptedFiles: File[]) => {
    const uploadedFile = acceptedFiles[0];
    setFile(uploadedFile);

    const formData = new FormData();
    formData.append("file", uploadedFile);

    try {
      const response = await fetch("/api/menteithUpdate?action=previewData", {
        method: "POST",
        body: formData,
      });

      const data = await response.json();
      if (data.success) {
        const filteredManagerRecords = data.managerRecords.filter(
          (record: any) => !/unknown/i.test(record.manager),
        );
        setManagerData(filteredManagerRecords);
        onManagerDataUpdate(filteredManagerRecords);
      }
    } catch (error) {
      console.error("Error previewing file: ", error);
    }
  };

  const handleUpdate = async () => {
    try {
      // Update manager records in DB
      await fetch("/api/menteithUpdate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          action: "updateManagerRecords",
          records: managerData,
        }),
      });

      alert("Manager data updated successfully.");
    } catch (error) {
      console.error("Error updating manager data: ", error);
    }
  };

  const { getRootProps, getInputProps } = useDropzone({ onDrop });

  return (
    <div className="p-4">
      <div
        {...getRootProps({
          className:
            "dropzone border-2 border-dashed p-4 rounded-md text-center cursor-pointer text-white",
        })}
      >
        <input {...getInputProps()} />
        <p>
          Drag & drop a vessel manager update file here, or click to select one
        </p>
      </div>

      {file && (
        <div className="mt-4">
          <p className="text-white">File: {file.name}</p>
        </div>
      )}

      <button
        onClick={handleUpdate}
        className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-white"
      >
        Update Data
      </button>

      {managerData.length > 0 && (
        <div className="mt-6">
          <h3 className="mb-2 bg-gray-800 p-2 text-lg text-white">
            Manager Changes
          </h3>
          <div className="max-h-96 overflow-auto">
            <table className="min-w-full border-collapse border border-gray-400">
              <thead className="sticky top-0 bg-gray-700">
                <tr>
                  <th className="border border-gray-300 px-4 py-2 text-white">
                    IMO Number
                  </th>
                  <th className="border border-gray-300 px-4 py-2 text-white">
                    Manager
                  </th>
                </tr>
              </thead>
              <tbody>
                {managerData.map((record, index) => (
                  <tr key={index}>
                    <td className="border border-gray-300 px-4 py-2 text-white">
                      {record.imo}
                    </td>
                    <td className="border border-gray-300 px-4 py-2 text-white">
                      {record.manager}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};

export default ManagerAndCoatingForm;
import React, { useState } from "react";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import ManagerAndCoatingForm from "@/components/forms/managerAndCoatingForm";
import { UpdateCoating, UpdateManager } from "@/types/vessel";

const MenteithUpdater: React.FC = () => {
  const [managerData, setManagerData] = useState<UpdateManager[]>([]);
  const [coatingData, setCoatingData] = useState<UpdateCoating[]>([]);

  return (
    <MinimalPage
      pageTitle={"Update Vessel Manager | Vessel Interface"}
      pageDescription={"Vessel Interface | Update Vessel Manager"}
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <div>
          <BackHomeButton />
        </div>
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>

      <PageHeading text="Update Vessel Manager" />

      <ManagerAndCoatingForm
        onManagerDataUpdate={setManagerData}
        onCoatingDataUpdate={setCoatingData}
      />
    </MinimalPage>
  );
};

export default MenteithUpdater;
import java.util.*;

public class Knapsack {

    public static double greedyKnapSack(ItemValue[] items, int capacity) {
        Arrays.sort(items, (a, b) -> Double.compare((double) b.profit / b.weight, (double) a.profit / a.weight));

        double totalProfit = 0;
        for (ItemValue item : items) {
            if (capacity >= item.weight) {
                capacity -= item.weight;
                totalProfit += item.profit;
            } else {
                totalProfit += (double) capacity / item.weight * item.profit;
                break;
            }
        }
        return totalProfit;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of items: ");
        int n = sc.nextInt();
        ItemValue[] items = new ItemValue[n];
        
        System.out.println("Enter weight and profit of each item:");
        for (int i = 0; i < n; i++) {
            items[i] = new ItemValue(sc.nextInt(), sc.nextInt());
        }

        System.out.print("Enter capacity: ");
        int capacity = sc.nextInt();
        
        System.out.println("Maximum profit: " + greedyKnapSack(items, capacity));
        sc.close();
    }
}

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




function greedyKnapSack(items, n, W):
    sort items in descending order of (profit/weight)

    totalProfit = 0
    remainingCapacity = W

    for each item in items:
        if remainingCapacity >= item's weight:
            totalProfit += item's profit
            remainingCapacity -= item's weight
        else:
            fraction = remainingCapacity / item's weight
            totalProfit += fraction * item's profit
            break

    return totalProfit





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

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

 is the knapsack size, and  is the solution vector.


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

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

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

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

end GREEDY_KNAPSACK



OUTPUT:

Enter the number of items: 
3
Enter weight, profit of each item: 
10 60
20 100
30 120
Enter capacity: 
50
Maximum profit: 240.0
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

data = pd.read_csv('Pune_rent.csv')

print(data.head())
print(data.info())

X = data.drop(columns=['rent'])
y = data['rent']

X = pd.get_dummies(X, drop_first=True)

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

model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

mae = mean_absolute_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
r2 = r2_score(y_test, y_pred)

print("Model Performance:")
print(f"Mean Absolute Error (MAE): {mae:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
print(f"R² Score: {r2:.2f}")
data={
    'Age' : [10,None, 30],
 'Name' : ['a', 'b', None],
 'City' : ['x', 'y', 'z'],
 }
df=pd.DataFrame(data)
print(df)
df_fill=df.fillna({'Name' : 'Gilbert', 'Age' : df['Age'].mean()})
print(df_fill)
df_drop=df.dropna()
print(df_drop)
print("no of missing values : \n",df.isnull().sum())
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[14,46,8,72,34]
plt.plot(x,y)
plt.title("practice plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
 import pandas as pd
 from sklearn.datasets import load_iris
 from sklearn.tree import DecisionTreeClassifier
 from sklearn.model_selection import train_test_split
 from sklearn.metrics import accuracy_score,confusion_matrix,classification_report
 iris=load_iris()
 df=pd.DataFrame(data=iris.data,columns=iris.feature_names)
 print(df.head())
 df['Species']=iris.target
 x=df.drop('Species',axis=1)
 y=df['Species']
 x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
 model=DecisionTreeClassifier(random_state=42)
 model.fit(x_train,y_train)
 y_pred=model.predict(x_test)
 print(accuracy_score(y_test,y_pred))
 print(confusion_matrix(y_test,y_pred))
 print(classification_report(y_test,y_pred))
 import pandas as pd
 from sklearn.datasets import load_iris
 from sklearn.neighbors import KNeighborsClassifier
 from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
 from sklearn.model_selection import train_test_split
 iris=load_iris()
 df=pd.DataFrame(iris.data,columns=iris.feature_names)
 print(df.head())
 df['Species']=iris.target
 x=df.drop('Species',axis=1)
 y=df['Species']
 x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=42)
 model=KNeighborsClassifier(n_neighbors=3)
 model.fit(x_train,y_train)
 y_pred=model.predict(x_test)
 print(accuracy_score(y_test,y_pred))
 print(confusion_matrix(y_test,y_pred))
 print(classification_report(y_test,y_pred))
 import pandas as ps
 from sklearn.ensemble import RandomForestClassifier
 from sklearn.model_selection import train_test_split
 from sklearn.preprocessing import LabelEncoder
 from sklearn.metrics import accuracy_score,confusion_matrix,classification_report,precision_score
 df=pd.read_csv("loan_data_set.csv")
 print(df.head())
 x=df.iloc[:614]
 y=df.Loan_Status
 encoder=LabelEncoder()
 x_train_enc=x.apply(encoder.fit_transform)
 x_train,x_test,y_train,y_test=train_test_split(x_train_enc,y,test_size=0.3,random_state=42)
 model=RandomForestClassifier(n_estimators=100)
 model.fit(x_train,y_train)
 y_pred=model.predict(x_test)
 print(accuracy_score(y_test,y_pred))
 print(precision_score(y_test,y_pred,average='weighted',pos_label='Y'))
 print(confusion_matrix(y_test,y_pred))
 print(classification_report(y_test,y_pred))
 import pandas as pd
 from sklearn.datasets import load_iris
 import matplotlib.pyplot as plt
 from scipy.cluster.hierarchy import dendrogram,linkage,fcluster
 from sklearn.preprocessing import StandardScaler
 iris=load_iris()
 df=pd.DataFrame(iris.data,columns=iris.feature_names)
 print(df.head())
 scaler=StandardScaler()
 scaled_data=scaler.fit_transform(df)
 z=linkage(scaled_data,method='ward')
 plt.figure(figsize=(7,5))
 dendrogram(z,labels=iris.target)
 plt.show()
 s=3
 cluster=fcluster(z,t=s,criterion='maxclust')
 df['cluster']=cluster
 df['Species']=iris.target
 print(df.groupby(['cluster','Species']).size())
 import pandas as pd
 from sklearn.cluster import KMeans
 from sklearn.datasets import load_iris
 from sklearn.preprocessing import StandardScaler
 from sklearn.metrics import silhouette_score,adjusted_rand_score
 iris=load_iris()
 df=pd.DataFrame(iris.data,columns=iris.feature_names)
 print(df.head())
 scaler=StandardScaler()
 x_scaled=scaler.fit_transform(df)
 kmeans=KMeans(n_clusters=3,random_state=42)
 kmeans.fit(x_scaled)
 cluster_centers=kmeans.cluster_centers_
 print(cluster_centers)
 true_labels=iris.target
 print(silhouette_score(x_scaled,kmeans.labels_))
 print(adjusted_rand_score(true_labels,kmeans.labels_))
 import pandas as pd
 from sklearn.datasets import load_iris
 from sklearn.preprocessing import StandardScaler
 from sklearn.decomposition import PCA
 import seaborn as sns
 import matplotlib.pyplot as plt
 df=pd.read_csv("iris.csv")
 print(df.head())
 print(df.isnull().sum())
 #df.fillna(df.mean(),inplace=True)
 df_encoded=pd.get_dummies(df,columns=['Species'],drop_first=True)
 print(df_encoded.head())
 x=df_encoded
 x_scaled=StandardScaler().fit_transform(x)
 pca=PCA(n_components=2)
 x_pca=pca.fit_transform(x_scaled)
power iso if imager dont work

tools > usb tools > create bootable usb

clone 
server
ui

@ECHO OFF
set list=Desktop Documents Downloads Favorites Music Pictures Videos
set baseLocation="%USERPROFILE%\OneDrive - Olivet Nazarene University\LocalPC\"
set "Key=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
set "Typ=REG_EXPAND_SZ"
set RegList="Desktop" "Personal" "{374DE290-123F-4565-9164-39C4925E467B}" "Favorites" "My Music" "My Pictures" "My Video"
set /a c=0
setLocal enableDelayedExpansion
for %%j in (%RegList%) do (
    set RegList[!c!]=%%j & set /a c=c+1
)
for %%i in (%list%) do (
    if not exist %baseLocation%%%i (
        mkdir %baseLocation%%%i
    ) else (
        echo %%i already exsists
    )
)
set baseLocation=%baseLocation:"=%
for %%i in (%list%) do (
    RoboCopy.exe "%USERPROFILE%\%%~i\." "%baseLocation%\%%~i\." *.* /MOV /FP /NP /IS /Z /E /NFL /NDL /NJH
)
set /a d=0
for %%k in (%list%) do (
    call set val=%%RegList[!d!]%% & Reg Add "%Key%" /f /V !val! /T %Typ% /D "%baseLocation%%%k" & set /a d=d+1
 For /D /R j:\test %%1 IN (*) DO c:\trid_w32\trid "%%1"\* -ae
 
 
Replace j:\test with the directory that you want to move recursively through (TrID will not run on the files in the root of this directory).
 
Replace c:\trid_w32\trid with the path to trid.exe.
 
Dump the line in a batch file and run.
 #include <iostream>
#include <queue>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        this->data = d;
        this->left = NULL;
        this->right = NULL;
    }
};

Node* insertIntoBST(Node* root, int d) {
    // base case 
    if (root == NULL) {
        root = new Node(d); // Create a new node
        return root; // Return the newly created node
    }
    if (d > root->data) {
        // Insert in the right subtree
        root->right = insertIntoBST(root->right, d);
    } else {
        // Insert in the left subtree
        root->left = insertIntoBST(root->left, d);
    }
    return root; // Return the root of the subtree
}

void levelOrderTraversal(Node* root) {
    if (root == NULL) 
        return; // If the tree is empty, return

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        cout << temp->data << " "; // Print the current node's data

        // Push left and right children into the queue
        if (temp->left) {
            q.push(temp->left);
        }
        if (temp->right) {
            q.push(temp->right);
        }
    }
    cout << endl; // Print a new line after level order traversal
}

void takeInput(Node*& root) {
    int data;
    cin >> data;

    while (data != -1) {
        root = insertIntoBST(root, data); // Update the root pointer
        
        // Print the current state of the BST after each insertion
        cout << "Current state of the BST after inserting " << data << ": ";
        levelOrderTraversal(root);
        
        cin >> data;
    }
}
void inorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    inorder(root->left);
    cout << root-> data << " ";
    inorder(root->right);
}
void preorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    cout << root-> data << " ";
    preorder(root->left);
    preorder(root->right);
}
void postorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    postorder(root->left);
    postorder(root->right);
    cout << root-> data << " ";
}
Node* minVal(Node* root){
    Node* temp = root;
    
    while(temp->left != NULL){
        temp = temp->left;
    }
    return temp;
}
Node* maxVal(Node* root){
    Node* temp = root;
    
    while(temp->right != NULL){
        temp = temp->right;
    }
    return temp;
}
int main() {
    Node* root = NULL;
    cout << "Enter the data for BST (end with -1): ";
    takeInput(root);
    
    cout << "printing inorder" << endl;
    inorder(root);
    
    cout << endl <<"printing preorder" << endl;
    preorder(root);
    
    cout << endl<<  "printing postorder" << endl;
    postorder(root);
    
    cout <<endl <<" min value is "<< minVal(root) -> data << endl;
    cout <<" min value is "<< maxVal(root) -> data << endl;
    
    
    
    
    return 0;
}


//// Time complexity = O(logn)
///************** BST QUESTION*************///////////// 
/// IN THIS QUESTION THEY WILL GIVE US A NUMBER AND IF IT IS PRESENT IN THAT TREE GIVE US TRUE OTHERWISE RETURN FALSE TO JUS 

/// APPROACH 
// if we get null return false otherwise if root->data > (number passed) go to the left side else go to right side 

///// FIRST APPROACH 
bool searchInBST(BinaryTreeNode<int> *root, int x){
    BinaryTreeNode<int> *temp = root;
    
    while(temp != NULL)
    
    if(temp->data == x){
        return true;
    }
    if(temp->data > x){
        temp = temp->left;
    }
    else{
        temp = temp->right;
    }
    return false;
}

////// second approach 
bool searchInBST(BinaryTreeNode<int> *root , int x ){
    // base case 
    if(root == Null){
        return false;
    }
    
    if(root ->data == x){
        return true;
    }
    if(root->data > x){
      return seachInBST(root->left , x ); 
    }
    else{
         return seachInBST(root->right, x ); 
    }
///************** BST QUESTION*************///////////// 
/// IN THIS QUESTION THEY WILL GIVE US A NUMBER AND IF IT IS PRESENT IN THAT TREE GIVE US TRUE OTHERWISE RETURN FALSE TO JUS 

/// APPROACH 
// if we get null return false otherwise if root->data > (number passed) go to the left side else go to right side 

///// FIRST APPROACH 
bool searchInBST(BinaryTreeNode<int> *root, int x){
    BinaryTreeNode<int> *temp = root;
    
    while(temp != NULL)
    
    if(temp->data == x){
        return true;
    }
    if(temp->data > x){
        temp = temp->left;
    }
    else{
        temp = temp->right;
    }
    return false;
}

////// second approach 
bool searchInBST(BinaryTreeNode<int> *root , int x ){
    // base case 
    if(root == Null){
        return false;
    }
    
    if(root ->data == x){
        return true;
    }
    if(root->data > x){
      return seachInBST(root->left , x ); 
    }
    else{
         return seachInBST(root->right, x ); 
    }
public class MergeSort {
   
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int k = left;

        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[k] = arr[i];
                i++;
            } else {
                temp[k] = arr[j];
                j++;
            }
            k++;
        }

        while (i <= mid) {
            temp[k] = arr[i];
            i++;
            k++;
        }

        while (j <= right) {
            temp[k] = arr[j];
            j++;
            k++;
        }

        for (i = left; i <= right; i++) {
            arr[i] = temp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {38, 27, 43, 3, 9, 82, 10};
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);

        System.out.print("Sorted array: ");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
import java.util.Scanner;

public class QuickSort {

    public static void quicksort(int[] a, int lb, int ub) {
        int pivot, start, end;
        pivot = a[lb];
        start = lb;
        end = ub;

        if (start < end) {
            while (start < end) {
                while (start < end && a[start] <= pivot) {
                    start++;
                }
                while (a[end] > pivot) {
                    end--;
                }
                if (start < end) {
                    swap(a, start, end);
                }
            }
            swap(a, lb, end);

            quicksort(a, lb, end - 1);
            quicksort(a, end + 1, ub);
        }
    }

    
    public static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void display(int[] a) {
        System.out.println("Sorted array:");
        for (int i : a) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter array size:");
        int n = scanner.nextInt();
        int[] a = new int[n];

        System.out.println("Enter elements into array:");
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }

        quicksort(a, 0, n - 1);
        display(a);

        scanner.close();
    }
}
#include <iostream>
#include <queue>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        this->data = d;
        this->left = NULL;
        this->right = NULL;
    }
};

Node* insertIntoBST(Node* root, int d) {
    // base case 
    if (root == NULL) {
        root = new Node(d); // Create a new node
        return root; // Return the newly created node
    }
    if (d > root->data) {
        // Insert in the right subtree
        root->right = insertIntoBST(root->right, d);
    } else {
        // Insert in the left subtree
        root->left = insertIntoBST(root->left, d);
    }
    return root; // Return the root of the subtree
}

void levelOrderTraversal(Node* root) {
    if (root == NULL) 
        return; // If the tree is empty, return

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        cout << temp->data << " "; // Print the current node's data

        // Push left and right children into the queue
        if (temp->left) {
            q.push(temp->left);
        }
        if (temp->right) {
            q.push(temp->right);
        }
    }
    cout << endl; // Print a new line after level order traversal
}

void takeInput(Node*& root) {
    int data;
    cin >> data;

    while (data != -1) {
        root = insertIntoBST(root, data); // Update the root pointer
        
        // Print the current state of the BST after each insertion
        cout << "Current state of the BST after inserting " << data << ": ";
        levelOrderTraversal(root);
        
        cin >> data;
    }
}
void inorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    inorder(root->left);
    cout << root-> data << " ";
    inorder(root->right);
}
void preorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    cout << root-> data << " ";
    preorder(root->left);
    preorder(root->right);
}
void postorder(Node* root) {
    //base case
    if(root == NULL) {
        return ;
    }
    postorder(root->left);
    postorder(root->right);
    cout << root-> data << " ";
}

int main() {
    Node* root = NULL;
    cout << "Enter the data for BST (end with -1): ";
    takeInput(root);
    
    cout << "printing inorder" << endl;
    inorder(root);
    
    cout << endl <<"printing preorder" << endl;
    preorder(root);
    
    cout << endl<<  "printing postorder" << endl;
    postorder(root);
    return 0;
}


//// Time complexity = O(logn)
#KMeans Classification
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
# Sample dataset: Fruit type with average RGB values
data = {'Fruit': ['Apple', 'Apple', 'Apple', 'Orange', 'Orange', 'Orange', 'Banana', 'Banana', 'Banana'],
        'Red': [180, 190, 170, 255, 250, 245, 240, 230, 220],
        'Green': [20, 30, 25, 120, 110, 105, 240, 230, 220],
        'Blue': [30, 40, 35, 70, 65, 60, 240, 230, 220]}

df = pd.DataFrame(data)
print(df)
# Extracting the features (Red, Green, Blue)
X = df[['Red', 'Green', 'Blue']]

# Standardize the data
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Apply K-Means with 3 clusters
kmeans = KMeans(n_clusters=3, random_state=42)
kmeans.fit(X_scaled)

# Get the cluster labels
df['Cluster'] = kmeans.labels_
print(df)
# Reduce data to 2D using PCA for visualization
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# Plot the clusters
plt.figure(figsize=(8, 6))
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=kmeans.labels_, cmap='viridis')
plt.title('Fruit Clusters (K-Means)')
plt.xlabel('PCA Component 1')
plt.ylabel('PCA Component 2')
plt.show()
#Decision Tree

from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
import pandas as pd

# Load Soybean Dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/soybean/soybean-small.data"
columns = ['date', 'plant-stand', 'precip', 'temp', 'hail', 'crop-hist', 'area-damaged', 'severity', 'seed-tmt',
           'germination', 'plant-growth', 'leaves', 'leafspots-halo', 'leafspots-marg', 'leafspot-size',
           'leaf-shread', 'leaf-malf', 'leaf-mild', 'stem', 'lodging', 'stem-cankers', 'canker-lesion',
           'fruiting-bodies', 'external-decay', 'mycelium', 'int-discolor', 'sclerotia', 'fruit-pods',
           'roots', 'class'
          ]

data = pd.read_csv(url, header = None, names = columns)

X = data.drop(columns = ['class'])
y = data['class']

X = pd.get_dummies(X)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)
decision_tree = DecisionTreeClassifier(criterion="gini", max_depth=5, random_state=42)
decision_tree.fit(X_train, y_train)

y_pred = decision_tree.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
conf = confusion_matrix(y_test, y_pred)
classR = classification_report(y_test, y_pred)

print(accuracy)
print(conf)
print(classR)
#Naive Bayes

from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.datasets import load_iris
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

data = load_iris()
X = data.data
y = (data.target == 2).astype(int)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0)


model = GaussianNB()
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

accuracy = accuracy_score(y_test, y_pred)
conf = confusion_matrix(y_test, y_pred)
classR = classification_report(y_test, y_pred)

print(accuracy)
print(conf)
print(classR)
#KNN

from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
from sklearn.datasets import load_iris

data = load_iris()
X = data.data
y = data.target

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

scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.fit_transform(X_test)


knn = KNeighborsClassifier(n_neighbors = 5)
knn.fit(X_train, y_train)

y_pred = knn.predict(X_test)


accuracy = accuracy_score(y_test, y_pred)
conf = confusion_matrix(y_test, y_pred)
classR = classification_report(y_test, y_pred)

print(accuracy)
print(conf)
print(classR)
#Linear Regression

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_classification
from sklearn.metrics import confusion_matrix, accuracy_score, classification_report
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

X, y = make_classification(n_samples = 1000, n_features = 2, n_redundant =0, n_informative = 2,  n_classes = 2, random_state = 42)

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

linear_model = LinearRegression()
linear_model.fit(X_train, y_train)
y_pred_prob = linear_model.predict(X_test)
y_pred = (y_pred_prob >=0.5).astype(int)

cm = confusion_matrix(y_test, y_pred)
plt.figure(figsize = (6, 4))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False)
#Logistic Regression
# Import necessary libraries
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
from sklearn.datasets import load_iris

# Load sample data
data = load_iris()
X = data.data
y = (data.target == 2).astype(int)  # Create a binary target for the logistic regression example

# Split data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

# Create and train the logistic regression model
model = LogisticRegression()
model.fit(X_train, y_train)

# Make predictions
y_pred = model.predict(X_test)

# Evaluate the model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)

print("Accuracy:", accuracy)
print("Confusion Matrix:\n", conf_matrix)
print("Classification Report:\n", class_report)
star

Fri Nov 08 2024 01:46:22 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 01:31:42 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 01:27:48 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Nov 07 2024 23:57:34 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Thu Nov 07 2024 23:55:16 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Thu Nov 07 2024 23:14:28 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Thu Nov 07 2024 17:40:24 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:36:29 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:29:07 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:27:12 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:24:48 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 16:33:21 GMT+0000 (Coordinated Universal Time)

@maxwlrt

star

Thu Nov 07 2024 15:28:51 GMT+0000 (Coordinated Universal Time)

@jrray ##terminal

star

Thu Nov 07 2024 14:51:21 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Nov 07 2024 14:44:48 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Nov 07 2024 12:22:18 GMT+0000 (Coordinated Universal Time) https://code.visualstudio.com/docs/editor/extension-marketplace

@Dewaldt

star

Thu Nov 07 2024 11:48:17 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Nov 07 2024 11:39:01 GMT+0000 (Coordinated Universal Time)

@saurabhp643

star

Thu Nov 07 2024 10:46:32 GMT+0000 (Coordinated Universal Time) https://bbs.archlinux.org/viewtopic.php?id

@Dewaldt

star

Thu Nov 07 2024 09:36:52 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Thu Nov 07 2024 09:32:18 GMT+0000 (Coordinated Universal Time)

@amrit_v

star

Thu Nov 07 2024 08:17:45 GMT+0000 (Coordinated Universal Time)

@codeing #javascript #react.js #nodejs

star

Thu Nov 07 2024 08:00:03 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 07:59:32 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 07:58:54 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 01:11:46 GMT+0000 (Coordinated Universal Time)

@login123

star

Thu Nov 07 2024 01:04:39 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:55:59 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:38:47 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:38:04 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:37:30 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:36:36 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:35:51 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Thu Nov 07 2024 00:29:24 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 23:27:34 GMT+0000 (Coordinated Universal Time)

@Jeremicah

star

Wed Nov 06 2024 21:27:39 GMT+0000 (Coordinated Universal Time)

@baamn #trid #batch #windows #file

star

Wed Nov 06 2024 20:26:16 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Wed Nov 06 2024 20:18:52 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Wed Nov 06 2024 20:15:35 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Wed Nov 06 2024 20:10:22 GMT+0000 (Coordinated Universal Time) https://www.dappfort.com/cryptocurrency-exchange-development-company/

@shakthichinnah #javascript #dappfort #cryptocurrencyexchange #crypto #trading #cryptocurrency #blockchain

star

Wed Nov 06 2024 19:42:37 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 19:28:47 GMT+0000 (Coordinated Universal Time)

@sagar123

star

Wed Nov 06 2024 19:23:57 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Wed Nov 06 2024 19:07:49 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 19:07:27 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 19:07:03 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 19:06:46 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 19:06:29 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 19:06:12 GMT+0000 (Coordinated Universal Time)

@signup_returns

Save snippets that work with our extensions

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