Snippets Collections
@ -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
I will toss you some code and at the and formulate what i want:

addOffshoreForm.tsx :

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 type { VesselInfo } from "@/components/forms/offshoreInfoForm";
import {
  fieldsNameHelper,
  formSchema,
  numberFields,
  toTitleCase,
} from "@/components/forms/offshoreInfoForm";
import type { PostgrestError } from "@supabase/supabase-js";

interface AddOffshoreFormProps {
  fields: string[];
  vesselType: string;
  vesselSubType: string;
  vesselMmsi: string;
  returnMmsi: (mmsi: any) => void;
}

export const AddOffshoreForm = ({
  fields,
  vesselType,
  vesselSubType,
  vesselMmsi,
  returnMmsi,
}: AddOffshoreFormProps) => {
  const excludeFields: string[] = [
    "id",
    "vessel_id",
    "postion_date",
    "eta_iso",
    "destination",
    "longitude",
    "latitude",
    "callsign",
  ];
  const disabledFields: string[] = ["type", "subType"];

  const [selectedType, setSelectedType] = useState<string>();
  const [selectedSubType, setSelectedSubType] = useState<string>(vesselSubType);
  const [mmsi, setMmsi] = useState<string>(vesselMmsi.toString());

  // update selectedType and selectedSubType when vesselType and vesselSubType change
  useEffect(() => {
    setSelectedType(vesselType);
    setSelectedSubType(vesselSubType);
    setMmsi(vesselMmsi);
  }, [vesselType, vesselSubType, vesselMmsi]);

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

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      type: selectedType,
      subType: selectedSubType,
      mmsi: mmsi,
    },
  });

  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;
        if (key === "subType") {
          acc[vesselInfoKey] = selectedSubType?.toLowerCase() || "";
        } else if (key === "type") {
          acc[vesselInfoKey] = selectedType?.toLowerCase() || "";
        } else if (key === "mmsi") {
          acc[vesselInfoKey] = mmsi;
        } else {
          acc[vesselInfoKey] = (value || "").toString().toLowerCase() || "";
        }
        return acc;
      },
      {},
    );

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

      if (response.ok) {
        toast.success("Success!", {
          description: "Vessel details inserted.",
        });
        returnMmsi(Number(mmsi));
      } 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(
      {
        type: vesselType,
        subType: selectedSubType || vesselSubType,
        mmsi: mmsi,
      },
      { 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)}>
                <If condition={key !== "buildYear"}>
                  <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>
                <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>
            </>
          ))}
          <div className="flex flex-row justify-end">
            <DestructiveButton type="submit" className="mt-4">
              <ButtonContent>Add vessel</ButtonContent>
            </DestructiveButton>
          </div>
          <Toaster />
        </form>
      </Form>
    </div>
  );
};

offshoreInfoForm.tsx :

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 type { PostgrestError } from "@supabase/supabase-js";
import wretch from "wretch";

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

interface AddOffshoreFormProps {
  vesselInfo: VesselInfo;
  vesselMmsi: number;
}

export const formSchema = z.object({
  beneficialOwner: z.string().optional(),
  bollardPull: z.string().optional(),
  bsW: z.string().optional(),
  bucketCapacity: z.string().optional(),
  buildYear: z.string().optional(),
  cableTanks: z.string().optional(),
  callsign: z.string().optional(),
  class: z.string().optional(),
  clearDeckArea: z.string().optional(),
  commercialOwner: z.string().optional(),
  craneSize: z.string().optional(),
  cranes: z.string().optional(),
  crudeProcessingCapacity: z.string().optional(),
  cutterPower: z.string().optional(),
  deckArea: z.string().optional(),
  deckLoadCapacity: z.string().optional(),
  designType: z.string().optional(),
  destination: z.string().optional(),
  dredgeDepth: z.string().optional(),
  dredgePumpPower: z.string().optional(),
  dynamicPositioningClass: z.string().optional(),
  engineTypePower: z.string().optional(),
  etaIso: z.string().optional(),
  excavatorPower: z.string().optional(),
  exportableCrude: z.string().optional(),
  fleetName: z.string().optional(),
  fleetOperator: z.string().optional(),
  fluidCapacity: z.string().optional(),
  fuelCapacity: z.string().optional(),
  gas: z.string().optional(),
  grossTonnage: z.string().optional(),
  hS: z.string().optional(),
  heliDeck: z.string().optional(),
  hopperCapacity: z.string().optional(),
  id: z.string().optional(),
  imo: z.string().optional(),
  jetPumps: z.string().optional(),
  latitude: z.string().optional(),
  legs: z.string().optional(),
  longitude: z.string().optional(),
  mainEnginesTypePower: z.string().optional(),
  maxDredgeWidth: z.string().optional(),
  maxFlow: z.string().optional(),
  maxSpeed: z.string().optional(),
  mmsi: z.string().optional(),
  moonPool: z.string().optional(),
  noOfBerths: z.string().optional(),
  oilContentWaterDischarged: z.string().optional(),
  pdfDownloaded: z.string().optional(),
  pipeDiameter: z.string().optional(),
  positionTime: z.string().optional(),
  producedWater: z.string().optional(),
  pumpingDistance: z.string().optional(),
  rov: z.string().optional(),
  rvp: z.string().optional(),
  slopTanks: z.string().optional(),
  specialisedCarriageCapability: z.string().optional(),
  speedConsumption: z.string().optional(),
  subType: z.string().optional(),
  totalPowerInstalled: z.string().optional(),
  towingCapacity: z.string().optional(),
  tugType: z.string().optional(),
  type: z.string().optional(),
  vesselClass: z.string().optional(),
  vesselName: z.string().optional(),
  vesselType: z.string().optional(),
  vesselId: z.string().optional(),
  waterInjectionCapacity: z.string().optional(),
});

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

export const fieldsNameHelper: FieldsNameHelper = {
  beneficialOwner: {
    name: "beneficial owner",
    description: "The beneficial owner of the vessel",
  },
  bollardPull: {
    name: "bollard pull",
    description: "The force exerted by the vessel while tethered",
  },
  bsW: {
    name: "bs&w",
    description: "Basic sediment and water in oil measurement",
  },
  bucketCapacity: {
    name: "bucket capacity",
    description: "Maximum carrying capacity of the bucket",
  },
  buildYear: {
    name: "build year",
    description: "Year the vessel was constructed",
  },
  cableTanks: {
    name: "cable tanks",
    description: "Storage tanks for cables on the vessel",
  },
  callsign: {
    name: "callsign",
    description: "The identifying signal letters or numbers of the vessel",
  },
  class: {
    name: "class",
    description: "Classification society to which the vessel is registered",
  },
  clearDeckArea: {
    name: "clear deck area",
    description: "Total area available for use on the deck",
  },
  commercialOwner: {
    name: "commercial owner",
    description: "The commercial owner of the vessel",
  },
  craneSize: {
    name: "crane size",
    description: "The size and lifting capacity of the crane on the vessel",
  },
  cranes: {
    name: "cranes",
    description: "The number and type of cranes installed on the vessel",
  },
  crudeProcessingCapacity: {
    name: "crude processing capacity",
    description: "Capacity to process crude oil onboard",
  },
  cutterPower: {
    name: "cutter power",
    description: "Power output of the cutting equipment on the vessel",
  },
  deckArea: {
    name: "deck area",
    description: "Total area of the vessel's deck",
  },
  deckLoadCapacity: {
    name: "deck load capacity",
    description: "Maximum load capacity of the vessel’s deck",
  },
  designType: {
    name: "design/type",
    description: "The design and type classification of the vessel",
  },
  destination: {
    name: "destination",
    description: "The intended destination of the vessel",
  },
  dredgeDepth: {
    name: "dredge depth",
    description: "Maximum depth at which the vessel can dredge",
  },
  dredgePumpPower: {
    name: "dredge pump power",
    description: "Power of the dredging pump",
  },
  dynamicPositioningClass: {
    name: "dynamic positioning class",
    description: "Classification of the vessel's dynamic positioning system",
  },
  engineTypePower: {
    name: "engine type & power",
    description: "Type and power output of the vessel’s engines",
  },
  etaIso: {
    name: "eta_iso",
    description: "Estimated time of arrival following ISO standards",
  },
  excavatorPower: {
    name: "excavator power",
    description: "Power output of the excavator on the vessel",
  },
  exportableCrude: {
    name: "exportable crude",
    description: "Volume of crude oil that can be exported by the vessel",
  },
  fleetName: {
    name: "fleet name",
    description: "Name of the fleet the vessel belongs to",
  },
  fleetOperator: {
    name: "fleet operator",
    description: "Operator managing the fleet of vessels",
  },
  fluidCapacity: {
    name: "fluid capacity",
    description: "Total capacity for fluid storage on the vessel",
  },
  fuelCapacity: {
    name: "fuel capacity",
    description: "Fuel storage capacity of the vessel",
  },
  gas: {
    name: "gas",
    description:
      "Capabilities or systems related to gas handling on the vessel",
  },
  grossTonnage: {
    name: "gross tonnage",
    description: "Overall internal volume of the vessel",
  },
  hS: {
    name: "h2s",
    description: "Presence and handling of hydrogen sulfide on the vessel",
  },
  heliDeck: {
    name: "heli-deck",
    description: "Helicopter landing area available on the vessel",
  },
  hopperCapacity: {
    name: "hopper capacity",
    description: "Storage capacity of the hopper on the dredging vessel",
  },
  id: { name: "id", description: "Unique identifier of the vessel" },
  imo: {
    name: "imo",
    description:
      "International Maritime Organization number assigned to the vessel",
  },
  jetPumps: {
    name: "jet pumps",
    description: "Types and capacities of jet pumps on the vessel",
  },
  latitude: {
    name: "latitude",
    description: "Current latitude position of the vessel",
  },
  legs: {
    name: "legs",
    description:
      "Structural supports used in vessels, particularly in offshore applications",
  },
  longitude: {
    name: "longitude",
    description: "Current longitude position of the vessel",
  },
  mainEnginesTypePower: {
    name: "main engines type & power",
    description: "Type and power of the main engines on the vessel",
  },
  maxDredgeWidth: {
    name: "max dredge width",
    description: "Maximum width the vessel can dredge",
  },
  maxFlow: {
    name: "max flow",
    description: "Maximum flow rate achievable by the vessel’s systems",
  },
  maxSpeed: {
    name: "max speed (buckets/min)",
    description:
      "Maximum operational speed of the vessel in buckets per minute",
  },
  mmsi: {
    name: "mmsi",
    description:
      "Maritime Mobile Service Identity used for vessel tracking and safety",
  },
  moonPool: {
    name: "moon pool",
    description:
      "An opening in the bottom or side of the vessel for underwater operations",
  },
  noOfBerths: {
    name: "no of berths",
    description: "Number of sleeping berths available on the vessel",
  },
  oilContentWaterDischarged: {
    name: "oil content water discharged",
    description: "Measure of oil content in discharged water",
  },
  pdfDownloaded: {
    name: "pdf downloaded (y/n)",
    description:
      "Indicates if the vessel’s documentation has been downloaded as PDF",
  },
  pipeDiameter: {
    name: "pipe diameter",
    description: "Diameter of pipes used onboard the vessel",
  },
  positionTime: {
    name: "position_time",
    description: "Timestamp for the vessel's position",
  },
  producedWater: {
    name: "produced water",
    description: "Water produced as a byproduct of the vessel’s operations",
  },
  pumpingDistance: {
    name: "pumping distance",
    description: "Maximum distance over which the vessel can pump materials",
  },
  rov: {
    name: "rov",
    description: "Remotely operated vehicle capabilities of the vessel",
  },
  rvp: {
    name: "rvp",
    description:
      "Reid vapor pressure measurements related to the vessel’s operations",
  },
  slopTanks: {
    name: "slop tanks",
    description:
      "Tanks on the vessel used for temporary storage of oily waste water",
  },
  specialisedCarriageCapability: {
    name: "specialised carriage capability",
    description:
      "Specific carriage capabilities of the vessel for specialized cargoes",
  },
  speedConsumption: {
    name: "speed/consumption",
    description: "The vessel’s speed relative to fuel consumption",
  },
  subType: {
    name: "sub_type",
    description: "Sub-type classification of the vessel",
  },
  totalPowerInstalled: {
    name: "total power installed",
    description: "Total power output of all installed machinery",
  },
  towingCapacity: {
    name: "towing capacity",
    description: "Capacity of the vessel to tow other vessels or structures",
  },
  tugType: {
    name: "tug type",
    description: "Classification of the tug based on its design and use",
  },
  type: {
    name: "type",
    description: "General type classification of the vessel",
  },
  vesselClass: {
    name: "vessel class",
    description: "Class designation for regulatory and operational purposes",
  },
  vesselName: {
    name: "vessel name",
    description: "Official name of the vessel",
  },
  vesselType: {
    name: "vessel type",
    description: "Specific type classification based on structure and function",
  },
  vesselId: {
    name: "vessel_id",
    description: "Unique identification number of the vessel",
  },
  waterInjectionCapacity: {
    name: "water injection capacity",
    description: "Capacity for injecting water into surrounding sea or seabed",
  },
};

export const numberFields: string[] = [
  "bollardPull",
  "buildYear",
  "clearDeckArea",
  "grossTonnage",
  "noOfBerths",
  "dynamicPositioningClass",
  "fuelCapacity",
  "fluidCapacity",
  "deckArea",
  "crudeProcessingCapacity",
  "deckLoadCapacity",
  "waterInjectionCapacity",
  "speedConsumption",
  "totalPowerInstalled",
  "dredgeDepth",
  "maxDredgeWidth",
  "cuttingPower",
  "pumpingDistance",
  "hopperCapacity",
  "bucketCapacity",
  "maxSpeed",
  "mmsi",
  "imo",
];

export const uppercaseFields: string[] = [
  "eta_iso",
  "id",
  "imo",
  "mmsi",
  "h2s",
  "bs&w",
  "rov",
  "rvp",
];

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 OffshoreInfoForm = ({
  vesselInfo,
  vesselMmsi,
}: AddOffshoreFormProps) => {
  const disabledFields: string[] = [
    "destination",
    "etaIso",
    "id",
    "imo",
    "latitude",
    "longitude",
    "mmsi",
    "positionTime",
    "vesselId",
  ];
  const [selectedType, setSelectedType] = useState<string | null>(
    vesselInfo["type"] ?? null,
  );

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

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

  const reset = form.reset;

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

  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/offshoreVessel")
        .post(updatedVesselInfo)
        .res();
      if (response.ok) {
        await wretch(`/api/form/offshoreVessel?mmsi=${vesselMmsi}`)
          .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 PostgrestError | null)?.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) => (
            <>
              <If
                condition={Object.keys(vesselInfo).includes(
                  fieldsNameHelper[key].name,
                )}
              >
                <If
                  condition={
                    key !== "type" && key !== "subType" && key !== "buildYear"
                  }
                >
                  <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
                            {...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={"offshore support vessel"}>
                              Offshore Support Vessel
                            </SelectItem>
                            <SelectItem
                              value={"oil exploration and drilling vessel"}
                            >
                              Oil Exploration And Drilling Vessel
                            </SelectItem>
                            <SelectItem value={"offshore production vessel"}>
                              Offshore Production Vessel
                            </SelectItem>
                            <SelectItem value={"offshore construction vessel"}>
                              Offshore Construction Vessel
                            </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 === "offshore support vessel" && (
                              <SelectContent>
                                <SelectItem value={"mpsv"}>MPSV</SelectItem>
                                <SelectItem value={"ahts"}>AHTS</SelectItem>
                                <SelectItem value={"tug"}>Tug</SelectItem>
                                <SelectItem value={"psv"}>PSV</SelectItem>
                              </SelectContent>
                            )}
                          {selectedType &&
                            selectedType === "offshore production vessel" && (
                              <SelectContent>
                                <SelectItem value={"fpso"}>FPSO</SelectItem>
                              </SelectContent>
                            )}
                          {selectedType &&
                            selectedType === "offshore construction vessel" && (
                              <SelectContent>
                                <SelectItem value={"dredger"}>
                                  Dredger
                                </SelectItem>
                                <SelectItem value={"clv"}>CLV</SelectItem>
                                <SelectItem value={"wiv"}>WIV</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"
                            defaultValue={vesselInfo["build year"]}
                            min={1900}
                            max={2100}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </If>
              </If>
            </>
          ))}
          <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>
  );
};

insertOffshoreVessel.ts  :

import type {NextApiRequest, NextApiResponse} from "next";
import wretch from "wretch";
import {env} from "@/env/client.mjs";


/**
 * @swagger
 * /api/form/addLinearReport:
 *   post:
 *     summary: Create a bug report in linear
 *     description: Within the support team.
 *     parameters:
 *        - in: body
 *          name: report
 *          required: true
 *          type: object
 *          description: The report object
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: Success!
 *       400:
 *         description: No id present as a query parameter.
 *       401:
 *         description: The user does not have an active session or is not authenticated.
 *       405:
 *         description: Method not allowed.
 *       500:
 *         description: Error!
 *     tags:
 *       - deprecated
 */

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

  switch (method) {
    case "POST":
      try {
        const response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}insert_vessel`)
          .post(req.body)
          .json();
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: POST /api/form/insertOffshoreVessel", error);
        return res.status(500).json(error);
      }
    default:
      res.setHeader("Allow", ["POST"]);
      return res
        .status(405)
        .send(`Method ${method ?? "Undefined"} Not Allowed`);
  }
}

import type {NextApiRequest, NextApiResponse} from "next";
import wretch from "wretch";
import {env} from "@/env/client.mjs";


/**
 * @swagger
 * /api/form/addLinearReport:
 *   post:
 *     summary: Create a bug report in linear
 *     description: Within the support team.
 *     parameters:
 *        - in: body
 *          name: report
 *          required: true
 *          type: object
 *          description: The report object
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: Success!
 *       400:
 *         description: No id present as a query parameter.
 *       401:
 *         description: The user does not have an active session or is not authenticated.
 *       405:
 *         description: Method not allowed.
 *       500:
 *         description: Error!
 *     tags:
 *       - deprecated
 */

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

  switch (method) {
    case "GET":
      try {
        const mmsi = req.query.mmsi;
        const subType = req.query.sub_type;
        let response;
        if (subType) {
          response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}attributes_by_sub_type?sub_type=${subType}`)
            .get()
            .json();
        } else {
          response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}get_mmsi?mmsi=${mmsi}`)
          .get()
          .json();
        }

        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: GET /api/form/offshoreVessel | ", error);
        return res.status(500).json(error);
      }

    case "POST":
      try {
        const response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}update_vessel`)
          .post(req.body)
          .json();
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: POST /api/form/offshoreVessel | ", error);
        return res.status(500).json(error);
      }

    case "INSERT_POST":
      try {
        const response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}insert_vessel`)
          .post(req.body)
          .json();

        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: POST /api/form/offshoreVessel", error);
        return res.status(500).json(error);
      }
    default:
      res.setHeader("Allow", ["POST", "GET"]);
      return res
        .status(405)
        .send(`Method ${method ?? "Undefined"} Not Allowed`);
  }
}

offshoreVessel.ts :

import type {NextApiRequest, NextApiResponse} from "next";
import wretch from "wretch";
import {env} from "@/env/client.mjs";


/**
 * @swagger
 * /api/form/addLinearReport:
 *   post:
 *     summary: Create a bug report in linear
 *     description: Within the support team.
 *     parameters:
 *        - in: body
 *          name: report
 *          required: true
 *          type: object
 *          description: The report object
 *     produces:
 *       - application/json
 *     responses:
 *       200:
 *         description: Success!
 *       400:
 *         description: No id present as a query parameter.
 *       401:
 *         description: The user does not have an active session or is not authenticated.
 *       405:
 *         description: Method not allowed.
 *       500:
 *         description: Error!
 *     tags:
 *       - deprecated
 */

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

  switch (method) {
    case "GET":
      try {
        const mmsi = req.query.mmsi;
        const subType = req.query.sub_type;
        let response;
        if (subType) {
          response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}attributes_by_sub_type?sub_type=${subType}`)
            .get()
            .json();
        } else {
          response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}get_mmsi?mmsi=${mmsi}`)
          .get()
          .json();
        }

        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: GET /api/form/offshoreVessel | ", error);
        return res.status(500).json(error);
      }

    case "POST":
      try {
        const response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}update_vessel`)
          .post(req.body)
          .json();
        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: POST /api/form/offshoreVessel | ", error);
        return res.status(500).json(error);
      }

    case "INSERT_POST":
      try {
        const response = await wretch(`${env.NEXT_PUBLIC_UI_FLASK_URL}insert_vessel`)
          .post(req.body)
          .json();

        return res.status(200).json(response);
      } catch (error) {
        console.error("Error origin: POST /api/form/offshoreVessel", error);
        return res.status(500).json(error);
      }
    default:
      res.setHeader("Allow", ["POST", "GET"]);
      return res
        .status(405)
        .send(`Method ${method ?? "Undefined"} Not Allowed`);
  }
}

offshoreVesselInfo.tsx :

import type { NextPage } from "next";
import {
  BackHomeButton,
  CommandPalletteButton,
  If,
  Input,
  MinimalPage,
  PageHeading,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from "ui";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import type { ChangeEvent } from "react";
import { useEffect, useState } from "react";
import wretch from "wretch";
import { AddOffshoreForm } from "@/components/forms/addOffshoreForm";
import { OffshoreInfoForm } from "@/components/forms/offshoreInfoForm";

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

const OffshoreVesselInfo: NextPage = () => {
  const [vesselInfo, setVesselInfo] = useState<VesselInfo | null>();
  const [mmsi, setMmsi] = useState<number | null>();
  const [vesselSubType, setVesselSubType] = useState<string>("");
  const [offshoreType, setOffshoreType] = useState<string>("");
  const [newOffshoreForm, setNewOffshoreForm] = useState<any>();

  // get vessel info data from the api endpoint
  useEffect(() => {
    const fetchData = async () => {
      if (mmsi) {
        setVesselInfo(null);
        try {
          const response = await wretch(`/api/form/offshoreVessel?mmsi=${mmsi}`)
            .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();
  }, [mmsi]);

  useEffect(() => {
    const fetchData = async () => {
      if (vesselSubType) {
        try {
          const response = await wretch(
            `/api/form/offshoreVessel?sub_type=${vesselSubType}`,
          )
            .get()
            .res();
          if (response.ok) {
            const data: any = await response.json();
            setNewOffshoreForm(data);
          } else {
            console.error("Error:", response.statusText);
          }
        } catch (error) {
          console.error("Error:", error);
        }
      } else {
        setNewOffshoreForm(null);
      }
    };
    fetchData();
  }, [vesselSubType]);

  function capitalizeFirstLetter(string: string): string {
    return string.replace(/\b\w/g, function (l) {
      return l.toUpperCase();
    });
  }

  useEffect(() => {
    if (!mmsi) {
      setVesselSubType("");
      setOffshoreType("");
    }
  }, [mmsi]);

  function getVesselAfterInsert(mmsi: number) {
    setMmsi(mmsi);
    const fetchData = async () => {
      if (mmsi) {
        try {
          const response = await wretch(`/api/form/offshoreVessel?mmsi=${mmsi}`)
            .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();
  }

  return (
    <MinimalPage
      pageTitle={"Offshore Vessel Info | Email Interface"}
      pageDescription={"Spot Ship Email Interface | Offshore 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="Offshore 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"}
          >
            MMSI
          </div>
          <Input
            type={"number"}
            className={"text-md"}
            maxLength={9}
            onChange={(event: ChangeEvent<HTMLInputElement>) => {
              setMmsi(parseFloat(event.target.value) || null);
            }}
          />
        </div>
        <div className={"font-sans text-sm text-black dark:text-white"}>
          International Maritime Mobile Service Identity (MMSI) from 0 to
          9-digit identifier.
        </div>
      </div>
      <If condition={!!(mmsi && 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 MMSI: {mmsi}. Add new offshore vessel
          </div>
          <div>
            <div className={"grid grid-cols-2 gap-4"}>
              <Select
                onValueChange={(type: any) => {
                  setVesselSubType("");
                  if (!offshoreType || offshoreType !== type) {
                    setOffshoreType(type);
                  } else if (offshoreType === type) {
                    setOffshoreType("");
                  }
                }}
              >
                <SelectTrigger>
                  {capitalizeFirstLetter(offshoreType) || "Select vessel type"}
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value={"offshore support vessel"}>
                    Offshore Support Vessel
                  </SelectItem>
                  <SelectItem value={"oil exploration and drilling vessel"}>
                    Oil Exploration And Drilling Vessel
                  </SelectItem>
                  <SelectItem value={"offshore production vessel"}>
                    Offshore Production Vessel
                  </SelectItem>
                  <SelectItem value={"offshore construction vessel"}>
                    Offshore Construction Vessel
                  </SelectItem>
                </SelectContent>
              </Select>
              <If condition={offshoreType === "offshore support vessel"}>
                <div>
                  <Select
                    onValueChange={(value: any) => {
                      setVesselSubType(value);
                    }}
                  >
                    <SelectTrigger>
                      {vesselSubType.toUpperCase() || "Select vessel sub type"}
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={"mpsv"}>MPSV</SelectItem>
                      <SelectItem value={"ahts"}>AHTS</SelectItem>
                      <SelectItem value={"tug"}>Tug</SelectItem>
                      <SelectItem value={"psv"}>PSV</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </If>
              <If condition={offshoreType === "offshore production vessel"}>
                <div>
                  <Select
                    onValueChange={(value: any) => {
                      setVesselSubType(value);
                    }}
                  >
                    <SelectTrigger>
                      {vesselSubType.toUpperCase() || "Select vessel sub type"}
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={"fpso"}>FPSO</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </If>
              <If condition={offshoreType === "offshore construction vessel"}>
                <div>
                  <Select
                    onValueChange={(value: any) => {
                      setVesselSubType(value);
                    }}
                  >
                    <SelectTrigger>
                      {vesselSubType.toUpperCase() || "Select vessel sub type"}
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value={"dredger"}>Dredger</SelectItem>
                      <SelectItem value={"clv"}>CLV</SelectItem>
                      <SelectItem value={"wiv"}>WIV</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </If>
            </div>
            <If condition={!!newOffshoreForm}>
              <div className={"mt-6"}>
                <AddOffshoreForm
                  fields={newOffshoreForm}
                  vesselType={offshoreType}
                  vesselSubType={vesselSubType}
                  vesselMmsi={mmsi ? mmsi.toString() : ""}
                  returnMmsi={(mmsi: number) => {
                    getVesselAfterInsert(mmsi);
                    setOffshoreType("");
                    setVesselSubType("");
                  }}
                />
              </div>
            </If>
          </div>
        </div>
      </If>
      <If
        condition={
          !!(
            mmsi &&
            vesselInfo &&
            !vesselInfo?.["message"] &&
            typeof vesselInfo === "object"
          )
        }
      >
        <OffshoreInfoForm
          vesselInfo={vesselInfo as VesselInfo}
          vesselMmsi={mmsi as number}
        />
      </If>
    </MinimalPage>
  );
};

export default OffshoreVesselInfo;


and now, I want to create similar structure for regular vessel. We have less in this part :

export const fieldsNameHelper: FieldsNameHelper = {
  beneficialOwner: {
    name: "beneficial owner",
    description: "The beneficial owner of the vessel",
  },
  bollardPull: {
    name: "bollard pull",
    description: "The force exerted by the vessel while tethered",
  },
  bsW: {
    name: "bs&w",
    description: "Basic sediment and water in oil measurement",
  },
  bucketCapacity: {
    name: "bucket capacity",
    description: "Maximum carrying capacity of the bucket",
  },
  buildYear: {
    name: "build year",
    description: "Year the vessel was constructed",
  },
  cableTanks: {
    name: "cable tanks",
    description: "Storage tanks for cables on the vessel",
  },
  callsign: {
    name: "callsign",
    description: "The identifying signal letters or numbers of the vessel",
  },
  class: {
    name: "class",
    description: "Classification society to which the vessel is registered",
  },
  clearDeckArea: {
    name: "clear deck area",
    description: "Total area available for use on the deck",
  },
  commercialOwner: {
    name: "commercial owner",
    description: "The commercial owner of the vessel",
  },
  craneSize: {
    name: "crane size",
    description: "The size and lifting capacity of the crane on the vessel",
  },
  cranes: {
    name: "cranes",
    description: "The number and type of cranes installed on the vessel",
  },
  crudeProcessingCapacity: {
    name: "crude processing capacity",
    description: "Capacity to process crude oil onboard",
  },
  cutterPower: {
    name: "cutter power",
    description: "Power output of the cutting equipment on the vessel",
  },
  deckArea: {
    name: "deck area",
    description: "Total area of the vessel's deck",
  },
  deckLoadCapacity: {
    name: "deck load capacity",
    description: "Maximum load capacity of the vessel’s deck",
  },
  designType: {
    name: "design/type",
    description: "The design and type classification of the vessel",
  },
  destination: {
    name: "destination",
    description: "The intended destination of the vessel",
  },
  dredgeDepth: {
    name: "dredge depth",
    description: "Maximum depth at which the vessel can dredge",
  },
  dredgePumpPower: {
    name: "dredge pump power",
    description: "Power of the dredging pump",
  },
  dynamicPositioningClass: {
    name: "dynamic positioning class",
    description: "Classification of the vessel's dynamic positioning system",
  },
  engineTypePower: {
    name: "engine type & power",
    description: "Type and power output of the vessel’s engines",
  },
  etaIso: {
    name: "eta_iso",
    description: "Estimated time of arrival following ISO standards",
  },
  excavatorPower: {
    name: "excavator power",
    description: "Power output of the excavator on the vessel",
  },
  exportableCrude: {
    name: "exportable crude",
    description: "Volume of crude oil that can be exported by the vessel",
  },
  fleetName: {
    name: "fleet name",
    description: "Name of the fleet the vessel belongs to",
  },
  fleetOperator: {
    name: "fleet operator",
    description: "Operator managing the fleet of vessels",
  },
  fluidCapacity: {
    name: "fluid capacity",
    description: "Total capacity for fluid storage on the vessel",
  },
  fuelCapacity: {
    name: "fuel capacity",
    description: "Fuel storage capacity of the vessel",
  },
  gas: {
    name: "gas",
    description:
      "Capabilities or systems related to gas handling on the vessel",
  },
  grossTonnage: {
    name: "gross tonnage",
    description: "Overall internal volume of the vessel",
  },
  hS: {
    name: "h2s",
    description: "Presence and handling of hydrogen sulfide on the vessel",
  },
  heliDeck: {
    name: "heli-deck",
    description: "Helicopter landing area available on the vessel",
  },
  hopperCapacity: {
    name: "hopper capacity",
    description: "Storage capacity of the hopper on the dredging vessel",
  },
  id: { name: "id", description: "Unique identifier of the vessel" },
  imo: {
    name: "imo",
    description:
      "International Maritime Organization number assigned to the vessel",
  },
  jetPumps: {
    name: "jet pumps",
    description: "Types and capacities of jet pumps on the vessel",
  },
  latitude: {
    name: "latitude",
    description: "Current latitude position of the vessel",
  },
  legs: {
    name: "legs",
    description:
      "Structural supports used in vessels, particularly in offshore applications",
  },
  longitude: {
    name: "longitude",
    description: "Current longitude position of the vessel",
  },
  mainEnginesTypePower: {
    name: "main engines type & power",
    description: "Type and power of the main engines on the vessel",
  },
  maxDredgeWidth: {
    name: "max dredge width",
    description: "Maximum width the vessel can dredge",
  },
  maxFlow: {
    name: "max flow",
    description: "Maximum flow rate achievable by the vessel’s systems",
  },
  maxSpeed: {
    name: "max speed (buckets/min)",
    description:
      "Maximum operational speed of the vessel in buckets per minute",
  },
  mmsi: {
    name: "mmsi",
    description:
      "Maritime Mobile Service Identity used for vessel tracking and safety",
  },
  moonPool: {
    name: "moon pool",
    description:
      "An opening in the bottom or side of the vessel for underwater operations",
  },
  noOfBerths: {
    name: "no of berths",
    description: "Number of sleeping berths available on the vessel",
  },
  oilContentWaterDischarged: {
    name: "oil content water discharged",
    description: "Measure of oil content in discharged water",
  },
  pdfDownloaded: {
    name: "pdf downloaded (y/n)",
    description:
      "Indicates if the vessel’s documentation has been downloaded as PDF",
  },
  pipeDiameter: {
    name: "pipe diameter",
    description: "Diameter of pipes used onboard the vessel",
  },
  positionTime: {
    name: "position_time",
    description: "Timestamp for the vessel's position",
  },
  producedWater: {
    name: "produced water",
    description: "Water produced as a byproduct of the vessel’s operations",
  },
  pumpingDistance: {
    name: "pumping distance",
    description: "Maximum distance over which the vessel can pump materials",
  },
  rov: {
    name: "rov",
    description: "Remotely operated vehicle capabilities of the vessel",
  },
  rvp: {
    name: "rvp",
    description:
      "Reid vapor pressure measurements related to the vessel’s operations",
  },
  slopTanks: {
    name: "slop tanks",
    description:
      "Tanks on the vessel used for temporary storage of oily waste water",
  },
  specialisedCarriageCapability: {
    name: "specialised carriage capability",
    description:
      "Specific carriage capabilities of the vessel for specialized cargoes",
  },
  speedConsumption: {
    name: "speed/consumption",
    description: "The vessel’s speed relative to fuel consumption",
  },
  subType: {
    name: "sub_type",
    description: "Sub-type classification of the vessel",
  },
  totalPowerInstalled: {
    name: "total power installed",
    description: "Total power output of all installed machinery",
  },
  towingCapacity: {
    name: "towing capacity",
    description: "Capacity of the vessel to tow other vessels or structures",
  },
  tugType: {
    name: "tug type",
    description: "Classification of the tug based on its design and use",
  },
  type: {
    name: "type",
    description: "General type classification of the vessel",
  },
  vesselClass: {
    name: "vessel class",
    description: "Class designation for regulatory and operational purposes",
  },
  vesselName: {
    name: "vessel name",
    description: "Official name of the vessel",
  },
  vesselType: {
    name: "vessel type",
    description: "Specific type classification based on structure and function",
  },
  vesselId: {
    name: "vessel_id",
    description: "Unique identification number of the vessel",
  },
  waterInjectionCapacity: {
    name: "water injection capacity",
    description: "Capacity for injecting water into surrounding sea or seabed",
  },
};
and everywhere we have fields or name like this above. Those are things that we will be updating in our db so similar to whats above:

  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",
  },
}; 
+ also 
/* Clean, readable code and simplicity are major goals of Go development. Therefore, the names of things in Go should be short, concise, and evocative. Long names with mixed caps and underscores which are often seen e.g., in Java or Python code, sometimes hinder readability. Names should not contain an indication of the package. A method or function which returns an object is named as a noun, no Get… is needed. To change an object, use SetName. If necessary, Go uses MixedCaps or mixedCaps rather than underscores to write multiword names. */

// Filenames are in lower case and separated by an underscore if necessary

lower_case.go

/* Go keywords: break, default, func, interface, select, case, defer, go, map, struct, chan, else, goto, package, switch, const, fallthrough, if, range, type, continue, for, import, return, var */

/* Identifuers are case-sensitive, begin with a letter or an underscore, and are followed by 0 or more letter or Unicode digits. For example: X56, group1, _x23, i, etc.

Blank identifiers (_) can be used in declarations or variable assignments, but their value is discarded, so it can't be used in the code that follows. 

Delimiters used in Go: parentheses (), Braces {} and Brackets [].

Punctuation characters in GO:
- .
- ,
- ;
- :
- ...
*/

/* Go programs consist of keywords, constants, variables, operators, types and functions. 

The code is structured in statements. Statements don't need to end with a ;. The Go compiler automatically inserts semicolons at the end of statements. 

However, if multiple statements are written on one line (not encouraged), they must be separated by a semicolon.
NPS_Survey__c survey1 = new NPS_Survey__c(
  Case__c = testCase.Id,
  Status__c = 'NotStarted'
);
insert survey1;

Test.setCreatedDate(survey1.Id, DateTime.newInstance(2024, 06, 06));
// functions are declared with the keyword "func", a name, and a mandatory parentheses

func main()

/* Between the parentheses, no, one or more parameters separated by commas can be given as input.
The main functions is required as a starting point of every app. It has no parameters and no return type. */

func func_Name(param1 type 1, param2 type2){
  ...
}
  
/* The code or body in functions is enclosed between braces "{}". The first brace MUST be on the same line as the function declaration, and the last brace is positiones ageter the function code. */
  
func func_NameA(param1 type1, param2 type2) type1 {
  ...
}
  
 func func_NameB(param1 type1, param2 type2) type1 {
  ...
}

func func_NameC(param1 type1, param2 type2) }(ret1 type1, ret2 type2) {
  ...
}
  
/* We can specify the type that a function returns as seen in func_NameA, or the variable name and type as in func_NameB. A general function returning multple variables looks like func_NameC */
  
func Sum(a, b int) int { return a + b}

// Smaller functions can be written in one line.  
package main
// Every go file belongs to only one package
// One package can comprise many Go files
// The package to which the code file belongs must be indicated on the first line
// The package name is always written in lowercase letters
// Each Go app contains one "main" package

import (
	"fmt"
  	"os"
  	we "whatever"
)
// Here we factor the keyword, meaning we call it once on multiple instances.
// This factoring is also applicable to keywords like "const", "var" and "type".
// In the last import we're using an alias, so later we can use it as "we".

object, err := we.Object
if err != nil {
		panic(err)
	}

/* Here we import an visible object (must begin with capital letter) from the package "whatever", using its alias "we"

/* Quote carousel - ensure list item font defaults to the correct font. */ 
.block-quote--carousel .block-quote__text p, 
.block-quote--carousel .block-quote__text ul > li { 
	font-family: var(--font-family-body); 
} 
 vector<int> bfsOfGraph(int v,vector<int> adj[])
{
  vector<int> vis(v+1,0);
  vis[0]=1;
  queue<int> q;
  q.push(0);
  vector<int> bfs;
  while(!q.empty())
    {
      int node = q.front();
      bfs.push_back(node);
      q.pop();
      vis[node]=1;
      for(auto x:adj[node])
        {
          if(!vis[x]){
            q.push(x);
              vis[x]=1;
          }
        }
    }
    return bfs;
}
SELECT uid, pid, ExtractValue(pi_flexform,'//field[@index="settings.flexform.sender.subject"]/value') as psubject,  ExtractValue(pi_flexform,'//field[@index="settings.flexform.main.form"]/value') as pform FRoM tt_content WHERE CType LIKE "%powermail%" OR list_type LIKE "%powermail%" 
Promises are a fundamental concept in JavaScript for managing asynchronous operations. They represent a value that may be available now, or in the future, or never. Understanding promises is crucial for handling asynchronous code more effectively and avoiding callback hell.

Key Concepts of Promises
State: A promise can be in one of three states:

Pending: The initial state, neither fulfilled nor rejected.
Fulfilled: The operation completed successfully.
Rejected: The operation failed.
Value: Once a promise is fulfilled, it has a value. If it’s rejected, it has a reason (an error).

Settled: A promise is settled if it is either fulfilled or rejected.

Creating Promises
You can create a promise using the Promise constructor, which takes a function (executor) with two arguments: resolve and reject.

javascript
Copy code
const myPromise = new Promise((resolve, reject) => {
  const success = true; // Simulate an async operation

  if (success) {
    resolve('Operation was successful!');
  } else {
    reject('Operation failed.');
  }
});
Handling Promises
then Method
Used to handle a fulfilled promise and to chain multiple promises.

javascript
Copy code
myPromise.then(value => {
  console.log(value); // "Operation was successful!"
}).catch(error => {
  console.error(error); // "Operation failed."
});
catch Method
Used to handle a rejected promise.

javascript
Copy code
myPromise.catch(error => {
  console.error(error); // "Operation failed."
});
finally Method
Runs regardless of the promise’s outcome.

javascript
Copy code
myPromise.finally(() => {
  console.log('Promise has been settled.');
});
Chaining Promises
You can chain multiple then calls to handle a sequence of asynchronous operations.

javascript
Copy code
myPromise
  .then(value => {
    console.log(value);
    return 'Next operation';
  })
  .then(nextValue => {
    console.log(nextValue);
  })
  .catch(error => {
    console.error(error);
  })
  .finally(() => {
    console.log('All done!');
  });
Promise Methods
Promise.all
Waits for all promises to settle and returns an array of their results. If any promise rejects, it immediately rejects with that reason.

javascript
Copy code
const promise1 = Promise.resolve('First');
const promise2 = Promise.resolve('Second');
const promise3 = Promise.resolve('Third');

Promise.all([promise1, promise2, promise3])
  .then(values => {
    console.log(values); // ["First", "Second", "Third"]
  })
  .catch(error => {
    console.error(error);
  });
Promise.race
Returns the first promise that settles (either fulfills or rejects).

javascript
Copy code
const promise1 = new Promise((resolve) => setTimeout(resolve, 500, 'First'));
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'Second'));

Promise.race([promise1, promise2])
  .then(value => {
    console.log(value); // "Second"
  })
  .catch(error => {
    console.error(error);
  });
Promise.allSettled
Waits for all promises to settle and returns an array of their results with their status.

javascript
Copy code
const promise1 = Promise.resolve('First');
const promise2 = Promise.reject('Error');
const promise3 = Promise.resolve('Third');

Promise.allSettled([promise1, promise2, promise3])
  .then(results => {
    results.forEach((result) => console.log(result.status));
    // "fulfilled"
    // "rejected"
    // "fulfilled"
  });
Promise.any
Returns the first promise that fulfills, ignoring rejections.

javascript
Copy code
const promise1 = Promise.reject('Error 1');
const promise2 = Promise.reject('Error 2');
const promise3 = Promise.resolve('First successful');

Promise.any([promise1, promise2, promise3])
  .then(value => {
    console.log(value); // "First successful"
  })
  .catch(error => {
    console.error('All promises were rejected', error);
  });
Using Async/Await
async and await provide a more readable way to work with promises, allowing you to write asynchronous code that looks synchronous.

javascript
Copy code
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    console.log('Fetch operation complete.');
  }
}

fetchData();
Summary
Promises simplify asynchronous programming by providing a clear and manageable way to handle asynchronous operations.
then, catch, and finally methods help in handling fulfilled, rejected, and settled promises.
Promise methods like all, race, allSettled, and any provide utilities for managing multiple promises.
Async/await syntax allows for writing asynchronous code in a synchronous style, improving readability.
Sub GetImportFileName()
  
  Dim Finfo As String
  Dim FilterIndex As Long
  Dim Title As String
  Dim FileName As Variant
'  Set up list of file filters
  Finfo = "Excel Files (*.xlsx),*.xlsx"

'  Display *.* by default
  FilterIndex = 5

'  Set the dialog box caption
  Title = "Escolhe caminho e ficheiro"
  
  
'Get the filename
  FileName = Application.GetOpenFilename(Finfo, _
    FilterIndex, Title)

'  Handle return info from dialog box
  If FileName = False Then
    MsgBox "Nenhum ficheiro foi escolhido."
  Else
    MsgBox "You selected " & FileName
  

  End If
End Sub
Sub SelectFolder()
    Dim diaFolder As FileDialog
    Dim selected As Boolean

    ' Open the file dialog
    Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    selected = diaFolder.Show

    If selected Then
        MsgBox diaFolder.SelectedItems(1)
    End If

    Set diaFolder = Nothing
End Sub
global proc helloWorld(string $name)
{
	print ("Hello "+$name+"!");
}
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

star

Fri Jun 14 2024 23:32:00 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Fri Jun 14 2024 22:20:20 GMT+0000 (Coordinated Universal Time)

@pag0dy #go

star

Fri Jun 14 2024 21:09:09 GMT+0000 (Coordinated Universal Time) https://www.linkedin.com/pulse/manipulating-created-date-salesforce-lq5ic/

@gbritgs #apex

star

Fri Jun 14 2024 17:21:12 GMT+0000 (Coordinated Universal Time)

@pag0dy

star

Fri Jun 14 2024 17:08:46 GMT+0000 (Coordinated Universal Time)

@pag0dy

star

Fri Jun 14 2024 14:08:13 GMT+0000 (Coordinated Universal Time)

@rdoelmackaway

star

Fri Jun 14 2024 13:28:19 GMT+0000 (Coordinated Universal Time)

@ayushg103 #c++

star

Fri Jun 14 2024 11:53:32 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/52442557/how-to-select-xml-attribute-value-in-mysql

@mhaschke_works #sql #pi_flexform

star

Fri Jun 14 2024 11:51:20 GMT+0000 (Coordinated Universal Time) https://www.blockchainx.tech/nft-gaming-platform-development/

@blockchainxtech

star

Fri Jun 14 2024 09:58:04 GMT+0000 (Coordinated Universal Time) https://maticz.com/computer-assisted-learning

@carolinemax ##computer_assited_learning ##what_is_computer_assisted_learning ##computer_aided_learning

star

Fri Jun 14 2024 09:20:41 GMT+0000 (Coordinated Universal Time) https://chatgpt.com/

@devdutt

star

Fri Jun 14 2024 09:17:36 GMT+0000 (Coordinated Universal Time)

@cmrfreitas

star

Fri Jun 14 2024 09:16:23 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5971292/get-file-path-ends-with-folder

@cmrfreitas

star

Fri Jun 14 2024 04:21:49 GMT+0000 (Coordinated Universal Time)

@nouhad #mel

star

Thu Jun 13 2024 21:15:16 GMT+0000 (Coordinated Universal Time) https://or-lebanonfire.civicplus.com/

@Cody_Gant

star

Thu Jun 13 2024 21:14:34 GMT+0000 (Coordinated Universal Time) https://www.pahrumpnv.gov/327/Home---2024

@Cody_Gant

Save snippets that work with our extensions

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