Snippets Collections
//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);
}
{
  "userAccountInfoId": 0,
  "name": "Uditha",
  "bankName": "Uco bank",
  "bankAccountNumber": "8956238956",
  "bankRoutingTypeId": 46,
  "bankRoutingCode": "IFSC",
  "upiId": "string",
  "bankingPaymentTypeId": 170,
  "isDefault": true,
  "kycTypeId": 116,
  "kycDocumentUrl": "https://s3.ap-south-1.amazonaws.com/myassociation-dev-objects/kyc document/kyc details.pdf",
  "kycVerificationStatusId": 0,
  "kycType": "",
  "kycVerificationStatus": ""
}
const express = require('express');
const app = express();

const bodyParser = require('body-parser');
app.use(bodyParser.json());
const cors = require('cors');

const dotenv = require('dotenv');
dotenv.config();

//! add db hear
const dbService = require('./utils/dbService');
const connection = require('./utils/dbService');
const multer = require('multer')
const moment = require("moment")
const fs = require('fs');
const path = require('path');



app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));





// Import the routes from routes.js
const routes = require('./routes/userRoute');

// Use the imported routes in your app.js file
// app.use(routes);


// Add a prefix to all routes
app.use('/api/v1', routes);




app.post('/login', (req, res) => {
    const { ao_name, ao_status } = req.body;
    console.log('Received login data:', req.body);

    var sql = "INSERT INTO app_occasion ( ao_name, ao_status ) VALUES ?";
    var values = [[ao_name, ao_status]];

    connection.query(sql, [values], function (err, result) {
        if (err) throw err;
        console.log("Records inserted: " + result.affectedRows);
        // Show alert message
        res.status(200).json({ message: 'Login data received' });
    });
});


 // TODO testing

 app.use("/uploads", express.static("./uploads"))
// // Image storage config
// const imgconfig = multer.diskStorage({
//     destination: (req, file, callback) => {
//         callback(null, "./uploads");
//     },
//     filename: (req, file, callback) => {
//         const uniqueName = `image-${Date.now()}-${file.originalname}`;
//         callback(null, uniqueName);
//     }
// });
// // Image filter
// const isImage = (req, file, callback) => {
//     if (file.mimetype.startsWith("image")) {
//         callback(null, true);
//     } else {
//         callback(new Error("Only images are allowed"));
//     }
// };
// const upload = multer({
//     storage: imgconfig,
//     fileFilter: isImage
// });


// 


// Function to generate folder name from organization name


// checking if same name folder name is exist  
// fs.readdir(uploadsPath, (err, files) => {
//     if (err) {
//         console.error('Error reading directory:', err);
//     } else {
//         if (files.includes(newFolderName)) {
//             console.log('Found  folder in uploads directory');


//         } else {
//             console.log(' folder NOT found in uploads directory');
//         }
//     }
// });





// Helper function to create a folder name based on the organization name
const generateFolderName = (orgName, basePath) => {
    // Start with the first letter of each word
    const folderName = orgName
        .split(" ")
        .map((word) => word[0].toLowerCase())
        .join("");

    // Check if the folder already exists
    const existingFolders = fs.readdirSync(basePath);
    let uniqueFolderName = folderName;
    let folderSuffix = '';
    const words = orgName.split(" ");

    // If the folder exists and has more words, add the second word in parentheses
    if (existingFolders.includes(uniqueFolderName) && words.length > 1) {
        folderSuffix = `(${words[1].toLowerCase()})`;
        uniqueFolderName += folderSuffix;
    }

    // If it still exists, keep adding next words in parentheses until unique
    let index = 2; // Start with the third word if needed
    while (existingFolders.includes(uniqueFolderName) && index < words.length) {
        folderSuffix = `(${words[index].toLowerCase()})`;
        uniqueFolderName = folderName + folderSuffix;
        index++;
    }

    // If after all words, it's still not unique, append a number to make it unique
    let counter = 2;
    while (existingFolders.includes(uniqueFolderName)) {
        uniqueFolderName = `${folderName}${folderSuffix}(${counter})`;
        counter++;
    }

    return uniqueFolderName;
};

// multer disk storage configuration
const imgconfig = multer.diskStorage({
    destination: (req, file, callback) => {
        const { ar_org_name } = req.body;
        if (!ar_org_name) {
            return callback(new Error("Organization name not provided"), false);
        }

        const uploadsPath = path.join(__dirname, 'uploads');
        const newFolderName = generateFolderName(ar_org_name, uploadsPath);
        const newFolderPath = path.join(uploadsPath, newFolderName);
        
        // Create the new directory if it doesn't exist
        fs.mkdirSync(newFolderPath, { recursive: true });

        callback(null, newFolderPath);
    },
    filename: (req, file, callback) => {
        const uniqueName = `image-${Date.now()}-${file.originalname}`;
        callback(null, uniqueName);
    }
});
















// Image filter
const isImage = (req, file, callback) => {
    if (file.mimetype.startsWith("image")) {
        callback(null, true);
    } else {
        callback(new Error("Only images are allowed"), false);
    }
};



const upload = multer({
    storage: imgconfig,
    fileFilter: isImage
});








// Middleware
app.use(express.json());
app.use(cors());

// Handle form submission
app.post("/testing", upload.single("ar_org_logo"), (req, res) => {
    const {
        ar_org_name,
        ar_cp_signature,
        ar_contract_number,
        ar_emaill,
        ar_password,
        ar_conform_password,
        // ar_occecation_id
    } = req.body;

    // console.log("ar_org_name:", ar_org_name); 

// const newFolderName = ar_org_name;   //'newFolder'; // Replace with your logic to generate the folder name
// const uploadsPath = path.join(__dirname, 'uploads');
// const newFolderPath = path.join(uploadsPath, newFolderName);

// // Create the new directory
// fs.mkdirSync(newFolderPath, { recursive: true });

// console.log( "res.json({ message: 'Directory created successfully' });" );





    const { filename } = req.file;

    if (!ar_org_name || !ar_cp_signature || !ar_contract_number || !ar_emaill || !ar_password || !ar_conform_password  || !filename) {
        return res.status(422).json({ status: 422, message: "Fill all the details" });
    }

    try {
        const date = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");

        const userData = {
            ar_org_name,
            ar_cp_signature,
            ar_contract_number,
            ar_emaill,
            ar_password,
            ar_conform_password,
            // ar_occecation_id,
            ar_org_logo: filename,
            ar_creat_at: date,
            ar_status: 'pending'
        };
     

        connection.query("INSERT INTO app_cp_info SET ?", userData, (err, result) => {
            if (err) {
                console.error("Error inserting data", err);
                return res.status(500).json({ status: 500, message: "Database insertion error" });
            }
            console.log("Data added successfully");
            res.status(201).json({ status: 201, data: userData });
        });







       


    } catch (error) {
        console.error("Error in try block", error);
        res.status(500).json({ status: 500, message: "Internal server error" });
    }
});




// ! i want to show all data of app_registration 
app.get("/all-data-app_registration",(req,res)=>
{
    try {
        connection.query("SELECT * FROM app_registration",(err,result)=>{
            if(err){
                console.log(err)
            }else{
                console.log("get data successfully");
                res.status(201).json({ status: 201, data: result })
            }
        })
    } catch (error) {
        res.status(422).json({ status: 422, error })
    }
}
)



// Get all data (assuming this is for populating the select dropdown)
// app.get("/testing-get-data", (req, res) => {
//     conn.query("SELECT ao_id, ao_name FROM some_table", (err, results) => {
//         if (err) {
//             console.error("Error fetching data", err);
//             return res.status(500).json({ status: 500, message: "Database fetching error" });
//         }
//         res.status(200).json(results);
//     });
// });


// !
// // Multer storage configuration
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         cb(null, './public/Images');
//     },
//     filename: function (req, file, cb) {
//         cb(null, `${Date.now()}_${file.originalname}`);
//     }
// });

// const upload = multer({ storage });

// app.post('/testing', upload.single('ar_org_logo'), (req, res) => {
//     const { ar_org_name, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;
//     const ar_org_logo = req.file.filename;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
//     const values = [ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id];

//     connection.query(sql, values, function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed', error: err.message });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully registered', ao_id: ar_occecation_id });
//     });
// });




                                                                                                                                                                                                                                


// !

// app.post('/testing', (req, res) => {
//     const { ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id } = req.body;

//     const sql = "INSERT INTO app_registration (ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id) VALUES ?";
//     const values = [[ar_org_name, ar_org_logo, ar_cp_singhter, ar_contract_number, ar_emaill, ar_password, ar_conform_password, ar_occecation_id]];

//     connection.query(sql, [values], function (err, result) {
//         if (err) {
//             console.error('Error inserting into app_registration:', err);
//             return res.status(500).json({ message: 'Registration failed not send ' });
//         }
//         console.log("Registration record inserted: " + result.affectedRows);
//         res.status(200).json({ message: 'Successfully send bireswar', ao_id: ar_occecation_id });
//     });
// });




app.get('/testing-get-data', (req, res) => {
    const query = 'SELECT * FROM app_occasion';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});



// // for file upload
// const storage = multer.diskStorage({
//     destination: function (req, file, cb) {
//         return cb(null, "./public/Images")
//     },
//     filename: function (req, file, cb) {
//         return cb(null, `${Date.now()}_${file.originalname}`)
//     }
// })

// const upload = multer({ storage })

// app.post('/upload', upload.single('file'), (req, res) => {
//     console.log(req.body)
//     console.log(req.file)
// })


// // app.post('/upload', upload.single('image'), (req, res) => {
// //     const image = req.file.filename;
// //     const sql = "UPDATE app_registration SET ar_org_logo = ?";
// //     db.query(sql, [image], (err, result) => {
// //         if (err) return res.json({ Message: "Error" });
// //         return res.json({ Status: "Success" });
// //     });
// // });


// // demo 002
// app.post('/upload', upload.single('image'), (req, res) => {
//     const image = req.file.filename;

//     const sql = "UPDATE users SET image = ? WHERE id = ?";  // Adjust the query as needed
//     const userId = 3;  // Replace with the actual user ID
//     const values = [image, userId];

//     db.query(sql, values, (err, result) => {
//         if (err) {
//             return res.json({ Message: "Error" });
//         }
//         return res.json({ Status: "Success" });
//     });
// });













// TODO testing



app.put('/update-application-status/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "1" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});







app.put('/rejected/:userId', async (req, res) => {
    const { userId } = req.params;
    const { application_status } = req.body;

    // Update logic for the database (example using a fictitious database function)
    // await database.updateApplicationStatus(userId, application_status);

    // var sql = "UPDATE  leave_from_rgpl SET application_status = 1 WHERE id = ?",[userId];
    connection.query('UPDATE leave_from_rgpl SET ? WHERE id = ?', [{ application_status: "2" }, userId]);


    // connection.query(sql, function (err, result) {
    //     if (err) throw err;
    //     console.log("Records updated: " + result.affectedRows);
    //     // Show alert message
    //     res.status(200).send('Login data received');
    //   });
    console.log("working")




});











// app_super_section
// login_table_rgpl


// !  login from app_super_section
app.post('/aa', (req, res) => {
    const sql = "SELECT * FROM app_super_section WHERE email = ? AND password = ?";
    // const values = [
    //     req.body.email,
    //     req.body.password
    // ];

    connection.query(sql, [req.body.email, req.body.password], (err, data) => {
        if (err) return res.json("Login Failed");
        if (data.length > 0) {
            return res.json("Login Successful")

        } else {
            return res.json("INCORRECT EMAIL OR PASSWORD");
        }


    });
});









// var sql = "INSERT INTO leave_from_rgpl (name, college_name, class_coordinator_name, leave_date_from, leave_time_from, leave_date_up_to, leave_time_up_to, leave_type, reason_for_leave) VALUES ?";
// var values = [
//   [name, college_name, class_coordinator_name, `DATE_FORMAT('${leave_date_from}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_from}', '%H:%i:%s.%f`, // Format the time `DATE_FORMAT('${leave_date_up_to}', '%Y-%m-%d`, // Format the date `TIME_FORMAT('${leave_time_up_to}', '%H:%i:%%f')`, // Format the time leave_type, reason_for_leave,
//   ],
// ];

// connection.query(sql, [values], function (err, result) {
//   if (err) throw err;
//   console.log("Records inserted: " + result.affectedRows);
//   // Show alert message
//   res.status(200).send('Login data received');
// });








// !my code
// app.post('/login', (req, res) => {
//     const { username, password } = req.body;

//     console.log('Received login data:');
//     // console.log('Username:', username);
//     // console.log('Password:', password);

//   var q = req.body.username;
//   var w = req.body.password;
// //   console.log(q,w);

// // module.exports =q;

//   // Export q and w variables




//   res.status(200).send('Login data received');


// });






// connection.connect((err) => {
//   if (err) {
//       console.log(err.message);
//   }
// //     //! this is i added for database state 
//   console.log('db ' + connection.state);
//   // console.log(q)
//   // console.log(msg);
// // });

// var sql = "INSERT INTO login (name,user_name,password) VALUES ?";

// // var { q, w } = require('./app');
// // console.log(q,w);

// var values =[[q,w,'123456']];

// connection.query(sql, [values], function (err, result) {
// if (err) throw err;
// console.log("records inserted: "+result.affectedRows);
// });

// });




// // Get all beers
// app.get('', (req, res) => {
//     pool.getConnection((err, connection) => {
//         if (err) throw err;
//         console.log(`connected as id ${connection.threadId}`);

//         connection.query('SELECT * from login', (err, rows) => {
//             connection.release(); // return the connection to the pool

//             if (err) {
//                 res.send(rows);
//             } else {
//                 console.log(err);
//             }
//         });
//     });
// });











app.get('/get-all-data', (req, res) => {
    const query = 'SELECT * FROM leave_from_rgpl';
    connection.query(query, (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json(results);
    });
});









app.put('/update-data/:id', (req, res) => {
    const { id } = req.params;
    const { newData } = req.body; // Replace `newData` with actual fields you want to update
    const query = 'UPDATE login SET ? WHERE id = ?'; // Replace with your table and field names

    connection.query(query, [newData, id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data updated successfully', results });
    });
});





// Endpoint to delete data
app.delete('/delete-data/:id', (req, res) => {
    const { id } = req.params;
    const query = 'DELETE FROM login WHERE id = ?';
    connection.query(query, [id], (err, results) => {
        if (err) {
            console.error(err.message);
            return res.status(500).send(err);
        }
        res.json({ success: true, message: 'Data deleted successfully', results });
    });
});






app.listen(process.env.PORT, () => console.log('app is running -->', process.env.PORT));


// module.exports = 'hello world';
#divBusca {
    position: relative;
    margin: auto;
    margin-bottom: 20px;

}

#txtBusca {
    width: 100%;

    padding: 10px 40px 10px 10px;
    border: 2px solid #ccc;
    border-radius: 25px;
    font-size: 16px;
    transition: border-color 0.3s;

}

#txtBusca:focus {
    border-color: #007bff;
    outline: none;
}

#divBusca i {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #007bff;
    font-size: 20px;
}




table {

    font-family: arial, sans-serif;

    border-collapse: collapse;
    margin: auto;


}

body > section > div.content > div > table > tbody{
    width: 300px;
    border-radius: 20px;
}





td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 10px;
}

tr {
    background-color: #fff;
    color: #111111;
    border-radius: 20px;
}
    int orangesRotting(vector<vector<int>>& grid) {
        int n= grid.size();
        int t;
        int m = grid[0].size();
        int vis[n][m];
        queue<pair<pair<int,int>,int>> q;
        for(int i=0;i<n;++i)
        {
            for(int j=0;j<m;++j)
            {
                if(grid[i][j]==2){
                q.push({{i,j},0});
                vis[i][j]=2;}
                else
                    vis[i][j]=0;
            }
        }
        int tm=0;
            while(!q.empty())
            {
                int r = q.front().first.first;
                int c = q.front().first.second;
                 t = q.front().second;
                 tm = max(t,tm);
                q.pop();
                int drow[] = {0,1,-1,0};
                int dcol[] = {1,0,0,-1};
                for(int i=0;i<4;++i)
                {
                    int nr = r+drow[i];
                    int nc = c+dcol[i];
                    if(nr>=0 && nr<n && nc>=0 && nc<m && vis[nr][nc]!=2 && grid[nr][nc]==1)
                    {
                        q.push({{nr,nc},t+1});
                        vis[nr][nc]=2;
                    }
                    
                }
            }
        
        for(int i=0;i<n;++i)
        {
            for(int j=0;j<m;++j)
            {
                if(grid[i][j]==1 && vis[i][j]!=2)
                return -1; 
            }

        }

        return tm;
    }
#Make directory in files, then right-click the directory and select "Open in Terminal"
#All following "sudo" command can be ignored by obtaining root permission from the opened terminal
sudo apt -y install git
sudo apt  -y install tpm2-tools

#Create script and run it in the current directory for software dependencies:
sudo apt -y install \
autoconf-archive \
libcmocka0 \
libcmocka-dev \
procps \
iproute2 \
build-essential \
git \
pkg-config \
gcc \
libtool \
automake \
libssl-dev \
uthash-dev \
autoconf \
doxygen \
libjson-c-dev \
libini-config-dev \
libcurl4-openssl-dev \
uuid-dev \
libltdl-dev \
libusb-1.0-0-dev \
libftdi-dev

#Copy & Paste these next commands in the terminal tab you are currently working in:

#Getting source, compiling and installing tpm2-tss:
git clone https://github.com/tpm2-software/tpm2-tss.git
cd tpm2-tss
./bootstrap
./configure  --with-udevrulesdir=/etc/udev/rules.d/
make -j`nproc`
sudo make install
sudo ldconfig
sudo udevadm control --reload-rules && sudo udevadm trigger
sudo pkill -HUP dbus-daemon
cd ..

#Install pre-requisties for tpm2-abrmd:
sudo apt -y install libglib2.0-dev

Getting Source, compiling and install tpm2-abrmd:
git clone https://github.com/tpm2-software/tpm2-abrmd.git
cd tpm2-abrmd
./bootstrap
./configure --with-dbuspolicydir=/etc/dbus-1/system.d
make -j`nproc`
sudo make install
sudo ldconfig
cd ..

#Source, compiling and installing tpm2-tools:
git clone https://github.com/tpm2-software/tpm2-tools.git
cd tpm2-tools
./bootstrap
./configure
make -j`nproc`
sudo make install
sudo ldconfig

#Should be able to use TPM device to generate a random number:
sudo tpm2_getrandom --hex 8
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

star

Sat Jun 15 2024 12:29:02 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Sat Jun 15 2024 11:06:26 GMT+0000 (Coordinated Universal Time)

@codeing #javascript

star

Sat Jun 15 2024 08:36:48 GMT+0000 (Coordinated Universal Time)

@gabriellesoares

star

Sat Jun 15 2024 08:01:29 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Sat Jun 15 2024 06:21:11 GMT+0000 (Coordinated Universal Time)

@jrray #python

Save snippets that work with our extensions

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