Snippets Collections
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+"!");
}
vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
       vector<int> dis(V,1e8);
       dis[S] = 0;
       for(int cnt = 0; cnt<=V-1; cnt++){
           for(auto edge : edges){
               int u = edge[0];
               int v = edge[1];
               int w = edge[2];
               if(dis[u] != 1e8 and dis[u] + w < dis[v]){
                   dis[v] = dis[u] + w;
               }
           }
       }
       
       // Check for negative weight cycles
       for(auto edge : edges) {
           int u = edge[0];
           int v = edge[1];
           int w = edge[2];
           if(dis[u] != 1e8 && dis[u] + w < dis[v]) {
               // If we can still relax an edge, there is a negative weight cycle
               return {-1}; // Return an empty vector to indicate the presence of a negative cycle
           }
       }
       
       return dis;
    }
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Responsive Swiper Slider with Background Image</title>
  <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">
  <style>
    body, html {
      margin: 0;
      padding: 0;
      overflow-x: hidden;
    }

    .Banner {
      overflow: hidden;
      position: relative;
    }

    .swiper-container {
      width: 100%;
      height: 100vh;
    }

    .swiper-slide {
      display: flex;
      justify-content: center;
      align-items: center;
      background-size: cover;
      background-position: center;
      height: 100%;
    }

    /* Define different background images for each slide */
    .swiper-slide:nth-child(1) {
      background-image: url('img/soccer-player-action-stadium.png');
    }

    .swiper-slide:nth-child(2) {
      background-image: url('img/soccer-player-action-stadium.png');
    }

    .swiper-slide:nth-child(3) {
      background-image: url('img/soccer-player-action-stadium.png');
    }

    .slider {
      width: 100%;
      text-align: center;
      color: white; /* Adjust text color for visibility */
    }

    .slide-main {
      max-width: 800px;
      margin: auto;
      padding: 20px;
    }

    .slide-main p {
      font-size: 1rem;
      margin-bottom: 10px;
    }

    .slide-main h2 {
      font-size: 1.5rem;
      margin-bottom: 20px;
    }

    .slide-main a {
    display: inline-block;
    padding: 10px 20px;
    background-color: #08351e;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    font-size: 1rem;
}

    @media (min-width: 768px) {
      .slide-main p {
        font-size: 1.25rem;
      }
      .slide-main h2 {
        font-size: 2rem;
      }
      .slide-main a {
        font-size: 1.25rem;
      }
      .swiper-container {
    width: 100%;
    height: 50vh;
}
    }
    @media (min-width: 500px ) {
      .swiper-container {
    width: 100%;
    height: 40vh !important;
}
    }
    @media (min-width: 400px ) {
      .swiper-container {
    width: 100%;
    height: 35vh !important;
}
    }
    @media (min-width: 320px ) {
      .swiper-container {
    width: 100%;
    height: 30vh !important;
}
    }
  </style>
</head>
<body>
  <section class="Banner">
    <div class="swiper-container">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <div class="slider">
            <div class="slide-main">
              <p>Free <strong>3D Render</strong> Models</p>
              <h2>Exclusive Promotional Gift Solutions Await You!</h2>
              <a href="#">Corporate Gifts</a>
            </div>
          </div>
        </div>
        <div class="swiper-slide">
          <div class="slider">
            <div class="slide-main">
              <p>From <strong>the best</strong> designers</p>
              <h2>Peruse Giveaway Categories</h2>
              <a href="#">Corporate Gifts</a>
            </div>
          </div>
        </div>
        <div class="swiper-slide">
          <div class="slider">
            <div class="slide-main">
              <p>Quality <strong>You Can</strong> Trust!</p>
              <h2>Elevate Gifting with Our Exclusive Selection</h2>
              <a href="#">All Shop</a>
            </div>
          </div>
        </div>
      </div>
      <!-- Add Navigation -->
      <div class="swiper-button-next"></div>
      <div class="swiper-button-prev"></div>
    </div>
  </section>

  <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
  <script>
    var swiper = new Swiper('.swiper-container', {
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
      pagination: {
        el: '.swiper-pagination',
        clickable: true,
      },
      slidesPerView: 1,
      spaceBetween: 30,
      breakpoints: {
        640: {
          slidesPerView: 1,
          spaceBetween: 20,
        },
        768: {
          slidesPerView: 1,
          spaceBetween: 30,
        },
        1024: {
          slidesPerView: 1,
          spaceBetween: 40,
        },
      },
    });
  </script>
</body>
</html>
Cascading Style Sheets

CSS - 
SASS - Syntactically Awesome Style Sheet
LESS - Leaner CSS
...

How to add CSS
////////////////////
INLINE CSS
<html style="background: blue">
  </html>

////////////////////
INTERNAL CSS
<html>
  <head>
   <style>
    	html {
    	  background: red;
  		  }
		h1 {
          background: green;
        }
	</style>
  </head>
</html>
 
////////////////////
EXTERNAL CSS
<html>
  <head>
   <link
		rel="stylesheet"
		href="./styles.css"
    />
  </head>
</html>


CSS Selectors
////////////////////
ELEMENT SELECTOR
h1 {
  color: blue
}
You can add the same group of styles to many elements by creating a list of selectors. Each selector is separated with commas like this:
selector1, selector2 {
  property: value;
}
 
////////////////////
CLASS SELECTOR. used for many elements
.red-heading {
  color: red
}
<h1 class="red-heading"></h1>
 
////////////////////
ID SELECTOR. used for one specific element
#main {
color: red
}
<h1 id="main"></h1>
 
////////////////////
ATTRIBUTE SELECTOR. used for all elements with specific attributes
p[draggable="true"]{
  color: red
}
<p id="" class="" draggable="true"></p> //applied
<p id="" class="" draggable="false"></p> //not applied
 
////////////////////
UNIVERSAL SELECTOR. used to select everything where stylesheet is active
* {
  color: red
}

COLOR PROPERTIES

Named Colors: background-color: blue

Hex Codes: background-color: #5D3891


FONT SIZE
//static sizes
1px = 1/96th of an inch //PIXEL
1pt = 1/72nd of an inch //POINT
 
//relative sizes (scalable)
1em = 100% of parent
1rem = 100% of root

FONT WEIGHT
//Keywords
normal; //-100
bold; //+100

//Relative to Parent
lighter;
bolder;

//Number
light-bold
100-900;


FONT FAMILY
h1{
  font-family: "FONTNAME", "BACKUP GENERIC FONT TYPE" //Helvetica, sans-serif
}
fonts needs quotation marks with multiple words
include link in html file under style element

TEXT ALIGN
sets the horizontal alignment of the element


THE BOX MODEL

border: 10px solid black //border: "thickness" "style" "color"
	border-top: 0px //has to come after border property
border property adds outwards of the html element

border-width: 0px 10px 20px 30px //border-width: "top" "right" "bottom" "left"
border-width: 0px 20px //border-width: "top+bottom" "left+right"

padding: 20px //doesn't affect height or width of element, adds to it. around paragraph, inside border

margin: 10px //adds space around element, outside of border


CONTENT DIVISION ELEMENT

<div>		//take as many elements as needed
  <p><p/>
  <img/>
</div> 

horizontally center div with img

div{
width: 50%;
margin-left: 25%;
}
img{
  width: 100%;
}


CASCADE

resolving conflicting styling rules for elements

css rules apply by:

Position
order in stylesheet
li {
  color: red; 
  color: blue; //overwrites red value
}
li{
  color: green; //overwrites blue value
}

Specificity
how specific a selector is
<li id="first-id" class="first-class" draggable></li>

li{color: blue;} //selects all list item elements(least specific)
.first-class{color: red;} //class selector with classname, second specific
li[draggable] {color: purple;} //attribute selector, third specific
#first-id {color: orange;} //id selector, most specific

Type
<link rel="stylesheet" href="./style.css">	//external, least important
<style> <style/>							//internal, second important
<h1 style="">Hello</h1>						//inline, most important

Importance
color: red;
color: green !important; //gets most important rule for element

Color

The CSS linear-gradient function lets you control the direction of the transition along a line, and which colors are used.
linear-gradient(gradientDirection, color1, color2, ...);
gradientDirection is the direction of the line used for the transition. color1 and color2 are color arguments, which are the colors that will be used in the transition itself. These can be any type of color, including color keywords, hex, rgb, or hsl.
background: linear-gradient(90deg, rgb(255, 0, 0), rgb(0, 255, 0), rgb(0, 0, 255));

With the CSS opacity property, you can control how opaque or transparent an element is. With the value 0, or 0%, the element will be completely transparent, and at 1.0, or 100%, the element will be completely opaque like it is by default.

The rgba function works just like the rgb function, but takes one more number from 0 to 1.0 for the alpha channel:
rgba(redValue, greenValue, blueValue, alphaValue);

The box-shadow property lets you apply one or more shadows around an element.
box-shadow: offsetX offsetY color;

both offsetX and offsetY accept number values in px and other CSS units
a positive offsetX value moves the shadow right and a negative value moves it left
a positive offsetY value moves the shadow down and a negative value moves it up
if you want a value of zero (0) for any or both offsetX and offsetY, you don't need to add a unit. Every browser understands that zero means no change.

If a blurRadius value isn't included, it defaults to 0 and produces sharp edges. The higher the value of blurRadius, the greater the blurring effect is.
box-shadow: offsetX offsetY blurRadius color;

The vh unit stands for viewport height, and is equal to 1% of the height of the viewport. This makes it relative to the viewport height.

Now, get rid of the horizontal scroll-bar, by setting the body default margin added by some browsers to 0.






















add_action( 'sp_tabs_name_slug', '__return_true' );
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 {
  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>
  );
}
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;
HTML Elements

<h1> //opening tag
</h1> // closing tag

Heading Element
<h1> to <h6>
not good practice to have more than one h1 or skip levels.

  
Paragraph
<p></p>
adds a linebreak
  

Horizontal Rule Element (self closing)
<hr />
doesn't take content
adds a horizontal line
  
Break Element (self closing)
<br />
doesn't take content
adds a break at the end
don't use break elements to break up paragraphs
  
List Element

Unordered
<ul>		//unordered
  <li></li> // list item
</ul>
will create bullet points. order of items don't matter
  
Ordered
<ol>
  <li></li>
</ol>
adds numbers to every item

Anchor Element
<a href="LINK"></a>
adds a target to some content
  
Image Element
<img src="URL" alt="ALTERNATIVE TEXT DESCRIPTION" />

HTML Boilerplate
<!DOCTYPE html> //tells browser code is written in html
  <html lang="en"> //language of text content, used for screen readers
    <head> //important information that does not get displayed
    <meta charset="UTF-8"> //character encoding
      <title>TITLE</title> //gets displayed in tab bar
      </head>
      
      <body> //content of website goes here
        
      </body>
  </html>

Main Element
The main element is used to represent the main content of the body of an HTML document.
<main>
  <h1>Most important content of the document</h1>
  <p>Some more important content...</p>
</main>

Section Element
The section element is used to define sections in a document, such as chapters, headers, footers, or any other sections of the document. It is a semantic element that helps with SEO and accessibility.
<section>
  <h2>Section Title</h2>
  <p>Section content...</p>
</section>

Figure Element
The figure element represents self-contained content and will allow you to associate an image with a caption.
A figure caption (figcaption) element is used to add a caption to describe the image contained within the figure element.
<figure>
  <img src="image.jpg" alt="A description of the image">
  <figcaption>A cute cat</figcaption>
</figure>

Form Element
The form element is used to get information from a user like their name, email, and other details.
The action attribute indicates where form data should be sent.
<form action="/submit-url"></form>

Input element
The input element allows you several ways to collect data from a web form.
There are many kinds of inputs you can create using the type attribute. You can easily create a password field, reset button, or a control to let users select a file from their computer.
In order for a form's data to be accessed by the location specified in the action attribute, you must give the text field a name attribute and assign it a value to represent the data being submitted.
To prevent a user from submitting your form when required information is missing, you need to add the required attribute to an input element.

Fieldset Element
The fieldset element is used to group related inputs and labels together in a web form.

Legend Element
The legend element acts as a caption for the content in the fieldset element. It gives users context about what they should enter into that part of the form.

Footer Element
The footer element is used to define a footer for a document or section. A footer typically contains information about the author of the document, copyright data, links to terms of use, contact information, and more.

Select Element
Adding a dropdown to the form is easy with the select element. The select element is a container for a group of option elements, and the option element acts as a label for each dropdown option. Both elements require closing tags.









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`);
  }
}
# Create a virtual environment
python -m venv venv  # Windows
python3 -m venv venv  # MacOS/Linux

# Activate the virtual environment
venv\Scripts\activate  # Windows
source venv/bin/activate  # MacOS/Linux

# Install required packages
pip install kivy

# Create requirements.txt file
pip freeze > requirements.txt

# Run a test script
python test.py

--------------------------
in case of an POLICY error -- 
PS D:\Coding Stuff, Editing\Visual Studio Python Codings\MyProjects\BurgerBillingSystem> .\burger-billing-system-env\Scripts\activate     
.\burger-billing-system-env\Scripts\activate : File D:\Coding Stuff, Editing\Visual Studio Python 
Codings\MyProjects\BurgerBillingSystem\burger-billing-system-env\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system.     
For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ .\burger-billing-system-env\Scripts\activate
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess

The error message you are encountering indicates that running scripts is disabled on your systems PowerShell execution policy. This is a security measure to prevent malicious scripts from running.

Here is how to fix this and activate your virtual environment:

Change the Execution Policy (For Administrators Only):

Open PowerShell as Administrator. "Right-click on the PowerShell" icon and select "Run as administrator".

Type the following command and press Enter:
"PowerShell Set-ExecutionPolicy RemoteSigned -Scope CurrentUser"

Activate the Virtual Environment (After Policy Change):
Navigate to your project directory using the cd command in PowerShell.
Run the activation command again:

---------------------------------
For Anaconda Jupyter Notebook -
pip install venv
python -m venv env_test
.\env_test\Scripts\activate
pip install ipykernel
python -m ipykernel install --user --name kernel_ai_cnn_1
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,
  } = 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
    ) 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,
      ],
      (error, results) => {
        if (error) {
          return reject(error);
        }
        resolve(results);
      },
    );
  });
};
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`);
  }
}
	$(document).ready(function () {
			$(document).on('mousewheel', function (event) {
				if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
					// Mouse wheel up
					$('.nav-main, .header__contact').css({
						opacity: '1',
						visibility: 'visible',
						overflow: 'visible',
					});
				} else {
					// Mouse wheel down
					$('.nav-main, .header__contact').css({
						opacity: '0',
						visibility: 'hidden',
						overflow: 'hidden',
					});
				}
			});
		});
# installs nvm (Node Version Manager)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# download and install Node.js (you may need to restart the terminal)
npm install 20
# verifies the right Node.js version is in the environment
node -v # should print `v20.14.0`
# verifies the right NPM version is in the environment
npm -v # should print `10.7.0`
img {
          margin: 0 auto;
          width: 800px;
          @include respond-to(maxlarge) {
            width: 700px;
          }
            @include respond-to(desktop) {
                width: 600px;
            }
            @include respond-to(tabs) {
                width: 500px;
            }
            @include respond-to(phablet) {
                width: 450px;
            }
          @include respond-to(mobile) {
            width: 420px;
          }
        }


   .slide-video{
            border-radius: 20px;
            width: 800px;
            @include respond-to(maxlarge) {
              width: 700px;
            }
            @include respond-to(desktop) {
              width: 600px;
            }
            @include respond-to(tabs) {
              width: 500px;
            }
            @include respond-to(phablet) {
              width: 450px;
            }
          }
#include <iostream>
using namespace std;

int main() {
    float a, b, c;

    for (int i = 1; i < 30; ++i) {
        cout << "Digite as notas: " << endl;
        cin >> a >> b >> c;
       cout << "Media do aluno e de: "<< (a + b + c)/3 << endl;
    }

    return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
  string meses[12] = {"Janeiro", "Fevereiro", "Marco", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"};
  int numero;
  cin >> numero;
  if (numero >= 1 && numero <= 12){
    cout << meses[numero -1] << endl;
  } else {
    cout << "Numero invalido" << endl;
  }
}
	add_filter('woocommerce_product_add_to_cart_text', 'custom_woocommerce_product_add_to_cart_text');

	function custom_woocommerce_product_add_to_cart_text($text) {
		global $product;
		if ($product->is_type('external')) {
			return __('See Prices', 'woocommerce');
		}
		return $text;
	}
function custom_external_add_to_cart_button($button, $product) {
    if ($product->is_type('external')) {
        // URL of the Amazon icon image
        $icon_url = 'https://mejormovil.es/wp-content/themes/woodmart/images/amazon-icon.png';
        $button_text = 'See Prices';

        // Create the button HTML with the Amazon icon and new text
        $button = sprintf(
            '<a href="%s" class="button product_type_external add-to-cart-loop customize-unpreviewable" data-product_id="%s" aria-label="%s" rel="nofollow">
                <img src="%s" style="width: 20px; height: auto; margin-right: 5px; vertical-align: middle;" alt="Amazon Icon"/> %s
            </a>',
            esc_url($product->add_to_cart_url()), // URL for the product
            esc_attr($product->get_id()), // Product ID
            esc_attr($product->add_to_cart_description()), // ARIA label
            esc_url($icon_url), // Amazon icon URL
            esc_html($button_text) // Button text
        );
    }
    return $button;
}
add_filter('woocommerce_loop_add_to_cart_link', 'custom_external_add_to_cart_button', 10, 2);
impl Point {
    pub fn new(x: u16, y: u16) -> Self {
        Self { x, y }
    }

    pub fn transform(&self, direction: Direction, times: u16) -> Self {
        let times = times as i16;
        let transformation = match direction {
            Direction::Up => (0, -times),
            Direction::Right => (times, 0),
            Direction::Down => (0, times),
            Direction::Left => (-times, 0),
        };

        Self::new(
            Self::transform_value(self.x, transformation.0),
            Self::transform_value(self.y, transformation.1),
        )
    }

    fn transform_value(value: u16, by: i16) -> u16 {
        if by.is_negative() && by.abs() as u16 > value {
            panic!("Transforming value {} by {} would result in a negative number", value, by);
        } else {
            (value as i16 + by) as u16
        }
    }
}
<!DOCTYPE html>
<html>
<body>
​
<h2>Image Maps</h2>
<p>Click on the computer, the phone, or the cup of coffee to go to a new page and read more about the topic:</p>
​
<img src="workplace.jpg" alt="Workplace" usemap="#workmap" width="400" height="379">
​
<map name="workmap">
  <area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
  <area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
  <area shape="circle" coords="337,300,44" alt="Cup of coffee" href="coffee.htm">
</map>
​
</body>
</html>
​
​
options = map();
optionlist = list();
optionlist.add("workflow");
options.put("trigger",optionlist);
updateRec= zoho.crm.updateRecord(module_name, updatemap, options, connection);
<StyledTableCell>
                                        {connectedEmail.credentialInfoProvider.toUpperCase() === "IMAP" ? (
                                            <Tooltip
                                                arrow
                                                title="IMAP provider support emails incoming and outgoing, not calendar functionalities"
                                                placement="top"
                                                classes={{ tooltip: classes.tooltip }}
                                            >
                                                <StyledChip style={statusChipColor("WARNING")}>
                                                    {connectedEmail.credentialInfoProvider.toUpperCase()}
                                                </StyledChip>
                                            </Tooltip>
                                        ) : (
                                                <StyledChip style={statusChipColor("WARNING")}>
                                                {connectedEmail.credentialInfoProvider.toUpperCase()}
                                            </StyledChip>
                                        )}
                                    </StyledTableCell>
{
  "associationAccountInfoId": 11,
  "associationId": 30,
  "name": "Dr.Reddys foundation",
  "bankName": "Indian Bank",
  "bankAccountNumber": "6245789568",
  "bankRoutingTypeId": 46,
  "bankRoutingCode": "Indian bank 1234",
  "associationAccountTypeId": 170
}





{
  "associationAccountInfoId": 12,
  "associationId": 30,
  "upiId": "Reddysfoundations@IndianBank",
  "associationAccountTypeId": 171
}
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

star

Thu Jun 13 2024 14:06:35 GMT+0000 (Coordinated Universal Time)

@divay6677 ##c++

star

Thu Jun 13 2024 13:37:03 GMT+0000 (Coordinated Universal Time)

@shees

star

Thu Jun 13 2024 12:33:47 GMT+0000 (Coordinated Universal Time)

@NoFox420 #html

star

Thu Jun 13 2024 11:52:23 GMT+0000 (Coordinated Universal Time) https://secure.helpscout.net/reports/happiness/

@Pulak

star

Thu Jun 13 2024 11:44:55 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 11:44:17 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 11:43:51 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 11:11:30 GMT+0000 (Coordinated Universal Time)

@NoFox420 #html

star

Thu Jun 13 2024 08:24:42 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 08:24:06 GMT+0000 (Coordinated Universal Time) https://www.google.com/search?q

@eziokittu #python #env #kernel #jupyter #anaconda

star

Thu Jun 13 2024 08:23:59 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 08:23:38 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Jun 13 2024 07:41:07 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/crypto-casino-game-development

@steeve #crypto #casino #game #development

star

Thu Jun 13 2024 06:40:29 GMT+0000 (Coordinated Universal Time)

@divyasoni23 #jquery

star

Thu Jun 13 2024 05:16:51 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/crypto-casino-game-development

@steeve #crypto #casino #game

star

Thu Jun 13 2024 03:35:26 GMT+0000 (Coordinated Universal Time)

@jrray

star

Thu Jun 13 2024 01:08:48 GMT+0000 (Coordinated Universal Time)

@galaxy #css

star

Wed Jun 12 2024 20:48:26 GMT+0000 (Coordinated Universal Time)

@tomasp #c++

star

Wed Jun 12 2024 20:43:19 GMT+0000 (Coordinated Universal Time)

@tomasp #c++

star

Wed Jun 12 2024 19:18:26 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Wed Jun 12 2024 19:17:31 GMT+0000 (Coordinated Universal Time)

@Promakers2611

star

Wed Jun 12 2024 19:07:16 GMT+0000 (Coordinated Universal Time) https://blog.scottlogic.com/2020/10/08/lets-build-snake-with-rust.html

@ORDINAL

star

Wed Jun 12 2024 15:21:53 GMT+0000 (Coordinated Universal Time)

@tokoyami_ds

star

Wed Jun 12 2024 12:46:06 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/html/tryit.asp?filename

@sandeepv

star

Wed Jun 12 2024 12:45:59 GMT+0000 (Coordinated Universal Time) https://www.w3schools.com/html/tryit.asp?filename

@sandeepv #undefined

star

Wed Jun 12 2024 10:57:31 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Wed Jun 12 2024 10:18:30 GMT+0000 (Coordinated Universal Time)

@taufiq_ali

star

Wed Jun 12 2024 10:17:35 GMT+0000 (Coordinated Universal Time) https://studio.youtube.com/channel/UCkNG6QrabEQdyroozJp4nCg/editing/sections

@calazar23

star

Wed Jun 12 2024 10:14:31 GMT+0000 (Coordinated Universal Time)

@Ranjith

Save snippets that work with our extensions

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