Snippets Collections
SELECT SubscriberKey, EmailAddress, System_Language__c, Mailing_Country__c, First_Name__c, Cat_Campaign_Most_Recent__c, Business_Unit__c, System_Opt_in_for_eMail__c, DateAdded, PCCReg
FROM (
SELECT
DISTINCT i.SubscriberKey
	,i.EmailAddress
	,i.System_Language__c
	,i.Mailing_Country__c
	,i.First_Name__c
	,i.Cat_Campaign_Most_Recent__c
	,i.Business_Unit__c
	,i.System_Opt_in_for_eMail__c
	,i.DateAdded
	,i.PCCReg,
 
ROW_NUMBER() OVER(PARTITION BY c.ID ORDER BY inta.LastModifiedDate DESC) as RowNum
 
FROM ent.Interaction__c_Salesforce inta
JOIN ent.Contact_Salesforce_1 c ON LOWER(c.Email) = LOWER(inta.Email__c)
JOIN [Proposed_Retail_TA_News_2024_INCLUDE] i ON LOWER(inta.Email__c) = LOWER(i.EmailAddress)
LEFT JOIN ps_an_en_us_s190010_Retail_TA_Segment_sendable_2021 mst ON LOWER(inta.Email__c) = LOWER(mst.EmailAddress)
WHERE 1 = 1
    AND i.SYSTEM_OPT_IN_FOR_EMAIL__C = '1'
    AND NOT EXISTS (
        SELECT NULL
        FROM [Proposed_Retail_TA_News_2024_EXCLUDE] ex
        WHERE 1 = 1
            AND i.SubscriberKey = ex.SubscriberKey
    ))t2
 
WHERE RowNum = 1
RenameColumns = Table.TransformColumnNames("Removed Other Columns", each Text.Proper(Text.Replace(Text.Replace(_, "crb3f_", ""), "_", " ")))
//TS
import { Component } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
  selector: 'app-bar-line',
  templateUrl: './bar-line.component.html',
  styleUrls: ['./bar-line.component.scss']
})
export class BarLineComponent {
  ngOnInit(): void {
    this.createChart();
  }
  public chart: any;
  createChart(){
    this.chart = new Chart("bar-line", {
      type: 'line',
      data: {
        labels: ['Shirt', 'Jacket', 'Men Tops', 'Men Pants', 
                 'Swimwear', 'Shoes', 'Sleepwear', 'Men Accessories'],
        datasets:[
          {
            label:"2022",
            data: ['446','551','462','158','171','553','566','231']
          },
          {
            type:'bar',
            label:"2023",
            data: ['623','431','525','306','100','369','417','420']
          }
        ]
      }
    });
  }
}
//HTML
<div class="chart-container">
    <h2>Product Sales</h2>
    <canvas id="bar-line">{{ chart }}</canvas>
</div>
//TS
import { Component } from '@angular/core';
import {Chart, ChartDataset, ChartType} from 'chart.js';

@Component({
  selector: 'app-pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.scss']
})
export class PieChartComponent {
  ngOnInit(): void {
    this.createChart();
  }
  public chart: any;
  createChart(){
    this.chart = new Chart("pie-chart", {
      type: 'pie',
      data: {
        labels: ['Shirt', 'Jacket', 'Men Tops', 'Men Pants', 
                 'Swimwear', 'Shoes', 'Sleepwear', 'Men Accessories'],
        datasets:[
          {
            label:"2022",
            data: ['446','551','462','158','171','553','566','231']
          },
          {
            label:"2023",
            data: ['623','431','525','306','100','369','417','420']
          }
        ]
      }
    });
  }
}
//HTML
<div class="chart-container">
    <h2>Product Sales</h2>
    <canvas id="pie-chart">{{ chart }}</canvas>
</div>
//TS
import { Component } from '@angular/core';
import {Chart, ChartDataset, ChartType} from 'chart.js';



@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
  
})
export class HomeComponent {
  ngOnInit(): void {
    this.createChart();
  }
  public chart: any;
  createChart(){
    this.chart = new Chart("barChart", {
      type: 'bar',
      data: {
        labels: ['Shirt', 'Jacket', 'Men Tops', 'Men Pants', 
                 'Swimwear', 'Shoes', 'Sleepwear', 'Men Accessories'],
        datasets:[
          {
            label:"2022",
            data: ['446','551','462','158','171','553','566','231'],
            backgroundColor: 'blue'
          },
          {
            label:"2023",
            data: ['623','431','525','306','100','369','417','420'],
            backgroundColor: 'red'
          }
        ]
      }
    });
  }
}
//HTML
<div class="chart-container">
    <h2>Product Sales</h2>
    <canvas id="barChart">{{ chart }}</canvas>
</div>
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends
//User function template for C++
class Solution{
public:
    
    int onesinrow(vector<vector<int>> &arr, int i){
        int lower = lower_bound(arr[i].begin(), arr[i].end(), 1) - arr[i].begin();
        return arr[i].size() - lower;
    }

    int rowWithMax1s(vector<vector<int>> &arr, int n, int m) {
        int ans = 0;
        int ind = -1;
        for(int i = 0; i < n; i++){
            int ones = onesinrow(arr, i);
            if(ones > ans){
                ans = ones;
                ind = i;
            }
        }
        return ind;
    }
};

//{ Driver Code Starts.
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m;
        cin >> n >> m;
        vector< vector<int> > arr(n,vector<int>(m));
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cin>>arr[i][j];
            }
        }
        Solution ob;
        auto ans = ob.rowWithMax1s(arr, n, m);
        cout << ans << "\n";
    }
    return 0;
}

// } Driver Code Ends
<nav class="navbar navbar-expand-sm bg-success navbar-dark">
  <a class="navbar-brand" href="#">Reporting</a>
  <button class="navbar-toggler"> data-target="#mynav">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="mynav">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-1link" routerLink="home">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-1link" routerLink="pie-chart">Pie Chart</a>
      </li>
      <li class="nav-item">
        <a class="nav-1link" routerLink="bar-line">Bar Line Chart</a>
      </li>
    </ul>
  </div>
</nav>
#include <bits/stdc++.h>
using namespace std;

class Solution{   
public:
    // Function to count elements <= mid_val using binary search
    int countSmallerThanOrEqualToMid(vector<int> &row, int mid_val) {
        int low = 0, high = row.size() - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (row[mid] <= mid_val) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return low;  // The number of elements <= mid_val
    }

    int median(vector<vector<int>> &matrix, int R, int C){
        int min_val = INT_MAX;
        int max_val = INT_MIN;

        // Find the minimum and maximum element in the matrix
        for (int i = 0; i < R; ++i) {
            if (matrix[i][0] < min_val) min_val = matrix[i][0];
            if (matrix[i][C - 1] > max_val) max_val = matrix[i][C - 1];
        }

        int desired_count = (R * C + 1) / 2;
        
        while (min_val < max_val) {
            int mid_val = min_val + (max_val - min_val) / 2;
            int count = 0;

            // Count elements <= mid_val using binary search
            for (int i = 0; i < R; ++i) {
                count += countSmallerThanOrEqualToMid(matrix[i], mid_val);
            }

            // Adjust search range based on the count
            if (count < desired_count) {
                min_val = mid_val + 1;
            } else {
                max_val = mid_val;
            }
        }
        
        return min_val;
    }
};

int main() {
    int t;
    cin >> t;
    while (t--) {
        int r, c;
        cin >> r >> c;
        vector<vector<int>> matrix(r, vector<int>(c));
        for (int i = 0; i < r; ++i)
            for (int j = 0; j < c; ++j)
                cin >> matrix[i][j];
        Solution obj;
        int ans = obj.median(matrix, r, c);
        cout << ans << "\n";        
    }
    return 0;
}
const getSelectValue = (callback) => {
  const options = getElement("#city-select");

  options.addEventListener("change", function (e) {
    const value = e.target.value;
    // pass the value into the callback function we can use later
    callback(value); // this value needs to be passed into the function where we are using the getSelectValue function ie  getSelectValue(value)
  });
};




// app function
const init = () => {
  // populate the DOM with the cities data on load
  const selectDOM = getElement("#city-select");
  populateDOM(cities, selectDOM);

  let selectedCity = ""; // this gets updated with the function below

  // need to run the callback here
  // get the value and assign it to a variable outside the function
  getSelectValue((value) => {
    selectedCity = value; // Assign the value to selectedCity
    //  // Log the selected city
    if (selectedCity !== "") {
      const container = getElement(".container h3");
      container.textContent = selectedCity;
    }
  });
};

window.addEventListener("DOMContentLoaded", init);

let score = 85;

let grade = (score >= 90) ? 'A' : 
            (score >= 80) ? 'B' : 
            (score >= 70) ? 'C' : 
            (score >= 60) ? 'D' : 'F';

console.log(`The grade is ${grade}`);
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { RegisterUser } from '../shared/register-user';
import { LoginUser } from '../shared/login-user';
import { User } from '../shared/user';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BackendService {

  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json'
    })
  };

  constructor(private http: HttpClient) {}
  endPoint: string = "http://localhost:5240/api/";

  RegisterUser(registerUser: RegisterUser) {
    return this.http.post(`${this.endPoint}Authentication/Register`, registerUser, this.httpOptions);
  }

  LoginUser(loginUser: LoginUser): Observable<User> {
    return this.http.post<User>(`${this.endPoint}Authentication/Login`, loginUser, this.httpOptions);
  }
}
//TS
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { BackendService } from '../services/backend.service';
import { MaterialModule } from '../shared/material.module';
import { FlexLayoutModule } from '@angular/flex-layout';
import { MatSnackBar } from '@angular/material/snack-bar';

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    MaterialModule,
    ReactiveFormsModule,
    RouterLink,
    CommonModule,
    HttpClientModule, 
    FlexLayoutModule
],
  templateUrl: './login.component.html',
  styleUrl: './login.component.scss'
})
export class LoginComponent {
  loginFormGroup: FormGroup;
  isLoading: boolean = false;

  constructor(
    private router: Router,
    private backendService: BackendService,
    private fb: FormBuilder,
    private snackBar: MatSnackBar
  ) {
    this.loginFormGroup = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]]
    });
  }

  ngOnInit(): void {}

  LoginUser() {
    if (this.loginFormGroup.valid) {
      this.isLoading = true;

      this.backendService.LoginUser(this.loginFormGroup.value).subscribe({
        next: (result) => {
          localStorage.setItem('User', JSON.stringify(result));
          this.loginFormGroup.reset();
          this.router.navigateByUrl('product-listing');
          this.snackBar.open('Login successful', 'X', { duration: 2000 });
          this.isLoading = false;
        },
        error: (err) => {
          let errorMessage = 'Login failed. Please try again.';
          if (err.status === 401) {
            errorMessage = 'Invalid email or password.';
          } else if (err.status === 500) {
            errorMessage = 'Internal server error. Please contact support.';
          }
          this.snackBar.open(errorMessage, 'X', { duration: 3000 });
          this.isLoading = false;
        }
      });
    } else {
      this.snackBar.open('Please fill out the form correctly.', 'X', { duration: 3000 });
    }
  }
}
//Memo
export class LoginComponent implements OnInit {

  loginFormGroup: FormGroup = this.fb.group({
    emailaddress: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required],
  })

  isLoading:boolean = false

  constructor(private router: Router, private apiService: APIService, private fb: FormBuilder, private snackBar: MatSnackBar) { }

  ngOnInit(): void {}

  async LoginUser(){
    if(this.loginFormGroup.valid)
    {
      this.isLoading = true

      await this.apiService.LoginUser(this.loginFormGroup.value).subscribe(result => {
        localStorage.setItem('User', JSON.stringify(result))
        this.loginFormGroup.reset();
        this.router.navigateByUrl('productListing');
      })
    }
  }
}
//Logout
ngOnInit(): void {
    this.isLoggedIn = localStorage.getItem('User') ? true : false;
  }
logout(): void {
    localStorage.removeItem('User');
    this.router.navigateByUrl('login');
    this.snackBar.open('You have been successfully logged out.', 'X', {duration: 3000});
  }
//OR
logout(){
    if(localStorage.getItem('User'))
    {
      localStorage.removeItem('User')
      this.router.navigateByUrl('login');
    }
  }
//HTML
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
  <mat-card class="box" *ngIf="!isLoading">
    <mat-card-header>
      <mat-card-title>Log in</mat-card-title>
    </mat-card-header>
    <form class="form" [formGroup]="loginFormGroup" (ngSubmit)="LoginUser()">
      <mat-card-content>
        <mat-form-field class="full-width">
          <mat-label>Email Address</mat-label>
          <input matInput placeholder="e.g., user@example.com" formControlName="email">
          <mat-error *ngIf="loginFormGroup.controls['email'].hasError('required')">Email is required</mat-error>
          <mat-error *ngIf="loginFormGroup.controls['email'].hasError('email')">Enter a valid email</mat-error>
        </mat-form-field>
        <mat-form-field class="full-width">
          <mat-label>Password</mat-label>
          <input type="password" matInput placeholder="e.g., 8-16 characters" formControlName="password">
          <mat-error *ngIf="loginFormGroup.controls['password'].hasError('required')">Password is required</mat-error>
          <mat-error *ngIf="loginFormGroup.controls['password'].hasError('minlength')">Minimum 8 characters required</mat-error>
          <mat-error *ngIf="loginFormGroup.controls['password'].hasError('maxlength')">Maximum 16 characters allowed</mat-error>
        </mat-form-field>
      </mat-card-content>
      <mat-card-actions>
        <button mat-stroked-button color="primary" class="btn-block" type="submit">Log in</button>
      </mat-card-actions>
      <div style="text-align: center;">Don't have an account? <a [routerLink]="['../register']">Register</a></div>
    </form>
  </mat-card>
  <mat-progress-spinner mode="indeterminate" *ngIf="isLoading"></mat-progress-spinner>
</div>
//TS
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { BackendService } from '../services/backend.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import { MaterialModule } from '../shared/material.module';
import { CommonModule } from '@angular/common';
import { HttpClientModule } from '@angular/common/http';
import { FlexLayoutModule } from '@angular/flex-layout';

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [
    MaterialModule,
    ReactiveFormsModule,
    RouterLink,
    CommonModule,
    HttpClientModule, 
    FlexLayoutModule
  ],
  templateUrl: './register.component.html',
  styleUrl: './register.component.scss'
})
export class RegisterComponent{
  registerFormGroup: FormGroup;

  constructor(private router: Router, private backendService: BackendService, private fb: FormBuilder, private snackBar: MatSnackBar) { 
    this.registerFormGroup = this.fb.group({
      email: ['', [Validators.required, Validators.email]],
      password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(16)]]
    });
  }

  ngOnInit(): void {
  }

  RegisterUser() {
    if (this.registerFormGroup.valid) {
      this.backendService.RegisterUser(this.registerFormGroup.value).subscribe({
        next: () => {
          this.registerFormGroup.reset();
          this.router.navigate(['/login']).then(navigated => {
            if (navigated) {
              this.snackBar.open('Registered successfully', 'X', { duration: 2000 });
            }
          });
        },
        error: (err) => {
          let errorMessage = 'Registration failed. Please try again.';
          if (err.status === 403) {
            errorMessage = 'Account already exists.';
          } else if (err.status === 500) {
            errorMessage = 'Internal server error. Please contact support.';
          }
          this.snackBar.open(errorMessage, 'X', { duration: 3000 });
        }
      });
    } else {
      this.snackBar.open('Please fill out the form correctly.', 'X', { duration: 3000 });
    }
  }
  

  cancel() {
    this.registerFormGroup.reset();
    this.router.navigate(['/login']);
  }
}

//HTML
<div class="login-wrapper" fxLayout="row" fxLayoutAlign="center center">
  <mat-card class="box">
    <mat-card-header>
      <mat-card-title>Register</mat-card-title>
    </mat-card-header>
    <form class="form" [formGroup]="registerFormGroup" (ngSubmit)="RegisterUser()">
      <mat-card-content>
        <mat-form-field class="full-width">
          <mat-label>Email Address</mat-label>
          <input matInput placeholder="e.g., user@example.com" formControlName="email">
          <mat-error *ngIf="registerFormGroup.controls['email'].hasError('required')">Email is required</mat-error>
          <mat-error *ngIf="registerFormGroup.controls['email'].hasError('email')">Enter a valid email</mat-error>
        </mat-form-field>
        <mat-form-field class="full-width">
          <mat-label>Password</mat-label>
          <input type="password" matInput placeholder="Enter between 8 to 16 characters" formControlName="password">
          <mat-error *ngIf="registerFormGroup.controls['password'].hasError('required')">Password is required</mat-error>
          <mat-error *ngIf="registerFormGroup.controls['password'].hasError('minlength')">Minimum 8 characters required</mat-error>
          <mat-error *ngIf="registerFormGroup.controls['password'].hasError('maxlength')">Maximum 16 characters allowed</mat-error>
        </mat-form-field>
      </mat-card-content>
      <mat-card-actions>
        <button mat-stroked-button color="primary" class="btn-block" type="submit">Register</button>
        <button mat-stroked-button color="warn" class="btn-block" type="button" (click)="cancel()">Cancel</button>
      </mat-card-actions>
    </form>
  </mat-card>
</div>
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-9QI4G7U\\SQLEXPRESS;Database=INF354Assignment3;Trusted_Connection=True;MultipleActiveResultSets=True"
  },
  "Tokens": {
    "Key": "y+VRv[&)0XhxJ<sk=yUpW{yE5CH@xh",
    "Issuer": "localhost",
    "Audience": "localhost"
  }
}
using Assignment3_Backend.Factory;
using Assignment3_Backend.Models;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options => options.AddDefaultPolicy(
    include =>
    {
        include.AllowAnyHeader();
        include.AllowAnyMethod();
        include.AllowAnyOrigin();
    }));

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//For identity
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
    options.Password.RequireUppercase = false;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireDigit = true;
    options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();

//Adding JWT Bearer
builder.Services.AddAuthentication()
                .AddCookie()
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidIssuer = builder.Configuration["Tokens:Issuer"],
                        ValidAudience = builder.Configuration["Tokens:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Tokens:Key"]))
                    };
                });

// File upload functionality
builder.Services.Configure<FormOptions>(o =>
{
    o.ValueLengthLimit = int.MaxValue;
    o.MultipartBodyLengthLimit = int.MaxValue;
    o.MemoryBufferThreshold = int.MaxValue;
});

builder.Services.AddScoped<IUserClaimsPrincipalFactory<AppUser>, AppUserClaimsPrincipalFactory>();

builder.Services.Configure<DataProtectionTokenProviderOptions>(options => options.TokenLifespan = TimeSpan.FromHours(3));

//For Entity Framework
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IRepository, Repository>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseCors();
app.UseAuthentication();
app.UseAuthorization();


app.MapControllers();

app.Run();
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
    private readonly UserManager<AppUser> _userManager;
    private readonly IRepository _repository;
    private readonly IUserClaimsPrincipalFactory<AppUser> _claimsPrincipalFactory;
    private readonly IConfiguration _configuration;

    public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IConfiguration configuration, IRepository repository)
    {
        _userManager = userManager;
        _claimsPrincipalFactory = claimsPrincipalFactory;
        _configuration = configuration;
        _repository = repository;
    }

    [HttpPost]
    [Route("RegisterUser")]
    public async Task<IActionResult>RegisterUser(UserViewModel uvm)
    {
        var user = await _userManager.FindByNameAsync(uvm.username);
        if (user == null)
        {
            try
            {
                string phoneNumberPattern = @"^0\d{9}$";
                bool isValidPhoneNumber = Regex.IsMatch(uvm.phonenumber, phoneNumberPattern);
                if (!isValidPhoneNumber) return BadRequest("Please enter a valid 10-digit phone number");
                user = new AppUser
                {
                    Id= Guid.NewGuid().ToString(),
                    UserName= uvm.username,
                    Email=  uvm.emailaddress,
                    PhoneNumber= uvm.phonenumber
                };
                var result= await _userManager.CreateAsync(user, uvm.password);
                if (result.Errors.Count() > 0)
                {
                    StringBuilder errorlist = new StringBuilder("These registration errors need to be resolved");
                    foreach (var error in result.Errors)
                    {
                        errorlist.Append($"{error.Code}: {error.Description}");
                    }
                    return BadRequest($"{errorlist}");
                }
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, $"Error occured{ex.Message}");
            }
        }
        else
        {
            return Conflict($"The username '{uvm.username}' already exists. Please use a different username");
        }
        return Ok($"Your account '{uvm.username}' was created successfully. You may proceed with logging in");
    }
}
//Password and Email
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
    options.User.RequireUniqueEmail = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Password.RequiredLength = 12;
    options.Password.RequireDigit = true;
    options.Password.RequireUppercase = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
[Route("api/[controller]")]
[ApiController]
public class AuthenticationController : ControllerBase
{
    private readonly UserManager<AppUser> _userManager;
    private readonly IUserClaimsPrincipalFactory<AppUser> _claimsFactory;
    private readonly IRepository _repository;
    private readonly IConfiguration _configuration;

    public AuthenticationController(UserManager<AppUser> userManager, IUserClaimsPrincipalFactory<AppUser> claimsPrincipalFactory, IRepository repository, IConfiguration configuration)
    {
        _repository = repository;
        _userManager = userManager;
        _claimsFactory = claimsPrincipalFactory;
        _configuration = configuration;
    }

    [HttpPost]
    [Route("Register")]
    public async Task<IActionResult> Register(UserViewModel userViewModel)
    {
        var user = await _userManager.FindByIdAsync(userViewModel.email);

        if (user == null)
        {
            user = new AppUser
            {
                Id = Guid.NewGuid().ToString(),
                UserName = userViewModel.email,
                Email = userViewModel.email
            };

            var result = await _userManager.CreateAsync(user, userViewModel.password);

            if (result.Errors.Count() > 0) return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
        }
        else
        {
            return Forbid("Account already exists.");
        }

        return Ok();
    }

    [HttpPost]
    [Route("Login")]
    public async Task<ActionResult> Login(UserViewModel uvm)
    {
        var user = await _userManager.FindByNameAsync(uvm.email);

        if (user != null && await _userManager.CheckPasswordAsync(user, uvm.password))
        {
            try
            {
                var userPrincipal = await _claimsFactory.CreateAsync(user);
                return GenerateJWTToken(user);
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
            }
        }
        else
        {
            return NotFound("Does not exist");
        }
    }

    [HttpGet]
    private ActionResult GenerateJWTToken(AppUser user)
    {
        // Create JWT Token
        var userClaims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.Email),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
        var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            _configuration["Tokens:Issuer"],
            _configuration["Tokens:Audience"],
            userClaims  ,
            signingCredentials: credentials,
            expires: DateTime.UtcNow.AddHours(3)
        );

        return Created("", new
        {
            token = new JwtSecurityTokenHandler().WriteToken(token),
            user = user.UserName
        });
    }
}
@ -0,0 +1,159 @@
import {
  ButtonContent,
  DestructiveButton,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Icon,
  If,
  Input,
  Toaster,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import type * as z from "zod";
import React, { useEffect, useState } from "react";
import { toast } from "sonner";
import wretch from "wretch";
import {
  fieldsNameHelper,
  formSchema,
  numberFields,
  toTitleCase,
} from "./regularVesselInfoForm";

interface AddRegularVesselFormProps {
  fields: string[];
  vesselId?: string;
  imo?: string;
  returnIdentifier: (identifier: any) => void;
}

export const AddRegularVesselForm = ({
  fields,
  vesselId,
  imo,
  returnIdentifier,
}: AddRegularVesselFormProps) => {
  const excludeFields: string[] = ["id"];
  const disabledFields: string[] = ["vessel_id", "imo"];

  const [identifier, setIdentifier] = useState<string>(vesselId || imo || "");

  fields = fields?.sort().filter((item) => !excludeFields.includes(item));

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      vessel_id: vesselId,
      imo: imo,
    },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    const addVessel: VesselInfo = Object.entries(values).reduce(
      (acc: VesselInfo, [key, value]) => {
        const vesselInfoKey: string = fieldsNameHelper[key].name;
        acc[vesselInfoKey] = (value || "").toString().toLowerCase();
        return acc;
      },
      {},
    );

    try {
      const response = await wretch("/api/form/regularVessel")
        .post(addVessel)
        .res();

      if (response.ok) {
        toast.success("Success!", {
          description: "Vessel details inserted.",
        });
        returnIdentifier({ vessel_id: values.vessel_id, imo: values.imo });
      } else {
        toast.error("Error submitting form");
      }
    } catch (error) {
      toast.error("Something went wrong", {
        description: (error as PostgrestError | null)?.message,
      });
    }
  }

  const reset = form.reset;

  useEffect(() => {
    reset({}, { keepValues: false });

    reset(
      {
        vessel_id: vesselId,
        imo: imo,
      },
      { keepValues: false },
    );
  }, [reset]);

  return (
    <div className={"mt-4"}>
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          {Object.keys(formSchema.shape).map((key, index) => (
            <>
              <If condition={fields?.includes(fieldsNameHelper[key].name)}>
                <FormField
                  key={key + index}
                  control={form.control}
                  name={key as any}
                  render={({ field }) => (
                    <FormItem className={"flex flex-row items-center"}>
                      <FormLabel className={"w-64 text-lg font-light"}>
                        {toTitleCase(fieldsNameHelper[key].name)}
                      </FormLabel>
                      <div className={"mr-2"}>
                        <TooltipProvider>
                          <Tooltip>
                            <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                              <Icon name="unknown" style="h-5 w-5" />
                            </TooltipTrigger>
                            <TooltipContent>
                              <p>{fieldsNameHelper[key].description}</p>
                            </TooltipContent>
                          </Tooltip>
                        </TooltipProvider>
                      </div>
                      <FormControl className={"w-full"}>
                        <Input
                          className={"text-md font-light"}
                          required={false}
                          {...field}
                          type={numberFields.includes(key) ? "number" : "text"}
                          value={field.value ?? ""}
                          disabled={disabledFields.includes(key)}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </If>
            </>
          ))}
          <div className="flex flex-row justify-end">
            <DestructiveButton type="submit" className="mt-4">
              <ButtonContent>Add vessel</ButtonContent>
            </DestructiveButton>
          </div>
          <Toaster />
        </form>
      </Form>
    </div>
  );
};
@ -0,0 +1,396 @@
import {
  ButtonContent,
  DestructiveButton,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Icon,
  If,
  Input,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Toaster,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import React, { useEffect, useState } from "react";
import { toast } from "sonner";
import wretch from "wretch";

export interface VesselInfo {
  [key: string]: string | undefined;
}

interface RegularVesselFormProps {
  vesselInfo: VesselInfo;
  vesselId?: string;
  imo?: string;
}

export const formSchema = z.object({
  imo: z.string().optional(),
  cargoType: z.string().optional(),
  cargoSubType: z.string().optional(),
  mmsi: z.string().optional(),
  vesselName: z.string().optional(),
  yearOfBuild: z.string().optional(),
  flag: z.string().optional(),
  dwt: z.string().optional(),
  maximumDraft: z.string().optional(),
  geared: z.string().optional(),
  gearDetails: z.string().optional(),
});

type FieldsNameHelper = {
  [key: string]: { name: string; description: string };
};

export const fieldsNameHelper: FieldsNameHelper = {
  imo: {
    name: "IMO",
    description: "International Maritime Organization identifier",
  },
  cargoType: {
    name: "Cargo Type",
    description: "The type of cargo the vessel carries",
  },
  cargoSubType: {
    name: "Cargo Sub Type",
    description: "The subtype of cargo the vessel carries",
  },
  mmsi: { name: "MMSI", description: "Maritime Mobile Service Identity" },
  vesselName: { name: "Vessel Name", description: "The name of the vessel" },
  yearOfBuild: {
    name: "Year of Build",
    description: "The year the vessel was built",
  },
  flag: { name: "Flag", description: "The flag country code" },
  dwt: { name: "DWT", description: "Dead Weight Tonnage" },
  maximumDraft: {
    name: "Maximum Draft",
    description:
      "The deepest point of the vessel below the waterline when fully loaded",
  },
  geared: {
    name: "Geared",
    description: "Indicates if the vessel is geared (yes or no)",
  },
  gearDetails: {
    name: "Gear Details",
    description: "Details about the vessel's gear",
  },
};

export const numberFields: string[] = [
  "dwt",
  "yearOfBuild",
  "maximumDraft",
  "mmsi",
  "imo",
];

export const uppercaseFields: string[] = ["imo", "mmsi"];

export function toTitleCase(str: string): string {
  if (uppercaseFields.includes(str)) {
    return str.toUpperCase().replace("_", " ");
  } else {
    str = str.replace("_", " ");
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
  }
}

export const RegularVesselInfoForm = ({
  vesselInfo,
  vesselId,
  imo,
}: RegularVesselFormProps) => {
  const disabledFields: string[] = ["vesselId", "imo"];
  const [selectedType, setSelectedType] = useState<string | null>(
    vesselInfo?.cargoType ?? null,
  );

  const defaultFieldsValues = Object.fromEntries(
    Object.keys(fieldsNameHelper).map((key) => [
      key,
      vesselInfo ? vesselInfo[fieldsNameHelper[key].name as string] ?? "" : "",
    ]),
  );

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: defaultFieldsValues,
  });

  useEffect(() => {
    if (vesselInfo) {
      form.reset(defaultFieldsValues);
    }
  }, [vesselInfo]);

  async function onSubmit(values: z.infer<typeof formSchema>) {
    const updatedVesselInfo: VesselInfo = Object.entries(values).reduce(
      (acc: VesselInfo, [key, value]) => {
        const vesselInfoKey: string = fieldsNameHelper[key].name;
        acc[vesselInfoKey] = (value || "").toString().toLowerCase();
        return acc;
      },
      {},
    );

    try {
      const response = await wretch("/api/form/regularVessel")
        .post(updatedVesselInfo)
        .res();
      if (response.ok) {
        await wretch(`/api/form/regularVessel?vessel_id=${vesselId}&imo=${imo}`)
          .get()
          .json();
        toast.success("Success!", {
          description: "Vessel details updated.",
        });
      } else {
        toast.error("Error submitting form");
      }
    } catch (error) {
      toast.error("Something went wrong", {
        description: (error as any)?.message,
      });
    }
  }

  return (
    <div className="mt-6 flex w-full flex-col gap-2 p-2 sm:w-1/2">
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
          {Object.keys(formSchema.shape).map((key, index) => (
            <React.Fragment key={key}>
              <If
                condition={Object.keys(vesselInfo || {}).includes(
                  fieldsNameHelper[key].name,
                )}
              >
                <If
                  condition={
                    key !== "type" && key !== "subType" && key !== "buildYear"
                  }
                >
                  <FormField
                    key={key}
                    control={form.control}
                    name={key as any}
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          {toTitleCase(fieldsNameHelper[key].name)}
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <FormControl className={"w-full"}>
                          <Input
                            {...field}
                            className={"text-md font-light"}
                            type={
                              numberFields.includes(key) ? "number" : "text"
                            }
                            value={field.value ?? ""}
                            disabled={disabledFields.includes(key)}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </If>
                <If condition={key === "type"}>
                  <FormField
                    control={form.control}
                    name="type"
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          Type
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <Select
                          onValueChange={(value: any) => {
                            field.onChange(value);
                            setSelectedType(value);
                          }}
                          value={field.value ?? ""}
                        >
                          <FormControl className={"text-md w-full font-light"}>
                            <SelectTrigger>
                              <SelectValue placeholder="Select a type" />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            <SelectItem value={"cargo vessel"}>
                              Cargo Vessel
                            </SelectItem>
                            <SelectItem value={"tanker"}>Tanker</SelectItem>
                            <SelectItem value={"passenger vessel"}>
                              Passenger Vessel
                            </SelectItem>
                            <SelectItem value={"other"}>Other</SelectItem>
                          </SelectContent>
                        </Select>
                      </FormItem>
                    )}
                  />
                </If>
                <If condition={key === "subType"}>
                  <FormField
                    control={form.control}
                    name="subType"
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          Sub type
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <Select
                          onValueChange={field.onChange}
                          value={field.value ?? ""}
                        >
                          <FormControl className={"text-md w-full font-light"}>
                            <SelectTrigger>
                              <SelectValue placeholder="Select a sub type" />
                            </SelectTrigger>
                          </FormControl>
                          {selectedType && selectedType === "cargo vessel" && (
                            <SelectContent>
                              <SelectItem value={"bulk carrier"}>
                                Bulk Carrier
                              </SelectItem>
                              <SelectItem value={"container ship"}>
                                Container Ship
                              </SelectItem>
                              <SelectItem value={"general cargo ship"}>
                                General Cargo Ship
                              </SelectItem>
                            </SelectContent>
                          )}
                          {selectedType && selectedType === "tanker" && (
                            <SelectContent>
                              <SelectItem value={"oil tanker"}>
                                Oil Tanker
                              </SelectItem>
                              <SelectItem value={"chemical tanker"}>
                                Chemical Tanker
                              </SelectItem>
                              <SelectItem value={"gas carrier"}>
                                Gas Carrier
                              </SelectItem>
                            </SelectContent>
                          )}
                          {selectedType &&
                            selectedType === "passenger vessel" && (
                              <SelectContent>
                                <SelectItem value={"cruise ship"}>
                                  Cruise Ship
                                </SelectItem>
                                <SelectItem value={"ferry"}>Ferry</SelectItem>
                              </SelectContent>
                            )}
                        </Select>
                      </FormItem>
                    )}
                  />
                </If>
                <If condition={key === "buildYear"}>
                  <FormField
                    control={form.control}
                    name="buildYear"
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          Build year
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <FormControl className={"w-full"}>
                          <Input
                            {...field}
                            className={"text-md font-light"}
                            type="number"
                            min={1900}
                            max={2100}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </If>
              </If>
            </React.Fragment>
          ))}
          <If
            condition={vesselInfo && Object.keys(formSchema.shape).length > 0}
          >
            <div className="flex flex-row justify-end">
              <DestructiveButton type="submit" className="mt-4">
                <ButtonContent>Update</ButtonContent>
              </DestructiveButton>
            </div>
          </If>
          <Toaster />
        </form>
      </Form>
    </div>
  );
};
@ -0,0 +1,121 @@
// regularVesselRds.ts

import {rdsConnection} from "@/lib/aws";
import type {Vessel, VesselDetails} from "@/types";

// Fetch regular vessel information by vessel_id or imo
export async function getRegularVessel(identifier: {
  vessel_id?: string;
  imo?: string;
}) {
  const { vessel_id, imo } = identifier;
  const query = vessel_id
    ? `SELECT v.vessel_id, v.dwt, v.imo, v.flag, v.mmsi, v.vessel_name, v.cargo_type, v.cargo_sub_type, v.year_of_build, v.maximum_draft, d.geared, d.gear_details
       FROM spotship_vessel AS v
       LEFT JOIN spotship_vesseldetails AS d ON v.vessel_id = d.vessel_id
       WHERE v.vessel_id = ? LIMIT 1`
    : `SELECT v.vessel_id, v.dwt, v.imo, v.flag, v.mmsi, v.vessel_name, v.cargo_type, v.cargo_sub_type, v.year_of_build, v.maximum_draft, d.geared, d.gear_details
       FROM spotship_vessel AS v
       LEFT JOIN spotship_vesseldetails AS d ON v.vessel_id = d.vessel_id
       WHERE v.imo = ? LIMIT 1`;

  const value = vessel_id || imo;

  return await new Promise<{ vessel: Vessel; details: VesselDetails }[]>(
    (resolve, reject) => {
      rdsConnection.query(
        query,
        [value],
        (
          error: unknown,
          elements: { vessel: Vessel; details: VesselDetails }[],
        ) => {
          if (error) {
            return reject(error);
          }
          return resolve(elements);
        },
      );
    },
  );
}

// Insert new regular vessel information
export async function insertRegularVessel(data: any) {
  const { vessel, details } = data;
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `INSERT INTO spotship_vessel (vessel_id, dwt, imo, flag, mmsi, vessel_name, cargo_type, cargo_sub_type, year_of_build, maximum_draft)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        vessel.vessel_id,
        vessel.dwt,
        vessel.imo,
        vessel.flag,
        vessel.mmsi,
        vessel.vessel_name,
        vessel.cargo_type,
        vessel.cargo_sub_type,
        vessel.year_of_build,
        vessel.maximum_draft,
      ],
      (error: unknown) => {
        if (error) {
          console.error("Insert spotship_vessel error: ", error); // Log error
          return reject(error);
        }
        rdsConnection.query(
          `INSERT INTO spotship_vesseldetails (vessel_id, geared, gear_details) VALUES (?, ?, ?)`,
          [vessel.vessel_id, details.geared, details.gear_details],
          (error: unknown) => {
            if (error) {
              console.error("Insert spotship_vesseldetails error: ", error); // Log error
              return reject(error);
            }
            return resolve();
          },
        );
      },
    );
  });
}

// Update existing regular vessel information
export async function updateRegularVessel(data: any) {
  const { vessel, details } = data;
  return await new Promise<void>((resolve, reject) => {
    rdsConnection.query(
      `UPDATE spotship_vessel SET dwt = ?, imo = ?, flag = ?, mmsi = ?, vessel_name = ?, cargo_type = ?, cargo_sub_type = ?, year_of_build = ?, maximum_draft = ?
       WHERE vessel_id = ?`,
      [
        vessel.dwt,
        vessel.imo,
        vessel.flag,
        vessel.mmsi,
        vessel.vessel_name,
        vessel.cargo_type,
        vessel.cargo_sub_type,
        vessel.year_of_build,
        vessel.maximum_draft,
        vessel.vessel_id,
      ],
      (error: unknown) => {
        if (error) {
          console.error("Update spotship_vessel error: ", error); // Log error
          return reject(error);
        }
        rdsConnection.query(
          `UPDATE spotship_vesseldetails SET geared = ?, gear_details = ? WHERE vessel_id = ?`,
          [details.geared, details.gear_details, vessel.vessel_id],
          (error: unknown) => {
            if (error) {
              console.error("Update spotship_vesseldetails error: ", error); // Log error
              return reject(error);
            }
            return resolve();
          },
        );
      },
    );
  });
}
@ -0,0 +1,49 @@
import type { NextApiRequest, NextApiResponse } from "next";
import {
  getRegularVessel,
  insertRegularVessel,
  updateRegularVessel,
} from "@/functions/aws/regularVesselRds";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const { method } = req;

  switch (method) {
    case "GET":
      try {
        const { vessel_id, imo } = req.query;
        const response = await getRegularVessel({ vessel_id, imo });
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error in GET /api/form/regularVessel: ", error);
        return res.status(500).json({ error: error.message });
      }

    case "POST":
      try {
        const response = await updateRegularVessel(req.body);
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error in POST /api/form/regularVessel: ", error);
        return res.status(500).json({ error: error.message });
      }

    case "PUT":
      try {
        const response = await insertRegularVessel(req.body);
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error in PUT /api/form/regularVessel: ", error);
        return res.status(500).json({ error: error.message });
      }

    default:
      res.setHeader("Allow", ["GET", "POST", "PUT"]);
      return res
        .status(405)
        .send(`Method ${method ?? "Undefined"} Not Allowed`);
  }
}
@ -0,0 +1,151 @@
import {
  BackHomeButton,
  CommandPalletteButton,
  If,
  Input,
  MinimalPage,
  PageHeading,
} from "ui";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import { useEffect, useState } from "react";
import wretch from "wretch";
import { AddRegularVesselForm } from "@/components/forms/addRegularVesselForm";
import {
  fieldsNameHelper,
  RegularVesselInfoForm,
  VesselInfo,
} from "@/components/forms/regularVesselInfoForm";

const RegularVesselInfo = () => {
  const [vesselInfo, setVesselInfo] = useState<VesselInfo | null>();
  const [identifier, setIdentifier] = useState<{
    vessel_id?: string;
    imo?: string;
  }>({
    vessel_id: "",
    imo: "",
  });
  const [newRegularVesselForm, setNewRegularVesselForm] = useState<any>();

  useEffect(() => {
    if (!identifier.vessel_id && !identifier.imo) {
      setVesselInfo(null);
    }
  }, [identifier]);

  useEffect(() => {
    const fetchData = async () => {
      if (identifier.vessel_id || identifier.imo) {
        setVesselInfo(null);
        try {
          const response = await wretch(
            `/api/form/regularVessel?vessel_id=${identifier.vessel_id}&imo=${identifier.imo}`,
          )
            .get()
            .res();
          if (response.ok) {
            const data: VesselInfo | null = await response.json();
            setVesselInfo(data);
          } else {
            console.error("Error:", response.statusText);
          }
        } catch (error) {
          console.error("Error:", error);
        }
      } else {
        setVesselInfo(null);
      }
    };
    fetchData();
  }, [identifier]);

  return (
    <MinimalPage
      pageTitle={"Regular Vessel Info | Email Interface"}
      pageDescription={"Spot Ship Email Interface | Regular Vessel Info"}
      commandPrompt
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <div>
          <BackHomeButton />
        </div>
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>
      <PageHeading text="Regular Vessel Info" />
      <div className="mt-6 flex w-full flex-col gap-2 p-2 sm:w-1/2">
        <div className={"flex flex-row items-center"}>
          <div
            className={"w-28 text-2xl font-normal text-black dark:text-white"}
          >
            IMO or Vessel ID
          </div>
          <Input
            type={"text"}
            className={"text-md"}
            onChange={(event: ChangeEvent<HTMLInputElement>) => {
              setIdentifier({
                vessel_id: event.target.value || "",
                imo: event.target.value || "",
              });
            }}
          />
        </div>
        <div className={"font-sans text-sm text-black dark:text-white"}>
          Enter either the Vessel ID or IMO number to fetch the vessel
          information.
        </div>
      </div>
      <If
        condition={
          !!(
            identifier.vessel_id ||
            (identifier.imo && vesselInfo?.["message"])
          )
        }
      >
        <div className={"mt-2 flex w-full flex-col gap-2 p-2 sm:w-1/2"}>
          <div
            className={"mb-6 text-center text-lg text-black dark:text-white"}
          >
            No information found for identifier:{" "}
            {identifier.vessel_id || identifier.imo}. Add new regular vessel
          </div>
          <div>
            <AddRegularVesselForm
              fields={Object.keys(fieldsNameHelper)}
              vesselId={identifier.vessel_id}
              imo={identifier.imo}
              returnIdentifier={(identifier: {
                vessel_id: string;
                imo: string;
              }) => {
                setIdentifier(identifier);
              }}
            />
          </div>
        </div>
      </If>
      <If
        condition={
          !!(
            identifier.vessel_id ||
            (identifier.imo && vesselInfo && !vesselInfo?.["message"])
          )
        }
      >
        <RegularVesselInfoForm
          vesselInfo={vesselInfo as VesselInfo}
          vesselId={identifier.vessel_id}
          imo={identifier.imo}
        />
      </If>
    </MinimalPage>
  );
};

export default RegularVesselInfo;
export type { User } from "./user";
export { emptyVessel, vesselSchema } from "./vessel";
export type { Vessel } from "./vessel";

export class VesselDetails {
}
.md_wrap {
    overflow: hidden;
    display: flex;
    gap: -4px;
    
    ul {
        display: flex;

        li {
            width: 340px;
            height: 544px;
            margin: 0 8px;
            background-color: #fff;
            display: flex;
        }
    }
    // 롤링배너 애니메이션
    #roller1 {
        animation: rollingleft1 90s linear infinite;
    }
    #roller2 {
        animation: rollingleft2 90s linear infinite;
    }
}

@keyframes rollingleft1 {
    0% { transform: translateX(0)}
	50% { transform: translateX(-100%)}
	50.01% { transform: translateX(100%)}
	100% { transform: translateX(0)}
}

@keyframes rollingleft2 {
    0% {transform: translateX(0)}
    100% {transform: translateX(-200%)}
}

<!-- 4. 미디어섹션(컴포넌트)-->
<section class="main_media">
    <h3>Media</h3>
    <div class="md_wrap">
        <div class="md_list">
            <ul>
                <MedComp v-for="(v, i) in mData" :key="i" :matchmedia="v" :dpt1val="v.depth1" :dpt2val="v.depth2"/>
            </ul>
        </div>
    </div>
</section>

methods: {
        rollBan() {
            // 롤링 배너 복제본 생성 
            let roller = document.querySelector('.md_list');
            roller.id = 'roller1'; // 아이디 부여
            
            // 노드 복제 (기본값은 false, 자식 노드까지 원하면 true)
            let clone = roller.cloneNode(true);
            clone.id = 'roller2';
            document.querySelector('.md_wrap').appendChild(clone); // .md_wrap 하위 자식으로 넣기

            document.querySelector('#roller1').style.left = '0px';
            document.querySelector('#roller2').style.left = document.querySelector('.md_list > ul').offsetWidth + 'px';
        },
    }
/* reset */
section { width: 100%; }
li { display: inline-block; list-style: none; }

/* 슬라이드 */
.slideWrap { display: flex; position: relative; top: 0; left: 0; height: 200px; overflow: hidden;  }
.slideWrap .imgSlide { display: flex; align-items: center; justify-content: space-between; padding-left: 0; }
.slideWrap .imgSlide.original { animation: 30s linear 0s infinite normal forwards running slide01; }
.slideWrap .imgSlide.clone { animation: 30s linear 0s infinite normal none running slide02; }
.slideWrap .imgSlide li { width: 200px; height: 200px; line-height: 200px; margin-right: 5vw; background-color: #ccc; text-align: center; }

/** 애니메이션 **/
/* 원본용 */
@keyframes slide01 { 
    0% { transform: translateX(0); }
    50% { transform: translateX(-100%); }
    50.01% { transform: translateX(100%); }
    100% { transform: translateX(0); }
}

/* 복제용 */
@keyframes slide02 { 
    0% { transform: translateX(0); }
    100% { transform: translateX(-200%); }
}
const imgSlide = document.querySelector(".imgSlide");

// 복제
const clone = imgSlide.cloneNode(true);

// 복제본 추가
document.querySelector(".slideWrap").appendChild(clone);

// 원본, 복제본 위치 지정
document.querySelector(".imgSlide").offsetWidth + "px";

// 클래스 할당
imgSlide.classList.add("original");
clone.classList.add("clone");
@ -0,0 +1,261 @@
import {
  ButtonContent,
  DestructiveButton,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Icon,
  Input,
  Toaster,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "ui";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import React, { useEffect, useState } from "react";
import { toast } from "sonner";
import wretch from "wretch";
import { useRouter } from "next/router";
import { useGetVesselFromIMO } from "@/hooks";

const formSchema = z.object({
  imo: z.string().max(7),
  cargo_type: z.string().optional(),
  cargo_sub_type: z.string().optional(),
  mmsi: z.string().max(9).optional(),
  vessel_name: z.string().optional(),
  year_of_build: z.string().optional(),
  flag: z.string().optional(),
  grt: z.string().optional(),
  dwt: z.string().optional(),
  overall_length: z.string().optional(),
  beam: z.string().optional(),
  maximum_draft: z.string().optional(),
});

type FormFields = z.infer<typeof formSchema>;

const fieldsNameHelper: Record<
  keyof FormFields,
  { name: string; description: string }
> = {
  imo: {
    name: "IMO",
    description: "International Maritime Organization identifier",
  },
  cargo_type: {
    name: "Cargo Type",
    description: "The type of cargo the vessel carries",
  },
  cargo_sub_type: {
    name: "Cargo Sub Type",
    description: "The subtype of cargo the vessel carries",
  },
  mmsi: { name: "MMSI", description: "Maritime Mobile Service Identity" },
  vessel_name: { name: "Vessel Name", description: "The name of the vessel" },
  year_of_build: {
    name: "Year of Build",
    description: "The year the vessel was built",
  },
  flag: { name: "Flag", description: "The flag country code" },
  grt: { name: "GRT", description: "Gross Registered Tonnage" },
  dwt: { name: "DWT", description: "Dead Weight Tonnage" },
  overall_length: {
    name: "Overall Length",
    description: "The overall length of the vessel",
  },
  beam: { name: "Beam", description: "The beam of the vessel" },
  maximum_draft: {
    name: "Maximum Draft",
    description:
      "The deepest point of the vessel below the waterline when fully loaded",
  },
};

interface VesselInfoFormProps {
  mode: "add" | "edit";
  initialValues?: FormFields;
  onModeChange?: (mode: "add" | "edit") => void;
}

export function VesselInfoForm({
  mode,
  initialValues,
  onModeChange,
}: VesselInfoFormProps) {
  const [imoChecked, setImoChecked] = useState(false);
  const [isEditMode, setIsEditMode] = useState(mode === "edit");
  const [updateError, setUpdateError] = useState(null);
  const form = useForm({
    resolver: zodResolver(formSchema),
    defaultValues: initialValues || {},
  });

  const router = useRouter();
  const imoValue = form.watch("imo");
  const {
    data: vesselData,
    isError,
    isLoading,
  } = useGetVesselFromIMO(imoValue);

  useEffect(() => {
    if (mode === "edit" && initialValues) {
      form.reset(initialValues);
    }
  }, [initialValues, mode, form]);

  useEffect(() => {
    if (vesselData && vesselData.length > 0 && mode === "add") {
      setIsEditMode(true);
      if (onModeChange) onModeChange("edit");
    } else {
      setIsEditMode(false);
      if (onModeChange) onModeChange("add");
    }
  }, [vesselData, mode, onModeChange]);

  async function onCheckIMO() {
    if (vesselData && vesselData.length > 0) {
      router.push(
        `/secure/manager/manageVessel/editRegularVessel?imo=${imoValue}`,
      );
    } else {
      setImoChecked(true);
    }
  }

  async function onSubmit(values: FormFields) {
    const updatedVesselInfo = Object.entries(values).reduce(
      (acc: Record<string, string>, [key, value]) => {
        const vesselInfoKey = fieldsNameHelper[key as keyof FormFields].name;
        acc[vesselInfoKey] = (value || "").toString().toLowerCase();
        return acc;
      },
      {},
    );

    setUpdateError(null);
    try {
      const apiUrl = isEditMode
        ? "/api/form/updateVessel"
        : "/api/form/insertVessel";
      const response = await wretch(apiUrl).post(updatedVesselInfo).res();
      if (response.ok) {
        toast.success("Success!", {
          description: isEditMode
            ? "Vessel details updated."
            : "Vessel details added.",
        });
        form.reset();
        setImoChecked(false);
      } else {
        throw new Error("Error submitting form");
      }
    } catch (error) {
      setUpdateError(error);
    }
  }

  return (
    <div className={"mt-4"}>
      <Form {...form}>
        <form className="space-y-4">
          <FormField
            control={form.control}
            name="imo"
            render={({ field }) => (
              <FormItem className={"flex flex-row items-center"}>
                <FormLabel className={"w-64 text-lg font-light"}>
                  {fieldsNameHelper.imo.name}
                </FormLabel>
                <div className={"mr-2"}>
                  <TooltipProvider>
                    <Tooltip>
                      <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                        <Icon name="unknown" style="h-5 w-5" />
                      </TooltipTrigger>
                      <TooltipContent>
                        <p>{fieldsNameHelper.imo.description}</p>
                      </TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                </div>
                <FormControl className={"w-full"}>
                  <Input
                    {...field}
                    className={"text-md font-light"}
                    type="text"
                    value={field.value ?? ""}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          {imoChecked &&
            (!vesselData || vesselData.length === 0) &&
            (Object.keys(formSchema.shape) as Array<keyof FormFields>).map(
              (key) =>
                key !== "imo" && (
                  <FormField
                    key={key}
                    control={form.control}
                    name={key}
                    render={({ field }) => (
                      <FormItem className={"flex flex-row items-center"}>
                        <FormLabel className={"w-64 text-lg font-light"}>
                          {fieldsNameHelper[key].name}
                        </FormLabel>
                        <div className={"mr-2"}>
                          <TooltipProvider>
                            <Tooltip>
                              <TooltipTrigger className="text-black hover:text-black/50 dark:text-white dark:hover:text-white/50">
                                <Icon name="unknown" style="h-5 w-5" />
                              </TooltipTrigger>
                              <TooltipContent>
                                <p>{fieldsNameHelper[key].description}</p>
                              </TooltipContent>
                            </Tooltip>
                          </TooltipProvider>
                        </div>
                        <FormControl className={"w-full"}>
                          <Input
                            {...field}
                            className={"text-md font-light"}
                            type="text"
                            value={field.value ?? ""}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                ),
            )}
          <div className="flex flex-row justify-end">
            <DestructiveButton
              onClick={imoChecked ? form.handleSubmit(onSubmit) : onCheckIMO}
              className="mt-4"
            >
              <ButtonContent>
                {isEditMode
                  ? "Save Changes"
                  : imoChecked
                    ? "Add Vessel"
                    : "Check IMO"}
              </ButtonContent>
            </DestructiveButton>
          </div>
          <Toaster />
        </form>
      </Form>
    </div>
  );
}
@ -0,0 +1,54 @@
import { rdsConnection } from "@/lib/aws";
import { v4 as uuidv4 } from "uuid";

export async function insertVessel(data) {
  const {
    cargo_type,
    cargo_sub_type,
    imo,
    mmsi,
    vessel_name,
    year_of_build,
    flag,
    grt,
    dwt,
    overall_length,
    beam,
    maximum_draft,
  } = data;

  const vessel_id = uuidv4();

  const query = `
    INSERT INTO spotship_vessel (
      vessel_id, cargo_type, cargo_sub_type, ais_enabled, map_enabled, imo, mmsi, vessel_name, year_of_build, flag, grt, dwt, overall_length, beam, maximum_draft
    ) VALUES (?, ?, ?, 1, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  return new Promise((resolve, reject) => {
    rdsConnection.query(
      query,
      [
        vessel_id,
        cargo_type,
        cargo_sub_type,
        imo,
        mmsi,
        vessel_name,
        year_of_build,
        flag,
        grt,
        dwt,
        overall_length,
        beam,
        maximum_draft,
      ],
      (error, results) => {
        if (error) {
          return reject(error);
        }
        resolve(results);
      },
    );
  });
};
import type { NextApiRequest, NextApiResponse } from "next";
import { rdsConnection } from "@/lib/aws";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  if (req.method === "POST") {
    const { imo } = req.body;
    const query = `
      SELECT COUNT(*) as count FROM spotship_vessel WHERE imo = ?
    `;

    rdsConnection.query(query, [imo], (error, results) => {
      if (error) {
        return res.status(500).json({ success: false, error: error.message });
      }
      const exists = results[0].count > 0;
      return res.status(200).json({ success: true, exists });
    });
  } else {
    res.setHeader("Allow", ["POST"]);
    return res
      .status(405)
      .send(`Method ${req.method ?? "Undefined"} Not Allowed`);
  }
}
@ -0,0 +1,59 @@
import type { NextApiRequest, NextApiResponse } from "next";
import { rdsConnection } from "@/lib/aws";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  if (req.method === "POST") {
    const {
      imo,
      cargo_type,
      cargo_sub_type,
      mmsi,
      vessel_name,
      year_of_build,
      flag,
      grt,
      dwt,
      overall_length,
      beam,
      maximum_draft,
    } = req.body;

    const query = `
      UPDATE spotship_vessel
      SET cargo_type = ?, cargo_sub_type = ?, mmsi = ?, vessel_name = ?, year_of_build = ?, flag = ?, grt = ?, dwt = ?, overall_length = ?, beam = ?, maximum_draft = ?
      WHERE imo = ?
    `;

    rdsConnection.query(
      query,
      [
        cargo_type,
        cargo_sub_type,
        mmsi,
        vessel_name,
        year_of_build,
        flag,
        grt,
        dwt,
        overall_length,
        beam,
        maximum_draft,
        imo,
      ],
      (error, results) => {
        if (error) {
          return res.status(500).json({ success: false, error: error.message });
        }
        return res.status(200).json({ success: true, data: results });
      },
    );
  } else {
    res.setHeader("Allow", ["POST"]);
    return res
      .status(405)
      .send(`Method ${req.method ?? "Undefined"} Not Allowed`);
  }
}
import type { NextApiRequest, NextApiResponse } from "next";
import { insertVessel } from "@/lib/db";

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  if (req.method === "POST") {
    try {
      const result = await insertVessel(req.body);
      return res.status(200).json({ success: true, data: result });
    } catch (error) {
      return res.status(500).json({ success: false, error: error.message });
    }
  } else {
    res.setHeader("Allow", ["POST"]);
    return res
      .status(405)
      .send(`Method ${req.method ?? "Undefined"} Not Allowed`);
  }
}
import { NextPage } from "next";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { VesselInfoForm } from "@/components/forms/vesselInfoForm";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import { useRouter } from "next/router";

const RegularVessel: NextPage = () => {
  const router = useRouter();

  const handleModeChange = (mode: "add" | "edit") => {
    if (mode === "edit") {
      const imo = router.query.imo;
      router.push(`/secure/manager/manageVessel/editRegularVessel?imo=${imo}`);
    }
  };

  return (
    <MinimalPage
      pageTitle={"Add Vessel | Vessel Interface"}
      pageDescription={"Vessel Interface | Vessel Info"}
      commandPrompt
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <BackHomeButton />
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>
      <PageHeading text="Vessel Info" />
      <VesselInfoForm mode="add" onModeChange={handleModeChange} />
    </MinimalPage>
  );
};

export default RegularVessel;
import { NextPage } from "next";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { VesselInfoForm } from "@/components/forms/vesselInfoForm";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import { useRouter } from "next/router";
import { useGetVesselFromIMO } from "@/hooks";

const EditRegularVessel: NextPage = () => {
  const router = useRouter();
  const { imo } = router.query;
  const {
    data: vesselData,
    isError,
    isLoading,
  } = useGetVesselFromIMO(imo as string);

  if (isLoading) {
    return (
      <MinimalPage
        pageTitle={"Edit Vessel | Vessel Interface"}
        pageDescription={"Vessel Interface | Edit Vessel Info"}
        commandPrompt
      >
        <div className="flex w-full flex-row justify-between pl-1 pt-1">
          <BackHomeButton />
          <Navigation />
          <div className="flex flex-row gap-4">
            <BugReportButton />
            <CommandPalletteButton />
            <CommandInterface />
          </div>
        </div>
        <PageHeading text="Edit Vessel Info" />
        <p>Loading...</p>
      </MinimalPage>
    );
  }

  if (isError || !vesselData || vesselData.length === 0) {
    return (
      <MinimalPage
        pageTitle={"Edit Vessel | Vessel Interface"}
        pageDescription={"Vessel Interface | Edit Vessel Info"}
        commandPrompt
      >
        <div className="flex w-full flex-row justify-between pl-1 pt-1">
          <BackHomeButton />
          <Navigation />
          <div className="flex flex-row gap-4">
            <BugReportButton />
            <CommandPalletteButton />
            <CommandInterface />
          </div>
        </div>
        <PageHeading text="Edit Vessel Info" />
        <p>Vessel not found.</p>
      </MinimalPage>
    );
  }

  return (
    <MinimalPage
      pageTitle={"Edit Vessel | Vessel Interface"}
      pageDescription={"Vessel Interface | Edit Vessel Info"}
      commandPrompt
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <BackHomeButton />
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>
      <PageHeading text="Edit Vessel Info" />
      <VesselInfoForm mode="edit" initialValues={vesselData[0]} />
    </MinimalPage>
  );
};

export default EditRegularVessel;
import pause

def test():
    print('done')

def run_after(func, amount_of_time):
    pause.milliseconds(amount_of_time)
    func()

run_after(test, 10000)
--text: #050315;
--background: #fbfbfe;
--primary: #2f27ce;
--secondary: #dedcff;
--accent: #433bff;
from textblob import TextBlob

text = 'how are you'

blob = TextBlob(text)

if blob.polarity > 0:
    print('Positive')
elif blob.polarity < 0:
    print('Negative')
else:
    print('Neutral')
users_db = [
    {'id': '2313', 'coins': 50},
    {'id': '8213', 'coins': 20},
    {'id': '9989', 'coins': 0},
    {'id': '4654', 'coins': 1},
    {'id': '7897', 'coins': 3},
    {'id': '9898', 'coins': 60}
]

users_db.sort(key = lambda user: user['coins'])
print(users_db)
users_db = [
    {'id': 'ax123', 'money': 5},
    {'id': 'z5541', 'money': 0}
]

def get_user_by_id(user_id):
    for user in users_db:
        if user['id'] == user_id:
            return user
        
def send_money(from_id, to_id, amount):
    from_user_a = get_user_by_id(from_id)
    to_user_b = get_user_by_id(to_id)

    if from_user_a and to_user_b:
        if from_user_a['money'] >= amount:
            from_user_a['money'] -= amount
            to_user_b['money'] += amount
        else:
            print('the amount of money is large than your balance')
        
    

send_money('ax123', 'z5541', 2)
send_money('ax123', 'z5541', 2)
print(users_db)
from faker import Faker
from random import randint, choice

f = Faker()
payment_methods = ['paypal', 'bitcoin']

for _ in range(20):
    money = randint(1, 100) * 0.99
    pyment_method = choice(payment_methods)
    user_email = "*****" + f.email()[6:]
    print(f'{money}$ --- {user_email} --- {pyment_method}')
This account does not seem to be open in any other location. However, there may be sessions that have not been signed out.
Visit Security Checkup for more details
Recent activity:
Access Type [ ? ]
(Browser, mobile, POP3, etc.)	Location (IP address) [ ? ]	Date/Time
(Displayed in your time zone)
Browser (Chrome) Show details	* Canada (198.2.85.220)	12:59 am (1 minute ago)
Authorized Application () Show details	Canada (198.2.85.220)	12:35 am (25 minutes ago)
Browser (Chrome) Show details	* Canada (198.2.85.220)	11:56 pm (1 hour ago)
Authorized Application () Show details	Canada (198.2.85.220)	11:55 pm (1 hour ago)
Browser (Chrome) Show details	* Canada (198.2.85.220)	10:45 pm (2 hours ago)
Authorized Application () Show details	Canada (198.2.85.220)	10:45 pm (2 hours ago)
Authorized Application () Show details	Canada (198.2.85.220)	Jun 9 (7 days ago)
Authorized Application () Show details	Canada (198.2.85.220)	Jun 9 (7 days ago)
Authorized Application () Show details	Canada (198.2.85.220)	Jun 9 (7 days ago)
Browser (Chrome) Show details	Canada (198.2.85.220)	Jun 9 (7 days ago)
* indicates activity from the current session.
This computer is using IP address 198.2.85.220. (Canada)
public class GFG {
 
    public static void main(String[] args)
    {
 
        Integer[] a = { 100, 22, 58, 41, 6, 50 };
 
        Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };
 
        String[] s = { "Virat", "Rohit", "Abhinay", "Chandu","Sam", "Bharat", "Kalam" };
 
        System.out.print("Sorted Integer array :  ");
        sort_generics(a);
 
        System.out.print("Sorted Character array :  ");
        sort_generics(c);
 
        System.out.print("Sorted String array :  ");
        sort_generics(s);
       
    }
 
    public static <T extends Comparable<T> > void sort_generics(T[] a)
    {
       
         //As we are comparing the Non-primitive data types 
          //we need to use Comparable class
       
        //Bubble Sort logic
        for (int i = 0; i < a.length - 1; i++) {
 
            for (int j = 0; j < a.length - i - 1; j++) {
 
                if (a[j].compareTo(a[j + 1]) > 0) {
 
                    swap(j, j + 1, a);
                }
            }
        }
 
        // Printing the elements after sorted
 
        for (T i : a) 
        {
            System.out.print(i + ", ");
        }
        System.out.println();
       
    }
 
    public static <T> void swap(int i, int j, T[] a)
    {
        T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }
   
}
class Test {
    // A Generic method example
    static <T> void genericDisplay(T element)
    {
        System.out.println(element.getClass().getName()
                           + " = " + element);
    }
 
    // Driver method
    public static void main(String[] args)
    {
        // Calling generic method with Integer argument
        genericDisplay(11);
 
        // Calling generic method with String argument
        genericDisplay("GeeksForGeeks");
 
        // Calling generic method with double argument
        genericDisplay(1.0);
    }
}
class Test<T> {
    // An object of type T is declared
    T obj;
    Test(T obj) { this.obj = obj; } // constructor
    public T getObject() { return this.obj; }
}
 
// Driver class to test above
class Main {
    public static void main(String[] args)
    {
        // instance of Integer type
        Test<Integer> iObj = new Test<Integer>(15);
        System.out.println(iObj.getObject());
 
        // instance of String type
        Test<String> sObj
            = new Test<String>("GeeksForGeeks");
        System.out.println(sObj.getObject());
    }
}
About
 
C++ Guide
 
C++ Tips
 
Fast Tips
 
Python Guide
 
Blog
 
Community
 
SWE Book
Community
Contribution Guidelines Code of Conduct
The Abseil Community
Abseil aims to have an active community of developers who are using, enhancing and building valuable integrations with other software projects. We’d love your help to improve and extend the project. You can reach us via the Abseil Mailing List at abseil-io@googlegroups.com or Twitter to start engaging with the project and its members.

Code of Conduct
Abseil wants to foster an open and welcoming environment for both our contributors and maintainers. We pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. To faciliate this open environment, please review our Code of Conduct.

Mailing List
Any questions or suggestions? Just want to be in the loop of what is going on with the project? Join the Abseil mailing list at abseil-io@googlegroups.com.

The Abseil Community
Code of Conduct
Mailing List

©2017 Abseil | Live at Head

Privacy Policy

 
 const players = [...document.querySelectorAll('section.player')];

    for (const [index, item] of players.entries()) {
      console.log(i, v);
    }




// 0 <section class=​"player player--0 player--active">​…​</section>
// 1 <section class=​"player player--1">​…​</section>
import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
  loss='sparse_categorical_crossentropy',
  metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
<button class="btn btn--new">🔄 New game</button>


.btn {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    color: #444;
    background: none;
    border: none;
    font-family: inherit;
    font-size: 1.8rem;
    text-transform: uppercase;
    cursor: pointer;
    font-weight: 400;
    transition: all 0.2s;
    background-color: white;
    background-color: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(10px);
    padding: 0.7rem 2.5rem;
    border-radius: 50rem;
    box-shadow: 0 1.75rem 3.5rem rgba(0, 0, 0, 0.1);
}

.btn:active {
    transform: translate(-50%, 3px);
    box-shadow: 0 1rem 2rem rgba(0, 0, 0, 0.15);
}
star

Mon Jun 17 2024 19:30:56 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Mon Jun 17 2024 17:55:55 GMT+0000 (Coordinated Universal Time)

@bdusenberry

star

Mon Jun 17 2024 17:22:43 GMT+0000 (Coordinated Universal Time) https://www.facebook.com/checkpoint/?next

@gangaa

star

Mon Jun 17 2024 13:31:13 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 13:26:04 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 13:03:44 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 13:00:01 GMT+0000 (Coordinated Universal Time)

@Xeno_SSY #c++

star

Mon Jun 17 2024 12:45:27 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 12:30:16 GMT+0000 (Coordinated Universal Time)

@Xeno_SSY

star

Mon Jun 17 2024 11:39:55 GMT+0000 (Coordinated Universal Time)

@davidmchale #callback

star

Mon Jun 17 2024 11:06:30 GMT+0000 (Coordinated Universal Time)

@davidmchale #loop #index #array

star

Mon Jun 17 2024 10:05:47 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 09:35:03 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 09:19:07 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 09:14:49 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 09:01:45 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 08:48:51 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 08:45:49 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 08:41:47 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Mon Jun 17 2024 07:18:57 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 07:18:31 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 07:17:21 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 07:16:40 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 07:15:43 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 07:15:08 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Mon Jun 17 2024 05:12:25 GMT+0000 (Coordinated Universal Time) https://ziszini.tistory.com/114

@rwdkjy

star

Mon Jun 17 2024 02:37:49 GMT+0000 (Coordinated Universal Time) https://webd.tistory.com/153

@rwdkjy

star

Mon Jun 17 2024 02:37:28 GMT+0000 (Coordinated Universal Time) https://webd.tistory.com/153

@rwdkjy

star

Sun Jun 16 2024 23:08:07 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:07:44 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:06:54 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:06:12 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:05:27 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:04:39 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 23:04:08 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Sun Jun 16 2024 15:49:48 GMT+0000 (Coordinated Universal Time) https://www.realtimecolors.com/?colors

@atticus1990

star

Sun Jun 16 2024 08:16:58 GMT+0000 (Coordinated Universal Time) https://www.roblox.com/users/1727610081/profile

@Misha

star

Sun Jun 16 2024 05:03:06 GMT+0000 (Coordinated Universal Time) https://mail.google.com/mail/u/0/?ui

@curtisbarry

star

Sun Jun 16 2024 02:44:26 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/generics-in-java/

@iyan #java

star

Sun Jun 16 2024 02:24:12 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/generics-in-java/

@iyan

star

Sun Jun 16 2024 02:15:24 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/generics-in-java/

@iyan #java

star

Sun Jun 16 2024 02:06:23 GMT+0000 (Coordinated Universal Time) https://abseil.io/community/

@curtisbarry

star

Sun Jun 16 2024 01:21:28 GMT+0000 (Coordinated Universal Time)

@davidmchale #loop #index #array

star

Sat Jun 15 2024 23:38:06 GMT+0000 (Coordinated Universal Time) https://www.tensorflow.org/

@calazar23

star

Sat Jun 15 2024 22:56:13 GMT+0000 (Coordinated Universal Time)

@davidmchale #active #button #animation

Save snippets that work with our extensions

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