Snippets Collections
class Codec:
    def serialize(self, root):
        res = []

        def dfs(node):
            if not node:
                res.append("N")
                return
            res.append(str(node.val))
            dfs(node.left)
            dfs(node.right)

        dfs(root)
        return ",".join(res)

    def deserialize(self, data):
        vals = data.split(",")
        self.i = 0

        def dfs():
            if vals[self.i] == "N":
                self.i += 1
                return None
            node = TreeNode(int(vals[self.i]))
            self.i += 1
            node.left = dfs()
            node.right = dfs()
            return node

        return dfs()
class Solution:
    def maxPathSum(self, root: TreeNode) -> int:
        res = [root.val]

        # return max path sum without split
        def dfs(root):
            if not root:
                return 0

            leftMax = dfs(root.left)
            rightMax = dfs(root.right)
            leftMax = max(leftMax, 0)
            rightMax = max(rightMax, 0)

            # compute max path sum WITH split
            res[0] = max(res[0], root.val + leftMax + rightMax)
            return root.val + max(leftMax, rightMax)

        dfs(root)
        return res[0]
class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder or not inorder:
            return None

        root = TreeNode(preorder[0])
        mid = inorder.index(preorder[0])
        root.left = self.buildTree(preorder[1 : mid + 1], inorder[:mid])
        root.right = self.buildTree(preorder[mid + 1 :], inorder[mid + 1 :])
        return root
class Solution:
    def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []

        q = deque([root])
        level = 1
        res = []

        while q:
            if (level % 2): ## < this is nice
                res.append([x.val for x in q])
            else:
                res.append([x.val for x in reversed(q)])
            for _ in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
            level += 1
        return res
my_list.reverse() ### <<< in-place! 
my_list[::-1]
list(reversed(my_list))
[item for item in reversed(my_list)]
// validators.jsx

// Function to validate email
export const validateEmail = (email) => {
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\\.,;:\s@\"]+\.)+[^<>()[\]\\.,;:\s@\"]{2,})$/i;
    return re.test(email);
};

// Function to validate password
export const validatePassword = (password) => {
    if (password.length < 8 || password.length > 32) return false;
    if (!/[A-Z]/.test(password)) return false; // At least one uppercase letter
    if (!/[a-z]/.test(password)) return false; // At least one lowercase letter
    if (!/[0-9]/.test(password)) return false; // At least one digit
    if (!/[^A-Za-z0-9]/.test(password)) return false; // At least one special character
    return true;
};


// LoginForm.jsx

import React, { useState } from 'react';
import { validateEmail, validatePassword } from './validators.jsx';

const LoginForm = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [alert, setAlert] = useState('');

    const handleSubmit = (event) => {
        event.preventDefault();
        setAlert(''); // Clear previous alerts

        // Validate inputs
        if (!validateEmail(email)) {
            setAlert('Please enter a valid email address.');
            return;
        }

        if (!validatePassword(password)) {
            setAlert('Please enter a valid password. Password must be at least 8 characters.');
            return;
        }

        // Call backend API here if validations pass
        console.log('API call here');
    };

    return (
        <div>
            {alert && (
                <div className="alert">
                    {alert}
                    <button onClick={() => setAlert('')}>Okay</button>
                </div>
            )}
            <form onSubmit={handleSubmit}>
                <label>
                    Email:
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
                </label>
                <label>
                    Password:
                    <input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
                </label>
                <button type="submit">Login</button>
            </form>
        </div>
    );
};

export default LoginForm;



// In your route file, e.g., authRoutes.js

const { check, validationResult } = require('express-validator');

// Define the validation chain for the password and email
const validationChain = [
    check('email')
      .normalizeEmail()
      .isEmail()
      .withMessage('Invalid email address.'),
    check('password')
      .isLength({ min: 8, max: 32 })
      .withMessage('Password must be between 8 to 32 characters long.')
      .matches(/[A-Z]/)
      .withMessage('Password must contain at least one uppercase letter.')
      .matches(/[a-z]/)
      .withMessage('Password must contain at least one lowercase letter.')
      .matches(/[0-9]/)
      .withMessage('Password must contain at least one digit.')
      .matches(/[^A-Za-z0-9]/)
      .withMessage('Password must contain at least one special character.')
];

// Add to your route, e.g., for user registration or login
app.post('/your-route', validationChain, (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ success: false, errors: errors.array() });
    }

    // Proceed with backend logic here if validation passes
});

# -- weird, I think my version is better than NC: I just don't add None nodes
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []

        q = deque([root])
        res = []

        while q:
            res.append(q[-1].val)
            for _ in range(len(q)):
                node = q.popleft()
                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)
        return res

# class Solution: NC version 
    def rightSideView(self, root: TreeNode) -> List[int]:
        res = []
        q = collections.deque([root])

        while q:
            rightSide = None
            qLen = len(q)

            for i in range(qLen):
                node = q.popleft()
                if node:
                    rightSide = node
                    q.append(node.left)
                    q.append(node.right)
            if rightSide:
                res.append(rightSide.val)
        return res
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        
        # -- VERY good for a review!
        # -- mine 
        res = [0]
        def dfs(node):
            if not node:
                return 0
            
            left = dfs(node.left)
            right = dfs(node.right)

            res[0] = max(left+right, res[0])
            return 1 + max(left, right) # Don't forget +1 for current node!

        dfs(root)
        return res[0]
import 'package:flutter/material.dart';
import 'package:notes_app/homepage.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}
.gelatine {
  animation: gelatine 0.5s infinite;
}
@keyframes gelatine {
  from, to { transform: scale(1, 1); }
  25% { transform: scale(0.9, 1.1); }
  50% { transform: scale(1.1, 0.9); }
  75% { transform: scale(0.95, 1.05); }
}
String jsonMessageString = Files.readString(Paths.get("src/main/resources/data.json").toAbsolutePath());
JSONObject jsonObject = new JSONObject(jsonMessageString);
jsonObject.getJSONObject("message").put("from", credentials.getAddress());
jsonObject.getJSONObject("message").put("nonce", nonce);
jsonObject.getJSONObject("message").put("data", encodedFunction);

String modifiedJsonString = jsonObject.toString();
Sign.SignatureData signature = Sign.signTypedData(modifiedJsonString, credentials.getEcKeyPair());
MinimalForwarder minimalForwarder = MinimalForwarder.load("<minimalForwarder_contract_address>", web3j, credentials, new StaticGasProvider(BigInteger.valueOf(4_100_000_000L),BigInteger.valueOf(6721975L)));
Recipient recipient = Recipient.load("<recipient_contract_address>", web3j, credentials, new StaticGasProvider(BigInteger.valueOf(4_100_000_000L),BigInteger.valueOf(6721975L)));
MinimalForwarder minimalForwarder = MinimalForwarder.load("<minimalForwarder_contract_address>", web3j, credentials, new StaticGasProvider(BigInteger.valueOf(4_100_000_000L),BigInteger.valueOf(6721975L)));
Recipient recipient = Recipient.load("<recipient_contract_address>", web3j, credentials, new StaticGasProvider(BigInteger.valueOf(4_100_000_000L),BigInteger.valueOf(6721975L)));
Introduction to SQL
SQL
Let's get back to relational databases and take a look at the basics of how to access tables and work with table data. 

SQL (Structured Query Language) is the most common computer language for managing data in relational databases. With the power of SQL, you can insert, modify or remove data, and manage data tables.

Your First SQL Statement
To do anything with tables, you need to write a statement, also known as a query. A statement is a request written according to SQL syntax. Your statement should specify what data to select and how to process it. 

SELECT
The SELECT operator takes the selection of one or many rows or columns from a table. SELECT statements look like this:

-- Select columns from the table
SELECT 
    column_1,
    column_2, 
    column_3 ...  
FROM 
    table_name;
 Save
We have two keywords in our statement: SELECT and FROM. SELECT specifies the necessary columns from the database table. FROM specifies the table from which the data should be taken. To keep things tidy and easy to read, we indent the lines after operators. The statement ends with a semicolon  ;. The beginning of a single-line comment is marked with two hyphens:  --.

Note that commands are written in capital letters, and line breaks are inserted after each keyword. These are common, but not required, practices.

Now let's see how this statement works by trying to get data from columns in the Stock table:

Stock
ID	Name	Price	Amount
19960	Hermione Granger's wand	10	15
79789	Delorean DMC-12	500	7
51339	Luke Skywalker's lightsaber	15	3
16307	Daenerys Targaryen's necklace	20	2
-- Getting the columns containing names and prices from the Stock table
SELECT 
    Name, 
    Price
FROM 
    Stock;
 Save
Here's the result of our query:

Stock
Name	Price
Hermione Granger's wand	10
Delorean DMC-12	500
Luke Skywalker's lightsaber	15
Daenerys Targaryen's necklace	20
To select all columns from the table, add  * to the SELECT operator:

SELECT 
    *
FROM 
    Stock;
 Save
To add a condition to our query, we'll use the WHERE operator:

SELECT 
    *
FROM 
    Stock
WHERE 
    Price < 100; -- Defining the condition of row selection
 Save
The order of operators is strictly defined:

1)SELECT 

2)FROM

3)WHERE

The query above will return the following result:

Stock
ID	Name	Price	Amount
19960	Hermione Granger's wand	10	15
51339	Luke Skywalker's lightsaber	15	3
16307	Daenerys Targaryen's necklace	20	2
PostgreSQL: Using Relational Databases in Express.js Apps
If you decide to use relational databases for your application, you'll need to choose an appropriate database management system (DBMS) and use its Node.js driver to connect it to your app.

We recommend using PostgreSQL (or Postgres), a free and open-source relational database management system. PostgreSQL is widely used by companies for their database needs.

Install the npm module called pg-promise first:

npm install pg-promise
 Save
pg-promise is a PostgreSQL client for Node.js that is based on a powerful query-formatting engine and supports methods that return a promise.

Connect your database to the Express.js app:

var pgp = require('pg-promise')(/* options */)
var db = pgp('postgres://username:password@host:port/database') //connect to your local databasw

db.one('SELECT $1 AS value', 123) //create a query to pull desired data
  .then(function (data) {
    console.log('DATA:', data.value)
  })
  .catch(function (error) {
    console.log('ERROR:', error)
  })
 Save
Going deeper into SQL
This lesson just covers the basics of SQL — do you want to know more? Perfect! We've prepared a completely free, self-paced course for SQL newcomers, chock full of helpful theory and exercises. Check SQL101 out!
Building Relationships
In the past, NoSQL entailed a completely non-relational approach to database creation. Over time, though, non-relational databases began to incorporate some of the strengths of the relational approach. One of these strengths is building relationships. In this lesson, we will learn how to set up relationships between models in MongoDB.

1. Building a Relationship Between Two Schemas
Building a relationship begins with a schema. 

Imagine an app that has two entities: users and ads. The user schema looks like this:

const userSchema = new mongoose.Schema({
  name: { // the user only has a name
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
});

module.exports = mongoose.model('user', userSchema);
 Save
Users can create ads that are defined by a title and a text field:

const adSchema = new mongoose.Schema({
  title: {
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
  text: {
    type: String,
    minlength: 2,
    required: true,
  },
});

module.exports = mongoose.model('ad', adSchema);
 Save
Now we'll need a way to assign an author to each advertisement. Let's make another field titled 'creator'. This field will store a link to the ad author.

An identifier is the best way to set up a relationship between documents. MongoDB automatically creates the _id field, which provides a unique identifier for each document and allows documents to be linked to one another.

To do this with schemas, the type property should be set to mongoose.Schema.Types.ObjectId. It should also have a ref property, which will contain the name of the model we are linking:

const adSchema = new mongoose.Schema({
  title: {
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
  text: {
    type: String,
    minlength: 2,
    required: true,
  },
  // add the creator field
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user',
    required: true
  },
});
 Save
2. Including the _id Field During Document Creation
In the previous step, we created a model and specified that there should be a customer document identifier in the creator field. Now we need to make sure this identifier is recorded in the creator field whenever a new ad is created:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.createAd = (req, res) => {
  const { title, text, creatorId } = req.body;

  Ad.create({ title, text, creator: creatorId })
    .then(ad => res.send({ data: ad }));
};
 Save
3. Acquiring Complete Information via the populate() Method
The two models are now linked. However, the ad schema only stores the user ID. To get all  information about the author of the ad, you'll need to use the populate() method by passing it the field name:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.getAds = (req, res) => {
  Ad.find({})
    .populate('creator')
    .then(ad => res.send({ data: ad }));
};
 Save
In order to send a response containing the multiple fields resulting from the relationships, we need to pass an array to the populate() method:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.getAds = (req, res) => {
  Ad.find({})
    .populate(['creator', 'followers'])
    .then(ad => res.send({ data: ad }));
};
 Save
Links
Find out more about relationships in this mongoose guide:

https://mongoosejs.com/docs/populate.html
Code Structuring. Controllers
In the previous lesson, we connected routes to our database. Now when a route receives a request, the database is examined and the user receives an answer:

// routes/users.js

const User = require('../models/user');

router.get('/:id', (req, res) => {
  // search the database
  User.findById(req.params.id)
    // return the found data to the user
    .then(user => res.send({ data: user }))
    // if the record was not found, display an error message
    .catch(err => res.status(500).send({ message: 'Error' }));
});

router.post('/', (req, res) => {
  const { name, about } = req.body;

  User.create({ name, about })
    .then(user => res.send({ data: user }))
    .catch(err => res.status(500).send({ message: 'Error' }));
});

// and so on
 Save
If you're using a lot of routes, they tend to get lost in the code. For convenience, we'll divide the code into two files: a controller file and a routes file. We'll also put the controller file into a separate folder named controllers.

// controllers/users.js
// this file is the user controller

const User = require('../models/user');

// the getUser request handler
module.exports.getUser = (req, res) => {
  User.findById(req.params.id)
    .then(user => res.send({ data: user }))
    .catch(err => res.status(500).send({ message: 'Error' }));
};

// the createUser request handler
module.exports.createUser = (req, res) => {
  const { name, about } = req.body;

  User.create({ name, about })
    .then(user => res.send({ data: user }))
    .catch(err => res.status(500).send({ message: 'Error' }));
};
 Save
// routes/users.js
// this is the routes file
    
const { getUser, createUser } = require('../controllers/users');

// route definitions
router.get('/:id', getUser)
router.post('/', createUser);
 Save
A controller is a collection of request handler functions responsible for interacting with a particular model (in this case, the User model). These handler functions can read, create, update, and delete documents, and send a response back to the client.

While the routes file defines the routes themselves, it passes off the actual handling of the request to the controller files, which is why the functions inside the controller are called "request handlers" or just "controller functions".

In Express, each request handler is often the last middleware executed, because instead of calling next(), it returns an answer to the user.

The controller file describes the logic of request processing, and the routes file determines when this logic should be applied depending on the requested path and HTTP method.
class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:
        
        intervals.sort(key=lambda x: x[0])
        res = [intervals[0]]

        for i in range(1, len(intervals)):
            # is overlapping
            if intervals[i][0] <= res[-1][1]:
                # merge and replace
                res[-1][1] = max(res[-1][1], intervals[i][1])
            else:
                res.append(intervals[i])

        return res




export function TailwindIndicator() {
  if (process.env.NODE_ENV === "production") return null

  return (
    <div className="fixed bottom-1 left-1 z-50 flex h-6 w-6 items-center justify-center rounded-full bg-gray-800 p-3 font-mono text-xs text-white">
      <div className="block sm:hidden">xs</div>
      <div className="hidden sm:block md:hidden">sm</div>
      <div className="hidden md:block lg:hidden">md</div>
      <div className="hidden lg:block xl:hidden">lg</div>
      <div className="hidden xl:block 2xl:hidden">xl</div>
      <div className="hidden 2xl:block">2xl</div>
    </div>
  )
}
class Solution:
    def minWindow(self, s: str, t: str) -> str:
        
        counts = Counter(t)

        def contains():
            return sum([x>0 for x in counts.values()]) == 0

        l = 0
        res = ""
        size = float('INF')
        for r in range(len(s)):
            if s[r] in counts:
                counts[s[r]] -= 1
                # print("R: ", s[r], counts)
                while l <= r and contains():
                    if contains() and r-l+1 < size:
                        size = r-l+1
                        res = s[l:r+1]
                    # print("record res:", res)
                    if s[l] in counts:
                        counts[s[l]] += 1
                        # print("remove L: ", s[l], counts, s[l:r+1])
                    l += 1
        return res


Creating, Reading, Updating and Deleting Documents
In the last lesson, we created a model which allows us to interact with our collection of documents. The user and card models allow you to manage the user and card collections respectively.

You can perform the following actions with the model:

Create: create()
Read: findById(), findOne(), find()
Update: findByIdAndUpdate(), findOneAndUpdate(), updateOne(), updateMany()
Delete: findByIdAndRemove(), findOneAndRemove(), delete(), deleteMany()
These four actions are abbreviated as CRUD, which represents a common set of tasks when dealing with data. Let's explore the most popular methods for each of them.

Creating Documents (C)
Documents can be created via the create() method. It accepts objects with data as input and records them to the database:

// routes/users.js

/*
    code for creating routers, etc.
*/

// import the model
const User = require('../models/user');

router.post('/', (req, res) => {
  const { name, about } = req.body; // get the name and description of the user

  User.create({ name, about }); // create a document based on the input data 
});
 Save
The create() method is like a promise in that you can add then() and catch() handlers to it. This is usually done to return the data or an error to the user:

// routes/users.js

/*
    code for creating routers, etc.
*/

const User = require('../models/user');

router.post('/', (req, res) => {
  const { name, about } = req.body;

  User.create({ name, about })
    // returns the recorded data
    .then(user => res.send({ data: user }))
    // data not recorded, prompting an error
    .catch(err => res.status(500).send({ message: 'Error' }));
});
 Save
Reading Documents (R)
This involves searching for documents and reading data from them if found. There are many ways to find a document, the three most popular being findById(), findOne() and find().

Searching for a specific document: The findById() method uses the identifier to do this, i.e. the _id property that is assigned to each document in MongoDB. To find a specific document, pass the findById() identifier to the method in the form of a string:
// routes/users.js

/*
    code for creating routers, etc.
*/

const User = require('../models/user');

router.get('/:id', (req, res) => {
    User.findById(req.params.id)
        .then(user => res.send({ data: user }))
        .catch(err => res.status(500).send({ message: 'Error' }));
});
 Save
Searching for one document by specific parameters: The findOne() method returns the first document that matches the request parameters:
// find the first match with a field that equals "Elise Taylor"
User.findOne({ name: 'Elise Taylor' });
 Save
Searching all documents by specific parameters: The find() method works the same way as the findOne() method, except that it returns all documents that match the request parameters:
// find all 30-year-old users
User.find({ age: 30 });

// find all users
User.find({});
 Save
Updating Documents (U)
This is similar to reading but includes an extra step. When we update documents, first we find an entry, then we change its properties.

You can use the findByIdAndUpdate() method to update a specific document. It accepts an identifier in string form as the first argument. The second argument is an object with the properties that need to be updated:

  // routes/users.js

  // ...

  const User = require('../models/user');

  router.patch('/:id', (req, res) => {
    // updating the name of the user found by _id
    User.findByIdAndUpdate(req.params.id, { name: 'Henry George' })
      .then(user => res.send({ data: user }))
      .catch(err => res.status(500).send({ message: 'Error' }));
  });
  
 Save
You can also find the first match for the request and update it. This is done using the  findOneAndUpdate() method, which accepts two objects as arguments. The first argument is the object we're looking for, and the second argument is the updated object:

  // find the first match with the name field that equals to "Sam Taylor" and replace is with "Henry George"
  User.findOneAndUpdate({ name: 'Sam Taylor' }, { name: 'Henry George' }));
  
 Save
You can also turn every 'Sam Taylor' into 'Henry George' using the updateMany() method:

  // find all matches with the name field that equals to "Sam Taylor" and replace it with "Henry George"
  User.updateMany({ name: 'Sam Taylor' }, { name: 'Henry George' });
  
 Save
These update methods come with a caveat. By default, the parameter that the handler receives as input is the original document before the update:

User.findByIdAndUpdate(req.params.id, { name: 'Henry George' })
  // user here means the document before the update
  .then(user => res.send({ data: user }));
 Save
Fortunately, there's a way to change this. All these methods can take a third argument, which is an options object. We are interested in these three options:

Option	Description	Default Value
new	pass the updated object as input to the then() handler	false
runValidators	validate the new data before recording it into the database	false
upsert	if the document wasn't found, create it	false
Thanks to the options object, we can transfer an updated record to the then() handler. We can also set up validation or create a document if it was not found:

User.findByIdAndUpdate(
    req.params.id,
    { name: 'Henry George' },
    // pass the options object:
    {
        new: true, // the then handler receives the updated entry as input
        runValidators: true, // the data will be validated before the update 
        upsert: true // if the user entry wasn't found, it will be created
    }
)
  .then(user => res.send({ data: user }))
  .catch(user => res.send({ 'Data validation failed or another error occured.' }));
 Save
Deleting Documents (D)
Deleting a specific document: You can do this by using the findByIdAndRemove() method:
// routes/users.js

// ...

const User = require('../models/user');

router.delete('/:id', (req, res) => {
    User.findByIdAndRemove(req.params.id)
        .then(user => res.send({ data: user }))
        .catch(err => res.status(500).send({ message: 'Error' }));
});
 Save
Deleting the first match: Use findOneAndRemove():
// delete a user with a specific name
User.findOneAndRemove({ name: 'Sam Taylor' });
 Save
Delete all matches: To do this, call deleteMany():
// delete all 30-year-old users
User.deleteMany({ age: 30 });
 Save
Links
We've listed the most popular methods in this lesson, but there are many others available for working with mongoose models. You can find them all in this guide:

https://mongoosejs.com/docs/api/model.html
Creating a Schema
In the REST API, data is represented through resources, which correspond to users and cards in the "Around the U.S." project. Each of these resources must correlate with a predetermined structure. For example, every user has a name along with other information about themselves. Let's have a go at setting up a schema for a user via Mongoose. We do this using the mongoose.Schema() constructor to create a new instance of the schema:

// models/user.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { // every user has a name field, the requirements for which are described below:
    type: String, // the name is a string
    required: true, // every user has a name, so it's a required field
    minlength: 2, // the minimum length of the name is 2 characters
    maxlength: 30, // the maximum length is 30 characters
  },
  pronouns: {
    type: String, // the pronouns are a string
    enum: ['they/them', 'she/her', 'he/him', 'other pronouns'] // every user can choose their pronouns
  },
  about: String, // type: String
});
 Save
This schema ensures that every user in the system has:

a name between 2 and 30 characters long
pronouns that can take one of the four assigned values
an about property, which is a string
You probably noticed the enum option that Mongoose uses. Enumerations are special data types that restrict a variable to take only one value from a predefined set. In Mongoose schemas, enum type adds a validator to the field which checks whether it's strictly equal to one of the unique values of a specific array.

Sometimes, the standard features of a schema are insufficient for ensuring that data is entered correctly, but Mongoose provides more precise ways of validating information. For example, we can make use of the validation property. This property is an object, which in turn includes the following properties:

validator — a validation function. It returns a boolean value.
message — an error message. It is rendered if the validator function returns false.
Here's an example. Let's add the age property to the userSchema and restrict its value from being anything less than 18: 

// models/user.js
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  name: { // every user has a name field, the requirements for which are described below:
    type: String, // the name type is a string
    required: true, // every user has a name, so it's a required field
    minlength: 2, // the minimum length of the name is 2 characters
    maxlength: 30, // the maximum length is 30 characters
  },
  pronouns: {
    type: String, // the pronouns are a string
    enum: ['they/them', 'she/her', 'he/him', 'other pronouns'] // every user can choose their pronouns
  },
    age: { // every user has an age field
        type: Number, // the age type is a number
        required: true, // the user has to specify their age
        validate: { // describe the validate feature
            validator(v) { // validator is a data validation feature. v is the age value
                return v >= 18; // if the age is less than 18, it will return false
            },
            message: 'Sorry. You have to be at least 18 years old', // when the validator returns false, this message will be displayed
        }
    },
  about: String, // type: String
});
 Save
This is a very basic form of validation. We can do much more complex validation using regular expressions, which we'll learn about in the next chapter.

Anyway, let's go back to data types. When creating schemas, we will be using 5 basic data types:

String 
Number
Date 
Boolean // logic: true or false
Array 
 Save
Subdocuments
If you use another schema as a property of your schema, you'll have to use the Schema method twice:

the first call is needed to create a schema that will describe the property's structure
the second call will pass the schema to the property. It should have the following structure:
// models/user.js

const mongoose = require('mongoose');

// create a schema for the "Pet" document 
const petSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 30,
  },
  age: Number
});
// once the schema is ready, pass it to the property which should correspond to this template:
const userSchema = new mongoose.Schema({
  ...
  pet: petSchema // describe the pet property with this schema
});
 Save
Array Properties
Arrays are used to store multiple data items of the same type. This is why the schema of an array is a schema for a single array element inside square brackets:

// models/user.js

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  ...
  hobbies: [{ // describe the schema for a single element and put it in square brackets
    type: String,
    minlength: 2,
    maxlength: 30,
  }]
});
 Save
This schema defines the hobbies property. It must contain an array of strings, each one from 2 to 30 characters in length.

Creating a Model Based on a Schema
Our schema now describes what a database document should look like. Let's proceed to the next stage, which is creating the documents themselves. To do this, we will build a model based on the schema.

A model is basically a wrapper around the schema. It enables us to read, add, delete, and update documents. The mongoose.model() method is used to create models in Mongoose:

// models/user.js

const mongoose = require('mongoose');
// Describe the schema:
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 30,
  },
  about: String,
});

// create the model and export it
module.exports = mongoose.model('user', userSchema);
 Save
We passed two arguments to the mongoose.model method: the name of the model and the schema which will describe future documents. 

It can get a little confusing at this point, so let's go over this again. The first argument (the name of the model) must be a singular noun. However, Compass displays it as a plural. This is because Mongoose automatically adds an 's' at the end of the collection name:


'user' has become 'users'

Recap: Model Creation
Set the API resources
Describe the resource schemas
Create models based on the schemas
Once the models are ready, you can use them to interact with the database i.e., to create, edit, and delete documents. We'll get to this in the next lesson. 

Additional links
Schema types in Mongoose: https://mongoosejs.com/docs/schematypes.html

More information about schemas: https://mongoosejs.com/docs/guide.html
to "about me:"

<style>
.online { visibility: hidden; } .online img { content: url("https://64.media.tumblr.com/b8fc75e9138e37bfb64a26a7fa5986d0/2876fd94cc96fa58-6d/s75x75_c1/906bfaf54646edadab980865f05d588e416b50ea.gifv"); animation-name: none; visibility: visible; height: 20px; width: 20px; 
</style>

<style>
body {

        background: url("https://64.media.tumblr.com/e50018944f93ddc93783489a47653fff/tumblr_nspfvo8j4I1sgurego1_540.gif");

        background-size: 2000px;       

        background-attachment:no-repeat;
</style>

<style>
.profile-pic {
    background: #fff;
    padding: 5px 5px 196px;
    box-shadow: 3px 3px 10px silver;
</style>

<style>
 main {
  background-color: #121212;
  color: #121212;
</style>


<style>
.profile .friends .comments-table td {
  background-color: #ffffff;
}
</style>


<style>
p {
color: #e0d7d9;
}
</style>

<style>
@import url("https://fonts.googleapis.com/css?family=Creepster");

.w-40 h1{
font-family: Creepster;
font-size: 40px;
text-align: center;
background: -webkit-linear-gradient(#ffffff, #ffffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
</style>

<style>
.profile .contact .heading, .profile .table-section .heading, .home-actions .heading {
  background-color: #444;
  color: #bbb;
</style>

<style>
:root {
    --logo-blue: #1c1c1c;
</style>

<style>
.profile .contact,
.profile .url-info,
.profile .table-section,
.home-actions {
    border: none;
</style>

<style>
* a {
color:#f0f0f0 !important;
}

a * {
color:#f0f0f0 !important;
}
?
If not, to change just those links specifically, try this:

div.contact a { color:#f0f0f0;}
</style>


<style>
.blurbs .inner .section:first-of-type h4{
	font-size:0;
}
.blurbs .inner .section:first-of-type h4:after{
	content:"About Me:";
font-size:.8rem;
}
.blurbs .inner .section:last-of-type h4{
font-size:0;
}
.blurbs .inner .section:last-of-type h4:after{
content:"Who I'd Like To Meet:";
font-size:.8rem;
}
</style>

<style>
.profile .blurbs .heading, .profile .friends .heading {
  background-color: #050505;
  color: #f5f5f5;
}
</style>

<style> 
.profile .table-section .details-table td {   background-color: #1a1a1a;   color: #1a1a1a; } </style>

<style>
.logo{content:url("); animation-name: none; visibility: visible; height: 20px; width: 20px;
}
</style>

<style>

  .blurbs .heading{ font-size:0; }

.blurbs .heading:before{ content: "𖦹 𝐖𝐞𝐥𝐜𝐨𝐦𝐞 𝐭𝐨 𝐭𝐡𝐞 𝐕𝐨𝐫𝐭𝐞𝐱 𝐂𝐥𝐮𝐛 ~"; font-size:.8rem; font-weight:bold; color:insert color; }

</style>

<style>
--darker-blue: #7d2020;
</style>

<style>
 --lightest-blue: #7d2020;
</style>

<style>
   --lighter-blue: #7d2020;
</style>

<style>
  --even-lighter-blue: #7d2020;
</style>

<style>
nav .links {
    background-image:url(https://i.pinimg.com/564x/b8/6d/5c/b86d5c425d2cfc7f04d22f39fe10bad0.jpg);
    padding: 3.5px 16px 5.5px 16px;
}
</style>

<style>
nav .links a{
   color: #4f4f4f;
}
</style>

<style>
li.active .icon { content:url('https://gifcity.carrd.co/assets/images/gallery92/e9c997f9.gif?v=26dffab5'); width: 20PX;height: 20px;}
</style>

<style>
img.logo{
content: url("https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5");
width: 40px !important;
height: 40px !important;
</style>

<style>
.contact .inner a img {

font-size: 0;

}

.contact .inner a img:before {

font-size: 1em;

display: block

}

.contact .inner .f-row:nth-child(1) .f-col:nth-child(1) a:before {

*add to friends*

content: url("https://gifcity.carrd.co/assets/images/gallery92/60b334b8.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(1) .f-col:nth-child(2) a:before {

*add to favorites*

content: url("https://gifcity.carrd.co/assets/images/gallery92/27aa4253.png?v=26dffab5")

}

.contact .inner .f-row:nth-child(2) .f-col:nth-child(1) a:before {

*send message*

content: url("https://gifcity.carrd.co/assets/images/gallery92/e7af8c6b.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(2) .f-col:nth-child(2) a:before {

*forward to friend*

content: url("https://gifcity.carrd.co/assets/images/gallery92/d7a03eb6.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(3) .f-col:nth-child(1) a:before {

*instant message*

content: url("https://gifcity.carrd.co/assets/images/gallery10/85c18b66.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(3) .f-col:nth-child(2) a:before {

*block user*

content: url("https://gifcity.carrd.co/assets/images/gallery92/60b334b8.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(4) .f-col:nth-child(1) a:before {

*add to group*

content: url("https://gifcity.carrd.co/assets/images/gallery92/a3c39389.png?v=26dffab5")

}

.contact .inner .f-row:nth-child(4) .f-col:nth-child(2) a:before {

*report user*

content: url("https://gifcity.carrd.co/assets/images/gallery92/f94e6961.gif?v=26dffab5")

}
</style>

<style>main:before {
	width: 100%;
	height: 150px ;
	display: block;
	content: "";
	background-image: url('https://64.media.tumblr.com/5ce6eb03f09ed2e74823663728192182/9bc07afd2e4604e8-b8/s540x810/81932368e7d14229eac3b0552793b9ac7fbe1bfc.jpg');
	background-position: center center;
	background-size: cover;
}
@media only screen and (max-width: 600px) {
	main:before{
		height: 150px;
	}
}</style>

<style>
.profile-pic img,.friends-grid img,.comments-table img{border-radius:5px;}
</style>

<style>* {cursor: url(https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5), url(https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5), auto !important;}</style>

<style>
@import url('https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@700&family=Roboto:wght@700&display=swap');
p{
font-family: 'Josefin Sans', sans-serif;
text-transform:lowercase !important;
color:#ffedf9;
}

<style>
footer {
border-radius: 15px; background-image: url(https://i.pinimg.com/736x/1e/d9/8e/1ed98e5a5698a153c46b617b6e1f11b1.jpg);
 color: black;
}
</style>

<style>
body:before {

content: " ";

height: 100vh;

width: 100vw;

display: block;

position: fixed; 

top: 0; 

left: 0; 

z-index: 100;

background-image: url('https://s6.ezgif.com/tmp/ezgif-6-b1665aeafb.gif');

background-size: cover;

background-repeat: no-repeat;

background-position:center;

animation: yourAnimation 1s ease 1s 1 normal forwards;

pointer-events: none;}

@keyframes yourAnimation { 0.0%{ opacity: 1;} 75%{ opacity: 1; } 100%{ opacity: 0;} } 
</style>

<style>
<div style="float:  ; max-height: 400px; position: fixed; left: 1px; bottom: 9px; z-index: 200;">

<style>
<img src="https://64.media.tumblr.com/da0a2e73793f9b0b3673fc2aefda8e02/d7da8c3f0d487409-20/s500x750/7d46ef6d3ecb28d8425bd8f9aec51bbf7997c0b7.pnj" width="250" height="250"/>
</style>

<style>
.profile .friends .person img:not(.icon):hover {
    transform: scale(1.2);
    transition: 0.5s ease;
}
.profile .friends .person img:not(.icon) {
    transition: 0.5s ease
}
</style>

<style>
.general-about .profile-pic:not(.icon):hover {
    transform: scale(1.2);rotate(-3deg);
    transition: 0.5s ease;
}
</style>

<style>
.profile-pic > img { display:none; }
.profile-pic:after { background-image: url("https://s5.ezgif.com/tmp/ezgif-5-5321953d6e.webp"); display: inline-block; content:"" }
.blog-entry .profile-pic:after, .bulletin .profile-pic:after { background-size: cover; width: 110px; height: 110px; } /* blogs, bulletins */
.general-about .profile-pic:after { background-size: cover; width: 160px; height: 160px; } /* profile */ 
</style>

<style>
.profile .friends .comments-table td {
  background-color: #121212;
}
</style>

<style>
@import url("https://robins.one/spacehey/addons/modern-comments.css");
</style>

<style>

{

  animation: type 3s steps(27);


  }



@keyframes type{

  0%{

    width:0ch;

  }

  

  100%{

    width:27ch;

  }

}



@keyframes blink{

  0%{opacity:1;}

  50%{opacity:0;}

  100%{opacity:1;}

}



.col, main, footer, nav::before, .online, nav .links, nav .top {

animation: float 4s;

animation-iteration-count: infinite;

animation-timing-function: ease-in-out;

}



.col, main, footer, nav::before, .online, nav .links, nav .top {

animation: float 4s;

animation-iteration-count: infinite;

animation-timing-function: ease-in-out;

}

@keyframes float {

0% { transform: translate(0, 0px);

}

50% {

transform: translate(0, 8px);

}

100% {

transform: translate(0, -0px);

}
</style>

  to "who i'd like to meet"
  
  <style>
 .blurbs .section h4{display: none !important;}
</style>
<p>
<img src="https://64.media.tumblr.com/d4ddf5c1d1c654e58e746ccefe6c5a68/0f39a7bc6fa5cf02-02/s1280x1920/ee775c60c166eb7ddc279bd3fd994d8970db490d.pnj" width=""/>
</p>
<img src="https://64.media.tumblr.com/791a54bc6cccd06a8b49438af7f2e727/378cc34521d8aa11-bb/s500x750/aebf82d480ec7218f4a330f61b69ff9f5b1efdf4.jpg"/>


<iframe width="0" height="0" src="https://www.youtube.com/embed/2IIERc-XOqw?si=xNCfPn9dbkqtxygE//?&;amp;;autoplay=1&;loop=1&;controls=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy">
</iframe>
  
  to "general interests"
  
  <img src="https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/1ec254ab-132a-4934-bf16-749c7fbe46c5/d8htei8-3636b3f9-1022-4168-8c14-48f82c838a78.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwiaXNzIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsIm9iaiI6W1t7InBhdGgiOiJcL2ZcLzFlYzI1NGFiLTEzMmEtNDkzNC1iZjE2LTc0OWM3ZmJlNDZjNVwvZDhodGVpOC0zNjM2YjNmOS0xMDIyLTQxNjgtOGMxNC00OGY4MmM4MzhhNzgucG5nIn1dXSwiYXVkIjpbInVybjpzZXJ2aWNlOmZpbGUuZG93bmxvYWQiXX0.e3ULvZCBqsV9PULN0ZLfcm4TsNhu6YwyWoU75R1Rlvw"/>
function current_year_shortcode() {
    $current_year = date('Y');
    return $current_year;
}
add_shortcode('current_year', 'current_year_shortcode');
import Upscaler from 'upscaler';
const upscaler = new Upscaler();
upscaler.upscale('/path/to/image').then(upscaledImage => {
  console.log(upscaledImage); // base64 representation of image src
});
terraform {

   required_version = ">=0.12"

   required_providers {
     azurerm = {
       source = "hashicorp/azurerm"
       version = "~>2.0"
     }
   }
 }

 provider "azurerm" {
   features {}
 }

 resource "azurerm_resource_group" "test" {
   name     = "acctestrg"
   location = "West US 2"
 }

 resource "azurerm_virtual_network" "test" {
   name                = "acctvn"
   address_space       = ["10.0.0.0/16"]
   location            = azurerm_resource_group.test.location
   resource_group_name = azurerm_resource_group.test.name
 }

 resource "azurerm_subnet" "test" {
   name                 = "acctsub"
   resource_group_name  = azurerm_resource_group.test.name
   virtual_network_name = azurerm_virtual_network.test.name
   address_prefixes     = ["10.0.2.0/24"]
 }

 resource "azurerm_public_ip" "test" {
   name                         = "publicIPForLB"
   location                     = azurerm_resource_group.test.location
   resource_group_name          = azurerm_resource_group.test.name
   allocation_method            = "Static"
 }

 resource "azurerm_lb" "test" {
   name                = "loadBalancer"
   location            = azurerm_resource_group.test.location
   resource_group_name = azurerm_resource_group.test.name

   frontend_ip_configuration {
     name                 = "publicIPAddress"
     public_ip_address_id = azurerm_public_ip.test.id
   }
 }

 resource "azurerm_lb_backend_address_pool" "test" {
   loadbalancer_id     = azurerm_lb.test.id
   name                = "BackEndAddressPool"
 }

 resource "azurerm_network_interface" "test" {
   count               = 2
   name                = "acctni${count.index}"
   location            = azurerm_resource_group.test.location
   resource_group_name = azurerm_resource_group.test.name

   ip_configuration {
     name                          = "testConfiguration"
     subnet_id                     = azurerm_subnet.test.id
     private_ip_address_allocation = "dynamic"
   }
 }

 resource "azurerm_managed_disk" "test" {
   count                = 2
   name                 = "datadisk_existing_${count.index}"
   location             = azurerm_resource_group.test.location
   resource_group_name  = azurerm_resource_group.test.name
   storage_account_type = "Standard_LRS"
   create_option        = "Empty"
   disk_size_gb         = "1023"
 }

 resource "azurerm_availability_set" "avset" {
   name                         = "avset"
   location                     = azurerm_resource_group.test.location
   resource_group_name          = azurerm_resource_group.test.name
   platform_fault_domain_count  = 2
   platform_update_domain_count = 2
   managed                      = true
 }

 resource "azurerm_virtual_machine" "test" {
   count                 = 2
   name                  = "acctvm${count.index}"
   location              = azurerm_resource_group.test.location
   availability_set_id   = azurerm_availability_set.avset.id
   resource_group_name   = azurerm_resource_group.test.name
   network_interface_ids = [element(azurerm_network_interface.test.*.id, count.index)]
   vm_size               = "Standard_DS1_v2"

   # Uncomment this line to delete the OS disk automatically when deleting the VM
   # delete_os_disk_on_termination = true

   # Uncomment this line to delete the data disks automatically when deleting the VM
   # delete_data_disks_on_termination = true

   storage_image_reference {
     publisher = "Canonical"
     offer     = "UbuntuServer"
     sku       = "16.04-LTS"
     version   = "latest"
   }

   storage_os_disk {
     name              = "myosdisk${count.index}"
     caching           = "ReadWrite"
     create_option     = "FromImage"
     managed_disk_type = "Standard_LRS"
   }

   # Optional data disks
   storage_data_disk {
     name              = "datadisk_new_${count.index}"
     managed_disk_type = "Standard_LRS"
     create_option     = "Empty"
     lun               = 0
     disk_size_gb      = "1023"
   }

   storage_data_disk {
     name            = element(azurerm_managed_disk.test.*.name, count.index)
     managed_disk_id = element(azurerm_managed_disk.test.*.id, count.index)
     create_option   = "Attach"
     lun             = 1
     disk_size_gb    = element(azurerm_managed_disk.test.*.disk_size_gb, count.index)
   }

   os_profile {
     computer_name  = "hostname"
     admin_username = "testadmin"
     admin_password = "Password1234!"
   }

   os_profile_linux_config {
     disable_password_authentication = false
   }

   tags = {
     environment = "staging"
   }
 }
  
<style>
.profile {

background: #ab9b90; opacity: 0.8;

 }
</style>

<style>
.general-about {

 background:#94857b;

  border-radius: 15px;
</style>

<style>
.friends:not(#comments) {

  grid-area: friends;

  background:#8f847c;  

  border-radius: 15px

}

</style>

<style>
.profile .friends td {

  background: #94857b;

  border-radius: 15px

} 

</style>

<style>
.profile .table-section .details-table td {
  background-color: #8f847c;
  color: #blue;
}

.profile .blurbs .heading, .profile .friends .heading {
  background-color:#7d7169;
  color: #bbb;
</style>

<style>
.profile-pic {

border-radius: 500px;

overflow: hidden;

}


.profile .friends .person img {

border-radius: 500px;

}
</style>

<style>
.profile .contact, .profile .table-section, .profile .url-info {
  border: 4px solid #8f847c;
</style>

<style>
.profile .contact .heading, .profile .table-section .heading, .home-actions .heading {
  background-color: #8f847c;
  color: #bbb;
}
</style>

<style>
body {
     background-image: url("https://images4.alphacoders.com/685/685747.jpg") !important;
     background-color: black !important;
     background-attachment: fixed !important;
     margin: 0;
     padding: 0;
}
</style>

<style>
main a {
  color: var(--black);
}
</style>

<style>
p {
color: #403b37;
}
</style>

<style>
@import url("https://fonts.googleapis.com/css2?family=Gochi+Hand&display=swap");

.w-40 h1{
font-family: Gochi Hand;
font-size: 40px;
text-align: center;
background: -webkit-linear-gradient(#ffffff, #ffffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
-webkit-text-stroke: ;
}
</style>

<style>
@import url('https://fonts.googleapis.com/css2?family=Gochi+Hand&display=swap');
p{
  font-family: 'Gochi Hand', cursive;
  font-size: 150%;
}
h1,h2,h3,h4,h5{
  font-family: 'Gochi Hand', cursive;
  font-size: 120%;  
</style>

<style>
:root {
    --logo-blue: transparent;
</style>

<style>
:root {
   --lighter-blue: url("https://i.pinimg.com/564x/d6/a8/9a/d6a89aee36a02bd2a33577ab084cdde4.jpg"); 
</style>

<style>
main:before {
	width: 100%;
	height: 130px;
	display: block;
	content: "";
	background-image: url('https://i.pinimg.com/564x/9d/e0/84/9de0846eb7b19356cc4b58c6b4d27b96.jpg');
	background-position: center center;
</style>

<style>
	background-size: cover;
}
@media only screen and (max-width: 600px) {
	main:before{
		height: 130px;
	}
}
</style>

<style>

 .blurbs .section h4{display: none !important;}

</style>

<style>

.contact .inner a img {

font-size: 0;

}

.contact .inner a img:before {

font-size: 1em;

display: block

}

</style>

<img src="https://i.pinimg.com/564x/d6/a8/9a/d6a89aee36a02bd2a33577ab084cdde4.jpg"/>

<img src="https://i.pinimg.com/564x/08/31/04/08310477513b325942fd418e0344359b.jpg"/>


<style>

  .blurbs .heading{ font-size:0; }

.blurbs .heading:before{ content: "❝Everything is a picture waiting to be taken...❞ "; font-size:.8rem; font-weight:bold; color:insert color; }
</style>

<style>
.friends#comments .heading{ font-size:0; }

.friends#comments .heading:before{ content: "Comments!!"; font-size:.8rem; font-weight:bold; }
</style>

<style>
img.logo{
content: url("https://gifcity.carrd.co/assets/images/gallery06/9e454399.gif?v=26dffab5");
width: 50px !important;
height: 50px !important;
</style>

<style>
.online { visibility: hidden; } .online img { content: url("https://s4.ezgif.com/tmp/ezgif-4-3af269179e.gif"); animation-name: none; visibility: visible; height: 40px; width: 40px; 
</style>

<style>
li.active .icon { content:url('https://gifcity.carrd.co/assets/images/gallery92/a3c39389.png?v=26dffab5'); width: 20PX;height: 20px;}
</style>

<style>
.profile .friends .person img:not(.icon):hover {
    transform: scale(1.2);
    transition: 0.5s ease;
}
.profile .friends .person img:not(.icon) {
    transition: 0.5s ease
}
</style>

<style>
body:before {

content: " ";

height: 100vh;

width: 100vw;

display: block;

position: fixed; 

top: 0; 

left: 0; 

z-index: 100;

background-image: url('https://s6.ezgif.com/tmp/ezgif-6-b1665aeafb.gif');

background-size: cover;

background-repeat: no-repeat;

background-position:center;

animation: yourAnimation 1s ease 1s 1 normal forwards;

pointer-events: none;}

@keyframes yourAnimation { 0.0%{ opacity: 1;} 75%{ opacity: 1; } 100%{ opacity: 0;} } 
</style>

<style>* {cursor: url(http://www.rw-designer.com/cursor-view/110065.png), url(http://www.rw-designer.com/cursor-view/110065.png), auto !important;}</style>

<iframe width="0" height="0" src="https://www.youtube.com/embed/AoHFCLxTkE4?si=EuMz_QDerHQwZrky//?&;amp;;autoplay=1&;loop=1&;controls=1" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy">

</iframe>
<style>
.online { visibility: hidden; } .online img { content: url("https://64.media.tumblr.com/b8fc75e9138e37bfb64a26a7fa5986d0/2876fd94cc96fa58-6d/s75x75_c1/906bfaf54646edadab980865f05d588e416b50ea.gifv"); animation-name: none; visibility: visible; height: 20px; width: 20px; 
</style>

<style>
body {

        background: url("https://64.media.tumblr.com/e50018944f93ddc93783489a47653fff/tumblr_nspfvo8j4I1sgurego1_540.gif");

        background-size: 2000px;       

        background-attachment:no-repeat;
</style>

<style>
.profile-pic {
    background: #fff;
    padding: 5px 5px 196px;
    box-shadow: 3px 3px 10px silver;
</style>

<style>
 main {
  background-color: #121212;
  color: #121212;
</style>


<style>
.profile .friends .comments-table td {
  background-color: #ffffff;
}
</style>


<style>
p {
color: white;
}
</style>

<style>
@import url("https://fonts.googleapis.com/css?family=Creepster");

.w-40 h1{
font-family: Creepster;
font-size: 40px;
text-align: center;
background: -webkit-linear-gradient(#ffffff, #ffffff);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
</style>

<style>
.profile .contact .heading, .profile .table-section .heading, .home-actions .heading {
  background-color: #444;
  color: #bbb;
</style>

<style>
:root {
    --logo-blue: #1c1c1c;
</style>

<style>
.profile .contact,
.profile .url-info,
.profile .table-section,
.home-actions {
    border: none;
</style>

<style>
* a {
color:#f0f0f0 !important;
}

a * {
color:#f0f0f0 !important;
}
?
If not, to change just those links specifically, try this:

div.contact a { color:#f0f0f0;}
</style>


<style>
.blurbs .inner .section:first-of-type h4{
	font-size:0;
}
.blurbs .inner .section:first-of-type h4:after{
	content:"About Me:";
font-size:.8rem;
}
.blurbs .inner .section:last-of-type h4{
font-size:0;
}
.blurbs .inner .section:last-of-type h4:after{
content:"Who I'd Like To Meet:";
font-size:.8rem;
}
</style>

<style>
.profile .blurbs .heading, .profile .friends .heading {
  background-color: #050505;
  color: #f5f5f5;
}
</style>

<style> 
.profile .table-section .details-table td {   background-color: #1a1a1a;   color: #1a1a1a; } </style>

<style>
.logo{content:url("); animation-name: none; visibility: visible; height: 20px; width: 20px;
}
</style>

<style>

  .blurbs .heading{ font-size:0; }

.blurbs .heading:before{ content: "𖦹 𝐖𝐞𝐥𝐜𝐨𝐦𝐞 𝐭𝐨 𝐭𝐡𝐞 𝐕𝐨𝐫𝐭𝐞𝐱 𝐂𝐥𝐮𝐛 ~"; font-size:.8rem; font-weight:bold; color:insert color; }

</style>

<style>
--darker-blue: #7d2020;
</style>

<style>
 --lightest-blue: #7d2020;
</style>

<style>
   --lighter-blue: #7d2020;
</style>

<style>
  --even-lighter-blue: #7d2020;
</style>

<style>
nav .links {
    background-image:url(https://i.pinimg.com/564x/b8/6d/5c/b86d5c425d2cfc7f04d22f39fe10bad0.jpg);
    padding: 3.5px 16px 5.5px 16px;
}
</style>

<style>
nav .links a{
   color: #4f4f4f;
}
</style>

<style>
li.active .icon { content:url('https://gifcity.carrd.co/assets/images/gallery92/e9c997f9.gif?v=26dffab5'); width: 20PX;height: 20px;}
</style>

<style>
img.logo{
content: url("https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5");
width: 40px !important;
height: 40px !important;
</style>

<style>
.contact .inner a img {

font-size: 0;

}

.contact .inner a img:before {

font-size: 1em;

display: block

}

.contact .inner .f-row:nth-child(1) .f-col:nth-child(1) a:before {

*add to friends*

content: url("https://gifcity.carrd.co/assets/images/gallery92/60b334b8.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(1) .f-col:nth-child(2) a:before {

*add to favorites*

content: url("https://gifcity.carrd.co/assets/images/gallery92/27aa4253.png?v=26dffab5")

}

.contact .inner .f-row:nth-child(2) .f-col:nth-child(1) a:before {

*send message*

content: url("https://gifcity.carrd.co/assets/images/gallery92/e7af8c6b.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(2) .f-col:nth-child(2) a:before {

*forward to friend*

content: url("https://gifcity.carrd.co/assets/images/gallery92/d7a03eb6.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(3) .f-col:nth-child(1) a:before {

*instant message*

content: url("https://gifcity.carrd.co/assets/images/gallery10/85c18b66.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(3) .f-col:nth-child(2) a:before {

*block user*

content: url("https://gifcity.carrd.co/assets/images/gallery92/60b334b8.gif?v=26dffab5")

}

.contact .inner .f-row:nth-child(4) .f-col:nth-child(1) a:before {

*add to group*

content: url("https://gifcity.carrd.co/assets/images/gallery92/a3c39389.png?v=26dffab5")

}

.contact .inner .f-row:nth-child(4) .f-col:nth-child(2) a:before {

*report user*

content: url("https://gifcity.carrd.co/assets/images/gallery92/f94e6961.gif?v=26dffab5")

}
</style>

<style>main:before {
	width: 100%;
	height: 150px ;
	display: block;
	content: "";
	background-image: url('https://64.media.tumblr.com/5ce6eb03f09ed2e74823663728192182/9bc07afd2e4604e8-b8/s540x810/81932368e7d14229eac3b0552793b9ac7fbe1bfc.jpg');
	background-position: center center;
	background-size: cover;
}
@media only screen and (max-width: 600px) {
	main:before{
		height: 150px;
	}
}</style>

<style>
.profile-pic img,.friends-grid img,.comments-table img{border-radius:5px;}
</style>

<style>* {cursor: url(https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5), url(https://gifcity.carrd.co/assets/images/gallery10/aa81d95b.gif?v=26dffab5), auto !important;}</style>

<style>
@import url('https://fonts.googleapis.com/css2?family=Josefin+Sans:wght@700&family=Roboto:wght@700&display=swap');
p{
font-family: 'Josefin Sans', sans-serif;
text-transform:lowercase !important;
color:#ffedf9;
}

<style>
footer {
border-radius: 15px; background-image: url(https://i.pinimg.com/736x/1e/d9/8e/1ed98e5a5698a153c46b617b6e1f11b1.jpg);
 color: black;
}
</style>

<style>
body:before {

content: " ";

height: 100vh;

width: 100vw;

display: block;

position: fixed; 

top: 0; 

left: 0; 

z-index: 100;

background-image: url('https://s6.ezgif.com/tmp/ezgif-6-b1665aeafb.gif');

background-size: cover;

background-repeat: no-repeat;

background-position:center;

animation: yourAnimation 1s ease 1s 1 normal forwards;

pointer-events: none;}

@keyframes yourAnimation { 0.0%{ opacity: 1;} 75%{ opacity: 1; } 100%{ opacity: 0;} } 
</style>

<style>
<div style="float:  ; max-height: 400px; position: fixed; left: 1px; bottom: 9px; z-index: 200;">

<style>
<img src="https://64.media.tumblr.com/da0a2e73793f9b0b3673fc2aefda8e02/d7da8c3f0d487409-20/s500x750/7d46ef6d3ecb28d8425bd8f9aec51bbf7997c0b7.pnj" width="250" height="250"/>
</style>

<style>
.profile .friends .person img:not(.icon):hover {
    transform: scale(1.2);
    transition: 0.5s ease;
}
.profile .friends .person img:not(.icon) {
    transition: 0.5s ease
}
</style>

<style>
.general-about .profile-pic:not(.icon):hover {
    transform: scale(1.2);rotate(-3deg);
    transition: 0.5s ease;
}
</style>
sudo apt install apache2 -y
-- =============================================
-- Author:      Vignesh (Developer)
-- Create date: 15-03-2024
-- Description: For the Receptionist Regiration Insert Stored Procedure 
-- =============================================
extends CharacterBody3D

var mouse_sense = 0.1 
const SPEED = 5.0
const JUMP_VELOCITY = 4.5

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/3d/default_gravity")


@onready var head = $head
@onready var camera = $head/Camera3D

func _ready():
	#hides the cursor
	Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)


func _input(event):
	#get mouse input for camera rotation
	if event is InputEventMouseMotion:
		rotate_y(deg_to_rad(-event.relative.x * mouse_sense))
		head.rotate_x(deg_to_rad(-event.relative.y * mouse_sense))
		head.rotation.x = clamp(head.rotation.x, deg_to_rad(-89), deg_to_rad(89))


func _physics_process(delta):
	# Add the gravity.
	if not is_on_floor():
		velocity.y -= gravity * delta

	# Handle jump.
	if Input.is_action_just_pressed("ui_accept") and is_on_floor():
		velocity.y = JUMP_VELOCITY

	# Get the input direction and handle the movement/deceleration.
	# As good practice, you should replace UI actions with custom gameplay actions.
	var input_dir = Input.get_vector("left", "right", "up", "down")
	var direction = (transform.basis * Vector3(input_dir.x, 0, input_dir.y)).normalized()
	if direction:
		velocity.x = direction.x * SPEED
		velocity.z = direction.z * SPEED
	else:
		velocity.x = move_toward(velocity.x, 0, SPEED)
		velocity.z = move_toward(velocity.z, 0, SPEED)

	move_and_slide()
shader_type spatial;
render_mode cull_front, unshaded;

uniform vec4 outline_color : source_color;
uniform float outline_width = 1.0;

void vertex() {
	vec4 clip_position = PROJECTION_MATRIX * (MODELVIEW_MATRIX * vec4(VERTEX, 1.0));
	vec3 clip_normal = mat3(PROJECTION_MATRIX) * (mat3(MODELVIEW_MATRIX) * NORMAL);
	
	vec2 offset = normalize(clip_normal.xy) / VIEWPORT_SIZE * clip_position.w * outline_width * 2.0;
	
	clip_position.xy += offset;
	
	POSITION = clip_position;
}

void fragment() {
	ALBEDO = outline_color.rgb;
	if (outline_color.a < 1.0) {
		ALPHA = outline_color.a;
	}
}
IF INDEX() = 1
  THEN 0
ELSE 
  (1 + AVG([Value])) * (PREVIOUS_VALUE(1) +1) -1
END
# List: Dynamic array, allows duplicate elements
list_example = [1, 2, 3]  # Initialization
list_example.append(4)  # O(1) - Add element to end
list_example.insert(1, 5)  # O(n) - Insert element at index
list_example.pop()  # O(1) - Remove last element
list_example.pop(1)  # O(n) - Remove element at index
element = list_example[2]  # O(1) - Access by index
# Note: Searching for an element is O(n), but not shown here

# Dictionary: Key-Value pairs, allows unique keys
dict_example = {'a': 1, 'b': 2}  # Initialization
dict_example['c'] = 3  # O(1) - Add or update
dict_example.pop('b')  # O(1) - Remove key
value = dict_example['a']  # O(1) - Access by key
# Note: Searching for a key is O(1), but not shown here

# Set: Unordered collection of unique elements
set_example = {1, 2, 3}  # Initialization
set_example.add(4)  # O(1) - Add element
set_example.remove(2)  # O(1) - Remove element
# Note: Checking if an element exists is O(1), but not shown here

# Tuple: Immutable sequence, allows duplicate elements
tuple_example = (1, 2, 3)  # Initialization
element = tuple_example[1]  # O(1) - Access by index
# Note: Searching for an element is O(n), but not shown here

# Heap: (Using heapq module for min heap)
import heapq  # Importing heapq module
heap_example = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]  # Example list
heapq.heapify(heap_example)  # O(n) - Transform list into a heap, in-place
heapq.heappush(heap_example, -5)  # O(log n) - Add element
smallest_element = heapq.heappop(heap_example)  # O(log n) - Pop the smallest item

# Deque: Double-ended queue, allows appending and popping from both ends
from collections import deque  # Importing deque from collections
deque_example = deque([1, 2, 3])  # Initialization
deque_example.append(4)  # O(1) - Add element to the right
deque_example.appendleft(0)  # O(1) - Add element to the left
deque_example.pop()  # O(1) - Remove element from the right
deque_example.popleft()  # O(1) - Remove element from the left
# Note: Access by index is O(n), but faster for operations on ends, not shown here
class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:

        rows, cols = len(grid), len(grid[0])
        visit = set()
        count = 0

        def dfs(r, c):
            if r in range(rows) and c in range(cols) and (r,c) not in visit and grid[r][c] == "1":
                visit.add((r,c))
                for dr, dc in [[0, 1], [1, 0], [-1, 0], [0, -1]]:
                    dfs(r+dr, c+dc)

        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1" and (r,c) not in visit:
                    count += 1
                    dfs(r,c)
        
        return count
#include<bits/stdc++.h>
using namespace std;

void solve(){
   
}

int main(){
    int t;
    cin>>t;
    while(t-->0){
        solve();
    }
    return 0;
}
#include<bits/stdc++.h>
using namespace std;

int main(){
    int t;
    cin>>t;
    while(t-->0){
    
    }
    return 0;
}
# Delete the logs of first 1000 actions related to a workflow from the server

WORKFLOW="My workflow name"
OWNER="owner"
REPOSITORY="repo"

gh run list --repo "$OWNER/$REPOSITORY" -w "$WORKFLOW" --limit 1000 --json databaseId \
| jq '.[].databaseId' \
| xargs -I{} gh api -X DELETE /repos/$OWNER/$REPOSITORY/actions/runs/{}/logs
addReceptionistRegistration -> For Reception Registration 

getReceptionRegisterDetails -> For Getting Using Send Id.

receptionAppShare -> Reception App Share.

Insert_otp_reception -> Insert Reception OTP to table.

approveReceptionistFor.

list_otp_reception

reception_login.

getParticularReceptionist.

update_otp_reception.

get_user_master_receptionist.

verify_reception_otp.

receptionistgetvendortypelist.

insertCommissionReceptionist. 

updateAdminReceptionContractDetails. 
create table mas_common_receptionist(
id bigint NOT NULL AUTO_INCREMENT,
vendor_id bigint null,
vendor_type_id bigint null,
receptionist_name varchar(250) null,
profile_path text null,
civil_id_path text null,
nationality varchar(250) null,
contact_email varchar(250) null,
contact_number varchar(250) null,
referal_code varchar(100) null,
civil_id_number varchar(250) null,
bank_name varchar(250) null,
account_name varchar(250) null,
account_number varchar(250) null,
iban varchar(500) null,
address varchar(300) null,
beneficiary_contact_number varchar(50) null,
salesAdmin_approveSts varchar(45) not null,
active_status varchar(45) not null,
created_on datetime not null,
decline_reason varchar(250) null,
salesAdminApproved_on datetime not null,
superAdminApproved_on datetime null,
modified_on datetime null,
modified_by varchar(45) null
)





--- For the Send Link to Member Table

create table sent_link_receptionist(
id bigint NOT NULL AUTO_INCREMENT,
receptionist_id bigint null,
vendor_name varchar(250) null,
vendor_mobileNo varchar(100) null,
created_by varchar(45) null,
created_date datetime null,
salesman_id varchar(45) null,
vendorType_id varchar(45) null,
country_code varchar(45) null,
e_mail varchar(45) null,
modified_by varchar(45) null,
modified_date datetime null,

PRIMARY KEY (id)
)




------ For the Move Mas common vendor to mas vendor



create table mas_receptionist(
id bigint not null,
vendor_type_id bigint null,
reception_contact varchar(250) null,
reception_clinic_name varchar(250) null,
reception_mobile varchar(250) null,
reception_code varchar(45) null,
reception_contact_mobile varchar(250) null,
reception_email varchar(250) null,
nationality varchar(250) null,
reception_address varchar(250) null,
active_flag tinyint(1) null,
created_by bigint null,
created_on datetime null,
modified_by int(11) null,
modified_on datetime null,
reception_approve_status varchar(1) not null,
apprrove_reject_time datetime null,
reception_profile_path text null,
reception_civil_path text null,
bank_name varchar(100) null,
account_name varchar(100) null,
account_number varchar(100) null,
iban varchar(100) null,
is_active varchar(45) null
);


--- Mas Commision Table For Receptionist

create table mas_commission_receptionist(
id bigint NOT NULL AUTO_INCREMENT,
receptionist_id bigint null,
contract_terms varchar(400) null,
active_flag tinyint(1) null,
created_by varchar(128) null,
created_on datetime null,
modified_by varchar(128) null,
modified_on datetime  null,
vendor_type_id int(11) null,
contact_acceptance_status  varchar(45) not null,
start_date datetime null,
end_date datetime null,
contract_accept_date datetime null,
signature_image longtext null,
signed_contract_file longtext null,
terms_and_condition_file longtext null,
admin_upload_status varchar(45) null,

PRIMARY KEY (id)
)


--- For Receptionist Vendor Tables

create table other_vendor_type(
id bigint NOT NULL AUTO_INCREMENT,
vendor varchar(100) null,
active_flag tinyint(1) null,
created_by varchar(128) null,
created_on datetime null,
modified_by varchar(128) null,
modified_on datetime  null,
web_url varchar(45) null,
reg_url varchar(45) null,
vendor_payment_days int(11) null,
doc_receive_thirty_days int(10) null,
doc_receive_sixty_days int(10) null,
PRIMARY KEY (id)
)
 private void CheckSuppExhPosition()
        {
            Point XtraTopLocation = new Point(xtraTabControl1.Location.X, xtraTabControl1.Location.Y);
            Point XtraButtomLocation = new Point(xtraTabControl2.Location.X, xtraTabControl2.Location.Y);
            Point GroupTopLocation = new Point(groupControl1.Location.X, groupControl1.Location.Y);
            Point GrouoButtomLocation = new Point(groupControl2.Location.X, groupControl2.Location.Y);
            
            if (Settings.GetUnit.SupplyPosition == "Top" || Settings.GetUnit.SupplyPosition == "Back")
            {
                xtraTabControl1.Location = XtraTopLocation;
                xtraTabControl2.Location = XtraButtomLocation;

                groupControl1.Location = GroupTopLocation;
                groupControl2.Location = GrouoButtomLocation;
            }
            else if (Settings.GetUnit.SupplyPosition == "Bottom" || Settings.GetUnit.SupplyPosition == "Front")
            {
                xtraTabControl1.Location = XtraButtomLocation;
                xtraTabControl2.Location = XtraTopLocation;

                groupControl1.Location = GrouoButtomLocation;
                groupControl2.Location = GroupTopLocation;
            }
          
          //refactor
          if (Settings.GetUnit.SupplyPosition == "Bottom" || Settings.GetUnit.SupplyPosition == "Front")
            {
                (xtraTabControl1.Location, xtraTabControl2.Location) = (xtraTabControl2.Location, xtraTabControl1.Location);
                (groupControl1.Location, groupControl2.Location) = (groupControl2.Location, groupControl1.Location);
            }
          
        }



"": {
  "prefix": "",
  "body": [
    ""
  ],
  "description": ""
}
#include<bits/stdc++.h>
using namespace std;

int main(){
  
  return 0;
}
const handleSubmit = async () => {
    const uri = encodeURIComponent(inputValue.toString());
    const url = "https://cleanuri.com";
    const shortenAPI = `${url}/api/v1/shorten`;
    if(uri!==""){
      try {
        const res = await fetch(shortenAPI, {
          method: "POST",
          body: `url=${uri}`,
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
          },
        });
  
        if (!res.ok) {
          throw new Error(`HTTP error! status: ${res.status}`);
        }
  
        const dataJSON = await res.json();
        setData([...data, { input: inputValue, result: dataJSON.result_url }]);
        setInputValue("");
        
      } catch (error) {
        console.error("Fetch error:", error);
      }
    }
    else{
      setAlertInput(!alertInput)
    }
  };
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace CarMaintenanceAppointment
{
    public partial class AppointmentForm : Form
    {
        public AppointmentForm()
        {
            InitializeComponent();
        }

        private void btnPrefill_Click(object sender, EventArgs e)
        {
            // Pre-fill the form with some valid data
            txtCustomerName.Text = "John Doe";
            txtAddress.Text = "123 Main St";
            txtCity.Text = "Toronto";
            txtProvince.Text = "ON";
            txtPostalCode.Text = "A1A 1A1";
            txtEmail.Text = "johndoe@example.com";
            txtHomePhone.Text = "123-456-7890";
            txtCellPhone.Text = "987-654-3210";
            txtMakeModel.Text = "Toyota Camry";
            txtYear.Text = "2019";
            dtpAppointmentDate.Value = DateTime.Now;
        }

        private void btnBookAppointment_Click(object sender, EventArgs e)
        {
            // Reset error label
            lblErrors.Text = "";

            // Validate input fields
            List<string> errors = new List<string>();

            // Validation rules
            if (string.IsNullOrWhiteSpace(txtCustomerName.Text))
                errors.Add("Customer name is required.");
            if (string.IsNullOrWhiteSpace(txtEmail.Text) && string.IsNullOrWhiteSpace(txtAddress.Text) && string.IsNullOrWhiteSpace(txtCity.Text) && string.IsNullOrWhiteSpace(txtProvince.Text) && string.IsNullOrWhiteSpace(txtPostalCode.Text))
                errors.Add("Postal information is required if email is not provided.");
            if (!string.IsNullOrWhiteSpace(txtProvince.Text) && (txtProvince.Text.Length != 2 || !ValidationHelper.IsValidProvinceCode(txtProvince.Text)))
                errors.Add("Province code is invalid.");
            if (!string.IsNullOrWhiteSpace(txtPostalCode.Text) && !ValidationHelper.IsValidPostalCode(txtPostalCode.Text))
                errors.Add("Postal code is invalid.");
            if (string.IsNullOrWhiteSpace(txtHomePhone.Text) && string.IsNullOrWhiteSpace(txtCellPhone.Text))
                errors.Add("Either home or cell phone must be provided.");
            if (!string.IsNullOrWhiteSpace(txtEmail.Text) && !IsValidEmail(txtEmail.Text))
                errors.Add("Email is invalid.");
            if (string.IsNullOrWhiteSpace(txtMakeModel.Text))
                errors.Add("Make & model is required.");
            if (!string.IsNullOrWhiteSpace(txtYear.Text) && (!int.TryParse(txtYear.Text, out int year) || year < 1900 || year > DateTime.Now.Year + 1))
                errors.Add("Year is invalid.");
            if (dtpAppointmentDate.Value.Date < DateTime.Today)
                errors.Add("Appointment date cannot be in the past.");

            // Display errors if any
            if (errors.Count > 0)
            {
                lblErrors.ForeColor = System.Drawing.Color.Red;
                lblErrors.Text = string.Join("\n", errors);
                FocusFirstErrorControl();
                return;
            }

            // Format and save appointment data to file
            string appointmentData = $"{ValidationHelper.Capitalize(txtCustomerName.Text)}|{ValidationHelper.Capitalize(txtAddress.Text)}|{ValidationHelper.Capitalize(txtCity.Text)}|{txtProvince.Text.ToUpper()}|{FormatPostalCode(txtPostalCode.Text)}|{txtEmail.Text.ToLower()}|{FormatPhoneNumber(txtHomePhone.Text)}|{FormatPhoneNumber(txtCellPhone.Text)}|{ValidationHelper.Capitalize(txtMakeModel.Text)}|{txtYear.Text}|{dtpAppointmentDate.Value.ToString("yyyy-MM-dd")}";

            try
            {
                using (StreamWriter writer = new StreamWriter("appointments.txt", true))
                {
                    writer.WriteLine(appointmentData);
                }
                MessageBox.Show("Appointment booked successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                ResetForm();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"An error occurred while saving the appointment: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            // Reset the form
            ResetForm();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            // Close the form
            Close();
        }

        private bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }

        private void FocusFirstErrorControl()
        {
            // Set focus to the first control with an error
            foreach (Control control in this.Controls)
            {
                if (control.GetType() == typeof(TextBox) && !string.IsNullOrEmpty(control.Text))
                {
                    control.Focus();
                    return;
                }
            }
        }

        private string FormatPostalCode(string postalCode)
        {
            // Format postal code with a single space
            return postalCode.ToUpper().Trim().Insert(3, " ");
        }

        private string FormatPhoneNumber(string phoneNumber)
        {
            // Format phone number with dashes
            return Regex.Replace(phoneNumber, @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
        }

        private void ResetForm()
        {
            // Reset the form to its original state
            txtCustomerName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            txtProvince.Text = "";
            txtPostalCode.Text = "";
            txtEmail.Text = "";
            txtHomePhone.Text = "";
            txtCellPhone.Text = "";
            txtMakeModel.Text = "";
            txtYear.Text = "";
            dtpAppointmentDate.Value = DateTime.Now;
            lblErrors.Text = "";
        }
    }

    public static class ValidationHelper
    {
        public static string Capitalize(string input)
        {
            if (string.IsNullOrEmpty(input))
                return string.Empty;

            string[] words = input.Trim().ToLower().Split(' ');
            for (int i = 0; i < words.Length; i++)
            {
                if (words[i].Length > 1)
                {
                    words[i] = char.ToUpper(words[i][0]) + words[i][1..];
                }
                else if (words[i].Length == 1)
                {
                    if (i == 0)
                        words[i] = char.ToUpper(words[i][0]).ToString();
                    else
                        words[i] = words[i].ToString();
                }
            }
            return string.Join(" ", words);
        }

        public static bool IsValidProvinceCode(string provinceCode)
        {
            if (string.IsNullOrEmpty(provinceCode))
                return false;

            // Array of valid Canadian province codes
            string[] validCodes = { "AB", "BC", "MB", "NB", "NL", "NS", "NT", "NU", "ON", "PE", "QC", "SK", "YT" };
            return Array.Exists(validCodes, code => code.Equals(provinceCode, StringComparison.OrdinalIgnoreCase));
        }

        public static bool IsValidPostalCode(string postalCode)
        {
            if (string.IsNullOrEmpty(postalCode))
                return false;

            // Regular expression to match Canadian postal code pattern
            Regex regex = new Regex(@"^[a-zA-Z]\d[a-zA-Z] ?\d[a-zA-Z]\d$");
            return regex.IsMatch(postalCode);
        }
    }
}
star

Sun Mar 17 2024 20:06:40 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=u4JAi2JJhI8

@playadust

star

Sun Mar 17 2024 20:05:10 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=Hr5cWUld4vU

@playadust

star

Sun Mar 17 2024 20:04:19 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=ihj4IQGZ2zc

@playadust

star

Sun Mar 17 2024 19:39:05 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sun Mar 17 2024 19:32:15 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sun Mar 17 2024 19:21:00 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/c/e49ca8a6-55e3-4648-8c33-02e68cee1123

@eziokittu

star

Sun Mar 17 2024 19:15:30 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sun Mar 17 2024 17:50:58 GMT+0000 (Coordinated Universal Time) https://app.powerbi.com/groups/a68e8e20-031e-49c1-9beb-fe81f6c95c8c/synapsenotebooks/d9c7fc1c-bbb9-488a-851f-063010bd1f80?experience

@okokokok

star

Sun Mar 17 2024 17:43:08 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sun Mar 17 2024 15:05:57 GMT+0000 (Coordinated Universal Time)

@GQlizer4

star

Sun Mar 17 2024 13:24:39 GMT+0000 (Coordinated Universal Time)

@marcopinero #css

star

Sun Mar 17 2024 06:23:53 GMT+0000 (Coordinated Universal Time) https://docs.web3j.io/4.10.0/use_cases/meta_transaction/

@katyno

star

Sun Mar 17 2024 06:21:49 GMT+0000 (Coordinated Universal Time) https://docs.web3j.io/4.10.0/use_cases/meta_transaction/

@katyno

star

Sun Mar 17 2024 06:21:33 GMT+0000 (Coordinated Universal Time) https://docs.web3j.io/4.10.0/use_cases/meta_transaction/

@katyno

star

Sun Mar 17 2024 02:54:24 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/c484c09d-cf39-4399-a67c-fcfa866665f0/

@Marcelluki

star

Sun Mar 17 2024 02:34:34 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/1aaed691-671a-4c35-bf64-5ebdf99a4002/task/180f36ba-a09e-4ae9-9f42-2af6d8e434cb/

@Marcelluki

star

Sun Mar 17 2024 01:54:49 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/7cf735f9-fbb6-4bae-a007-423cbd1725c6/task/2eeca908-aef2-44e3-be4d-53521dc1876b/

@Marcelluki

star

Sun Mar 17 2024 01:21:08 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sat Mar 16 2024 23:38:29 GMT+0000 (Coordinated Universal Time) https://github.com/shadcn-ui/taxonomy/blob/main/app/(auth)/login/page.tsx

@microdotmatrix #react #react.js #javascript #jsx #tailwind #css

star

Sat Mar 16 2024 22:55:12 GMT+0000 (Coordinated Universal Time)

@playadust

star

Sat Mar 16 2024 20:39:01 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/a7cc7f7d-b3eb-4048-a224-6995e7302a06/task/dbe8fba8-e1c8-4804-a659-97b1f5a19ee0/

@Marcelluki

star

Sat Mar 16 2024 20:08:13 GMT+0000 (Coordinated Universal Time) https://tripleten.com/trainer/web/lesson/489273e7-a2fd-4eb3-9b58-797312e24637/task/6f8411d4-1682-447a-921b-eeb275b6dc76/

@Marcelluki

star

Sat Mar 16 2024 19:40:04 GMT+0000 (Coordinated Universal Time)

@sunnywhateverr

star

Sat Mar 16 2024 18:56:59 GMT+0000 (Coordinated Universal Time)

@Y@sir #current-year #current-date

star

Sat Mar 16 2024 15:27:08 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/upscaler

@topthonder

star

Sat Mar 16 2024 15:00:11 GMT+0000 (Coordinated Universal Time) https://github.com/idealo/image-super-resolution

@topthonder

star

Sat Mar 16 2024 11:17:51 GMT+0000 (Coordinated Universal Time)

@mervickcloud

star

Sat Mar 16 2024 10:54:40 GMT+0000 (Coordinated Universal Time)

@sunnywhateverr

star

Sat Mar 16 2024 08:28:48 GMT+0000 (Coordinated Universal Time)

@sunnywhateverr

star

Sat Mar 16 2024 06:14:03 GMT+0000 (Coordinated Universal Time) https://syncbricks.com/snipe-it-instsallation-ubuntu-20-04/

@misibini13

star

Sat Mar 16 2024 06:04:07 GMT+0000 (Coordinated Universal Time)

@vigneshAvelator

star

Sat Mar 16 2024 03:29:40 GMT+0000 (Coordinated Universal Time)

@azariel #glsl

star

Sat Mar 16 2024 03:23:35 GMT+0000 (Coordinated Universal Time) https://godotshaders.com/shader/pixel-perfect-outline-shader/

@azariel #glsl

star

Fri Mar 15 2024 16:35:02 GMT+0000 (Coordinated Universal Time)

@cvdubs

star

Fri Mar 15 2024 16:08:24 GMT+0000 (Coordinated Universal Time)

@playadust

star

Fri Mar 15 2024 15:41:54 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/number-of-islands/

@playadust

star

Fri Mar 15 2024 14:31:30 GMT+0000 (Coordinated Universal Time)

@v1n6y #c++

star

Fri Mar 15 2024 14:30:37 GMT+0000 (Coordinated Universal Time)

@v1n6y #c++

star

Fri Mar 15 2024 13:52:13 GMT+0000 (Coordinated Universal Time)

@bmillot #git

star

Fri Mar 15 2024 13:19:10 GMT+0000 (Coordinated Universal Time)

@vigneshAvelator

star

Fri Mar 15 2024 12:21:19 GMT+0000 (Coordinated Universal Time)

@vigneshAvelator

star

Fri Mar 15 2024 11:05:15 GMT+0000 (Coordinated Universal Time)

@Simetra

star

Fri Mar 15 2024 11:02:02 GMT+0000 (Coordinated Universal Time) https://snippet-generator.app/?description

@sadjxt

star

Fri Mar 15 2024 10:21:53 GMT+0000 (Coordinated Universal Time) https://www.vblink777.club/robots.txt

@BichoSvCA

star

Fri Mar 15 2024 09:11:19 GMT+0000 (Coordinated Universal Time)

@v1n6y #c++

star

Fri Mar 15 2024 09:00:19 GMT+0000 (Coordinated Universal Time) https://eu.startpage.com/?sc

@fcku

star

Fri Mar 15 2024 07:07:08 GMT+0000 (Coordinated Universal Time)

@fazmi322

star

Fri Mar 15 2024 05:55:12 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/c/bf7e0b9b-404d-4d95-8b4b-95d8d70c6681

@Tanmay #c#

star

Fri Mar 15 2024 03:39:29 GMT+0000 (Coordinated Universal Time) http://127.0.0.1:5000/

@morrison27

star

Fri Mar 15 2024 03:39:25 GMT+0000 (Coordinated Universal Time) http://127.0.0.1:5000/

@morrison27

Save snippets that work with our extensions

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