Snippets Collections
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import axios from 'axios';
import { ConfigService } from '@nestjs/config';
import { OrderService } from './order.service';
import { CreateOrderDto } from 'src/dto/create-order.dto';

@Injectable()
export class OrderPollingService {
  private readonly spotwareApiUrl: string;
  private readonly apiToken: string;
  private readonly logger = new Logger(OrderPollingService.name);

  constructor(
    private readonly configService: ConfigService,
    private readonly orderService: OrderService,
  ) {
    this.spotwareApiUrl = `${this.configService.get<string>('SPOTWARE_API_URL')}`;
    this.apiToken = this.configService.get<string>('SPOTWARE_API_TOKEN');
  }

  @Cron(CronExpression.EVERY_MINUTE)
  async pollPositions() {
    this.logger.log('Polling for open and closed positions...');
    try {
      const openPositions = await this.fetchOpenPositions();
      const closedPositions = await this.fetchClosedPositions();

      await this.updateXanoWithPositions(openPositions, closedPositions);
    } catch (error) {
      this.logger.error(`Error polling positions: ${error.message}`);
    }
  }

  private async fetchOpenPositions() {
    try {
      const response = await axios.get(`${this.spotwareApiUrl}/v2/webserv/openPositions`, {
        headers: { Authorization: `Bearer ${this.apiToken}` },
        params: { token: this.apiToken },
      });
      this.logger.log('Fetched open positions from Spotware');
      console.log('Open Positions Data:', response.data);
      return this.parseCsvData(response.data);
    } catch (error) {
      this.logger.error(`Failed to fetch open positions: ${error.message}`);
      throw new HttpException('Failed to fetch open positions', HttpStatus.FORBIDDEN);
    }
  }

  private async fetchClosedPositions() {
    const now = new Date();
    const to = now.toISOString();
    const from = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000).toISOString(); // 2-day range

    try {
      const response = await axios.get(`${this.spotwareApiUrl}/v2/webserv/closedPositions`, {
        headers: { Authorization: `Bearer ${this.apiToken}` },
        params: { from, to, token: this.apiToken },
      });
      this.logger.log('Fetched closed positions from Spotware');
      console.log('Closed Positions Data:', response.data);
      return this.parseCsvData(response.data);
    } catch (error) {
      this.logger.error(`Failed to fetch closed positions: ${error.message}`);
      throw new HttpException('Failed to fetch closed positions', HttpStatus.FORBIDDEN);
    }
  }

  private parseCsvData(csvData: string): any[] {
    const rows = csvData.split('\n').slice(1); // Skip header row
    return rows
      .filter((row) => row.trim())
      .map((row) => {
        const columns = row.split(',');
        return {
          login: columns[0],
          positionId: columns[1],
          openTimestamp: columns[2],
          entryPrice: columns[3],
          direction: columns[4],
          volume: columns[5],
          symbol: columns[6],
          commission: columns[7],
          swap: columns[8],
          bookType: columns[9],
          stake: columns[10],
          spreadBetting: columns[11],
          usedMargin: columns[12],
        };
      });
  }

  private async updateXanoWithPositions(openPositions: any[], closedPositions: any[]) {
    for (const pos of openPositions) {
      const openOrderData: CreateOrderDto = this.mapOpenPositionToOrderDto(pos);
      try {
        // Only create if the order does not exist
        const existingOrder = await this.orderService.findOrderByTicketId(openOrderData.ticket_id);
        if (!existingOrder) {
          await this.orderService.createOrder(openOrderData);
          this.logger.log(`New open order created in Xano: ${JSON.stringify(openOrderData)}`);
        }
      } catch (error) {
        this.logger.error(`Failed to create open position in Xano: ${error.message}`);
      }
    }

    for (const pos of closedPositions) {
      const closedOrderData: CreateOrderDto = this.mapClosedPositionToOrderDto(pos);
      try {
        // Only update close details if order exists
        const existingOrder = await this.orderService.findOrderByTicketId(closedOrderData.ticket_id);
        if (existingOrder) {
          await this.orderService.updateOrderWithCloseData(closedOrderData);
          this.logger.log(`Closed order updated in Xano: ${JSON.stringify(closedOrderData)}`);
        }
      } catch (error) {
        this.logger.error(`Failed to update closed position in Xano: ${error.message}`);
      }
    }
  }

  private mapOpenPositionToOrderDto(position: any): CreateOrderDto {
    return {
      key: position.positionId.toString(),
      ticket_id: Number(position.positionId),
      account: Number(position.login),
      type: position.direction,
      symbol: position.symbol,
      volume: parseFloat(position.volume),
      entry_price: parseFloat(position.entryPrice),
      entry_date: position.openTimestamp,
      broker: 'Spotware',
      open_reason: position.bookType || 'AUTO',
    };
  }

  private mapClosedPositionToOrderDto(position: any): CreateOrderDto {
    return {
      key: position.positionId.toString(),
      ticket_id: Number(position.positionId),
      account: Number(position.login),
      type: position.direction,
      symbol: position.symbol,
      volume: parseFloat(position.volume),
      entry_price: parseFloat(position.entryPrice),
      entry_date: position.openTimestamp,
      close_price: parseFloat(position.closePrice),
      close_date: position.closeTimestamp,
      profit: parseFloat(position.pnl),
      broker: 'Spotware',
      open_reason: position.bookType || 'AUTO',
      close_reason: 'AUTO',
    };
  }
}
import numpy as np
from typing import Tuple


def find_baseline(mask: np.ndarray) -> Tuple[
                Tuple[int, int], Tuple[int, int]]:
    """Funkcja wyznacza punkty baseline na podstawie carti i bony roof.
    Algorytm znajduje najbardziej wysunięty na prawo punkt carti roof i na
    jego współrzędnej x +1 definiuje początek prawego punktu. Współrzędna y
    prawego punktu to współrzędna y bony roof na górnym obrysie na podanej
    współrzędnej x. Jeżeli dochodzi do wypadku gdzie carti roof jest dłuższe
    w poziomie od bony roof, to jako prawy punkt ustalany jest najbardziej
    wysunięty punkt górnego obrysu bony roof. Następnie szukana jest linia,
    posiadająca największe pokrycie z górnym obrysem bony roof. Do obliczania
    pokrycia pomijany jest górny obrys znajdujący się po prawo od wyznaczonego
    prawego punktu. Jako lewy punkt funkcja obiera ostatni punkt linii
    z największym pokryciem znajdujący się na górnym obrysie.

    Args:
        mask (np.ndarray): maska w formacie png

    Returns:
        Tuple[Tuple[int, int], Tuple[int, int]]: współrzędne prawego i lewego
                                                                punktu baseline
    """
    height, width = mask.shape
    label_upper_contour_bony = 5  # bony roof
    label_upper_contour_carti = 4  # cartilagineous roof

    binary_mask_bony = (mask == label_upper_contour_bony).astype(np.uint8)
    binary_mask_carti = (mask == label_upper_contour_carti).astype(np.uint8)

    upper_contour_bony = [
        (x, np.where(binary_mask_bony[:, x])[0][0]) for x in range(width)
        if np.any(binary_mask_bony[:, x])
    ]

    x_max_carti = max((x for x in range(width) if np.any(
        binary_mask_carti[:, x])), default=-1
        )
    if x_max_carti == -1:
        return (None, None), (None, None)

    # Ustalanie prawego punktu na podstawie przesunięcia
    rightmost_point_x = x_max_carti + 1
    if rightmost_point_x >= width or not upper_contour_bony:
        return (None, None), (None, None)

    bony_point_y = next(
        (y for x, y in upper_contour_bony if x == rightmost_point_x), None
    )
    if bony_point_y is None:
        rightmost_point_x, bony_point_y = upper_contour_bony[-1]

    # Wstępny punkt prawy przed przesunięciem
    original_rightmost_point = (rightmost_point_x, bony_point_y)

    best_line = []
    max_overlap = 0
    best_shift = 0  # Dodanie zmiennej do śledzenia najlepszego przesunięcia

    # Przechodzi przez każde przesunięcie od -10 do +5 pikseli
    for y0 in range(bony_point_y - 10, bony_point_y + 5):
        if not (0 <= y0 < height):
            continue
        current_shift = y0 - bony_point_y

        for angle in range(360):
            angle_rad = np.radians(angle)
            sin_angle = np.sin(angle_rad)
            cos_angle = np.cos(angle_rad)

            n = np.arange(2 * (width + height))
            x = rightmost_point_x + n * cos_angle
            y = y0 - n * sin_angle

            x_rounded = np.round(x).astype(int)
            y_rounded = np.round(y).astype(int)
            valid_mask = (x_rounded >= 0) & (x_rounded < width) & \
                         (y_rounded >= 0) & (y_rounded < height)

            line_points = list(
                zip(x_rounded[valid_mask], y_rounded[valid_mask])
                )

            overlap = len(
                set(line_points) &
                set(p for p in upper_contour_bony if p[0] <= rightmost_point_x)
            )

            if overlap > max_overlap:
                max_overlap = overlap
                best_line = line_points
                best_shift = current_shift

    adjusted_rightmost_point = (
        original_rightmost_point[0], original_rightmost_point[1] + best_shift
        )

    leftmost_point = None
    if best_line:
        for point in best_line:
            x, y = point
            if mask[y, x] == label_upper_contour_bony:
                if leftmost_point is None or x < leftmost_point[0]:
                    leftmost_point = (x, y)

    if leftmost_point is None:
        leftmost_point = (None, None)

    return adjusted_rightmost_point, leftmost_point
import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import axios from 'axios';
import { ConfigService } from '@nestjs/config';
import { CreateOrderDto } from 'src/dto/create-order.dto';
import { IOrder } from 'src/services/Interfaces/IOrder.interface';

@Injectable()
export class OrderService {
  private readonly xanoApiUrl: string;

  constructor(private readonly configService: ConfigService) {
    this.xanoApiUrl = `${this.configService.get<string>('XANO_API_URL')}`;
  }

  async createOrUpdateOrder(createOrderDto: CreateOrderDto): Promise<IOrder> {
    console.log('Sending to Xano:', createOrderDto);  // Log data before sending
    try {
      const response = await axios.post(this.xanoApiUrl, createOrderDto, {
        headers: {
          Authorization: `Bearer ${this.configService.get<string>('XANO_API_TOKEN')}`,
        },
      });
      console.log('Xano Response:', response.data); // Log Xano response
      return response.data;
    } catch (error) {
      console.error('Xano Error:', error.response?.data || error.message);
      throw new HttpException(
        `Failed to create or update order in Xano: ${error.message}`,
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
  

  async getAllOrders(): Promise<IOrder[]> {
    try {
      const response = await axios.get(this.xanoApiUrl);
      return response.data;
    } catch (error) {
      throw new HttpException('Failed to retrieve orders from Xano', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { Cron, CronExpression } from '@nestjs/schedule';
import axios from 'axios';
import { ConfigService } from '@nestjs/config';
import { OrderService } from './order.service';
import { CreateOrderDto } from 'src/dto/create-order.dto';

@Injectable()
export class OrderPollingService {
  private readonly spotwareApiUrl: string;
  private readonly apiToken: string;
  private readonly logger = new Logger(OrderPollingService.name);

  constructor(
    private readonly configService: ConfigService,
    private readonly orderService: OrderService,
  ) {
    this.spotwareApiUrl = `${this.configService.get<string>('SPOTWARE_API_URL')}`;
    this.apiToken = this.configService.get<string>('SPOTWARE_API_TOKEN');
  }

  // Poll Spotware API every minute
  @Cron(CronExpression.EVERY_MINUTE)
  async pollPositions() {
    this.logger.log('Polling for open and closed positions...');
    try {
      const openPositions = await this.fetchOpenPositions();
      const closedPositions = await this.fetchClosedPositions();

      // Process and push positions data to Xano
      await this.updateXanoWithPositions(openPositions, closedPositions);
    } catch (error) {
      this.logger.error(`Error polling positions: ${error.message}`);
    }
  }

  private async fetchOpenPositions() {
    try {
      const response = await axios.get(`${this.spotwareApiUrl}/v2/webserv/openPositions`, {
        headers: { Authorization: `Bearer ${this.apiToken}` },
        params: { token: this.apiToken },
      });
      this.logger.log('Fetched open positions from Spotware');
      console.log('Open Positions Data:', response.data);
      return this.parseCsvData(response.data);
    } catch (error) {
      this.logger.error(`Failed to fetch open positions: ${error.message}`);
      throw new HttpException('Failed to fetch open positions', HttpStatus.FORBIDDEN);
    }
  }

  private async fetchClosedPositions() {
    const now = new Date();
    const to = now.toISOString();
    const from = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000).toISOString(); // 2-day range

    try {
      const response = await axios.get(`${this.spotwareApiUrl}/v2/webserv/closedPositions`, {
        headers: { Authorization: `Bearer ${this.apiToken}` },
        params: { from, to, token: this.apiToken },
      });
      this.logger.log('Fetched closed positions from Spotware');
      console.log('Closed Positions Data:', response.data);
      return this.parseCsvData(response.data);
    } catch (error) {
      this.logger.error(`Failed to fetch closed positions: ${error.message}`);
      throw new HttpException('Failed to fetch closed positions', HttpStatus.FORBIDDEN);
    }
  }

  // Parse CSV data from Spotware response
  private parseCsvData(csvData: string): any[] {
    const rows = csvData.split('\n').slice(1); // Skip header row
    return rows
      .filter((row) => row.trim())
      .map((row) => {
        const columns = row.split(',');
        return {
          login: columns[0],
          positionId: columns[1],
          openTimestamp: columns[2],
          entryPrice: columns[3],
          direction: columns[4],
          volume: columns[5],
          symbol: columns[6],
          commission: columns[7],
          swap: columns[8],
          bookType: columns[9],
          stake: columns[10],
          spreadBetting: columns[11],
          usedMargin: columns[12],
        };
      });
  }

  private async updateXanoWithPositions(openPositions: any[], closedPositions: any[]) {
    // Process each open position
    for (const pos of openPositions) {
      const openOrderData: CreateOrderDto = this.mapOpenPositionToOrderDto(pos);
      try {
        // Log the payload for inspection
        console.log('Open Position Payload for Xano:', openOrderData);
        await this.orderService.createOrUpdateOrder(openOrderData);
        this.logger.log(`Open Position sent to Xano: ${JSON.stringify(openOrderData)}`);
      } catch (error) {
        this.logger.error(`Failed to send open position to Xano: ${error.message}`);
      }
    }

    // Process each closed position
    for (const pos of closedPositions) {
      const closedOrderData: CreateOrderDto = this.mapClosedPositionToOrderDto(pos);
      try {
        // Log the payload for inspection
        console.log('Closed Position Payload for Xano:', closedOrderData);
        await this.orderService.createOrUpdateOrder(closedOrderData);
        this.logger.log(`Closed Position sent to Xano: ${JSON.stringify(closedOrderData)}`);
      } catch (error) {
        this.logger.error(`Failed to send closed position to Xano: ${error.message}`);
      }
    }
  }

  private mapOpenPositionToOrderDto(position: any): CreateOrderDto {
    return {
      key: position.positionId.toString(),
      ticket_id: Number(position.positionId),
      account: Number(position.login),
      type: position.direction,
      symbol: position.symbol,
      volume: parseFloat(position.volume),  // Ensure volume is a number
      entry_price: parseFloat(position.entryPrice),
      entry_date: position.openTimestamp,
      broker: 'Spotware',
      open_reason: position.bookType || 'AUTO',
    };
  }
  
  private mapClosedPositionToOrderDto(position: any): CreateOrderDto {
    return {
      key: position.positionId.toString(),
      ticket_id: Number(position.positionId),
      account: Number(position.login),
      type: position.direction,
      symbol: position.symbol,
      volume: parseFloat(position.volume),
      entry_price: parseFloat(position.entryPrice),
      entry_date: position.openTimestamp,
      close_price: parseFloat(position.closePrice),
      close_date: position.closeTimestamp,
      profit: parseFloat(position.pnl),
      broker: 'Spotware',
      open_reason: position.bookType || 'AUTO',
      close_reason: 'AUTO',
    };
  }
  
  

}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Xero Boost Days- What's on! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Manchester! \n\n We're excited to kickstart another great week in the office with our new Boost Day Program! :zap: \n\nPlease see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-29: Tuesday, 29th October",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with *Ditto Coffee*, located at 61, Oxford Street, M1 6EQ and now also at Union, Albert Square, M2 6LW. (Please show your Xero ID to claim your free coffee)\n:breakfast: *Breakfast*: Provided by *Balance Kitchen* from *8:30AM* in the kitchen area. \n:man_in_lotus_position: *Reflexology*: From *2:30pm* in the Wellbeing room. Please book here to reserve your slot-<https://docs.google.com/document/d/1Q6y9U-XSPMnzbtTuDUDuxUJMET-GeIyT/edit>."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-30: Wednesday, 30th October",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Café-style beverages with *Ditto Coffee*, located at 61 Oxford Street, M1 6EQ and now also at Union, Albert Square, M2 6LW. (Please bring your Xero ID to claim your free coffee)\n:cake: *Afternoon Tea*: Provided by *Balance Kitchen* from *2:30PM* in the kitchen area."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-30: Wednesday, 30th October",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":blob-party:* Social+*:beers: *Join the Oktoberfest fun at 4pm!*:beers:\nGet ready to raise your steins and celebrate Oktoberfest with us! :tada:\nFrom the epic Pretzel Toss :pretzel: to testing your knowledge with Oktoberfest Trivia :brain: and even guessing the weight of the giant sausage :hotdog: - we’ve got it all! Bring your A-game because prizes are up for grabs! :gift: :beer: "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Comms will be via this slack channel, get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
internal final class TI_TestProcu
{
    /// <summary>
    /// Class entry point. The system will call this method when a designated menu 
    /// is selected or when execution starts and this class is set as the startup class.
    /// </summary>
    /// <param name = "_args">The specified arguments.</param>
    public static void main(Args _args)
    {
      // 1st part is working fine
        AgreementLine   AgreementLine;
        select AgreementLine where AgreementLine.RecId == 5637407089;
        
        LedgerDimensionAccount LedgerDimensionAccount = LedgerDimensionFacade::serviceCreateLedgerDimension(
            LedgerDefaultAccountHelper::getDefaultAccountFromMainAccountRecId(
            MainAccount::findByMainAccountId('210106'/*'610101'*/).RecId),
            AgreementLine.DefaultDimension);
        LedgerJournalTrans  LedgerJournalTrans;
        select forupdate LedgerJournalTrans where LedgerJournalTrans.Voucher == 'GEN-005903';
        LedgerJournalTrans.LedgerDimension = LedgerDimensionAccount;
        ttsbegin;
        LedgerJournalTrans.update();
        ttscommit;
///---------------------------

        int hcount, hidx;
        RecId   dimAttrId_mainAcc;
        LedgerRecId ledgerRecId;
        MainAccount MainAccount;
        RefRecId    recValue;
        DimensionAttribute      DimensionAttribute;
        DimensionAttributeValue DimensionAttributeValue;
        DimensionSetSegmentName DimensionSetSegmentName;
        DimensionStorage        DimensionStorage;
        LedgerAccountContract   LedgerAccountContract = new LedgerAccountContract();
        DimensionAttributeValueContract DimensionAttributeValueContract;
        List valueContracts = new List(Types::Class);
        DimensionAttributeValueCombination  combina;

        MainAccount =  MainAccount::findByMainAccountId('210106');
        recValue = DimensionHierarchy::getAccountStructure(MainAccount.RecId, Ledger::current());
        hcount = DimensionHierarchy::getLevelCount(recValue);
        DimensionSetSegmentName = DimensionHierarchyLevel::getDimensionHierarchyLevelNames(recValue);
        info(strFmt("%1", hcount));
        str value;
        DimensionAttributeValueSetStorage dimStorage;
        dimStorage = DimensionAttributeValueSetStorage::find(AgreementLine.DefaultDimension);
        for(hidx=1; hidx<=hcount; hidx++)
        {
            DimensionAttribute = DimensionAttribute::findByLocalizedName(DimensionSetSegmentName[hidx]);
            value = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName(DimensionAttribute.Name).RecId);

            //if(DimensionAttribute)
            //{
            //    DimensionAttributeValue = DimensionAttributeValue::findByDimensionAttributeAndValue(
            //        DimensionAttribute,
            //        conPeek(

            //}
        }
        //AgreementLine   AgreementLine;
        //select AgreementLine where AgreementLine.RecId == 5637407089;
        //DimensionAttributeValueSetStorage dimStorage;
        //dimStorage = DimensionAttributeValueSetStorage::find(AgreementLine.DefaultDimension);
        //str budget = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('BudgetCode').RecId);
        //str Department = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('Department').RecId);
        //str General = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('General').RecId);
        //str Vendor = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('Vendor').RecId);
        //str Worker = dimStorage.getDisplayValueByDimensionAttribute(DimensionAttribute::findByName('Worker').RecId);
        //info(strFmt("%1 %2 %3 %4 %5", budget, Department, General, Vendor, Worker));

        //MainAccount =  MainAccount::findByMainAccountId('610101');
        //recValue = DimensionHierarchy::getAccountStructure(MainAccount.RecId, Ledger::current());
        //hcount = DimensionHierarchy::getLevelCount(recValue);
        //DimensionSetSegmentName = DimensionHierarchyLevel::getDimensionHierarchyLevelNames(recValue);
        //info(strFmt("%1", hcount));

        //for(hidx=1; hidx<=hcount; hidx++)
        //{
        //    DimensionAttribute = DimensionAttribute::findByLocalizedName(DimensionSetSegmentName[hidx]);
        //    info(DimensionAttribute.Name);
        //}
    }

}
a45dcf4d522de183cc9943a83bd7882b44de76b4
a45dcf4d522de183cc9943a83bd7882b44de76b4
////////*********** ARRAY PART 2 IN JS  ******//////////////////

 const marvel_hero = ["thor","Ironman","Spiderman"]
 const dc_hero =["superman","flash", "batman"]
  
//******************PUSH FUNCTION//////////////////////

//marvel_hero.push(dc_hero)
//console.log(marvel_hero); 
// OUTPUT = [ 'thor', 'Ironman', 'Spiderman', [ 'superman', 'flash', 'batman' ] ]
//console.log(marvel_hero[3][2]); // OUTPUT = batman 


//////////////////////CONACTINATIONN FUNCTION /////////////

//const all_heros = marvel_hero.concat(dc_hero) /// it will add both the array and give single array 
//console.log(all_heros); 
///OUTPUT = [ 'thor', 'Ironman', 'Spiderman', 'superman', 'flash', 'batman' ]


//////////////////////DROP FUNCTION ///////////////////////
const all_new_heroes = [...marvel_hero , ...dc_hero]
console.log(all_new_heroes); ///  drop function 
///OUTPUT = [ 'thor', 'Ironman', 'Spiderman', 'superman', 'flash', 'batman' ]

/////////////////////////FLAT FUNCTION ///////////////////////

const an_array = [1,2,3,[2,3],3,[4,5,[3,42]]]
const and_array = an_array.flat(Infinity); //function which flat all nested array in single array
console.log(and_array);



////////////////////////////OTHER FUNCTION of ARRAY ///////////////////////

console.log(Array.isArray('Hitesh')); /// ASKING WHETER IT IS OR NOT 
//// OUTPUT = FALSE 

console.log(Array.from('Hitesh'));///// CONVERTING INTO ARRAY 
//// OUTPUT = [ 'H', 'i', 't', 'e', 's', 'h' ]

console.log(Array.from({name:"hitesh"}))/// complex
//// OUTPUT = []

////////////////converting array from elements using Array.of function////////////

let score1 = 100
let score2 = 200
let score3 = 1300
console.log(Array.of(score1, score2 , score3));
/// OUTPUT = [ 100, 200, 1300 ]
  Args          salesArgs = new Args();  
   SalesInvoiceContract  salesInvoiceContract;  
   SalesInvoiceController controller;  
   SrsReportRunImpl    srsReportRunImpl;  
   str fileName;  
   CustInvoiceJour     custInvoiceJour;// = _args.record();  
     select custInvoiceJour where custInvoiceJour.InvoiceId=="INV_00000009";  
   salesArgs.record(custInvoiceJour);  
   controller       = new SrsReportRunController();  
   salesInvoiceContract  = new SalesInvoiceContract();  
   controller.parmReportName(ssrsReportStr(SalesInvoice,Report));  
   controller.parmShowDialog(false);  
   controller.parmReportContract().parmPrintSettings().printMediumType(SRSPrintMediumType::Printer);  
   // controller.parmReportContract().parmPrintSettings().printerName(@"\\espprn03\Follow Me - MFP");  
   salesInvoiceContract.parmRecordId(custInvoiceJour.RecId); // Record id must be passed otherwise the report will be empty  
   salesInvoiceContract.parmCountryRegionISOCode(SysCountryRegionCode::countryInfo()); // comment this code if tested in pre release  
   controller.parmReportContract().parmRdpContract(salesInvoiceContract);  
   controller.startOperation();  
/////////////////*********ARRAYS IN JS*********///////////////
const arr =[0,1,2,3,4,5]
const heros = ["srk","sk", "akki"]

console.log(arr[1]);

const arr2 = new Array(1,2,3,4,5,5)
console.log(arr2[1]);

////////// array methodss/////////////////////


arr.push(6) /// adding elements in array 
arr.push(7)
console.log(arr); 

arr.pop()/// remove last element in array
console.log(arr);

arr.unshift(9) //// adding at first 
console.log(arr);

arr.shift() //// removed 9
console.log(arr);

console.log(arr.includes(9));/// boolean outcomes 
console.log(arr.indexOf(2));/// index at prsented elemensted

const newArr = arr.join()
console.log(newArr);/// prints without square braces  
console.log(typeof newArr); /// changes number into string beacuse we used join() method


//////// slice  method
console.log("a" , arr);

const myn1 = arr.slice(1,3) // 1 and 2 will be printed 
console.log("after slicing ",myn1);
console.log("original copy will be same as a " , arr); 
 

///////splice method
const myn2 = arr.splice(1,3) // 1 , 2 and 3  will be printed 
console.log("after splicing ",myn2);
console.log("splice elements will be deleted " , arr); ///it will deleted the splice part 

//// inportant for interview question !!!!!!!!!!!

/* the difference bw slicing and splicing 
slicing - will print 1 less than the final index and not effect the orginal copy..
spkicing - will print all the elements and delete all spliced elements from the original array*/
npm install three @types/three @react-three/fiber
//////////************ DATE AND TIME ****************///////////////


let myDate = new Date()
console.log(myDate);///2024-10-27T15:14:36.998Z
console.log(myDate.toString());///Sun Oct 27 2024 15:14:36 GMT+0000 (Coordinated Universal Time)
console.log(myDate.toDateString());////Sun Oct 27 2024
console.log(myDate.toISOString());////2024-10-27T15:14:36.998Z
console.log(myDate.toLocaleString());///10/27/2024, 3:14:36 PM 
console.log(myDate.toLocaleTimeString());////3:14:36 PM
console.log(typeof myDate); /// object


console.log(  "           new date       "   );
let myCreatedDate = new Date(2023 , 0, 23) //// in js months starts from 0 means 0=january 
console.log(myCreatedDate.toDateString()); ////Mon Jan 23 2023

let myCreatedDate2 = new Date(2023-01-23) //// in ddmmyy 1 = january in months 
console.log(myCreatedDate2.toDateString());

let myCreatedDate3 = new Date(01-41-2023) //// in mmddyy 1 = january in months 
console.log(myCreatedDate3.toDateString());

let myTimeStamp = Date.now()
console.log(myTimeStamp); 
console.log(myCreatedDate.getTime()); /// at time i started
console.log(Math.floor(Date.now()/1000));// converting in seconds and floor for gettting a acute time 


let newDate = new Date();
console.log(newDate.getMonth()+1);
console.log(newDate.getDay());


newDate.toLocaleString('default',{ //// for setting something as default setting
    weekday: "long"
    timeZone: ' '
})
///////////////////// number  in javascript //////////////

const score = new Number(400)
console.log(score); ///[Number: 400]

const score2 =500
console.log(score2); ///500

console.log(score2.toString().length);//3
console.log(score2.toFixed(2));  ///500.0
 
const othernumber = 23.9898
console.log(othernumber.toPrecision(3));///precise value (24.0)


const hundreds = 100000
console.log(hundreds.toLocaleString('en-IN')); /// comammas in value in indian number system (output =  1,00,000)



//////////////////////////*********MATHS IN JS *****************/////////////////

console.log(Math); 
console.log(Math.abs(-4));/// it works like modulus convert all in +ve 
console.log(Math.round(4.6));/// roundoff  (5)
console.log(Math.ceil(4.6)); /// roundoff at upper (5) 
console.log(Math.floor(4.6)); /// roundoff at lower (4)
console.log(Math.min(4,4 , 6, 1, 6));/// 1 
console.log(Math.max(4,4 , 6, 1, 6));/// 6

console.log(Math.random()); 
console.log((Math.random()*10) + 1);
console.log(Math.floor(Math.random()*10) + 1);

/////////******************* when limits are given *****////////////////
const min = 10
const max = 20
console.log(Math.floor(Math.random() * (max-min+1)) + min )


// for example, in my-custom-components.ts 
import { type RegisteredComponent } from "@builder.io/sdk-react";
import { MyFunComponent } from "./MyFunComponent";

export const customComponents: RegisteredComponent[] = [
  {
    component: MyFunComponent,
    // ---> You could also lazy load your component using:
    // component: React.lazy(() => import('./MyFunComponent')),
    name: 'MyFunComponent',
    inputs: [
      {
        name: 'text',
        type: 'string',
        defaultValue: 'Hello world',
      },
    ],
  },
];
// for example, MyFunComponent.tsx
import { useState } from 'react';

export const MyFunComponent = (props: { text: string }) => {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h3>{props.text.toUpperCase()}</h3>
      <p>{count}</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};
Subsets of an Array using Backtracking
Balanced Parentheses
String Partitioning
Smart Square
Bubble sort
Selection sort
Insertion sort
Sort 0's and 1's
Jaganmohan Reddy — 10/24/2024 1:36 PM
Lab Agenda

Smaller Elements
Sum of Pairs
Finding the Floor
Triplet with Sum K
Frequency Sort
Jaganmohan Reddy — 10/25/2024 1:29 PM
Lab Agenda

Finding Frequency 4,5,6 solutions
Finding CubeRoot
Cabinets Partitioning(BT and BS)
using Microsoft.Dynamics.ApplicationPlatform.Environment;

class CPLDevCapexUtility
{
  
  //---------------------Vendor Approval Notification-----------------------------------

    public static void sendFinanceForVendorApprovalNotification1(UserId	_usrId, AccountNum _vendor)
  {
    SystemNotificationDataContract notification = new SystemNotificationDataContract();
    notification.Users().value(1, _usrId);
    notification.Title("Vendor Approved");
    notification.RuleId('ExcelStaticExport');
    notification.Message(strFmt("%1 new vendor has added, please approved.", _vendor));
    notification.ExpirationDateTime(DateTimeUtil::addHours(DateTimeUtil::utcNow(), 72));

    ////// Set up the action associated with the notification
    ////SystemNotificationActionDataContract action = new SystemNotificationActionDataContract();
    ////action.Message("Click to download");
    ////action.Type(SystemNotificationActionType::AxActionMenuFunction);

    ////SystemNotificationMenuFunctionDataContract actionData = new SystemNotificationMenuFunctionDataContract();
    ////actionData.MenuItemName(menuItemActionStr(ExportToExcelStaticOpenFileAction));
    ////actionData.Data(fileName);
    ////action.Data(FormJsonSerializer::serializeClass(actionData));
    ////notification.Actions().value(1, action);

    SystemNotificationsManager::AddSystemNotification(notification);

  }

    public static void sendFinanceForVendorApprovalEmail(UserId	_usrId, AccountNum _vendor)
  {
    //SysEmailTable   sysEmailTable;
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
    //SysUserInfo        userInfo = SysUserInfo::find(_usrId, false);
    UserInfo userInfo;
    select * from userInfo where userInfo.Id==_usrId;
    var messageBuilder = new SysMailerMessageBuilder();

    //select firstonly sysEmailTable;

    //if(userInfo.Email)
    if(userInfo.networkAlias)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
     // messageBuilder.addTo(userInfo.Email);
      messageBuilder.addTo(userInfo.networkAlias);
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");
      messageBuilder.setSubject("New Vendor added, need to approve");
      messageBuilder.setBody(strFmt('%1 new vendor is added, please approve the vendor.', _vendor, curUserId()));
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    //---------------------Vendor Approval Notification End-----------------------------------

  //---------------------Vendor Approved Notification-----------------------------------
  public static void sendVendorApprovalNotification1(UserId	_usrId, AccountNum _vendor)
  {
      SystemNotificationDataContract notification = new SystemNotificationDataContract();
      notification.Users().value(1, _usrId);
      notification.Title("Vendor Approved");
      notification.RuleId('ExcelStaticExport');
      notification.Message(strFmt("%1 vendor has approved by finance team", _vendor));
      notification.ExpirationDateTime(DateTimeUtil::addHours(DateTimeUtil::utcNow(), 72));

      //// Set up the action associated with the notification
      //SystemNotificationActionDataContract action = new SystemNotificationActionDataContract();
      //action.Message("Click to download");
      //action.Type(SystemNotificationActionType::AxActionMenuFunction);

      //SystemNotificationMenuFunctionDataContract actionData = new SystemNotificationMenuFunctionDataContract();
      //actionData.MenuItemName(menuItemActionStr(ExportToExcelStaticOpenFileAction));
      //actionData.Data(fileName);
      //action.Data(FormJsonSerializer::serializeClass(actionData));
      //notification.Actions().value(1, action);

      SystemNotificationsManager::AddSystemNotification(notification);

  }

    public static void sendVendorApprovalEmail(UserId	_usrId, AccountNum _vendor)
  {
    //SysEmailTable   sysEmailTable;
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
    //SysUserInfo        userInfo = SysUserInfo::find(_usrId, false);
    UserInfo userInfo;
    select * from userInfo where userInfo.id==_usrId;
    var messageBuilder = new SysMailerMessageBuilder();

    //select firstonly sysEmailTable;

    if(userInfo.networkAlias)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
      messageBuilder.addTo(userInfo.networkAlias);
     // messageBuilder.addTo(userInfo.Email);
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");
      messageBuilder.setSubject("Vendor Approved by finance team");
      messageBuilder.setBody(strFmt('%1 vendor has been approved by %2', _vendor, curUserId()));
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    //---------------------Vendor Approved Notification End-----------------------------------
  
  
  //---------------------Fixed Asset Approval Notification -----------------------------------
  public static void sendFinanceForFixedAssetApprovalNotification1(UserId	_usrId, AssetId _assetId)
  {
    SystemNotificationDataContract notification = new SystemNotificationDataContract();
    notification.Users().value(1, _usrId);
    notification.Title("New Fixed Asset");
    notification.RuleId('ExcelStaticExport');
    notification.Message(strFmt("%1 new fixed asset has added, need to approve", _assetId));
    notification.ExpirationDateTime(DateTimeUtil::addHours(DateTimeUtil::utcNow(), 72));
    
    SystemNotificationsManager::AddSystemNotification(notification);
  }

    public static void sendFinanceForFixedAssetApprovalEmail(UserId	_usrId, AssetId _assetId)
  {
    //SysEmailTable   sysEmailTable;
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
    SysUserInfo        userInfo = SysUserInfo::find(_usrId, false);
    var messageBuilder = new SysMailerMessageBuilder();

    //select firstonly sysEmailTable;

    if(userInfo.Email)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
      messageBuilder.addTo(userInfo.Email);
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");
      messageBuilder.setSubject("New Fixed Asset added");
      messageBuilder.setBody(strFmt('%1 new fixed asset has added, need to approve', _assetId));
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    //---------------------Fixed Asset Approval Notification End-----------------------------------
  
  //---------------------Fixed Asset Approved Notification-----------------------------------
    public static void sendFixedAssetApprovalNotification1(UserId	_usrId, AssetId _assetId)
  {
    SystemNotificationDataContract notification = new SystemNotificationDataContract();
    notification.Users().value(1, _usrId);
    notification.Title("Fixed Asset Approved");
    notification.RuleId('ExcelStaticExport');
    notification.Message(strFmt("%1 fixed asset has been approved by finance team", _assetId));
    notification.ExpirationDateTime(DateTimeUtil::addHours(DateTimeUtil::utcNow(), 72));

    SystemNotificationsManager::AddSystemNotification(notification);

  }

    public static void sendFixedAssetApprovalEmail(UserId	_usrId, AssetId _assetId)
  {
    //SysEmailTable   sysEmailTable;
    SysUserInfo        userInfo = SysUserInfo::find(_usrId, false);
    var messageBuilder = new SysMailerMessageBuilder();
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();

    //select firstonly sysEmailTable;

    if(userInfo.Email)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
      messageBuilder.addTo(userInfo.Email);
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");
      messageBuilder.setSubject("Fixed asset Approved by finance team");
      messageBuilder.setBody(strFmt('%1 fixed asset has been approved by %2', _assetId, curUserId()));
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    //---------------------Fixed Asset Approved Notification End-----------------------------------
  
  //-------------------------------------------------------------------------------------------------------------------------------------

  public static void sendNotificationToCreaterForCapexApproval1(UserId	_usrId, CPLDevCapexRequestNo _capexReqNo)
  {
    SystemNotificationDataContract notification = new SystemNotificationDataContract();
    notification.Users().value(1, _usrId);
    notification.Title("Capex Approved");
    notification.RuleId('ExcelStaticExport');
    notification.Message(strFmt("%1 Capex has been approved by the team", _capexReqNo));
    notification.ExpirationDateTime(DateTimeUtil::addHours(DateTimeUtil::utcNow(), 72));

    SystemNotificationsManager::AddSystemNotification(notification);

  }

    public static void sendEmailToCreaterForCapexApprovalOld(UserId	_usrId, CPLDevCapexRequestNo _capexReqNo)
  {
    str             emailBody = '';
    SysEmailTable   sysEmailTable;
    CPLDevCapexHeader cplCapexHeader;
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
    SysUserInfo        userInfo = SysUserInfo::find(_usrId, false);
    var messageBuilder = new SysMailerMessageBuilder();

    select firstonly sysEmailTable;

    select firstonly cplCapexHeader where cplCapexHeader.CapexRequestNo == _capexReqNo;

    if(userInfo.Email)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
      messageBuilder.addTo(userInfo.Email);
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");

      emailBody = '<html>';
      emailBody = '<head><style>table, th, td{border: 1px solid black;border-collapse: collapse;}</style></head>';
      emailBody = '<html><body>';
      emailBody += '<p1>Hi ' + CPLDevCapexUtility::getUserName(_usrId) + '</p><br>';
      emailBody += 'This is to inform you that your capex request has been approved<br>';
      emailBody += 'Here is a brief summary of capex request:<br><br>';

      emailBody += '<table role="presentation" border="1" cellspacing="0" style="width:100%;"><tr>';
      emailBody += '<th>Capex Request No.</th>';
      emailBody += '<th>Capex/Project Name</th>';
      emailBody += '<th>Priority</th>';
      emailBody += '<th>Currency</th>';
      emailBody += '<th align="right">Total Amount</th>';
      emailBody += '<th align="right">Forecasted Amount</th>';
      emailBody += '<th>Request Date</th>';
      emailBody += '<th>Request Status</th></tr>';


      emailBody += '<tr>';
      emailBody += '<td><a href="' + CPLDevCapexUtility::getCapexURL(_capexReqNo) + '" target="_blank">' + _capexReqNo + '</td>';
      //emailBody += '<td>' + _capexReqNo + '</td>';
      emailBody += '<td>' + cplCapexHeader.CapexProjectName + '</td>';
      emailBody += '<td>' + enum2Str(cplCapexHeader.Priority) + '</td>';
      emailBody += '<td>' + cplCapexHeader.Currency + '</td>';
      emailBody += '<td align="right">' + num2Str(cplCapexHeader.TotalAmount(), 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
      emailBody += '<td align="right">' + num2Str(cplCapexHeader.ForecastedAmount, 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
      emailBody += '<td>' + date2Str(cplCapexHeader.RequestDate,321,DateDay::Digits2,DateSeparator::Hyphen, DateMonth::Digits2,DateSeparator::Hyphen,DateYear::Digits4) + '</td>';
      emailBody += '<td>' + enum2Str(cplCapexHeader.CPLCapexWorkflowStatusEnum) + '</td></tr></table>';

      emailBody += '<br><br>Thanks.<br>';
      emailBody += '</body></html>';


      messageBuilder.setSubject(strFmt("%1 Capex has approved ", _capexReqNo));
      messageBuilder.setBody(emailBody,true);
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    public static void sendEmailToCreaterForCapexChangeStatus(UserId	_usrId, CPLDevCapexRequestNo _capexReqNo, str csStatus,PurchId _purchid = null)
    //SIT3-104-To add Auto-created Purchase order number in mail-[PavanKini]03March2023 starts here--->
  {
    str                 emailBody = '';
    SysEmailTable       sysEmailTable;
    CPLDevCapexHeader   cplCapexHeader;
    SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
  //  SysUserInfo         userInfo = SysUserInfo::find(_usrId, false);   //Manju Y
    UserInfo userInfo;
    select * from userInfo where userInfo.id==_usrId;
    var messageBuilder = new SysMailerMessageBuilder();

    select firstonly sysEmailTable;

    select firstonly cplCapexHeader where cplCapexHeader.CapexRequestNo == _capexReqNo;

   // if(userInfo.Email)
   if(userInfo.networkAlias)
    {
      messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
     // messageBuilder.addTo(userInfo.Email);
     messageBuilder.addTo(userInfo.networkAlias);//manju y
      //messageBuilder.addCc("cc@example.com");
      //messageBuilder.addBcc("bcc@example.com");

      emailBody = '<html>';
      emailBody = '<head><style>table, th, td{border: 1px solid black;border-collapse: collapse;}</style></head>';
      emailBody = '<html><body>';
      emailBody += '<p1>Hi ' + CPLDevCapexUtility::getUserName(_usrId) + '</p><br>';
      if(csStatus == 'ChangeRequest')
      {
        emailBody += 'This is to inform you that your capex request has Change Request<br>';
      }
      else
      {
        emailBody += strFmt('This is to inform you that your capex request has been %1<br>', csStatus);
      }
      
      emailBody += 'Here is a brief summary of capex request:<br><br>';

      emailBody += '<table role="presentation" border="1" cellspacing="0" style="width:100%;"><tr>';
      emailBody += '<th>Capex Request No.</th>';
      emailBody += '<th>Capex/Project Name</th>';
      emailBody += '<th>Priority</th>';
      emailBody += '<th>Currency</th>';
      emailBody += '<th align="right">Total Amount</th>';
      emailBody += '<th align="right">Forecasted Amount</th>';
      emailBody += '<th>Request Date</th>';
     
     //SIT3-104-To add Auto-created Purchase order number in mail-[PavanKini]03March2023 starts here--->
      if(csStatus =="approved" && _purchid)  //[ManjuY]   added MV validation
      {
        emailBody += '<th>Request Status</th>';
        emailBody += '<th>Purchase Order No</th></tr>';
      }
      else
      {
        emailBody += '<th>Request Status</th></tr>';
      }
      //SIT3-104-To add Auto-created Purchase order number in mail-[PavanKini]03March2023 ends here--->

      emailBody += '<tr>';
      emailBody += '<td><a href="' + CPLDevCapexUtility::getCapexURL(_capexReqNo) + '" target="_blank">' + _capexReqNo + '</td>';
      //emailBody += '<td>' + _capexReqNo + '</td>';
      emailBody += '<td>' + cplCapexHeader.CapexProjectName + '</td>';
      emailBody += '<td>' + enum2Str(cplCapexHeader.Priority) + '</td>';
      emailBody += '<td>' + cplCapexHeader.Currency + '</td>';
      emailBody += '<td align="right">' + num2Str(cplCapexHeader.TotalAmount(), 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
      emailBody += '<td align="right">' + num2Str(cplCapexHeader.ForecastedAmount, 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
      emailBody += '<td>' + date2Str(cplCapexHeader.RequestDate,321,DateDay::Digits2,DateSeparator::Hyphen, DateMonth::Digits2,DateSeparator::Hyphen,DateYear::Digits4) + '</td>';
    
      //SIT3-104-To add Auto-created Purchase order number in mail-[PavanKini]03March2023 starts here-->
      if(csStatus == "approved" && _purchid)    //[ManjuY]   added MV validation
      {
        emailBody += '<td>' + csStatus + '</td>';
        emailBody += '<td>' + _purchid + '</td></tr></table>';
      }
      else
      {
        emailBody += '<td>' + csStatus + '</td></tr></table>';
      }
      //todo
      //SIT3-104-To add Auto-created Purchase order number in mail-[PavanKini]03March2023 ends here--->

      emailBody += '<br><br>Thanks.<br>';
      emailBody += '</body></html>';

      //SIT-106-Capex Approved email for both single and multiple vendor PDF attachment- PavanKini 06-March-2023
      if(csStatus =="approved")
      {
          //------------------------------RptGenerate-----------------------------------------------------

          Filename fileName = _capexReqNo + ".pdf";
          SrsReportRunController              controller = new SrsReportRunController();
          CPLDevCapexSingleVendorContract     dataContract1 = new CPLDevCapexSingleVendorContract();
          SRSPrintDestinationSettings         settings;
          Array                               arrayFiles;
          System.Byte[]                       reportBytes = new System.Byte[0]();
          SRSProxy                            srsProxy;
          SRSReportRunService                 srsReportRunService = new SrsReportRunService();
          Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[] parameterValueArray;
          Map                                 reportParametersMap;
          SRSReportExecutionInfo              executionInfo = new SRSReportExecutionInfo();

          if(cplCapexHeader.ForKnownVendor == NoYes::Yes)
          {
            controller.parmReportName(ssrsReportStr(CPLDevCaexSiingleVendorReport, Report));
          }
          else
          {
            controller.parmReportName(ssrsReportStr(CPLDevCaexSiingleVendorReport, CapexMVReport));
          }
          controller.parmShowDialog(false);
          //controller.parmExecutionMode(SysOperationExecutionMode::ScheduledBatch);
          //controller.parmInBatch(true);

          dataContract1 = controller.parmReportContract().parmRdpContract() as CPLDevCapexSingleVendorContract ;
          dataContract1.parmCPLDevCapexRequestNo(_capexReqNo); //_capexReqNo

          controller.parmLoadFromSysLastValue(false);
          // Provide printer settings
          settings = controller.parmReportContract().parmPrintSettings();
          settings.printMediumType(SRSPrintMediumType::File);
          settings.fileName(fileName);
          settings.fileFormat(SRSReportFileFormat::PDF);

          // Below is a part of code responsible for rendering the report
          controller.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());
          controller.parmReportContract().parmReportExecutionInfo(executionInfo);
 
          srsReportRunService.getReportDataContract(controller.parmreportcontract().parmReportName());
          srsReportRunService.preRunReport(controller.parmreportcontract());
          reportParametersMap = srsReportRunService.createParamMapFromContract(controller.parmReportContract());
          parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);
 
          srsProxy = SRSProxy::constructWithConfiguration(controller.parmReportContract().parmReportServerConfig());
          // Actual rendering to byte array
          reportBytes = srsproxy.renderReportToByteArray(controller.parmreportcontract().parmreportpath(),parameterValueArray,settings.fileFormat(),settings.deviceinfo());
 
          // You can also convert the report Bytes into an xpp BinData object if needed
          container binData;
          Binary binaryData;
          System.IO.MemoryStream mstream = new System.IO.MemoryStream(reportBytes);
          binaryData = Binary::constructFromMemoryStream(mstream);
          if(binaryData)
          {
            binData = binaryData.getContainer();
          }
 
          System.Byte[] binData1;
          System.IO.Stream stream1;
 
          // Turn the Bytes into a stream
          for(int i = 0; i < conLen(binData); i++)
          {
            binData1 = conPeek(binData,i+1);
            stream1 = new System.IO.MemoryStream(binData1);
          }

          messageBuilder.addAttachment(stream1, fileName);

      }

        //-----------------------------RptGenerateEnd----------------------------------------------------
      //SIT-106-Capex Approved email for both single and multiple vendor PDF attachment- PavanKini 06-March-2023
      messageBuilder.setSubject(strFmt("%1 Capex has %2 ", _capexReqNo, csStatus));
      messageBuilder.setBody(emailBody,true);

    
      SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
    }

  }

    public static void sendEmailToApprovarForCapexApproval(UserId	_usrId, CPLDevCapexRequestNo _capexReqNo, System.IO.Stream _stream = null)
    {
      str                 emailBody = '';
      SysEmailTable       sysEmailTable;
      CPLDevCapexHeader   cplCapexHeader;
      SysEmailParameters  sysEmailParameters = SysEmailParameters::find();
     // SysUserInfo         userInfo = SysUserInfo::find(_usrId, false);
      UserInfo userInfo;
      select * from userInfo where userInfo.id ==_usrId;          //manjuy
      var messageBuilder = new SysMailerMessageBuilder();
      //select firstonly sysEmailTable;
      select firstonly cplCapexHeader where cplCapexHeader.CapexRequestNo == _capexReqNo;
      URL attachmentUrl = CPLDevCapexUtility::getAttachmentURL(cplCapexHeader.RecId, cplCapexHeader.DataAreaId);
      

      changecompany(cplCapexHeader.DataAreaId)
      {
     // if(userInfo.Email)
     if(userInfo.networkAlias)
      {
        messageBuilder.setFrom(sysEmailParameters.SMTPUserName);
        //messageBuilder.addTo(userInfo.Email);
        messageBuilder.addTo(userInfo.networkAlias);  //manjuY
        //messageBuilder.addCc("cc@example.com");
        //messageBuilder.addBcc("bcc@example.com");

        
        emailBody = '<html>';
        emailBody += '<head><style>table, th, td{border: 1px solid black;border-collapse: collapse;}</style></head>';
        emailBody += '<html><body>';
        emailBody += '<p1>Hi ' + CPLDevCapexUtility::getUserName(_usrId) + '</p><br>';  //hcmWorker.name()
        emailBody += CPLDevCapexUtility::getUserName(cplCapexHeader.CreatedBy) + ' has sent you capex request for review and approval.<br><br>';  //hcmWorkerCreator.name()
        emailBody += 'Here is a brief summary of capex request:<br><br>';

        emailBody += '<table role="presentation" border="1" cellspacing="0" style="width:100%;"><tr>';
        emailBody += '<th>Capex Request No.</th>';
        emailBody += '<th>Capex/Project Name</th>';
        emailBody += '<th>Priority</th>';
        emailBody += '<th>Currency</th>';
        emailBody += '<th align="right">Total Amount</th>';
        emailBody += '<th align="right">Forecasted Amount</th>';
        emailBody += '<th>Request Date</th>';
        emailBody += '<th>Request Status</th></tr>';


        emailBody += '<tr>';
        emailBody += '<td><a href="' + CPLDevCapexUtility::getCapexURL(_capexReqNo) + '" target="_blank">' + _capexReqNo + '</td>';
        //emailBody += '<td>' + _capexReqNo + '</td>';
        emailBody += '<td>' + cplCapexHeader.CapexProjectName + '</td>';
        emailBody += '<td>' + enum2Str(cplCapexHeader.Priority) + '</td>';
        emailBody += '<td>' + cplCapexHeader.Currency + '</td>';
        emailBody += '<td align="right">' + num2Str(cplCapexHeader.TotalAmount(), 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
        emailBody += '<td align="right">' + num2Str(cplCapexHeader.ForecastedAmount, 0, 2, DecimalSeparator::Dot, ThousandSeparator::Comma) + '</td>';
        emailBody += '<td>' + date2Str(cplCapexHeader.RequestDate,321,DateDay::Digits2,DateSeparator::Hyphen, DateMonth::Digits2,DateSeparator::Hyphen,DateYear::Digits4) + '</td>';
        
        if(cplCapexHeader.CPLCapexWorkflowStatusEnum == CPLCapexWorkflowStatusEnum::Created || cplCapexHeader.CPLCapexWorkflowStatusEnum == CPLCapexWorkflowStatusEnum::Submitted)
        {
          emailBody += '<td>Submitted</td></tr></table>';
        }
        else
        {
          emailBody += '<td>' + enum2Str(cplCapexHeader.CPLCapexWorkflowStatusEnum) + '</td></tr></table>';
        }
        
        if(attachmentUrl != '')
        {
          emailBody += '<br><br>Please find below attachment url:';
          emailBody += '<br><a href="' + attachmentUrl + '" target="_blank">' + attachmentUrl + '</a>';
        }

        emailBody += '<br><br>Please help with your decision on approval/rejection/on-hold to proceed with the request.';
        emailBody += '<br><br>Thanks.<br>';
        emailBody += '</body></html>';
        //Capex Approval reminder email set Subject Line added by [Manju Y]
        if(cplCapexHeader.ReminderDate == today() && cplCapexHeader.CPLCapexWorkflowStatusEnum==CPLCapexWorkflowStatusEnum::Submitted)
        {
          messageBuilder.setSubject(strFmt("REMINDER: %1 Capex for review and approval ", _capexReqNo));
        }
        else
        {
          messageBuilder.setSubject(strFmt("%1 Capex for review and approval ", _capexReqNo));
        }
        //messageBuilder.setSubject(strFmt("%1 Capex for review and approval ", _capexReqNo));
        messageBuilder.setBody(emailBody,true);


        //------------------------------RptGenerate-----------------------------------------------------

        Filename fileName = _capexReqNo + ".pdf";
        SrsReportRunController              controller = new SrsReportRunController();
        CPLDevCapexSingleVendorContract     dataContract1 = new CPLDevCapexSingleVendorContract();
        SRSPrintDestinationSettings         settings;
        Array                               arrayFiles;
        System.Byte[]                       reportBytes = new System.Byte[0]();
        SRSProxy                            srsProxy;
        SRSReportRunService                 srsReportRunService = new SrsReportRunService();
        Microsoft.Dynamics.AX.Framework.Reporting.Shared.ReportingService.ParameterValue[] parameterValueArray;
        Map                                 reportParametersMap;
        SRSReportExecutionInfo              executionInfo = new SRSReportExecutionInfo();

        if(cplCapexHeader.ForKnownVendor == NoYes::Yes)
        {
          controller.parmReportName(ssrsReportStr(CPLDevCaexSiingleVendorReport, Report));
        }
        else
        {
          controller.parmReportName(ssrsReportStr(CPLDevCaexSiingleVendorReport, CapexMVReport));
        }
        controller.parmShowDialog(false);
        //controller.parmExecutionMode(SysOperationExecutionMode::ScheduledBatch);
        //controller.parmInBatch(true);

        dataContract1 = controller.parmReportContract().parmRdpContract() as CPLDevCapexSingleVendorContract ;
        dataContract1.parmCPLDevCapexRequestNo(_capexReqNo); //_capexReqNo

        controller.parmLoadFromSysLastValue(false);
        // Provide printer settings
        settings = controller.parmReportContract().parmPrintSettings();
        settings.printMediumType(SRSPrintMediumType::File);
        settings.fileName(fileName);
        settings.fileFormat(SRSReportFileFormat::PDF);

        // Below is a part of code responsible for rendering the report
        controller.parmReportContract().parmReportServerConfig(SRSConfiguration::getDefaultServerConfiguration());
        controller.parmReportContract().parmReportExecutionInfo(executionInfo);
 
        srsReportRunService.getReportDataContract(controller.parmreportcontract().parmReportName());
        srsReportRunService.preRunReport(controller.parmreportcontract());
        reportParametersMap = srsReportRunService.createParamMapFromContract(controller.parmReportContract());
        parameterValueArray = SrsReportRunUtil::getParameterValueArray(reportParametersMap);
 
        srsProxy = SRSProxy::constructWithConfiguration(controller.parmReportContract().parmReportServerConfig());
        // Actual rendering to byte array
        reportBytes = srsproxy.renderReportToByteArray(controller.parmreportcontract().parmreportpath(),parameterValueArray,settings.fileFormat(),settings.deviceinfo());
 
        // You can also convert the report Bytes into an xpp BinData object if needed
        container binData;
        Binary binaryData;
        System.IO.MemoryStream mstream = new System.IO.MemoryStream(reportBytes);
        binaryData = Binary::constructFromMemoryStream(mstream);
        if(binaryData)
        {
          binData = binaryData.getContainer();
        }
 
        System.Byte[] binData1;
        System.IO.Stream stream1;
 
        // Turn the Bytes into a stream
        for(int i = 0; i < conLen(binData); i++)
        {
          binData1 = conPeek(binData,i+1);
          stream1 = new System.IO.MemoryStream(binData1);
        }
        //-----------------------------RptGenerateEnd----------------------------------------------------

        messageBuilder.addAttachment(stream1, fileName);

        SysMailerFactory::getNonInteractiveMailer().sendNonInteractive(messageBuilder.getMessage());
      }

    }
    }

    public static void sendEmailToApprovarForCapexWorkflowApproval(CPLDevCapexRequestNo _capexReqNo)
  {
    WorkflowTable           workflowTable;
    WorkflowVersionTable    workflowVersionTable;
    WorkflowElementTable    workflowElementTable;
    WorkflowStepTable       workflowStepTable;
    WorkflowAssignmentTable workflowAssignmentTable;
    System.IO.Stream        streamAttachment;
    container               conUser;
    int                     conPos;

    select workflowAssignmentTable
      join workflowStepTable
      where workflowStepTable.RecId == workflowAssignmentTable.workflowStepTable
      join workflowElementTable
      where workflowElementTable.ElementId == workflowStepTable.ElementId
      join workflowVersionTable
      where workflowVersionTable.ConfigurationId == workflowElementTable.ConfigurationId
      && workflowVersionTable.Enabled == NoYes::Yes
      join workflowTable
      where workflowTable.RecId == workflowVersionTable.workflowTable
      && workflowTable.DocumentTableName == "CPLDevCapexHeader"
      && workflowTable.TemplateName == 'CPLDevCapexWFType';
    if(workflowAssignmentTable.UserValue != '')
    {
      conUser = str2con(workflowAssignmentTable.UserValue, ";");
      if(conLen(conUser) > 0)
      {
        for(conPos=1; conPos <= conlen(conUser); conPos++)
        {
            CPLDevCapexUtility::sendEmailToApprovarForCapexApproval(conPeek(conUser, conPos),_capexReqNo, streamAttachment);
        }
      } 
    }
    else if(workflowAssignmentTable.ParticipantTokenName !='')  //added by Manju Y [fetch users from group]
    {
      UserGroupList groupList;
      while select groupList where groupList.groupId==workflowAssignmentTable.ParticipantTokenName
      {
          CPLDevCapexUtility::sendEmailToApprovarForCapexApproval(groupList.userId, _capexReqNo, streamAttachment);
      }
    }
  }

    private static Name getUserName(UserId _userId)
  {
    UserInfo usrInfoLoc;
    select firstonly1 usrInfoLoc where usrInfoLoc.id == _userId;
    return usrInfoLoc.name;
  }

    public static str getCapexURL(CPLDevCapexRequestNo _requestNo)
  {

    try
    {
      // gets the generator instance
      var generator     = new Microsoft.Dynamics.AX.Framework.Utilities.UrlHelper.UrlGenerator();
      //var currentHost   = new System.Uri(UrlUtility::getUrl());

      IApplicationEnvironment env = EnvironmentFactory::GetApplicationEnvironment();
      str currentUrl = env.Infrastructure.HostUrl;
      System.Uri currentHost = new System.Uri(currentUrl);

      generator.HostUrl = currentHost.GetLeftPart(System.UriPartial::Authority);
      generator.Company = curext();
      generator.MenuItemName = 'CPLDevCapexSummMI';
      generator.Partition = getCurrentPartition();

      // repeat this segment for each datasource to filter
      var requestQueryParameterCollection = generator.RequestQueryParameterCollection;
      requestQueryParameterCollection.AddRequestQueryParameter('CPLDevCapexHeader', 'CapexRequestNo', _requestNo);

      //System.Uri retURI = generator.GenerateFullUrl().AbsoluteUri;

      // to get the encoded URI, use the following code
      return generator.GenerateFullUrl().AbsoluteUri;
    }
    catch(Exception::CLRError)
    {
      System.Exception ex = CLRInterop::getLastException();
      info(ex.Message);
      return '';
    }

  }

    public static URL getAttachmentURL(RefRecId _recId, DataAreaId _dataArea)
  {
    DocuRef     docuRef;
    DocuType    docuType;

    select  docuRef
          order by docuRef.createddatetime desc
          where docuRef.RefTableId == tableName2Id('CPLDevCapexHeader') //_common.TableId
          && docuRef.RefRecId      == _recId //_common.RecId
          && docuRef.RefCompanyId  == _dataArea //_common.DataAreaId
      exists join DocuType
          where DocuType.TypeId    == docuRef.TypeId
          && DocuType.TypeGroup    == DocuTypeGroup::URL;

    return docuRef.url();
  }

}
def sum_of_digits(number):
    sum = 0
    while number > 0:
        digit = number % 10
        sum += digit
        number = number // 10
    return sum

# Example usage
number = 12345
print("Sum of the digits:", sum_of_digits(number))
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize]
"AppsUseLightTheme"=dword:00000000
"SystemUsesLightTheme"=dword:00000000
 ///////////////stack and heap memory in js////////////////////
 
 //// STACK MEMORY(PRIMITIVE USED ) 
 let myYotubename ="hitensh" 
 let anothername = myYotubename //value assinged 
 anothername="chaiorcode"//value updates 
 
 /// copy is returning
 console.log(myYotubename);//hitensh  
console.log(anothername);//chaiorcode
 
 
 
 
 //////// HEAP (NON PRIMITIVE USED)
 
let UserOne = {
    email: "oldgmail.com",
    upi: "user@ybl"
}
let UserTwo = UserOne 

UserTwo.email ="new22gmail.com"

console.log(UserOne.email); /// new22gmail.com
console.log(UserTwo.email);/// new22gmail.com
/////////////////datatypes summary /////////////////////

/// primitive datatype 
// 7 types : string. number, boolean , null ,  undefined , symbol , bigint 

const score = 100
const scoreValue = 100.09
const isLoggedIn = false
const outsideTemp = null

let userEmail;// undefined 

const ID = Symbol('1234')
const anotherID = Symbol('1234')
console.log(ID === anotherID );// false

const biggNumber = 2774763796237673n // bigint 


// refrenced types(non primitive datatype )
// array , object and function 

const heros = ["her0","naagraj","doga"]; //array
let myObj= { // object
    name: "hitesh",
    age: 22,
}
const myFunction = function(){
    // function
    console.log("hello wrold");
}

console.log(typeof outsideTemp); // object
console.log(typeof myFunction); // function object 
console.log(typeof ID); // SYMBOL

selector .elementor-icon-box-wrapper {
    display: flex;
    align-items: flex-start; /* Aligns the icon and title to the top */
}

selector .elementor-icon-box-icon {
    align-self: flex-start; /* Ensures the icon stays at the top */
}

selector .elementor-icon-box-title {
    margin-top: 0 !important; /* Removes any top margin on the title */
    padding-top: 0 !important; /* Removes any top padding on the title */
    line-height: 1.2em; /* Adjusts line height for a closer alignment */
}
import os
import cv2
import numpy as np
from typing import Tuple

# Definicja kolorów i etykiet
CLASS_COLORS = {
    0: {'color_rgb': (0, 0, 0), 'label': 'background'},
    1: {'color_rgb': (255, 0, 0), 'label': 'chondroosseous border'},
    2: {'color_rgb': (0, 255, 0), 'label': 'femoral head'},
    3: {'color_rgb': (0, 0, 255), 'label': 'labrum'},
    4: {'color_rgb': (255, 255, 0), 'label': 'cartilagineous roof'},
    5: {'color_rgb': (0, 255, 255), 'label': 'bony roof'},
    6: {'color_rgb': (159, 2, 250), 'label': 'bony rim'},
    7: {'color_rgb': (255, 132, 0), 'label': 'lower limb'},
    8: {'color_rgb': (255, 0, 255), 'label': 'baseline'},
    9: {'color_rgb': (66, 135, 245), 'label': 'lower limb template'},
    10: {'color_rgb': (255, 69, 0), 'label': 'lower limb - alg. v3'}
}


def visualize_masks(input_dir, output_dir):
    # Tworzenie katalogu wyjściowego, jeśli nie istnieje
    os.makedirs(output_dir, exist_ok=True)

    # Iteracja po plikach PNG w katalogu wejściowym
    for filename in os.listdir(input_dir):
        if filename.endswith(".png"):
            # Wczytywanie maski
            mask_path = os.path.join(input_dir, filename)
            mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

            # Tworzenie pustego obrazu RGB o tych samych wymiarach co maska
            color_image = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)

            # Zamiana etykiet na kolory RGB zgodnie z CLASS_COLORS
            for class_id, color_info in CLASS_COLORS.items():
                color_rgb = color_info['color_rgb']
                color_image[mask == class_id] = color_rgb

            # Znajdowanie punktów baseline
            right_point, left_point = find_baseline(mask)
            
            # Rysowanie baseline na obrazie, jeżeli punkty istnieją
            if right_point[0] is not None and left_point[0] is not None:
                cv2.line(color_image, right_point, left_point, (255, 255, 255), 1)

            # Zapisanie obrazu kolorowego do katalogu wyjściowego
            output_path = os.path.join(output_dir, filename)
            cv2.imwrite(output_path, color_image)
            print(f"Maska {filename} została zapisana w katalogu wyjściowym.")

# Przykładowe użycie
input_dir = "./Angles/dane/ta_jedna"
output_dir = "./Angles/dane/wizul"
visualize_masks(input_dir, output_dir)
WebMidi.enable(function(err) {
148
    if (err) {
149
      console.log("WebMidi kon niet worden ingeschakeld.", err);
150
    } else {
151
      console.log("WebMidi ingeschakeld!");
152
    }
153
​
154
    let inputSoftware = WebMidi.inputs[0];
155
​
156
    // Luister naar 'noteon' events op alle kanalen
157
    inputSoftware.addListener('noteon', "all", function(e) {
158
      let note = e.note.number;
159
​
160
      // Roep de corresponderende nootfunctie aan
161
      if (noteFunctions[note]) {
162
        noteFunctions[note]();
163
      }
164
    });
165
  });
    <script src="https://cdn.jsdelivr.net/npm/webmidi@latest/dist/iife/webmidi.iife.js"></script>
In the on-demand industry, food delivery apps play an important role in the sectors. Many more entrepreneurs want to adopt this business strategy into their businesses. In such respect, if you want to integrate your business idea with a food delivery business, Here, is the best solution provider for any kind of business needs. Appticz is a well-known brand in the on-demand sector, successively availing on-demand services for their clients. In that way, you can proceed your business ideas with the best food delivery application development company that will make your dreamier business ideas into reality.
import java.util.*;

import javax.swing.plaf.synth.SynthOptionPaneUI;
public class LinkedList {
    int size;
    public class Node{
        int data;
        Node next;

        Node(int data){
            this.data=data;
            this.next=null;
            size++;
        }
    }
    LinkedList(){
        size=0;
    }
    Node head;
    public void addFirst(int data){
        Node newNode=new Node(data);
        newNode.next=head;
        head=newNode;
    }
    public void addLast(int data){
        Node newNode=new Node(data);
        if(head==null){
            newNode.next=head;
            head=newNode;
        }else{
            Node curNode=head;
            while(curNode.next!=null){
                curNode=curNode.next;
            }
            curNode.next=newNode;
        }
    }
    public void removeFirst(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            val=head.data;
            head=head.next;
            System.out.println(val+" Deleted...");
            size--;
        }
    }
    public void removeLast(){
        int val=0;
        if(head==null){
            System.out.println("Linked List Empty, can't perform Deletion");
        }else if(head.next==null){
            val=head.data;
            head=null;
            System.out.println(val+" Deleted...");
            size--;
        }else{
            Node curNode=head;
            Node lastNode=head.next;
            while(lastNode.next!=null){
                lastNode=lastNode.next;
                curNode=curNode.next;
            }
            val=lastNode.data;
            System.out.println(val+" Deleted...");
            curNode.next=null;
            size--;
        }
    }
    public void reverseIterate(){
        if(head==null || head.next==null){
            return;
        }else{
            Node prevNode=head;
            Node curNode=head.next;
            while(curNode!=null){
                Node nextNode=curNode.next;
                curNode.next=prevNode;
                prevNode=curNode;
                curNode=nextNode;
            }
            head.next=null;
            head=prevNode;
            System.out.println("Linked List Reversed...");
        }

    }
    public void sizeOfList(){
        System.out.println("Size of List: "+size);
    }
    public void printList(){
        Node curNode=head;
        while(curNode!=null){
            System.out.print(curNode.data+"-> ");
            curNode=curNode.next;
        }System.out.println("NULL");
    }
    public static void main(String args[]){
        LinkedList list=new LinkedList();
        Scanner sc=new Scanner(System.in);
        int val=0;
        while(true){
            System.out.println("1:addFirst  2:addLast  3:removeFirst  4:removeLast  5:reverseIterate  6:sizeOfList  7:printList  8:End");
            System.out.print("Select any Option: ");
            int option=sc.nextInt();
            if(option==8){
                System.out.println("Thank You!!! ");
                break;
            }
            if(option==1 || option==2){
                System.out.print("Enter Value: ");
                val=sc.nextInt();
            }
            switch(option){
                case 1: 
                    list.addFirst(val);
                    break;
                case 2:
                    list.addLast(val);
                    break;
                case 3:
                    list.removeFirst();
                    break;
                case 4:
                    list.removeLast();
                    break;
                case 5:
                    list.reverseIterate();
                    break;
                case 6:
                    list.sizeOfList();
                    break;
                case 7:
                    list.printList();
                    break;
                default:
                    System.out.println("INVALID INPUT");
            }
        }
        
        
    }
}
/////**************comaprison***************/////////////


console.log(2 > 1);
console.log(2 >= 1);
console.log(2 < 1);
console.log(2 == 1);
console.log(2 != 1);

console.log( null > 0);//fales
console.log( null == 0);//fales
console.log( null >= 0);// true

console.log( undefined > 0);//fales
console.log( undefined == 0);//fales
console.log( undefined >= 0);// fales
 
//// strit check 
console.log(2 == "2");///it will check  value (it will give true)
console.log(2 === "2");///it will check both dataype and value (it will give false)
let value = 4
let negvalue = -value 
console.log(negvalue);

/*console.log(2+2);
console.log(2-2);
console.log(2*2);
console.log(2**2);
console.log(2/2);
console.log(2%2);*/

let str1 = "hello "
let str2 = "namastey"
let str3 = str1 + str2 
console.log(str1 + str2)

/* javascript basic tricks*/

console.log(2+"3") //23
console.log("2"+"3") //23
console.log("1"+2+2) //122
console.log(1+2+'2') //32 

/* bad performance*/
console.log(+true);//true
console.log(+"");//fales

let gamecounter = 100
gamecounter++; // post increment and pre increment gives a same answer 
console.log(gamecounter);

let score = true


console.log(score);
console.log(typeof (score));
let valueInNumber = Number(score)
console.log(typeof valueInNumber);
console.log( valueInNumber);
/* PRINTING OF
"33" = 33
"33annaa" = NaN(not a number )
true = 1
false = 0*/


let isLoggedIn = 1
/* empty will give false 
0 will give false*/
let booleanIsLoggedIn = Boolean(isLoggedIn)
console.log(booleanIsLoggedIn); //true


let somenumber = 33;
console.log(typeof somenumber);
let stringNumber = String(somenumber)
console.log(stringNumber);
console.log(typeof stringNumber);
#Boot in Safe Mode (via msconfig)
#Open Registry Editor
#Navigateto:
#HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service
#The six keys in the registry to change the values of:
#Sense
#WdBoot
#WdFilter
#WdNisDrv
#WdNisSvc
#WinDefend

# To disable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	4

#To re-enable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	2



Run actions/github-script@e69ef5462fd455e02edcaf4dd7708eda96b9eda0
2
  with:
3
    github-token: ***
4
    script: // Only perform this action with GitHub employees
5
  try {
6
    await github.rest.teams.getMembershipForUserInOrg({
7
      org: %27github%27,
8
      team_slug: %27employees%27,
9
      username: context.payload.sender.login,
10
    });
11
  } catch(err) {
12
    // An error will be thrown if the user is not a GitHub employee
13
    // If a user is not a GitHub employee, we should stop here and
14
    // Not send a notification
15
    return
16
  }
"use strict"; // treated as all new js code version 

// alert(3+3) we are using nodejs not brpwser 

console.log(3+3+3);
console.log("tansihq dhingra ");// code readibility is very important 

let name = "tanishq"
let age = 18 
let isLoggedIn = false 

/* primitive 
number = 2 ki power 53
bigint
string = " "
boolean = true/ false 
null = standalone value (value is null )
undefined = not defined 
symbbol = uniqueness in react */

// object 
console.log(typeof undefined );//undefined
console.log(typeof null);//object 
import java.util.*;

public class Graph {
    private int vertices;  // Number of vertices
    private LinkedList<Integer>[] adjList;  // Adjacency list representation
    private int time;  // Time counter for DFS

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

    // Add an edge to the graph
    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);  // Since the graph is undirected
    }

    // Articulation Point (Art) Algorithm
    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];  // Discovery time of visited vertices
        int[] low = new int[vertices];  // Lowest discovery time reachable
        int[] parent = new int[vertices];  // Parent vertices in DFS
        Arrays.fill(parent, -1);  // Initialize all parents as -1

        // Start DFS from each unvisited node
        for (int i = 0; i < vertices; i++) {
            if (!visited[i]) {
                DFSArt(i, visited, dfn, low, parent);
            }
        }
    }

    private void DFSArt(int u, boolean[] visited, int[] dfn, int[] low, int[] parent) {
        visited[u] = true;  // Mark the current node as visited
        dfn[u] = low[u] = ++time;  // Initialize discovery time and low value
        int childCount = 0;  // Count of children in DFS tree
        boolean isArticulation = false;

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

                // Check if the subtree rooted at v has a connection back to one of u's ancestors
                low[u] = Math.min(low[u], low[v]);

                // u is an articulation point in two cases:
                // (1) u is not the root and low value of one of its child is more than discovery value of u
                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                // (2) u is the root of DFS tree and has two or more children
                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                // Update low value of u for back edge
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        // If u is an articulation point, print it
        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    // Construct graph from adjacency matrix
    public static Graph createGraphFromAdjMatrix(int[][] adjMatrix) {
        int n = adjMatrix.length;
        Graph g = new Graph(n);
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {  // Undirected graph, so only check i < j
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

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

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

        // Input the adjacency matrix
        System.out.println("Enter the adjacency matrix:");
        int[][] adjMatrix = new int[v][v];
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                adjMatrix[i][j] = scanner.nextInt();
            }
        }

        // Create the graph from adjacency matrix
        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        // Find and print the articulation points
        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}

output1:
Enter the number of vertices: 5
Enter the adjacency matrix:
0 1 1 0 0
1 0 1 1 0
1 1 0 0 0
0 1 0 0 1
0 0 0 1 0
Articulation Points:
Articulation Point: 1
Articulation Point: 3

output2:
Enter the number of vertices: 6
Enter the adjacency matrix:
0 1 1 0 0 0
1 0 1 1 0 0
1 1 0 0 1 0
0 1 0 0 1 1
0 0 1 1 0 1
0 0 0 1 1 0
Articulation Points:
Articulation Point: 2
Articulation Point: 3
const accountID = 145242;//constant value 
let accountEmail = "dhingra@gmail.com";// variable we will use it the most 
var accountPassword = "123433";// variable we dont use var generally
accountCity = "jaipur";

accountEmail = "dhbscbbcd@g.com";
accountPassword = "132322";
accountCity = "bengaluru";
let accountState;

console.log(accountID);
console.table({ accountID, accountEmail, accountPassword, accountCity ,accountState });
import base64

sample_string = "GeeksForGeeks is the best"
sample_string_bytes = sample_string.encode("ascii")

base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")

print(f"Encoded string: {base64_string}")
tar -xf node-v20.18.0-linux-x64.tar.xz

2. Mover Node.js a un directorio adecuado
Para que Node.js esté disponible globalmente, es recomendable moverlo a /usr/local. Puedes hacerlo con el siguiente comando:

sudo mv node-v20.18.0-linux-x64 /usr/local/nodejs

3. Configurar las variables de entorno
Para que el sistema reconozca los comandos de Node.js y npm, necesitas agregar el directorio de Node.js a tu variable de entorno PATH. Abre el archivo de configuración de tu shell. Si usas bash, puedes editar el archivo .bashrc:

nano ~/.bashrc

Agrega la siguiente línea al final del archivo:

4. Aplicar los cambios
Para aplicar los cambios realizados en el archivo .bashrc, ejecuta:

source ~/.bashrc

5. Verificar la instalación
Finalmente, verifica que Node.js y npm se hayan instalado correctamente ejecutando los siguientes comandos:

node -v
npm -v

pattrens = [
    '123456',
    '6665522',
    '887799',
    '123456',
    '6665522',
    '1111222',
    '123456',
    '6665522',
    '887799',
    '123456',
    '111111'
]


def classify_pattrens(pattrens_list):
    labels = {k : [] for k in pattrens_list}
    for pattren in pattrens_list:
        labels[pattren].append(pattren)

    return labels

print(classify_pattrens(pattrens))
ejemplo de exportar modulo
// archivo: miModulo.mjs
export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

ejemplo de importar modulo
// archivo: app.mjs
import { saludar } from './miModulo.mjs';

console.log(saludar('Mundo')); // Salida: Hola, Mundo!
/mi-proyecto
├── backend
│   ├── composer.json
│   ├── index.php
│   └── miModulo.mjs
└── frontend
    ├── package.json
    └── app.mjs

codigo:

1. Archivo composer.json (Backend)
Este archivo se encuentra en la carpeta backend y define las dependencias de PHP que necesitas. Aquí hay un ejemplo básico:

{
  "require": {
    "monolog/monolog": "^2.0"
  }
}

2. Archivo index.php (Backend)
Este archivo es el punto de entrada de tu aplicación PHP. Aquí puedes manejar las solicitudes y enviar respuestas. Un ejemplo simple podría ser:

<?php
// backend/index.php

require 'vendor/autoload.php'; // Asegúrate de que el autoload de Composer esté incluido

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Crear un logger
$log = new Logger('mi_proyecto');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));

// Registrar un mensaje
$log->warning('Esto es un mensaje de advertencia');

// Enviar una respuesta simple
header('Content-Type: application/json');
echo json_encode(['message' => 'Hola desde el backend!']);

3. Archivo miModulo.mjs (Backend)
Este archivo contiene un módulo que puedes importar en otros archivos. Aquí hay un ejemplo de cómo podría verse:

// backend/miModulo.mjs

export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

4. Archivo package.json (Frontend)
Este archivo se encuentra en la carpeta frontend y define las dependencias de JavaScript que necesitas. Aquí hay un ejemplo básico:

{
  "name": "mi-proyecto-frontend",
  "version": "1.0.0",
  "dependencies": {
    "axios": "^0.21.1"
  },
  "scripts": {
    "start": "node app.mjs"
  }
}

5. Archivo app.mjs (Frontend)
Este archivo contiene el código JavaScript que se ejecutará en el lado del cliente. Aquí hay un ejemplo que utiliza axios para hacer una solicitud al backend y también importa la función saludar del módulo:

// frontend/app.mjs

import { saludar } from '../backend/miModulo.mjs'; // Importar la función del módulo

const nombre = 'Mundo';
console.log(saludar(nombre)); // Salida: Hola, Mundo!

// Hacer una solicitud al backend
axios.get('http://localhost/backend/index.php')
  .then(response => {
    console.log('Respuesta del backend:', response.data);
  })
  .catch(error => {
    console.error('Error al hacer la solicitud:', error);
  });


Conclusión
Este ejemplo proporciona una base para un proyecto que combina un backend en PHP y un frontend en JavaScript utilizando módulos ES. Puedes expandirlo según tus necesidades, añadiendo más funcionalidades y dependencias según sea necesario. Asegúrate de tener configurado un servidor para el backend y de ejecutar el script del frontend para ver la interacción entre ambos.
star

Mon Oct 28 2024 10:12:40 GMT+0000 (Coordinated Universal Time)

@saurabhp643

star

Mon Oct 28 2024 10:02:44 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Mon Oct 28 2024 08:37:20 GMT+0000 (Coordinated Universal Time)

@saurabhp643

star

Mon Oct 28 2024 08:36:41 GMT+0000 (Coordinated Universal Time)

@saurabhp643

star

Mon Oct 28 2024 08:13:54 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Mon Oct 28 2024 07:29:51 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Mon Oct 28 2024 00:04:59 GMT+0000 (Coordinated Universal Time) https://linkati.win/member/tools/api

@jamile46

star

Mon Oct 28 2024 00:04:26 GMT+0000 (Coordinated Universal Time) https://linkati.win/member/tools/quick

@jamile46

star

Sun Oct 27 2024 20:16:14 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Oct 27 2024 18:44:25 GMT+0000 (Coordinated Universal Time) https://community.dynamics.com/forums/thread/details/?threadid

@pavankkm

star

Sun Oct 27 2024 18:29:23 GMT+0000 (Coordinated Universal Time) https://community.dynamics.com/blogs/post/?postid

@pavankkm

star

Sun Oct 27 2024 18:14:05 GMT+0000 (Coordinated Universal Time) https://microsoftdynamics365foroperation.blogspot.com/2018/10/dynamics-365fo-send-email-to-user-with.html

@pavankkm

star

Sun Oct 27 2024 17:32:37 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Oct 27 2024 17:30:12 GMT+0000 (Coordinated Universal Time) https://github.com/pmndrs/react-three-fiber

@luccas

star

Sun Oct 27 2024 17:06:33 GMT+0000 (Coordinated Universal Time)

@jwhitlow5

star

Sun Oct 27 2024 16:57:41 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Oct 27 2024 15:08:05 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Oct 27 2024 13:29:27 GMT+0000 (Coordinated Universal Time) https://www.builder.io/c/docs/custom-components-setup

@csd3x41

star

Sun Oct 27 2024 13:28:53 GMT+0000 (Coordinated Universal Time) https://www.builder.io/c/docs/custom-components-setup

@csd3x41

star

Sun Oct 27 2024 12:40:43 GMT+0000 (Coordinated Universal Time)

@javads

star

Sun Oct 27 2024 09:34:36 GMT+0000 (Coordinated Universal Time)

@Manjunath

star

Sun Oct 27 2024 06:47:58 GMT+0000 (Coordinated Universal Time) https://fullstackdevelopercampus.in/

@developercampus #training #onlinetraining #placement

star

Sun Oct 27 2024 06:14:44 GMT+0000 (Coordinated Universal Time) https://gist.github.com/PyroGenesis/e3f2d59b636f03653b64e07ba4e1e8aa

@Curable1600 #windows

star

Sat Oct 26 2024 17:55:02 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 17:35:13 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 17:13:37 GMT+0000 (Coordinated Universal Time)

@mrsdigital #elementor

star

Sat Oct 26 2024 15:51:58 GMT+0000 (Coordinated Universal Time) http://kikoumania.monorganisation.fr/administrator/index.php?option

@pcessac

star

Sat Oct 26 2024 15:08:37 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Sat Oct 26 2024 14:12:14 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Oct 26 2024 14:10:58 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Oct 26 2024 13:26:40 GMT+0000 (Coordinated Universal Time) https://appticz.com/food-delivery-app-development

@aditi_sharma_

star

Sat Oct 26 2024 13:20:44 GMT+0000 (Coordinated Universal Time)

@sukumar #java

star

Sat Oct 26 2024 11:58:12 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 11:54:31 GMT+0000 (Coordinated Universal Time) https://uiball.com/ldrs/

@Rishi1808

star

Sat Oct 26 2024 11:48:33 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 10:03:40 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:35:20 GMT+0000 (Coordinated Universal Time) https://lazyadmin.nl/win-11/turn-off-windows-defender-windows-11-permanently/

@Curable1600 #windows

star

Sat Oct 26 2024 09:31:43 GMT+0000 (Coordinated Universal Time) https://github.com/orgs/community/discussions/139005

@Ashsebahay0323_

star

Sat Oct 26 2024 09:28:15 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:01:51 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 26 2024 08:26:18 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 06:34:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/p2p-cryptocurrency-exchange-development

@jamielucas #nodejs

star

Sat Oct 26 2024 03:23:34 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/blog/new-in-devtools-130/?utm_source

@Ashsebahay0323_

star

Sat Oct 26 2024 01:44:49 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/encoding-and-decoding-base64-strings-in-python/

@jrb9000 #python

star

Fri Oct 25 2024 20:59:03 GMT+0000 (Coordinated Universal Time) https://www.go2bank.com/?utm_medium

@Ashsebahay0323_

star

Fri Oct 25 2024 19:12:59 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

Save snippets that work with our extensions

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