Snippets Collections
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)
#Line Plot
import matplotlib.pyplot as plt

x = [1,2,3,4,5]
y = [10, 20, 30, 40, 50]

plt.plot(x,y)
plt.title("Line Plot")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

#Bar Graph
plt.bar(x,y)
plt.title("Bar Graph")
plt.xlabel("X")
plt.ylabel("Y")
plt.show()

#Histogram
import numpy as np
data = np.random.randn(1000)

plt.hist(data, bins = 30)
plt.show()

#Box Plot
import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = sns.load_dataset('tips')

# Box plot
sns.boxplot(x='day', y='total_bill', data=data)
plt.title('Box Plot')
plt.show()

#Scatter Plot

import matplotlib.pyplot as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [1, 4, 9, 16, 25]

# Scatter plot
plt.scatter(x, y, color='red')
plt.title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
#Pie Chart

import matplotlib.pyplot as plt

# Example data
labels = ['Apple', 'Banana', 'Cherry', 'Date']
sizes = [10, 20, 30, 40]

# Pie chart
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()
#Heatmap

import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = np.random.rand(10, 12)

# Heatmap
sns.heatmap(data, cmap='coolwarm', annot=True)
plt.title('Heatmap')
plt.show()
#Pair plot
import seaborn as sns
import matplotlib.pyplot as plt

# Example data
data = sns.load_dataset('iris')

# Pair plot
sns.pairplot(data, hue='species')
plt.title('Pair Plot')
plt.show()
#MinMaxScaler
from sklearn.preprocessing import MinMaxScaler
data = {
    'Feature1' : [100,200,300,400,500],
    'Feature2' : [1,2,3,4,5]
}
data = pd.DataFrame(data)

min_max_scaler = MinMaxScaler()
data = min_max_scaler.fit_transform(data)
data = pd.DataFrame(data)
data
#Standard Scaler
import pandas as pd
from sklearn.preprocessing import StandardScaler
data = {
    'Feature1' : [100,200,300,400,500],
    'Feature2' : [1,2,3,4,5]
}

data = pd.DataFrame(data)

standard_scaler = StandardScaler()
data_scaled = standard_scaler.fit_transform(data)

data_scaled = pd.DataFrame(data_scaled, columns = data.columns)
data_scaled
#OneHot Encoding
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

data_one_hot = pd.get_dummies(data['Color'], prefix = 'Color')
df = pd.DataFrame(data_one_hot)
df
import pandas as pd
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 8, 12, 15, 18, 24, 28, 30, 34, 40]
}
df = pd.DataFrame(data)
# Standardize the features
scaler = StandardScaler()
X = scaler.fit_transform(df)
# Elbow method for finding optimal k
inertia = []
K = range(1, 11)
for k in K:
 kmeans = KMeans(n_clusters=k, random_state=42)
 kmeans.fit(X)
 inertia.append(kmeans.inertia_)
plt.plot(K, inertia, 'bo-')
plt.xlabel('Number of clusters, k')
plt.ylabel('Inertia')
plt.title('Elbow Method For Optimal k')
plt.show()
# Apply K-Means with the chosen number of clusters (e.g., 3)
kmeans = KMeans(n_clusters=3, random_state=42)
df['Cluster'] = kmeans.fit_predict(X)
# Visualize the clusters
plt.scatter(X[:, 0], X[:, 1], c=df['Cluster'], cmap='viridis', marker='o', edgecolor='k',
s=100)
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red',
marker='X') # Cluster centers
plt.xlabel('Feature1')
plt.ylabel('Feature2')
plt.title('K-Means Clustering')
plt.show()
#Label Encoding
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
import pandas as pd

data = {
    'Color': ['Red', 'Green', 'Blue', 'Red', 'Blue', 'Green', 'Green']
}

df = pd.DataFrame(data)
label_encoder = LabelEncoder()

data['Color-Label'] = label_encoder.fit_transform(data['Color'])
df = pd.DataFrame(data)
df
#Missing values
import pandas as pd
data = {
    'Name': ['John', 'Alice', 'Steve'],
    'Age': [18, None, 20],
    'City': ['New York', 'California', None]
}

df = pd.DataFrame(data)

df.fillna({'Age': df['Age'].mean(), 'City': 'Unknown'})
import pandas as pd

# Sample dictionary
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35],
    'City': ['New York', 'Los Angeles', 'Chicago']
}

# Convert dictionary to DataFrame
df = pd.DataFrame(data)

# Display the DataFrame
print(df)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
# Make predictions
y_pred = rf.predict(X_test)
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
https://tinyurl.com/ds-lab-datasets-123
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
tree.fit(X_train, y_train)
# Make predictions
y_pred = tree.predict(X_test)
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
public class OBSTree {

    public static void main(String[] args) {
        double[] P = {3, 3, 1, 1};
        double[] Q = {2, 3, 1, 1, 1};

        int n = P.length;

        OBSTResult result = OBST(P, Q, n);

        System.out.println("Cost Matrix C:");
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                System.out.printf("%.2f ", result.C[i][j]);
            }
            System.out.println();
        }

        System.out.println("\nRoot Matrix R:");
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                System.out.printf("%d ", result.R[i][j]);
            }
            System.out.println();
        }
    }

    public static OBSTResult OBST(double[] P, double[] Q, int n) {
        double[][] C = new double[n + 1][n + 1];
        double[][] W = new double[n + 1][n + 1];
        int[][] R = new int[n + 1][n + 1];

        for (int i = 0; i <= n; i++) {
            W[i][i] = Q[i];
            C[i][i] = 0;
            R[i][i] = 0;
            if (i < n) {
                W[i][i + 1] = Q[i] + Q[i + 1] + P[i];
                C[i][i + 1] = W[i][i + 1];
                R[i][i + 1] = i + 1;
            }
        }

        for (int m = 2; m <= n; m++) {
            for (int i = 0; i <= n - m; i++) {
                int j = i + m;
                W[i][j] = W[i][j - 1] + P[j - 1] + Q[j];

                double minCost = Double.MAX_VALUE;
                int bestRoot = -1;

                for (int k = R[i][j - 1]; k <= R[i + 1][j]; k++) {
                    double cost = C[i][k - 1] + C[k][j];
                    if (cost < minCost) {
                        minCost = cost;
                        bestRoot = k;
                    }
                }

                C[i][j] = W[i][j] + minCost;
                R[i][j] = bestRoot;
            }
        }

        return new OBSTResult(C, W, R);
    }
}

class OBSTResult {
    double[][] C;
    double[][] W;
    int[][] R;

    OBSTResult(double[][] C, double[][] W, int[][] R) {
        this.C = C;
        this.W = W;
        this.R = R;
    }
}

/*
Test Case 1:
Input:
P = {3, 3, 1, 1}
Q = {2, 3, 1, 1, 1}

Expected Output:
Cost Matrix C:
0.00 2.00 5.00 8.00 9.00 
0.00 0.00 4.00 7.00 8.00 
0.00 0.00 0.00 4.00 5.00 
0.00 0.00 0.00 0.00 1.00 
0.00 0.00 0.00 0.00 0.00 

Root Matrix R:
0 1 1 1 1 
0 0 1 1 2 
0 0 0 3 3 
0 0 0 0 4 
0 0 0 0 0

Test Case 2:
Input:
P = {4, 2, 3, 4, 2}
Q = {3, 1, 2, 1, 2, 3}

Expected Output:
Cost Matrix C:
0.00 3.00 7.00 10.00 15.00 18.00 
0.00 0.00 2.00 5.00 9.00 12.00 
0.00 0.00 0.00 2.00 5.00 7.00 
0.00 0.00 0.00 0.00 2.00 4.00 
0.00 0.00 0.00 0.00 0.00 2.00 
0.00 0.00 0.00 0.00 0.00 0.00 

Root Matrix R:
0 1 2 3 3 4 
0 0 1 2 3 3 
0 0 0 1 2 3 
0 0 0 0 1 2 
0 0 0 0 0 1 
0 0 0 0 0 0
*/
//DijkstraAlgorithm 
import java.util.Scanner;
import java.util.Arrays;

public class DijkstraAlgorithm {

    // Method to find the vertex with the minimum distance value that hasn't been processed yet
    static int getMinDistanceVertex(int[] distance, boolean[] processedVertices, int numberOfVertices) {
        int minDistance = Integer.MAX_VALUE;  // Initialize with a large value
        int minVertexIndex = -1;  // Index of the vertex with the minimum distance

        // Search for the vertex with the smallest distance value
        for (int vertex = 0; vertex < numberOfVertices; vertex++) {
            if (!processedVertices[vertex] && distance[vertex] <= minDistance) {
                minDistance = distance[vertex];  // Update minimum distance
                minVertexIndex = vertex;  // Update index of vertex with minimum distance
            }
        }
        return minVertexIndex;
    }

    // Method to implement Dijkstra's algorithm to find the shortest path from the source
    static void dijkstra(int[][] graph, int[] distance, boolean[] processedVertices, int numberOfVertices, int sourceVertex) {
        // Initialize distances and processedVertices
        Arrays.fill(distance, Integer.MAX_VALUE);  // Set all distances to infinity initially
        Arrays.fill(processedVertices, false);  // Mark all vertices as unprocessed

        distance[sourceVertex] = 0;  // Distance from source to itself is 0

        // Find the shortest path for all vertices
        for (int i = 0; i < numberOfVertices - 1; i++) {
            // Get the vertex with the minimum distance value that hasn't been processed yet
            int currentVertex = getMinDistanceVertex(distance, processedVertices, numberOfVertices);

            // Mark the current vertex as processed
            processedVertices[currentVertex] = true;

            // Update distance values of adjacent vertices of the current vertex
            for (int adjacentVertex = 0; adjacentVertex < numberOfVertices; adjacentVertex++) {
                // If the adjacent vertex is unprocessed, has a path from currentVertex, and distance can be minimized
                if (!processedVertices[adjacentVertex] && graph[currentVertex][adjacentVertex] != 0 &&
                        distance[currentVertex] != Integer.MAX_VALUE &&
                        distance[currentVertex] + graph[currentVertex][adjacentVertex] < distance[adjacentVertex]) {
                    // Update the distance to the adjacent vertex
                    distance[adjacentVertex] = distance[currentVertex] + graph[currentVertex][adjacentVertex];
                }
            }
        }
    }

    // Method to print the solution (distances from source vertex)
    static void printSolution(int[] distance, int numberOfVertices) {
        System.out.println("Vertex   Distance from Source");
        for (int i = 0; i < numberOfVertices; i++) {
            System.out.println(i + " \t\t " + distance[i]);
        }
    }

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

        // Taking input for number of vertices
        System.out.print("Enter the number of vertices: ");
        int numberOfVertices = sc.nextInt();

        // Initialize the graph matrix (adjacency matrix)
        int[][] graph = new int[numberOfVertices][numberOfVertices];

        // Taking input for the adjacency matrix (graph)
        System.out.println("Enter the adjacency matrix (0 means no edge between vertices):");
        for (int i = 0; i < numberOfVertices; i++) {
            for (int j = 0; j < numberOfVertices; j++) {
                graph[i][j] = sc.nextInt();
            }
        }

        // Taking input for the source vertex
        System.out.print("Enter the source vertex: ");
        int sourceVertex = sc.nextInt();

        // Arrays to store the distance and processed status of vertices
        int[] distance = new int[numberOfVertices];
        boolean[] processedVertices = new boolean[numberOfVertices];

        // Run Dijkstra's algorithm starting from the source vertex
        dijkstra(graph, distance, processedVertices, numberOfVertices, sourceVertex);

        // Print the shortest distances from the source vertex
        printSolution(distance, numberOfVertices);
    }
}

/*
Test Case
Enter the number of vertices: 5
Enter the adjacency matrix (0 means no edge between vertices):
0 10 0 0 0
0 0 5 0 0
0 0 0 15 0
0 0 0 0 20
0 0 0 0 0
Enter the source vertex: 0
Vertex   Distance from Source
0        0
1        10
2        15
3        30
4        50
*/
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 'Feature2': [5, 10, 15, 20, 25, 30, 35, 40, 45, 50],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
nb = GaussianNB()
nb.fit(X_train, y_train)
# Make predictions
y_pred = nb.predict(X_test)
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')
print('Confusion Matrix:')
print(conf_matrix)
print('Classification Report:')
print(class_report)
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# Sample data
data = {
 'Feature1': [2, 4, 4, 4, 6, 6, 6, 8, 8, 8],
 'Feature2': [4, 2, 4, 6, 2, 4, 6, 2, 4, 6],
 'Target': [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
}
df = pd.DataFrame(data)
# Split data into features and target
X = df[['Feature1', 'Feature2']]
y = df['Target']
# Split dataset
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# Initialize and fit model
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# Make predictions
y_pred = knn.predict(X_test)
# Evaluate model
accuracy = accuracy_score(y_test, y_pred)
conf_matrix = confusion_matrix(y_test, y_pred)
class_report = classification_report(y_test, y_pred)
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

star

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

@signup_returns

star

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

@signup_returns

star

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

@signup_returns

star

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

@signup_returns

star

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

@login123

star

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

@signup_returns

star

Wed Nov 06 2024 18:59:54 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

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

@signup_returns

star

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

@login123

star

Wed Nov 06 2024 18:57:02 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 18:56:21 GMT+0000 (Coordinated Universal Time)

@login123

star

Wed Nov 06 2024 18:56:15 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

Wed Nov 06 2024 18:53:39 GMT+0000 (Coordinated Universal Time)

@signup_returns

star

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

@login123

star

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

@login123

Save snippets that work with our extensions

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