Snippets Collections
function generate_gallery_tab_navigation($atts)
{
    $args = array(
        'taxonomy' => 'gallery_category',
        'hide_empty' => -1,
        'orderby' => 'name',
        'order' => 'ASC'
    );

    $categories = get_categories($args);

    ob_start(); ?>

    <div class="gallery-tabs-wrapper">
        <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
            <?php if (!empty($categories)) : ?>
                <?php $nav_counter = 1; ?>
                <?php foreach ($categories as $category) : ?>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link <?php echo ($nav_counter === 1) ? 'active' : ''; ?>" id="pills-<?php echo $category->slug; ?>-tab" data-bs-toggle="pill" data-bs-target="#pills-<?php echo $category->slug; ?>" type="button" role="tab" aria-controls="pills-<?php echo $category->slug; ?>" aria-selected="<?php echo ($nav_counter === 1) ? 'true' : 'false'; ?>">
                            <?php echo $category->name; ?>
                        </button>
                    </li>
                    <?php $nav_counter++; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </ul>
    </div>

<?php
    return ob_get_clean();
}
add_shortcode('gallery_tab_navigation', 'generate_gallery_tab_navigation');

function generate_gallery_tab_content($atts)
{
    $args = array(
        'post_type' => 'gallery',
        'posts_per_page' => -1,
        'order' => 'ASC',
    );

    $gallery_posts = new WP_Query($args);

    ob_start(); ?>

    <div class="tab-content" id="pills-tabContent">
        <?php if ($gallery_posts->have_posts()) : ?>
            <?php
            $active_set = false;
            while ($gallery_posts->have_posts()) :
                $gallery_posts->the_post();
                $categories = get_the_terms(get_the_ID(), 'gallery_category');
                if ($categories) : ?>
                    <?php foreach ($categories as $category) : ?>
                        <div class="tab-pane fade <?php echo (!$active_set) ? 'show active' : ''; ?>" id="pills-<?php echo $category->slug; ?>" role="tabpanel" aria-labelledby="pills-<?php echo $category->slug; ?>-tab">
                            <div class="gallerys">
                                <div class="row">
                                    <?php
                                    $category_posts_args = array(
                                        'post_type' => 'gallery',
                                        'posts_per_page' => -1,
                                        'tax_query' => array(
                                            array(
                                                'taxonomy' => 'gallery_category',
                                                'field' => 'term_id',
                                                'terms' => $category->term_id,
                                            ),
                                        ),
                                    );
                                    $category_posts = new WP_Query($category_posts_args);
                                    if ($category_posts->have_posts()) : ?>
                                        <?php while ($category_posts->have_posts()) :
                                            $category_posts->the_post(); ?>
                                            <div class="col-md-4 gall-img">
                                                <div class="gallery_inner">
                                                    <a class="fancybox" data-fancybox="gallery" href="<?php echo wp_get_attachment_url(get_post_thumbnail_id()); ?>">
                                                        <?php the_post_thumbnail(); ?>
                                                    </a>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php
                        $active_set = true;
                        ?>
                    <?php endforeach; ?>
                <?php endif; ?>
            <?php endwhile; ?>
        <?php endif; ?>
    </div>

<?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('gallery_tab_content', 'generate_gallery_tab_content');
package com.lgcns.esg.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.lgcns.esg.core.entity.BaseEntity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;
import java.util.List;

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "D_SYSTEM_TYPE")
public class SystemType extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "SYS_TYPE_ID")
    private Long id;
    @Column(name = "CODE",unique = true)
    private String code;
    @Column(name = "NAME")
    private String name;

    @Column(name = "DELETED_AT")
    private LocalDateTime deletedAt;

    @Column(name = "DELETED_BY")
    private String deletedBy;
    @Column(name = "IS_DELETED")
    private boolean deleted;
    @OneToMany(mappedBy = "systemType", cascade = CascadeType.ALL)
    @JsonBackReference
    private List<SystemParams> systemParams;
}
package com.lgcns.esg.entity;

import com.lgcns.esg.core.entity.BaseEntity;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.time.LocalDateTime;

@Entity
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "D_SYSTEM_PARAMS")
public class SystemParams extends BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "SYS_PARAMS_ID")
    private Long id;
    @Column(unique = true, name="CODE")
    private String code;
    @Column(name = "VALUE")
    private String value;

    @Column(name = "DELETED_AT")
    private LocalDateTime deletedAt;

    @Column(name = "DELETED_BY")
    private String deletedBy;
    @Column(name = "IS_DELETED")
    private boolean deleted;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "SYS_TYPE_ID" )
    private SystemType systemType;

}
javascript: (function () {
  let host = location.host;
  if (host.includes("youtube.com")) {
    const emb = document
      .querySelector("link[itemprop='embedUrl']")
      .getAttribute("href");
    window.location.assign(emb);
  } else {
    window.alert("⚠️not YouTube");
  }
})();
> powershell -command "Get-ChildItem -Path C:\ -Recurse | Sort-Object Length -Descending | Select-Object FullName, Length -First 20 | Format-Table -AutoSize";
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Introducing Xero Boost Days! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Toronto! \n\nWe're excited to announce the launch of our Boost Day Program!\n\nStarting this week, as part of our <https://xpresso.xero.com/blog/featured/more-opportunities-to-come-together-with-xeros-connect/|*Xeros Connect Strategy*>, you'll experience supercharged days at the office every *Tuesday* and *Thursday*. Get ready for a blend of delicious food, beverages, wellness activites, and fun connections!\n\nPlease see below for what's on this week! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-30: Tuesday, 30th July",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Enjoy coffee and café-style beverages from our partner, *HotBlack Coffee*, located at 245 Queen St W, by showing your *Xero ID*.\n:breakfast: *Breakfast*: Provided by *Pico de Gallo* at *9AM* in the Kitchen."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-1: Thursday, 1st August",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":coffee: *Café Partnership*: Enjoy coffee and café-style beverages from *HotBlack* by showing your *Xero ID*.\n:lunch: *Lunch*: Provided by *Chiang Mai* at *12:00PM* in the Kitchen.\n"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*LATER THIS MONTH:*"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Thursday, 15th August*\n :standup: *Stand Up* hosted by Intern Engineer, *Daniel Iseoluwa*  \n *Thursday, 29th August*\n:blob-party: *Social +*: Drinks, food, and engaging activities bringing everyone together. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/embed?src=c_c6b67359544047155a77a16a960e9fd5817f52d7682bdffee2582d0d820db732%40group.calendar.google.com&ctz=America%2FToronto|*Tor Happenings Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
Процедура ПриНачалеРаботыСистемы ()
	УстановитьКраткийЗаголовокПриложения ("Денис Кондрашов");
	
	МойВозраст = 25; 
	
	ЯИдуВДетскийСад = Ложь;
	ЯИдуВШколу = Ложь;
	ЯИдуНаРаботу = Ложь;  
	
	Если МойВозраст < 7 Тогда
		ЯИдуВДетскийСад = Истина;
		
	ИначеЕсли МойВозраст >= 7 И МойВозраст < 19 Тогда
		ЯИдуВШколу = Истина;
		
	Иначе ЯИдуНаРаботу = Истина;
		КонецЕсли;
				
КонецПроцедуры
Процедура ПриНачалеРаботыСистемы ()
	УстановитьКраткийЗаголовокПриложения ("Денис Кондрашов");
	
	МойВозраст = 20;
	Если МойВозраст < 7 Тогда
		ЯИдуВДетскийСад = Истина;
		ЯИдуВШколу = Ложь;
		
	ИначеЕсли МойВозраст >= 7 И МойВозраст < 19 Тогда
		ЯИдуВДетскийСад = Ложь;
		ЯИдуВШколу = Истина;
		
	Иначе ЯИдуНаРаботу = Истина;
		КонецЕсли;
				
КонецПроцедуры
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":brewbuddy: Boost Day: Brew Buddy Launch :brewbuddy:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "As a part of our exciting Boost Day program, the new elevated Cafe Experience will feature a new friend :people_hugging:\n \nJoin us in celebrating the launch of our favourite barista friend, *Brew Buddy*. To enhance and elevate your café experience, we're introducing a brand new tool for ordering your coffees, replacing the Asana board. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":info_: Here's a few things to know:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:dot-blue:Brew Buddy is an enhanced barista service software created by an awesome group of grads as a part of Hackathon.\n\n:dot-blue:Our favourite feature is the Slack notification you get once your coffee is ready to go!\n\n:dot-blue:BIt is a more efficient way to order your coffee that minimises time away from work and creates a more seamless experience for Xero's and our baristas."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Keep an eye out for the *'Weekly Special'* option in the ordering form to keep up with the latest caffeine trends and try something new!\n\n*Love*,\n*WX Team* :party-wx:"
			}
		}
	]
}
 <script>
    jQuery(document).ready(function($){
        if (window.location.href == "https://dinglecrystal.ie/pages/factory-demonstrations" || window.location.href == "https://dinglecrystal.ie/products/factory-tour-30min") {
            $('body').append('<a href="https://fareharbor.com/embeds/book/dinglecrystal/?full-items=yes" style="font-family:\'Twentieth Century\', sans-serif !important; border:2px solid #FFFFFF !important; font-weight:bold !important; letter-spacing: 4.2px !important; box-shadow:none !important; padding: .2em 2em !important;" class="fh-hide--mobile fh-fixed--side fh-icon--cal fh-button-true-flat-color">BOOK TOUR</a><a href="https://fareharbor.com/embeds/book/dinglecrystal/?full-items=yes" style="font-family:\'Twentieth Century\', sans-serif !important; font-size: 1.1em !important; border:2px solid #FFFFFF !important; font-weight:bold !important; letter-spacing: 4.2px !important; box-shadow:none !important; padding: .2em 3em !important;" class="fh-hide--desktop fh-size--small fh-fixed--side fh-button-true-flat-color fh-color--white">BOOK TOUR</a>');
        }
    });
    </script>
# CICD using GitHub actions

name: CI/CD

# Exclude the workflow to run on changes to the helm chart
on:
  push:
    branches:
      - main
    paths-ignore:
      - 'helm/**'
      - 'k8s/**'
      - 'README.md'

jobs:

  build:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Set up Go 1.22
      uses: actions/setup-go@v2
      with:
        go-version: 1.22

    - name: Build
      run: go build -o go-web-app

    - name: Test
      run: go test ./...
  
  code-quality:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Run golangci-lint
      uses: golangci/golangci-lint-action@v6
      with:
        version: v1.56.2
  
  push:
    runs-on: ubuntu-latest

    needs: build

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Set up Docker Buildx
      uses: docker/setup-buildx-action@v1

    - name: Login to DockerHub
      uses: docker/login-action@v3
      with:
        username: ${{ secrets.DOCKERHUB_USERNAME }}
        password: ${{ secrets.DOCKERHUB_TOKEN }}

    - name: Build and Push action
      uses: docker/build-push-action@v6
      with:
        context: .
        file: ./Dockerfile
        push: true
        tags: ${{ secrets.DOCKERHUB_USERNAME }}/go-web-app:${{github.run_id}}

  update-newtag-in-helm-chart:
    runs-on: ubuntu-latest

    needs: push

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4
      with:
        token: ${{ secrets.TOKEN }}

    - name: Update tag in Helm chart
      run: |
        sed -i 's/tag: .*/tag: "${{github.run_id}}"/' helm/go-web-app-chart/values.yaml

    - name: Commit and push changes
      run: |
        git config --global user.email "vivekstyne5@gmail.com"
        git config --global user.name "Vivek-kumar-official"
        git add helm/go-web-app-chart/values.yaml
        git commit -m "Update tag in Helm chart"
        git push
package com.lgcns.esg.core.util;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Ops;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.ComparableExpressionBase;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.core.types.dsl.StringExpression;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

public class QueryBuilder {
    private QueryBuilder() {
    }

    public static final String EQUAL = "=";
    public static final String NOT_EQUAL = "!=";
    public static final String LIKE = "%";
    public static final String GREATER_THAN = ">";
    public static final String LESS_THAN = "<";
    public static final String GREATER_THAN_OR_EQUAL = ">=";

    public static final String LESS_THAN_OR_EQUAL = "=<";
    public static final String IN = "IN";
    public static final String NOT_IN = "NOT_IN";

    public static <T extends Comparable<?>> void buildSearchPredicate(BooleanBuilder condition, String operation, ComparableExpressionBase<T> field, T searchData) {
        if (Objects.nonNull(searchData)) {
            BooleanExpression expression = null;
            switch (operation) {
                case EQUAL -> expression = field.eq(searchData);
                case NOT_EQUAL -> expression = field.ne(searchData);
                case LIKE -> {
                    if (field instanceof StringExpression stringExpression) {
                        expression = stringExpression.containsIgnoreCase(searchData.toString());
                    } else {
                        throw new IllegalArgumentException("Field does not support 'like' operation");
                    }
                }
                case GREATER_THAN ->
                        expression = Expressions.booleanOperation(Ops.GT, field, Expressions.constant(searchData));
                case LESS_THAN ->
                        expression = Expressions.booleanOperation(Ops.LT, field, Expressions.constant(searchData));
                case GREATER_THAN_OR_EQUAL ->
                        expression = Expressions.booleanOperation(Ops.GOE, field, Expressions.constant(searchData));
                case LESS_THAN_OR_EQUAL ->
                        expression = Expressions.booleanOperation(Ops.LOE, field, Expressions.constant(searchData));
                default -> throw new IllegalArgumentException("Not support operator:" + operation);
            }
            if (expression != null) {
                condition.and(expression);
            }
        }
    }

    public static <T extends Comparable<?>> void buildSearchPredicate(BooleanBuilder condition, String operation, ComparableExpressionBase<T> field, List<T> searchData) {
        if (Objects.nonNull(searchData) && !CollectionUtils.isEmpty(searchData)) {
            switch (operation) {
                case IN -> condition.and(field.in(searchData));
                case NOT_IN -> condition.and(field.notIn(searchData));
                default -> throw new IllegalArgumentException("Not support operator:" + operation);
            }
        }
    }
}

Ready to elevate your business to the next level? Build your own blockchain ecosystem with CoinsQueens! This custom digital ledger system is designed just for you, giving you full control over operations, governance, and features. Enjoy enhanced security, faster processes, and tailor-made solutions to fit your specific needs.
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-web-app
  labels:
    app: go-web-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: go-web-app
  template:
    metadata:
      labels:
        app: go-web-app
    spec:
      containers:
      - name: go-web-app
        image: vivekstyne/go-web-app:v1
        ports:
        - containerPort: 8080
// Select the parent element
const parent = document.getElementById('parentElementId');

// While the parent has child nodes, remove the first one
while (parent.firstChild) {
    parent.removeChild(parent.firstChild);
}
Date: 29-7-2024              Section: III-I CSE-E
Topic: Functions
---------------------------------------------------------------------

1.Write a function named printWelcomeMessage that prints "Welcome to the Online Shopping App!" to the console. 
2.Write a function named printGoodbyeMessage that prints "Thank you for visiting the Online Shopping App!" to the console.
3.Write a function named addProduct that takes a String parameter productName and prints "Product <productName> added to the inventory".
 Note: Call this function with different product names.

4.Write a function named removeProduct that takes a String parameter productName and prints "Product <productName> removed from the inventory.". 
Note: Call this function with different product names. 

5. Write a function named calculateDiscount that takes two Double parameters price and discountRate, and returns the discounted price. Print the returned value in the main function.
6.Write a function named isProductAvailable that takes a String parameter productName and returns true if the product is available in stock, and false otherwise. 
Print the result in the main function.
7. Write a single-expression function named calculateTax that takes a Double parameter price and returns the tax amount (assume a tax rate of 10%). 
Print the result in the main function.
8. Write a single-expression function named calculateTotalPrice that takes two Double parameters price and tax and returns their sum. 
Print the result in the main function.
9. Write a function named createUserAccount that takes a String parameter userName with a default value of "Guest" and prints "User account <userName> created.". 
Note: Call this function with and without passing a user name.
10. Write a function named applyCoupon that takes a Double parameter discount with a default value of 10.0 and prints "Coupon applied with <discount>% discount.". 
Note: Call this function with and without passing a discount.
11. Write a function named updateUserProfile that takes three String parameters firstName, lastName, and email, and prints "User profile updated: <firstName> <lastName>, Email: <email>". 
Call this function using named arguments.
12. Write a function named placeOrder that takes three String parameters productName, deliveryAddress, and paymentMethod, and prints "Order placed for <productName> to be delivered at <deliveryAddress> using <paymentMethod>". 
note: Call this function using named arguments and print the result.



Date: 29-7-2024              Section: III-I CSE-E
Topic: Functions
---------------------------------------------------------------------

1.Write a function named printWelcomeMessage that prints "Welcome to the Online Shopping App!" to the console. 
2.Write a function named printGoodbyeMessage that prints "Thank you for visiting the Online Shopping App!" to the console.
3.Write a function named addProduct that takes a String parameter productName and prints "Product <productName> added to the inventory".
 Note: Call this function with different product names.

4.Write a function named removeProduct that takes a String parameter productName and prints "Product <productName> removed from the inventory.". 
Note: Call this function with different product names. 

5. Write a function named calculateDiscount that takes two Double parameters price and discountRate, and returns the discounted price. Print the returned value in the main function.
6.Write a function named isProductAvailable that takes a String parameter productName and returns true if the product is available in stock, and false otherwise. 
Print the result in the main function.
7. Write a single-expression function named calculateTax that takes a Double parameter price and returns the tax amount (assume a tax rate of 10%). 
Print the result in the main function.
8. Write a single-expression function named calculateTotalPrice that takes two Double parameters price and tax and returns their sum. 
Print the result in the main function.
9. Write a function named createUserAccount that takes a String parameter userName with a default value of "Guest" and prints "User account <userName> created.". 
Note: Call this function with and without passing a user name.
10. Write a function named applyCoupon that takes a Double parameter discount with a default value of 10.0 and prints "Coupon applied with <discount>% discount.". 
Note: Call this function with and without passing a discount.
11. Write a function named updateUserProfile that takes three String parameters firstName, lastName, and email, and prints "User profile updated: <firstName> <lastName>, Email: <email>". 
Call this function using named arguments.
12. Write a function named placeOrder that takes three String parameters productName, deliveryAddress, and paymentMethod, and prints "Order placed for <productName> to be delivered at <deliveryAddress> using <paymentMethod>". 
note: Call this function using named arguments and print the result.



<section class="app">

  <aside class="sidebar">

         <header>

        Menu

      </header>

    <nav class="sidebar-nav">

 

      <ul>

        <li>

          <a href="#"><i class="ion-bag"></i> <span>Shop</span></a>

          <ul class="nav-flyout">

            <li>

              <a href="#"><i class="ion-ios-color-filter-outline"></i>Derps</a>

            </li>

            <li>

              <a href="#"><i class="ion-ios-clock-outline"></i>Times</a>

            </li>

            <li>

              <a href="#"><i class="ion-android-star-outline"></i>Hates</a>

            </li>

            <li>

              <a href="#"><i class="ion-heart-broken"></i>Beat</a>
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "🌟 Melbourne Boost Day Reminder! 🌟"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Good morning Melbourne!\n\n \n\n  Get ready for a fantastic Boost Day with these exciting offerings: \n\n ☕ *Xero Café:* Enjoy delicious café-style beverages crafted by our skilled baristas, and sweet treats like Lemon Slices, Yo-Yo Biscuits (Gluten Free), Almond Crescents + Biscoff Biscuits!\n\n 📋 *Weekly Café Special:* Indulge in a delicious Biscoff Latte! \n\n :cake: *Afternoon Tea*: Wind down your day with a delicious afternoon tea provided by Your Private Chef from 2pm - 3pm in the L3 Kitchen. \n\n 💆🏽‍♀️*Wellbeing:* Book a massage <https://bookings.corporatebodies.com/|*here*> to relax and unwind. \n *Username:* xero \n *Password:* 1234 \n\n :fruits: *Lastly*, we now have a blender! Create your perfect mix for a delicious smoothie using our fresh fruit delivered on Mondays and Wednesdays! \n\n Enjoy your delicious smoothies and remember to #washyourowncoffeecup and clean up after yourself so the next Xero can enjoy too!"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Stay tuned to this channel for more details, check out the <https://calendar.google.com/calendar/u/0?cid=Y19xczkyMjk5ZGlsODJzMjA4aGt1b3RnM2t1MEBncm91cC5jYWxlbmRhci5nb29nbGUuY29t|*Melbourne Social Calendar*>, and get ready to Boost your workdays!\n\nLove,\nWX Team :party-wx:"
			}
		}
	]
}
import pandas as pd
from sklearn.preprocessing import LabelEncoder

data={
    'Car':['Toyota','Ford','BMW','Audi','Toyota'],
}
df=pd.DataFrame(data)

label_encoder=LabelEncoder()
df['Car_Label']= label_encoder.fit_transform(df['Car'])
print(df)
***********************************
  import pandas as pd
from sklearn.preprocessing import LabelEncoder

data={
    'Student':['Alica','Bob','Charlie','David','Eva'],
    'Score':[85,67,90,45,76],
    'Pass/Fail':['Pass','Pass','Pass','Fail','Pass']
}
df=pd.DataFrame(data)
print(df)

********************************
  #label encoding for the pass/fail column
label_encoder=LabelEncoder()
df['Pass/Fail_label']= label_encoder.fit_transform(df['Pass/Fail'])
print('data frame after encoding:')
print(df)
*******************************************
  import pandas as pd
from sklearn.preprocessing import OneHotEncoder

data={'City':['New York','Los Angels','Chicago','Houston','Phoenix']}
df=pd.DataFrame(data)
print(df)
*************************************
  one_hot_encoder=OneHotEncoder(sparse=False)
one_hot_encoded=one_hot_encoder.fit_transform(df[['City']])

one_hot_df=pd.DataFrame(one_hot_encoded,columns=one_hot_encoder.get_feature_names_out(['City']))
df=pd.concat([df,one_hot_df],axis=1)

print(df)
*****************************************************************
  O_h_e=OneHotEncoder(sparse=False)
One_h_e=O_h_e.fit_transform(df[['City']])
o_h_df=pd.DataFrame(One_h_e,columns=O_h_e.get_feature_names_out(['City']))
pd=pd.concat([df,o_h_df],axis=1)
print(pd)
************************************************************
  import pandas as pd
from sklearn.preprocessing import OneHotEncoder
data={
    'name':['Alice','Bob','Charlie','David','Eve'],
    'gender':['Female','Male','Male','Male','Female'],
    'age':[24,30,22,35,28]
}
df=pd.DataFrame(data)
print(df)
O_h_e=OneHotEncoder(sparse=False)
One_h_e=O_h_e.fit_transform(df[['gender']])
o_h_df=pd.DataFrame(One_h_e,columns=O_h_e.get_feature_names_out(['gender']))
pd=pd.concat([df,o_h_df],axis=1)
print(pd)
****************************************************
  import pandas as pd
from sklearn.preprocessing import OrdinalEncoder
data={
    'Student':['Alice','Bob','Charlie','David','Eve'],
    'Grade':['A','B','A','C','B']
}
df=pd.DataFrame(data)
df
a=OrdinalEncoder(categories=[['C','B','A']])
df['Grade_Ordinal']=a.fit_transform(df[['Grade']])
df
************************************************
%matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
data=pd.read_csv("/content/Data.csv")
data.head()
****************
  data.shape
df=pd.DataFrame(data)
df

X=df.iloc[:,:-1].values
Y=df.iloc[:,-1].values
print(X)
********************************************
  df2=df.copy()
df2.fillna(df2["Age"].mean(),inplace=True)
df2.fillna(df2["Salary"].mean(),inplace=True)
print(df2.isnull().sum())
*****************************************
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct=ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[0])],remainder='passthrough')
x=np.array(ct.fit_transform(x))
print(x)
*****************************
  from sklearn.preprocessing import LabelEncoder
le=LabelEncoder()
y=le.fit_transform(y)
y
*************************************
  from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=1)
print(x_train)
Get-ChildItem ".\FileStore" |
Select-Object Name, PSPath |
Add-Member -MemberType MemberSet `
           -Name PSStandardMembers `
           -Value ([System.Management.Automation.PSPropertySet]::new(
                      'DefaultDisplayPropertySet',
                      [string[]]('Name')
                  )) `
           -PassThru |
Out-GridView -PassThru -Title "Quick Notes" |
Get-Content | Set-Clipboard
   # Create the new ACE  
   $identity = 'domain\group'  
   $rights = 'FullControl'  
   $type = 'Allow'  
     
   # Folders and files inherit this permission, no need to propagate because it will be inherited  
   $inheritance = 'ContainerInherit, ObjectInherit'  
   $propagate = 'None'  
     
   $ace = New-Object System.Security.AccessControl.FileSystemAccessRule($identity, $rights, $inheritance, $propagate, $type)  
     
   # Apply to existing file system object  
   $acl = Get-Acl -Path 'YourPath'  
   $acl.AddAccessRule($ace)  
   Set-Acl -Path 'YourPath' -AclObject $acl  
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Boost Day is Here! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Brisbane! \n\nIt's Boost Day!\n\nCheck out today's fantastic lineup: "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-29: Monday, 29th July",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Café Partnership*: Enjoy free coffee and café-style beverages from our Cafe partner *Edwards*.\n:Lunch: *Lunch*: Provided by *DannyBoys Rockstar Sandwiches* from *12pm* in the kitchen.\n:massage:*Wellbeing*: Pilates at *SP Brisbane City* is bookable every Monday! Watch this channel on how to book."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "plain_text",
				"text": "Have an amazing Boost Day, Brisbane!\n\nLove,\n\nWX  :party-wx:  ",
				"emoji": true
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":star: Boost Day is Here! :star:"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Wellington! \n\nIt's Boost Day!\n\nCheck out today's fantastic lineup: "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":calendar-date-30: Tuesday, 30th July",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n:coffee: *Xero Café*: Café-style beverages and sweet treats.\n:clipboard: *Weekly Café Special*: _Caramel Mocha Latte_.\n:breakfast: *Breakfast*: Provided by *Simply Food* from *8AM - 10AM* in the All Hands.\n:massage:*Wellbeing - Massage*: Book a session <https://www.google.com/|*here*> to relax and unwind."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "plain_text",
				"text": "Have an amazing Boost Day, Wellington!\n\nLove,\n\nWX  :party-wx:  ",
				"emoji": true
			}
		}
	]
}
function validateString(str) {
  return str && str.trim().length > 5 ? str : null;
}
WEBSITEpwd=4.12345
GOOGLEpwd=4.12345
SYMENUpwd=4.12345
UGMFREEpwd=4.12345
#include<iostream>
using namespace std;

int main()
{
   cout << "hello world"<< endl;
}
[
  {
    "key": "tab",
    "command": "editor.action.inlineSuggest.commit",
    "when": "textInputFocus && inlineSuggestionHasIndentationLessThanTabSize && inlineSuggestionVisible && !editorTabMovesFocus"     
  }
]
a, b, c = 5, 3.2, 'Hello'

print (a)  # prints 5
print (b)  # prints 3.2
print (c)  # prints Hello 
docker run --rm \
    -v $PWD:/local openapitools/openapi-generator-cli generate \
    -i /local/petstore.yaml \
    -g go \
    -o /local/out/go
                
# install the latest version of "openapi-generator-cli"
npm install @openapitools/openapi-generator-cli -g

# use a specific version of "openapi-generator-cli"
openapi-generator-cli version-manager set 6.2.0

# Or install it as dev-dependency in your node.js projects
npm install @openapitools/openapi-generator-cli -D
                
print("She said: \"Hello\" and then left.")
import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)
import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()
import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)
Update sr.ht build manifest for mirroring to Github
# install the latest version of "openapi-generator-cli"
npm install @openapitools/openapi-generator-cli -g

# use a specific version of "openapi-generator-cli"
openapi-generator-cli version-manager set 6.2.0

# Or install it as dev-dependency in your node.js projects
npm install @openapitools/openapi-generator-cli -D
                
//html
<div class="register-wrapper d-flex justify-content-center align-items-center">
    <div class="card box">
      <div class="card-header text-center">
        <h4 class="card-title">Sign-up</h4>
      </div>
      <form class="form" [formGroup]="registerForm" (ngSubmit)="RegisterEmployee()">
        <div class="card-body">
          <div class="row">
            <div class="col-md-6">
              <div class="form-group">
                <label for="Name" class="form-label">Name</label>
                <input type="text" class="form-control" id="Name" placeholder="Enter your Name" formControlName="Name">
                <div *ngIf="registerForm.controls['Name'].invalid && (registerForm.controls['Name'].dirty || registerForm.controls['Name'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Name'].errors?.['required']">Name is required.</div>
                  <div *ngIf="registerForm.controls['Name'].errors?.['minlength']">Name must be at least 2 characters long.</div>
                  <div *ngIf="registerForm.controls['Name'].errors?.['maxlength']">Name must be at most 20 characters long.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Surname" class="form-label">Surname</label>
                <input type="text" class="form-control" id="Surname" placeholder="Enter your Surname" formControlName="Surname">
                <div *ngIf="registerForm.controls['Surname'].invalid && (registerForm.controls['Surname'].dirty || registerForm.controls['Surname'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Surname'].errors?.['required']">Surname is required.</div>
                  <div *ngIf="registerForm.controls['Surname'].errors?.['minlength']">Surname must be at least 2 characters long.</div>
                  <div *ngIf="registerForm.controls['Surname'].errors?.['maxlength']">Surname must be at most 20 characters long.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Email" class="form-label">Email Address</label>
                <input type="Email" class="form-control" id="Email" placeholder="Enter a valid Email address" formControlName="Email">
                <div *ngIf="registerForm.controls['Email'].invalid && (registerForm.controls['Email'].dirty || registerForm.controls['Email'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Email'].errors?.['required']">Email is required.</div>
                  <div *ngIf="registerForm.controls['Email'].errors?.['email']">Email is invalid.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Password" class="form-label">Password</label>
                <input type="Password" class="form-control" id="password" placeholder="Enter between 8 to 15 characters" formControlName="Password">
                <div *ngIf="registerForm.controls['Password'].invalid && (registerForm.controls['Password'].dirty || registerForm.controls['Password'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Password'].errors?.['required']">Password is required.</div>
                  <div *ngIf="registerForm.controls['Password'].errors?.['minlength']">Password must be at least 8 characters.</div>
                  <div *ngIf="registerForm.controls['Password'].errors?.['maxlength']">Password cannot be more than 15 characters.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="PhoneNumber" class="form-label">Phone Number</label>
                <input type="text" class="form-control" id="PhoneNumber" placeholder="Enter your Phone Number" formControlName="PhoneNumber">
                <div *ngIf="registerForm.controls['PhoneNumber'].invalid && (registerForm.controls['PhoneNumber'].dirty || registerForm.controls['PhoneNumber'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['PhoneNumber'].errors?.['required']">Phone Number is required.</div>
                  <div *ngIf="registerForm.controls['PhoneNumber'].errors?.['pattern']">Phone Number format invalid.</div>
                </div>
              </div>
            </div>
  
            <div class="col-md-6">
              <div class="form-group">
                <label for="Date_of_Birth" class="form-label">Date of Birth</label>
                <input type="date" class="form-control" id="Date_of_Birth" placeholder="Enter your Date of Birth" formControlName="Date_of_Birth">
                <div *ngIf="registerForm.controls['Date_of_Birth'].invalid && (registerForm.controls['Date_of_Birth'].dirty || registerForm.controls['Date_of_Birth'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Date_of_Birth'].errors?.['required']">Date of Birth is required.</div>
                  <div *ngIf="registerForm.controls['Date_of_Birth'].errors?.['futureDate']">Date of birth cannot be a future date.</div>
                  <div *ngIf="registerForm.controls['Date_of_Birth'].errors?.['olderThan100']">Date of birth cannot be more than 100 years ago.</div>
                  <div *ngIf="registerForm.controls['Date_of_Birth'].errors?.['futureYear']">User cannot be younger than 16.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Id_Number" class="form-label">ID Number</label>
                <input type="text" class="form-control" id="Id_Number" placeholder="Enter your ID Number" formControlName="Id_Number">
                <div *ngIf="registerForm.controls['Id_Number'].invalid && (registerForm.controls['Id_Number'].dirty || registerForm.controls['Id_Number'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Id_Number'].errors?.['required']">ID Number is required.</div>
                  <div *ngIf="registerForm.controls['Id_Number'].errors?.['pattern']">ID Number must be 13 digits.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Physical_Address" class="form-label">Physical Address</label>
                <input type="text" class="form-control" id="Physical_Address" placeholder="Enter your Physical Address" formControlName="Physical_Address">
                <div *ngIf="registerForm.controls['Physical_Address'].invalid && (registerForm.controls['Physical_Address'].dirty || registerForm.controls['Physical_Address'].touched)" class="text-danger">
                  <div *ngIf="registerForm.controls['Physical_Address'].errors?.['required']">Physical Address is required.</div>
                  <div *ngIf="registerForm.controls['Physical_Address'].errors?.['minlength']">Physical Address must be at least 7 characters long.</div>
                  <div *ngIf="registerForm.controls['Physical_Address'].errors?.['maxlength']">Physical Address must be at most 100 characters long.</div>
                </div>
              </div>
              <div class="form-group">
                <label for="Photo" class="form-label">Photo</label>
                <input type="file" class="form-control" id="Photo" (change)="onFileChange($event)">
              </div>
            </div>
          </div>
        </div>
        <div class="card-footer d-flex justify-content-between">
          <button type="submit" class="btn btn-primary">Sign-up</button>
          <button type="button" class="btn btn-secondary">Cancel</button>
        </div>
      </form>
    </div>
  </div>
//ts
import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { FlexLayoutModule } from '@angular/flex-layout';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { UserService } from '../Services/userprofile.service';

@Component({
  selector: 'app-register-employee',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule, FlexLayoutModule],
  templateUrl: './register-employee.component.html',
  styleUrl: './register-employee.component.css'
})
export class RegisterEmployeeComponent {
  registerForm: FormGroup;
  selectedFile: File | null = null;

  constructor(
    private router: Router,
    private userService: UserService,
    private fb: FormBuilder,
    private snackBar: MatSnackBar
  ) {
    this.registerForm = this.fb.group({
      Name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      Surname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      Email: ['', [Validators.required, Validators.email]],
      Physical_Address: ['', [Validators.required, Validators.minLength(7), Validators.maxLength(100)]],
      PhoneNumber: ['', [Validators.required, Validators.pattern('^\\d{10}$')]],
      Password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(15)]],
      Id_Number: ['', [Validators.required, Validators.pattern('^\\d{13}$')]],
      Date_of_Birth: ['', [Validators.required, this.validateDateOfBirth]],
      User_Status_ID: [1, Validators.required],
      User_Type_ID: [2, Validators.required],
      Employment_Date: [new Date(), Validators.required],
      Hours_Worked: [0, Validators.required],
      Employee_Type_ID: [1, Validators.required],
      Shift_ID: [null]
    });    
  }

  validateDateOfBirth(control: any): { [key: string]: any } | null {
    const selectedDate = new Date(control.value);
    const currentDate = new Date();
    const minDate = new Date(currentDate.getFullYear() - 100, currentDate.getMonth(), currentDate.getDate());
    const maxDate = new Date(currentDate.getFullYear() - 16, currentDate.getMonth(), currentDate.getDate());
  
    if (selectedDate > currentDate) {
      return { 'futureDate': true };
    }
  
    if (selectedDate < minDate) {
      return { 'olderThan100': true };
    }
  
    if (selectedDate > maxDate) {
      return { 'futureYear': true };
    }
  
    return null;
  }
  

  onFileChange(event: any) {
    this.selectedFile = event.target.files[0];
  }

  RegisterEmployee() {
    if (this.registerForm.invalid) {
      return;
    }

    if (!this.selectedFile) {
      this.snackBar.open('Photo is required', 'Close', { duration: 3000 });
      return;
    }

    const formValues = this.registerForm.value;
    formValues.Date_of_Birth = new Date(formValues.Date_of_Birth).toISOString();

    this.userService.registerEmployee(this.registerForm.value, this.selectedFile).subscribe({
      next: (response) => {
        console.log('Registration Success:', response);
        this.snackBar.open('Employee registered successfully', 'Close', { duration: 3000 });
        this.registerForm.reset();
        this.selectedFile = null;
        this.router.navigate(['/login']);
      },
      error: (error) => {
        console.log('Registration Error:', error);
        this.snackBar.open('Failed to register employee', 'Close', { duration: 3000 });
      }
    });
  }
}

//css
.register-wrapper {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #f0f4f7; /* Light blue background */
  }
  
  .box {
    padding: 60px 50px 40px;
    width: 100%;
    max-width: 800px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    text-align: center;
    font-weight: 700;
    color: #000; /* Blue color for header text */
  }
  
  .card-title {
    font-size: 30px;
    margin: 0;
  }
  
  .form-group label {
    color: #000; /* Blue color for form labels */
  }
  
  .form-control {
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 5px;
    transition: border-color 0.3s ease-in-out;
  }
  
  .form-control:focus {
    border-color: #000; /* Blue border on focus */
    box-shadow: 0 0 5px rgba(63, 81, 181, 0.2); /* Light blue shadow on focus */
  }
  
  .text-danger {
    color: #f44336; /* Red color for error messages */
  }
  
  .btn-primary {
    background-color: #4caf50; /* Green background for primary button */
    border-color: #4caf50; /* Green border for primary button */
    color: #fff; /* White text for primary button */
  }
  
  .btn-secondary {
    background-color: #f44336; /* Red background for secondary button */
    border-color: #f44336; /* Red border for secondary button */
    color: #fff; /* White text for secondary button */
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    padding: 20px;
  }
  
  .card-footer .btn {
    width: 48%;
  }
  
  /* Snackbar Styles */
  .snackbar {
    visibility: visible;
    min-width: 250px;
    margin-left: -125px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    padding: 16px;
    position: fixed;
    z-index: 1;
    left: 50%;
    bottom: 30px;
    font-size: 17px;
  }
  
  .snackbar-success {
    background-color: #4caf50; /* Green for success */
  }
  
  .snackbar-danger {
    background-color: #f44336; /* Red for error */
  }
  
  .close-snackbar {
    color: white;
    font-weight: bold;
    float: right;
    font-size: 22px;
    line-height: 20px;
    cursor: pointer;
    background: none;
    border: none;
  }
  
//html
<div class="register-wrapper d-flex justify-content-center align-items-center">
  <div class="card box">
    <div class="card-header text-center">
      <h4 class="card-title">Sign-up</h4>
    </div>
    <form class="form" [formGroup]="registerFormGroup" (ngSubmit)="RegisterUser()">
      <div class="card-body">
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label for="name" class="form-label">Name</label>
              <input type="text" class="form-control" id="name" placeholder="Enter your Name" formControlName="name">
              <div *ngIf="registerFormGroup.controls['name'].invalid && (registerFormGroup.controls['name'].dirty || registerFormGroup.controls['name'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['name'].errors?.['required']">Name is required.</div>
                <div *ngIf="registerFormGroup.controls['name'].errors?.['minlength']">Name must be at least 2 characters long.</div>
                <div *ngIf="registerFormGroup.controls['name'].errors?.['maxlength']">Name must be at most 20 characters long.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="surname" class="form-label">Surname</label>
              <input type="text" class="form-control" id="surname" placeholder="Enter your Surname" formControlName="surname">
              <div *ngIf="registerFormGroup.controls['surname'].invalid && (registerFormGroup.controls['surname'].dirty || registerFormGroup.controls['surname'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['surname'].errors?.['required']">Surname is required.</div>
                <div *ngIf="registerFormGroup.controls['surname'].errors?.['minlength']">Surname must be at least 2 characters long.</div>
                <div *ngIf="registerFormGroup.controls['surname'].errors?.['maxlength']">Surname must be at most 20 characters long.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="email" class="form-label">Email Address</label>
              <input type="email" class="form-control" id="email" placeholder="Enter a valid Email address" formControlName="email">
              <div *ngIf="registerFormGroup.controls['email'].invalid && (registerFormGroup.controls['email'].dirty || registerFormGroup.controls['email'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['email'].errors?.['required']">Email is required.</div>
                <div *ngIf="registerFormGroup.controls['email'].errors?.['email']">Email is invalid.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="password" class="form-label">Password</label>
              <input type="password" class="form-control" id="password" placeholder="Enter between 8 to 15 characters" formControlName="password">
              <div *ngIf="registerFormGroup.controls['password'].invalid && (registerFormGroup.controls['password'].dirty || registerFormGroup.controls['password'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['password'].errors?.['required']">Password is required.</div>
                <div *ngIf="registerFormGroup.controls['password'].errors?.['minlength']">Password must be at least 8 characters.</div>
                <div *ngIf="registerFormGroup.controls['password'].errors?.['maxlength']">Password cannot be more than 15 characters.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="PhoneNumber" class="form-label">Phone Number</label>
              <input type="text" class="form-control" id="PhoneNumber" placeholder="Enter your Phone Number" formControlName="PhoneNumber">
              <div *ngIf="registerFormGroup.controls['PhoneNumber'].invalid && (registerFormGroup.controls['PhoneNumber'].dirty || registerFormGroup.controls['PhoneNumber'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['PhoneNumber'].errors?.['required']">Phone Number is required.</div>
                <div *ngIf="registerFormGroup.controls['PhoneNumber'].errors?.['minlength']">Phone Number must be 10 digits.</div>
                <div *ngIf="registerFormGroup.controls['PhoneNumber'].errors?.['maxlength']">Phone Number must be 10 digits.</div>
              </div>
            </div>
          </div>

          <div class="col-md-6">
            <div class="form-group">
              <label for="Date_of_Birth" class="form-label">Date of Birth</label>
              <input type="date" class="form-control" id="Date_of_Birth" placeholder="Enter your Date of Birth" formControlName="Date_of_Birth">
              <div *ngIf="registerFormGroup.controls['Date_of_Birth'].invalid && (registerFormGroup.controls['Date_of_Birth'].dirty || registerFormGroup.controls['Date_of_Birth'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['Date_of_Birth'].errors?.['required']">Date of Birth is required.</div>
                <div *ngIf="registerFormGroup.controls['Date_of_Birth'].errors?.['futureDate']">Date of birth cannot be a future date.</div>
                <div *ngIf="registerFormGroup.controls['Date_of_Birth'].errors?.['olderThan100']">Date of birth cannot be more than 100 years ago.</div>
                <div *ngIf="registerFormGroup.controls['Date_of_Birth'].errors?.['futureYear']">User cannot be younger than 16.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="Id_Number" class="form-label">ID Number</label>
              <input type="text" class="form-control" id="Id_Number" placeholder="Enter your ID Number" formControlName="Id_Number">
              <div *ngIf="registerFormGroup.controls['Id_Number'].invalid && (registerFormGroup.controls['Id_Number'].dirty || registerFormGroup.controls['Id_Number'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['Id_Number'].errors?.['required']">ID Number is required.</div>
                <div *ngIf="registerFormGroup.controls['Id_Number'].errors?.['minlength']">ID Number must be 13 digits.</div>
                <div *ngIf="registerFormGroup.controls['Id_Number'].errors?.['maxlength']">ID Number must be 13 digits.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="Physical_Address" class="form-label">Physical Address</label>
              <input type="text" class="form-control" id="Physical_Address" placeholder="Enter your Physical Address" formControlName="Physical_Address">
              <div *ngIf="registerFormGroup.controls['Physical_Address'].invalid && (registerFormGroup.controls['Physical_Address'].dirty || registerFormGroup.controls['Physical_Address'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['Physical_Address'].errors?.['required']">Physical Address is required.</div>
                <div *ngIf="registerFormGroup.controls['Physical_Address'].errors?.['minlength']">Physical Address must be at least 7 characters long.</div>
                <div *ngIf="registerFormGroup.controls['Physical_Address'].errors?.['maxlength']">Physical Address must be at most 100 characters long.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="Photo" class="form-label">Photo</label>
              <input type="file" class="form-control" id="Photo" (change)="onFileSelected($event)">
              <div *ngIf="registerFormGroup.controls['Photo'].invalid && (registerFormGroup.controls['Photo'].dirty || registerFormGroup.controls['Photo'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['Photo'].errors?.['required']">Photo is required.</div>
              </div>
            </div>
            <div class="form-group">
              <label for="User_Type_ID" class="form-label">User Type</label>
              <select class="form-control" id="User_Type_ID" formControlName="User_Type_ID">
                <option value="1">Owner</option>
                <option value="2">Employee</option>
                <option value="3">Member</option>
              </select>
              <div *ngIf="registerFormGroup.controls['User_Type_ID'].invalid && (registerFormGroup.controls['User_Type_ID'].dirty || registerFormGroup.controls['User_Type_ID'].touched)" class="text-danger">
                <div *ngIf="registerFormGroup.controls['User_Type_ID'].errors?.['required']">User Type is required.</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="card-footer d-flex justify-content-between">
        <button type="submit" class="btn btn-primary">Sign-up</button>
        <button type="button" class="btn btn-secondary" (click)="resetForm()">Cancel</button>
      </div>
    </form>
  </div>
</div>

//ts
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserService } from '../../Services/userprofile.service';
import { FlexLayoutModule } from '@angular/flex-layout';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [ReactiveFormsModule, CommonModule, FlexLayoutModule],
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent {
  submitted = false;
  registerFormGroup: FormGroup;
  selectedFile: File | null = null;

  constructor(
    private router: Router,
    private userService: UserService,
    private fb: FormBuilder,
    private snackBar: MatSnackBar
  ) {
    this.registerFormGroup = this.fb.group({
      // email: ['', [Validators.required, Validators.email, Validators.pattern(/^[a-z0-9._%+-]+@gmail\.com$/), Validators.minLength(3), Validators.maxLength(50)]],
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(15)]],
      name: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      surname: ['', [Validators.required, Validators.minLength(2), Validators.maxLength(20)]],
      // PhoneNumber: ['', [Validators.required, Validators.pattern(/^0\d{9}$/)]],
      PhoneNumber: ['', [Validators.required, Validators.minLength(10), Validators.maxLength(10)]],
      Date_of_Birth: ['', [Validators.required, this.validateDateOfBirth]],
      // Id_Number: ['', [Validators.required, Validators.pattern(/^\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{7}$/)]],
      Id_Number: ['', [Validators.required, Validators.minLength(13), Validators.maxLength(13)]],
      Physical_Address: ['', [Validators.required, Validators.minLength(7), Validators.maxLength(100)]],
      Photo: ['', Validators.required],
      // User_Status_ID: [1, [Validators.required, Validators.min(1), Validators.max(2)]],
      // User_Type_ID: ['', [Validators.required, Validators.min(1), Validators.max(3)]]
      User_Status_ID: [1, Validators.required],
      User_Type_ID: ['', Validators.required]
    });
  }

  ngOnInit() { }

  validateDateOfBirth(control: any): { [key: string]: any } | null {
    const selectedDate = new Date(control.value);
    const currentDate = new Date();
    const minDate = new Date(currentDate.getFullYear() - 100, currentDate.getMonth(), currentDate.getDate());
    const maxDate = new Date(currentDate.getFullYear() - 16, currentDate.getMonth(), currentDate.getDate());

    if (selectedDate > currentDate) {
      return { 'futureDate': true };
    }

    if (selectedDate < minDate) {
      return { 'olderThan100': true };
    }

    if (selectedDate > maxDate) {
      return { 'futureYear': true };
    }

    return null;
  }

  onFileSelected(event: any) {
    const file = event.target.files[0];
    if (file) {
      this.selectedFile = file;
      this.registerFormGroup.patchValue({ Photo: file });
    } else {
      this.selectedFile = null;
    }
  }

  RegisterUser() {
    this.submitted = true;
  
    if (this.registerFormGroup.valid && this.selectedFile) {
      console.log('Form is valid');
      console.log('Selected file:', this.selectedFile);

      const emailLowerCase = this.registerFormGroup.value.email.toLowerCase();
      this.registerFormGroup.patchValue({ email: emailLowerCase });
  
      const formData: FormData = new FormData();
      formData.append('name', this.registerFormGroup.value.name);
      formData.append('surname', this.registerFormGroup.value.surname);
      formData.append('email', this.registerFormGroup.value.email);
      formData.append('password', this.registerFormGroup.value.password);
      formData.append('PhoneNumber', this.registerFormGroup.value.PhoneNumber);
      formData.append('Date_of_Birth', this.registerFormGroup.value.Date_of_Birth);
      formData.append('Id_Number', this.registerFormGroup.value.Id_Number);
      formData.append('Physical_Address', this.registerFormGroup.value.Physical_Address);
      formData.append('Photo', this.selectedFile, this.selectedFile.name);
      formData.append('User_Status_ID', this.registerFormGroup.value.User_Status_ID);
      formData.append('User_Type_ID', this.registerFormGroup.value.User_Type_ID);
  
      this.userService.RegisterUser(formData).subscribe({
        next: (response) => {
          console.log('Registration Success:', response);
          this.registerFormGroup.reset();
          this.openSnackbar('Your user profile has been created', 'success');
          this.router.navigate(['/login']);
        },
        error: (error) => {
          console.log('Registration Error:', error);
          let errorMessage = 'Registration failed: ';
  
          if (error.error === 'DuplicateEmail') {
            errorMessage += 'This email address is already registered.';
          } else if (error.error === 'DuplicatePhoneNumber') {
            errorMessage += 'This phone number is already registered.';
          } else if (error.error === 'DuplicateDateOfBirth') {
            errorMessage += 'This date of birth is already registered.';
          } else if (error.error === 'DuplicateIdNumber') {
            errorMessage += 'This ID number is already registered.';
          } else if (error.error === 'DuplicatePhoto') {
            errorMessage += 'This photo is already associated with another user.';
          } else {
            errorMessage += 'Unknown error. Please try again later.';
          }
  
          this.openSnackbar(errorMessage, 'danger');
        }
      });
    } else {
      console.log('Form is not valid or file is not selected');
      console.log(this.registerFormGroup.errors);
      console.log(this.registerFormGroup.controls);

      this.openSnackbar('Form is not filled in correctly', 'danger');
    }
  }
  

  openSnackbar(message: string, type: 'success' | 'danger') {
    this.snackBar.open(message, 'Close', {
      duration: 5000,
      panelClass: type === 'success' ? 'snackbar-success' : 'snackbar-danger'
    });
  }

  get f() {
    return this.registerFormGroup.controls;
  }

  resetForm() {
    this.registerFormGroup.reset({
      user_status_id: 1  // Reset user_status_id to default value of 1 (Active)
    });
    this.router.navigate(['/login']);
  }
}

//css
.register-wrapper {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f0f4f7; /* Light blue background */
}

.box {
  padding: 60px 50px 40px;
  width: 100%;
  max-width: 800px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
  font-weight: 700;
  color: #000; /* Blue color for header text */
}

.card-title {
  font-size: 30px;
  margin: 0;
}

.form-group label {
  color: #000; /* Blue color for form labels */
}

.form-control {
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  transition: border-color 0.3s ease-in-out;
}

.form-control:focus {
  border-color: #000; /* Blue border on focus */
  box-shadow: 0 0 5px rgba(63, 81, 181, 0.2); /* Light blue shadow on focus */
}

.text-danger {
  color: #f44336; /* Red color for error messages */
}

.btn-primary {
  background-color: #4caf50; /* Green background for primary button */
  border-color: #4caf50; /* Green border for primary button */
  color: #fff; /* White text for primary button */
}

.btn-secondary {
  background-color: #f44336; /* Red background for secondary button */
  border-color: #f44336; /* Red border for secondary button */
  color: #fff; /* White text for secondary button */
}

.card-footer {
  display: flex;
  justify-content: space-between;
  padding: 20px;
}

.card-footer .btn {
  width: 48%;
}

/* Snackbar Styles */
.snackbar {
  visibility: visible;
  min-width: 250px;
  margin-left: -125px;
  background-color: #333;
  color: #fff;
  text-align: center;
  border-radius: 2px;
  padding: 16px;
  position: fixed;
  z-index: 1;
  left: 50%;
  bottom: 30px;
  font-size: 17px;
}

.snackbar-success {
  background-color: #4caf50; /* Green for success */
}

.snackbar-danger {
  background-color: #f44336; /* Red for error */
}

.close-snackbar {
  color: white;
  font-weight: bold;
  float: right;
  font-size: 22px;
  line-height: 20px;
  cursor: pointer;
  background: none;
  border: none;
}
The for...of loop
The basic tool for looping through a collection is the for...of loop:

js
Copy to Clipboard
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

for (const cat of cats) {
  console.log(cat);
}
In this example, for (const cat of cats) says:

Given the collection cats, get the first item in the collection.
Assign it to the variable cat and then run the code between the curly braces {}.
Get the next item, and repeat (2) until you've reached the end of the collection.

-------------------------------------------------
  
map() and filter()
JavaScript also has more specialized loops for collections, and we'll mention two of them here.

You can use map() to do something to each item in a collection and create a new collection containing the changed items:

js
Copy to Clipboard
function toUpper(string) {
  return string.toUpperCase();
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const upperCats = cats.map(toUpper);

console.log(upperCats);
// [ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]
Here we pass a function into cats.map(), and map() calls the function once for each item in the array, passing in the item. It then adds the return value from each function call to a new array, and finally returns the new array. In this case the function we provide converts the item to uppercase, so the resulting array contains all our cats in uppercase:

js
Copy to Clipboard
[ "LEOPARD", "SERVAL", "JAGUAR", "TIGER", "CARACAL", "LION" ]

You can use filter() to test each item in a collection, and create a new collection containing only items that match:

js
Copy to Clipboard
function lCat(cat) {
  return cat.startsWith("L");
}

const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const filtered = cats.filter(lCat);

console.log(filtered);
// [ "Leopard", "Lion" ]
This looks a lot like map(), except the function we pass in returns a boolean: if it returns true, then the item is included in the new array. Our function tests that the item starts with the letter "L", so the result is an array containing only cats whose names start with "L":

js
Copy to Clipboard
[ "Leopard", "Lion" ]

Note that map() and filter() are both often used with function expressions, which we will learn about in the Functions module. Using function expressions we could rewrite the example above to be much more compact:

js
Copy to Clipboard
const cats = ["Leopard", "Serval", "Jaguar", "Tiger", "Caracal", "Lion"];

const filtered = cats.filter((cat) => cat.startsWith("L"));
console.log(filtered);
// [ "Leopard", "Lion" ]

-------------------------------------------------
  
The standard for loop
In the "drawing circles" example above, you don't have a collection of items to loop through: you really just want to run the same code 100 times. In a case like that, you should use the for loop. This has the following syntax:

js
Copy to Clipboard
for (initializer; condition; final-expression) {
  // code to run
}
Here we have:

The keyword for, followed by some parentheses.
Inside the parentheses we have three items, separated by semicolons:
An initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. It is also sometimes referred to as a counter variable.
A condition — this defines when the loop should stop looping. This is generally an expression featuring a comparison operator, a test to see if the exit condition has been met.
A final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration. It usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where the condition is no longer true.
Some curly braces that contain a block of code — this code will be run each time the loop iterates.

-------------------------------------------------

Exiting loops with break
If you want to exit a loop before all the iterations have been completed, you can use the break statement. We already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves on to the code after it.

It's the same with loops — a break statement will immediately exit the loop and make the browser move on to any code that follows it.
  
Skipping iterations with continue
The continue statement works similarly to break, but instead of breaking out of the loop entirely, it skips to the next iteration of the loop. Let's look at another example that takes a number as an input, and returns only the numbers that are squares of integers (whole numbers).
  
-------------------------------------------------
  

while and do...while
for is not the only type of loop available in JavaScript. There are actually many others and, while you don't need to understand all of these now, it is worth having a look at the structure of a couple of others so that you can recognize the same features at work in a slightly different way.

First, let's have a look at the while loop. This loop's syntax looks like so:

js
Copy to Clipboard
initializer
while (condition) {
  // code to run

  final-expression
}
This works in a very similar way to the for loop, except that the initializer variable is set before the loop, and the final-expression is included inside the loop after the code to run, rather than these two items being included inside the parentheses. The condition is included inside the parentheses, which are preceded by the while keyword rather than for.

The same three items are still present, and they are still defined in the same order as they are in the for loop. This is because you must have an initializer defined before you can check whether or not the condition is true. The final-expression is then run after the code inside the loop has run (an iteration has been completed), which will only happen if the condition is still true.


The do...while loop is very similar, but provides a variation on the while structure:

js
Copy to Clipboard
initializer
do {
  // code to run

  final-expression
} while (condition)
In this case, the initializer again comes first, before the loop starts. The keyword directly precedes the curly braces containing the code to run and the final expression.

The main difference between a do...while loop and a while loop is that the code inside a do...while loop is always executed at least once. That's because the condition comes after the code inside the loop. So we always run that code, then check to see if we need to run it again. In while and for loops, the check comes first, so the code might never be executed.
    
    
Which loop type should you use?
If you're iterating through an array or some other object that supports it, and don't need access to the index position of each item, then for...of is the best choice. It's easier to read and there's less to go wrong.

For other uses, for, while, and do...while loops are largely interchangeable. They can all be used to solve the same problems, and which one you use will largely depend on your personal preference — which one you find easiest to remember or most intuitive. We would recommend for, at least to begin with, as it is probably the easiest for remembering everything — the initializer, condition, and final-expression all have to go neatly into the parentheses, so it is easy to see where they are and check that you aren't missing them.
@echo off
for /f "tokens=1* delims=*" %%a in (FILE.TXT) do (

>"%%a.url" echo [InternetShortcut]
>>"%%a.url" echo URL=%%b

)
//ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { Md5 } from 'ts-md5';
import { environment } from '../../environments/environment';
import { OrderService } from '../Services/order.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { UserService } from '../Services/userprofile.service';
import { CartItemViewModel, OrderViewModel } from '../shared/order';

declare global {
  interface Window {
    payfast_do_onsite_payment: (param1: any, callback: any) => any;
  }
}

@Component({
  selector: 'app-payfast',
  standalone: true,
  imports: [],
  templateUrl: './payfast.component.html',
  styleUrl: './payfast.component.css'
})
export class PayfastComponent implements OnInit {
  memberId!: number;

  constructor(private router : Router, private orderService : OrderService, private userService: UserService, private formBuilder: FormBuilder, private snackBar: MatSnackBar) {
    
  }

  ngOnInit(): void {
    this.fetchMemberId();
  }

  getSignature(data : Map<string, string>) : string {
    let tmp = new URLSearchParams();
    data.forEach((v, k)=> {
      tmp.append(k, v)
    });
    let queryString = tmp.toString();
    let sig = Md5.hashStr(queryString);
    return sig;
  }

  async doOnSitePayment() {
    await this.fetchMemberId();

    let onSiteUserData = new Map<string, string>();
    onSiteUserData.set("merchant_id", "10033427")
    onSiteUserData.set("merchant_key", "mu83ipbgas9p7")

    onSiteUserData.set('return_url', window.location.origin + '/payment-success')
    onSiteUserData.set('cancel_url', window.location.origin + '/payment-cancel')

    // Gather required user data from orderService or other sources
    const userData = this.orderService.getUserData();
    onSiteUserData.set("email_address", userData.email);
    
    // Set amount and item_name
    this.orderService.getTotalAmount().subscribe(amount => {
      onSiteUserData.set('amount', amount.toString());
      onSiteUserData.set('item_name', 'Cart Purchase');

      // Optional passphrase for added security
      onSiteUserData.set('passphrase', 'HelloWorldHello'); // Use if you have a passphrase

      let signature = this.getSignature(onSiteUserData);
      onSiteUserData.set('signature', signature);

      let formData = new FormData();
      onSiteUserData.forEach((val, key) => {
        formData.append(key, val);
      });

      fetch(environment.payfastOnsiteEndpoint, {
        method: 'POST',
        body: formData,
        redirect: 'follow'
      })
      .then(response => response.json())
      .then(respJson => {
          let uuid = respJson['uuid'];
          window.payfast_do_onsite_payment({ 'uuid': uuid }, (res: any) => {
            if (res == true) {            
              this.createOrder();
              this.snackBar.open('Payment Successful', 'Close', { duration: 5000 });          
            } else {
              this.snackBar.open('Payment Failed', 'Close', { duration: 5000 });
              
            }
          });
        })
        .catch(error => {
          console.error('Error processing payment:', error);
          this.router.navigate(['/cancel']);
        });
      });
    }

    //order
    private fetchMemberId() {
      const user = localStorage.getItem('User');
      if (user) {
        const userData = JSON.parse(user);
        this.memberId = userData.userId;
    
        // Optional: Fetch and validate member details if needed
        this.userService.getMemberByUserId(this.memberId).subscribe({
          next: (member) => {
            if (member && member.member_ID) {
              this.memberId = member.member_ID;
              console.log('Member ID:', this.memberId); // Check if this logs the correct ID
            } else {
              console.error('Member ID is undefined in the response');
              this.snackBar.open('Failed to retrieve member information', 'Close', { duration: 5000 });
            }
          },
          error: (error) => {
            console.error('Error fetching member:', error);
            this.snackBar.open('Failed to retrieve member information', 'Close', { duration: 5000 });
          }
        });
      } else {
        this.snackBar.open('User not logged in', 'Close', { duration: 5000 });
        this.router.navigate(['/login']);
      }
    }



  private createOrder() {
    if (this.memberId === undefined) {
      this.snackBar.open('Member ID is not available', 'Close', { duration: 5000 });
      return;
    }
    
    this.orderService.getCartItems().subscribe(cartItems => {
      const order  = this.prepareOrderDetails(cartItems);

      this.orderService.createOrder(order ).subscribe({
        next: (orderResponse) => {
          this.snackBar.open('Order Created Successfully', 'Close', { duration: 5000 });
          this.router.navigate(['/orders']);
          console.log("Order Creation Successful: ", orderResponse)
        },
        error: (error) => {
          console.error('Error creating order:', error);
          this.snackBar.open('Failed to create order', 'Close', { duration: 5000 });
          this.router.navigate(['/cart']);
        }
      });
    });
  }

  private prepareOrderDetails(cartItems: CartItemViewModel[]): OrderViewModel {
    const order: OrderViewModel = {
      order_ID: 0, // ID will be generated by backend
      member_ID: this.memberId,
      order_Date: new Date().toISOString(),
      total_Price: this.calculateTotalPrice(cartItems),
      order_Status_ID: 1, // Ready for Collection
      isCollected: false,
      orderLines: cartItems.map(item => ({
        order_Line_ID: 0, // ID will be generated by backend
        product_ID: item.product_ID,
        product_Name: item.product_Name,
        quantity: item.quantity,
        unit_Price: item.unit_Price
      }))
    };
  
    console.log('Prepared order details:', order);
    return order;
  }

  // Helper method to calculate the total price
  private calculateTotalPrice(cartItems: CartItemViewModel[]): number {
    return cartItems.reduce((total, item) => total + (item.unit_Price * item.quantity), 0);
  }
  
    
  }
//html
<app-navbar></app-navbar>
<br>
<br>
<br>
<div class="header-search-container">
    <i class="bi bi-arrow-left-circle header-icon" (click)="goBack()"></i>
    <h2 class="header-title">AV MERCH</h2>
</div>
<br>
<br>
<div class="checkout-container d-flex justify-content-center align-items-center">
    <br>
    <div class="row">
      <div class="col-12">
        <div class="card" style="width: 25rem;">
          <div class="card-header">
            <h3>Order Summary</h3>
          </div>
          <div class="card-body">
            <div *ngFor="let item of cartItems">
              <div>
                {{ item.product_Name }}: <span style="float: right">{{ item.unit_Price | currency: 'R ' }} x {{ item.quantity}}</span>
              </div>
            </div>
            <br>
            <div>
              Total Price: <span style="float: right">{{ totalAmount | currency: 'R ' }}</span>
            </div>
            <br>
            <div>
              <p>Use Discount</p>
              <input type="text" [(ngModel)]="discountCode" placeholder="Discount Code">
              <span style="float: right"><button (click)="applyDiscount()">Apply</button></span>
            </div>
          </div>
          <div class="card-footer">
            <div class="buttom-container">
                <span style="float: left">
                    <button (click)="cancel()" routerLink="/cart" class="btn btn-secondary">Cancel</button>
                </span>
                <span style="float: right">
                    <app-payfast></app-payfast>
                </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

//ts
import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { RouterLink } from '@angular/router';
import { NavbarComponent } from './navbar.component';
import { PayfastComponent } from "./payfast.component";
import { OrderService } from '../Services/order.service';
import { CartItemViewModel } from '../shared/order';
import { FormsModule } from '@angular/forms';
import { Location } from '@angular/common';

@Component({
  selector: 'app-checkout',
  standalone: true,
  imports: [CommonModule, FormsModule, RouterLink, NavbarComponent, PayfastComponent],
  templateUrl: './checkout.component.html',
  styleUrl: './checkout.component.css'
})
export class CheckoutComponent implements OnInit{
  cartItems: CartItemViewModel[] = [];
  totalAmount: number = 0;
  discountCode: string = '';

  constructor(private orderService: OrderService, private location:Location) {}

  ngOnInit(): void {
    this.loadCartItems();
  }

  loadCartItems(): void {
    this.orderService.getCartItems().subscribe(items => {
      this.cartItems = items;
      this.calculateTotal();
    });
  }

  calculateTotal(): void {
    this.totalAmount = this.cartItems.reduce((sum, item) => sum + (item.unit_Price * item.quantity), 0);
    // Apply discount logic if needed
  }

  applyDiscount(): void {
    // Apply discount logic
  }

  cancel(): void {
    // Navigate back to cart or home
    
  }
  
  goBack(): void {
    this.location.back();
  }
}

달리는 머리에서 도망치세요!
그룹:
https://www.roblox.com/groups/14856024

[2/05] 스테이지10 추가됨!
[5/16] 스테이지9 추가됨!
[3/31] 스테이지8 추가됨!
[3/07] 스테이지7 추가됨!
[3/03] 스테이지6 추가됨!
[2/21] 보스 추가됨!
[2/14] 스테이지 4 및 5가 추가되었습니다!
[2/13] 멀티플레이어를 지원합니다!
[2/10] 스테이지3 추가됨!

머리 이름은 Flamingo (YouTube) 팬이 만든 펠리페입니다.
Flamingo 님, 감사합니다.

게임에 문제가 있거나 제안 사항이 있으면 그룹에 알려주세요. 이 경험을 좋은 공간으로 만들려고 노력하고 있습니다.
https://www.roblox.com/groups/14856024

태그: 생존, 미로, 코미디, 장애물 게임
음악: 모우다마시
star

Tue Jul 30 2024 11:23:49 GMT+0000 (Coordinated Universal Time)

@BilalRaza12

star

Tue Jul 30 2024 08:41:11 GMT+0000 (Coordinated Universal Time)

@namnt

star

Tue Jul 30 2024 08:40:51 GMT+0000 (Coordinated Universal Time)

@namnt

star

Tue Jul 30 2024 01:20:15 GMT+0000 (Coordinated Universal Time)

@agedofujpn #javascript

star

Tue Jul 30 2024 01:01:41 GMT+0000 (Coordinated Universal Time)

@RobertoSilvaZ #powershell #windows11 #system #performance

star

Mon Jul 29 2024 20:28:20 GMT+0000 (Coordinated Universal Time)

@WXCanada

star

Mon Jul 29 2024 12:10:21 GMT+0000 (Coordinated Universal Time)

@Denixis24

star

Mon Jul 29 2024 12:02:27 GMT+0000 (Coordinated Universal Time)

@Denixis24

star

Mon Jul 29 2024 10:21:15 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Mon Jul 29 2024 09:46:05 GMT+0000 (Coordinated Universal Time)

@Shira

star

Mon Jul 29 2024 09:43:59 GMT+0000 (Coordinated Universal Time)

@Vivekstyn

star

Mon Jul 29 2024 09:40:30 GMT+0000 (Coordinated Universal Time)

@namnt

star

Mon Jul 29 2024 09:33:58 GMT+0000 (Coordinated Universal Time) https://www.coinsqueens.com/blog/create-your-own-blockchain-network

@Kiruthikaa #ownblockchainecosystem #blockchaindevelopment #smartcontractintegration

star

Mon Jul 29 2024 08:36:38 GMT+0000 (Coordinated Universal Time)

@Vivekstyn

star

Mon Jul 29 2024 08:32:29 GMT+0000 (Coordinated Universal Time)

@davidmchale #firstchild #remove

star

Mon Jul 29 2024 08:24:04 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon Jul 29 2024 08:22:37 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon Jul 29 2024 07:30:26 GMT+0000 (Coordinated Universal Time) https://dubverse.ai/

@UbedKhan

star

Mon Jul 29 2024 05:17:26 GMT+0000 (Coordinated Universal Time) https://codepen.io/StephenScaff/pen/bVbEbJ

@jg #undefined

star

Mon Jul 29 2024 04:43:05 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Mon Jul 29 2024 03:55:08 GMT+0000 (Coordinated Universal Time)

@signup

star

Mon Jul 29 2024 02:25:10 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/53323526/select-object-with-out-gridview

@baamn #powershell #out-gridview

star

Mon Jul 29 2024 00:35:27 GMT+0000 (Coordinated Universal Time) https://learn.microsoft.com/en-us/answers/questions/1118931/powershell-on-modifying-permissions

@baamn #powershell

star

Mon Jul 29 2024 00:26:46 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Mon Jul 29 2024 00:20:59 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Sun Jul 28 2024 23:43:44 GMT+0000 (Coordinated Universal Time)

@davidmchale #function #ternary

star

Sun Jul 28 2024 23:19:00 GMT+0000 (Coordinated Universal Time) https://www.ugmfree.it/forum/messages.aspx?TopicID

@baamn #passwords #security

star

Sun Jul 28 2024 21:42:10 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sun Jul 28 2024 15:37:46 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/71818580/how-to-enable-github-copilot-typing-tab-to-auto-completes-in-markdown-files

@destinyChuck #json #vscode

star

Sun Jul 28 2024 15:27:42 GMT+0000 (Coordinated Universal Time) undefined

@Shook87

star

Sun Jul 28 2024 14:48:24 GMT+0000 (Coordinated Universal Time) https://sourceforge.net/p/docfetcher/discussion/702424/thread/943ff8cc/

@baamn

star

Sun Jul 28 2024 14:05:57 GMT+0000 (Coordinated Universal Time)

@hacktivist

star

Sun Jul 28 2024 09:38:32 GMT+0000 (Coordinated Universal Time) https://openapi-generator.tech/

@Shook87 #bash

star

Sun Jul 28 2024 09:37:15 GMT+0000 (Coordinated Universal Time) https://openapi-generator.tech/

@Shook87 #bash

star

Sun Jul 28 2024 09:01:57 GMT+0000 (Coordinated Universal Time) https://app.auditorium.ai/lesson/eelyNMYJKXeNJAbjssSEQz0m88XvnhX6/49be1e94-c2d3-4683-ae14-36bbef39fc84?sl

@shlokgarg #python

star

Sun Jul 28 2024 08:29:03 GMT+0000 (Coordinated Universal Time) undefined

@Shook87

star

Sun Jul 28 2024 08:21:23 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/gzip.html

@Shook87

star

Sun Jul 28 2024 08:21:20 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/gzip.html

@Shook87

star

Sun Jul 28 2024 08:21:17 GMT+0000 (Coordinated Universal Time) https://docs.python.org/3/library/gzip.html

@Shook87

star

Sun Jul 28 2024 07:20:16 GMT+0000 (Coordinated Universal Time) https://git.sr.ht/~hwrd/bat-config

@Shook87

star

Sun Jul 28 2024 07:04:16 GMT+0000 (Coordinated Universal Time) undefined

@Shook87

star

Sun Jul 28 2024 07:03:24 GMT+0000 (Coordinated Universal Time) https://openapi-generator.tech/

@Shook87 #bash

star

Sun Jul 28 2024 04:34:29 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jul 28 2024 04:31:09 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jul 28 2024 02:17:54 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sun Jul 28 2024 00:44:43 GMT+0000 (Coordinated Universal Time) https://groups.google.com/g/alt.msdos.batch/c/ZornB-Th21M?hl

@baamn

star

Sat Jul 27 2024 18:12:32 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sat Jul 27 2024 17:00:38 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sat Jul 27 2024 14:05:56 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/games/6205205961/Escape-Running-Head#!/store

@Vitinlonlon73

Save snippets that work with our extensions

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