Loading...
}
Facebook is a social utility that connects people with friends and others who work, study and live around them. People use Facebook to keep up with friends, upload an unlimited number of photos, post links and videos, and learn more about the people they meet.
)
}
export default page
================================================
FILE: Video 129/layouts/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--foreground-rgb: 0, 0, 0;
--background-start-rgb: 214, 219, 220;
--background-end-rgb: 255, 255, 255;
}
@media (prefers-color-scheme: dark) {
:root {
--foreground-rgb: 255, 255, 255;
--background-start-rgb: 0, 0, 0;
--background-end-rgb: 0, 0, 0;
}
}
body {
color: rgb(var(--foreground-rgb));
background: linear-gradient(
to bottom,
transparent,
rgb(var(--background-end-rgb))
)
rgb(var(--background-start-rgb));
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: Video 129/layouts/app/layout.js
================================================
import { Inter } from "next/font/google";
import "./globals.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Facebook - Connect with friends and the world around you",
description: "Facebook is a social utility that connects people with friends and others who work, study and live around them. People use Facebook to keep up with friends, upload an unlimited number of photos, post links and videos, and learn more about the people they meet.",
};
export default function RootLayout({ children }) {
return (
'
// }),
],
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
if(account.provider == "github") {
await connectDb()
// Check if the user already exists in the database
const currentUser = await User.findOne({email: email})
if(!currentUser){
// Create a new user
const newUser = await User.create({
email: user.email,
username: user.email.split("@")[0],
})
}
return true
}
},
async session({ session, user, token }) {
const dbUser = await User.findOne({email: session.user.email})
session.user.name = dbUser.username
return session
},
}
})
export { authoptions as GET, authoptions as POST}
================================================
FILE: Video 131/app/api/razorpay/route.js
================================================
import { NextResponse } from "next/server";
import { validatePaymentVerification } from "razorpay/dist/utils/razorpay-utils";
import Payment from "@/models/Payment";
import Razorpay from "razorpay";
import connectDb from "@/db/connectDb";
import User from "@/models/User";
export const POST = async (req) => {
await connectDb()
let body = await req.formData()
body = Object.fromEntries(body)
// Check if razorpayOrderId is present on the server
let p = await Payment.findOne({oid: body.razorpay_order_id})
if(!p){
return NextResponse.json({success: false, message:"Order Id not found"})
}
// fetch the secret of the user who is getting the payment
let user = await User.findOne({username: p.to_user})
const secret = user.razorpaysecret
// Verify the payment
let xx = validatePaymentVerification({"order_id": body.razorpay_order_id, "payment_id": body.razorpay_payment_id}, body.razorpay_signature, secret)
if(xx){
// Update the payment status
const updatedPayment = await Payment.findOneAndUpdate({oid: body.razorpay_order_id}, {done: "true"}, {new: true})
return NextResponse.redirect(`${process.env.NEXT_PUBLIC_URL}/${updatedPayment.to_user}?paymentdone=true`)
}
else{
return NextResponse.json({success: false, message:"Payment Verification Failed"})
}
}
================================================
FILE: Video 131/app/dashboard/page.js
================================================
import Dashboard from '@/components/Dashboard'
const DashboardPage = () => {
return (
)
}
export default DashboardPage
export const metadata = {
title: "Dashboard - Get Me A Chai",
}
================================================
FILE: Video 131/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
.invertImg{
filter: invert(0.23)
}
================================================
FILE: Video 131/app/layout.js
================================================
import { Inter } from "next/font/google";
import "./globals.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import SessionWrapper from "@/components/SessionWrapper";
const inter = Inter({ subsets: ["latin"] });
export const metadata = {
title: "Get me A Chai - Fund your projects with chai",
description: "This website is a crowdfunding platform for creators.",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 131/app/login/page.js
================================================
"use client"
import React, {useEffect} from 'react'
import { useSession, signIn, signOut } from "next-auth/react"
import { useRouter } from 'next/navigation'
const Login = () => {
const { data: session } = useSession()
const router = useRouter()
useEffect(() => {
document.title = "Login - Get Me A Chai"
console.log(session)
if (session) {
router.push('/dashboard')
}
}, [])
return (
Login to Get Started
Continue with Google
Continue with LinkedIn
Continue with Twitter
Continue with Facebook
{ signIn("github") }}
className="flex items-center w-64 bg-slate-50 text-black border border-gray-300 rounded-lg shadow-md max-w-xs px-6 py-2 text-sm font-medium hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
Continue with Github
Continue with Apple
)
}
export default Login
================================================
FILE: Video 131/app/page.js
================================================
import Image from "next/image";
import Link from "next/link";
export default function Home() {
return (
<>
Get Me a Chai
A crowdfunding platform for creators to fund their projects.
A place where your fans can buy you a chai. Unleash the power of your fans and get your projects funded.
Start Here
Read More
Your Fans can buy you a Chai
Fans want to help
Your fans are available to support you
Fans want to contribute
Your fans are willing to contribute financially
Fans want to collaborate
Your fans are ready to collaborate with you
Learn more about us
{/* Responsive youtube embed */}
VIDEO
>
);
}
================================================
FILE: Video 131/components/Dashboard.js
================================================
"use client"
import React, { useEffect, useState } from 'react'
import { useSession, signIn, signOut } from "next-auth/react"
import { useRouter } from 'next/navigation'
import { fetchuser, updateProfile } from '@/actions/useractions'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Bounce } from 'react-toastify';
const Dashboard = () => {
const { data: session, update } = useSession()
const router = useRouter()
const [form, setform] = useState({})
useEffect(() => {
console.log(session)
if (!session) {
router.push('/login')
}
else {
getData()
}
}, [])
const getData = async () => {
let u = await fetchuser(session.user.name)
setform(u)
}
const handleChange = (e) => {
setform({ ...form, [e.target.name]: e.target.value })
}
const handleSubmit = async (e) => {
let a = await updateProfile(e, session.user.name)
toast('Profile Updated', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
return (
<>
{/* Same as */}
Welcome to your Dashboard
>
)
}
export default Dashboard
================================================
FILE: Video 131/components/Footer.js
================================================
import React from 'react'
const Footer = () => {
const currentYear = new Date().getFullYear();
return (
)
}
export default Footer
================================================
FILE: Video 131/components/Navbar.js
================================================
"use client"
import React, { useState } from 'react'
import { useSession, signIn, signOut } from "next-auth/react"
import Link from 'next/link'
const Navbar = () => {
const { data: session } = useSession()
const [showdropdown, setShowdropdown] = useState(false)
return (
Get Me a Chai!
{/*
Home
About
Projects
Sign Up
Login
*/}
{session && <>
setShowdropdown(!showdropdown)} onBlur={() => {
setTimeout(() => {
setShowdropdown(false)
}, 100);
}} id="dropdownDefaultButton" data-dropdown-toggle="dropdown" className="text-white mx-2 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-2 py-2.5 text-center inline-flex items-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button">Account
Dashboard
Your Page
signOut()} href="#" className="block px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-600 dark:hover:text-white">Sign out
>
}
{session &&
{ signOut() }}>Logout }
{!session &&
Login }
)
}
export default Navbar
================================================
FILE: Video 131/components/PaymentPage.js
================================================
"use client"
import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import { useSession } from 'next-auth/react'
import { fetchuser, fetchpayments, initiate } from '@/actions/useractions'
import { useSearchParams } from 'next/navigation'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { Bounce } from 'react-toastify';
import { useRouter } from 'next/navigation'
import { notFound } from "next/navigation"
const PaymentPage = ({ username }) => {
// const { data: session } = useSession()
const [paymentform, setPaymentform] = useState({name: "", message: "", amount: ""})
const [currentUser, setcurrentUser] = useState({})
const [payments, setPayments] = useState([])
const searchParams = useSearchParams()
const router = useRouter()
useEffect(() => {
getData()
}, [])
useEffect(() => {
if(searchParams.get("paymentdone") == "true"){
toast('Thanks for your donation!', {
position: "top-right",
autoClose: 5000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
transition: Bounce,
});
}
router.push(`/${username}`)
}, [])
const handleChange = (e) => {
setPaymentform({ ...paymentform, [e.target.name]: e.target.value })
}
const getData = async () => {
let u = await fetchuser(username)
setcurrentUser(u)
let dbpayments = await fetchpayments(username)
setPayments(dbpayments)
}
const pay = async (amount) => {
// Get the order Id
let a = await initiate(amount, username, paymentform)
let orderId = a.id
var options = {
"key": currentUser.razorpayid, // Enter the Key ID generated from the Dashboard
"amount": amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
"currency": "INR",
"name": "Get Me A Chai", //your business name
"description": "Test Transaction",
"image": "https://example.com/your_logo",
"order_id": orderId, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
"callback_url": `${process.env.NEXT_PUBLIC_URL}/api/razorpay`,
"prefill": { //We recommend using the prefill parameter to auto-fill customer's contact information especially their phone number
"name": "Gaurav Kumar", //your customer's name
"email": "gaurav.kumar@example.com",
"contact": "9000090000" //Provide the customer's phone number for better conversion rates
},
"notes": {
"address": "Razorpay Corporate Office"
},
"theme": {
"color": "#3399cc"
}
}
var rzp1 = new Razorpay(options);
rzp1.open();
}
return (
<>
{/* Same as */}
@{username}
Lets help {username} get a chai!
{payments.length} Payments . ₹{payments.reduce((a, b) => a + b.amount, 0)} raised
{/* Show list of all the supporters as a leaderboard */}
Top 10 Supporters
{payments.length == 0 && No payments yet }
{payments.map((p, i) => {
return
{p.name} donated ₹{p.amount} with a message "{p.message}"
})}
Make a Payment
{/* Or choose from these amounts */}
pay(1000)}>Pay ₹10
pay(2000)}>Pay ₹20
pay(3000)}>Pay ₹30
>
)
}
export default PaymentPage
================================================
FILE: Video 131/components/SessionWrapper.js
================================================
"use client"
import { SessionProvider } from "next-auth/react"
export default function SessionWrapper({children}) {
return (
{children}
)
}
================================================
FILE: Video 131/db/connectDb.js
================================================
import mongoose from "mongoose";
const connectDb = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`);
return conn;
} catch (error) {
console.error(error.message);
process.exit(1);
}
}
export default connectDb;
================================================
FILE: Video 131/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 131/models/Payment.js
================================================
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const PaymentSchema = new Schema({
name: { type: String, required: true },
to_user: { type: String, required: true },
oid: { type: String, required: true },
message: { type: String },
amount: { type: Number, required: true },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
done: { type: Boolean, default: false },
});
export default mongoose.models.Payment || model("Payment", PaymentSchema);;
================================================
FILE: Video 131/models/User.js
================================================
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const UserSchema = new Schema({
email: { type: String, required: true },
name: { type: String},
username: { type: String, required: true },
profilepic: {type: String},
coverpic: {type: String},
razorpayid: { type: String },
razorpaysecret: { type: String },
createdAt: { type: Date, default: Date.now },
updatedAt: { type: Date, default: Date.now },
});
export default mongoose.models.User || model("User", UserSchema);;
================================================
FILE: Video 131/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 131/package.json
================================================
{
"name": "get-me-a-chai",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"mongoose": "^8.2.2",
"next": "^14.1.3",
"next-auth": "^4.24.7",
"razorpay": "^2.9.2",
"react": "^18",
"react-dom": "^18",
"react-toastify": "^9.1.3"
},
"devDependencies": {
"autoprefixer": "^10.0.1",
"eslint": "^8",
"eslint-config-next": "14.1.3",
"postcss": "^8",
"tailwindcss": "^3.3.0"
}
}
================================================
FILE: Video 131/postcss.config.js
================================================
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
================================================
FILE: Video 131/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
};
================================================
FILE: Video 132/next-navigation-tutorial/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 132/next-navigation-tutorial/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 132/next-navigation-tutorial/README.md
================================================
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
================================================
FILE: Video 132/next-navigation-tutorial/app/about/page.js
================================================
import React from 'react'
const About = () => {
return (
About
)
}
export default About
================================================
FILE: Video 132/next-navigation-tutorial/app/blogpost/[slug]/page.js
================================================
"use client"
import React, { useEffect } from 'react'
import { useParams } from 'next/navigation'
import { useRouter } from 'next/navigation'
const page = () => {
const params = useParams()
const router = useRouter()
useEffect(() => {
setTimeout(() => {
router.push('/dashboard')
}, 2333);
}, [])
return (
{params.slug}
router.push('/dashboard')}>
Dashboard
)
}
export default page
================================================
FILE: Video 132/next-navigation-tutorial/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: Video 132/next-navigation-tutorial/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
import Navbar from "@/components/Navbar";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 132/next-navigation-tutorial/app/page.js
================================================
"use client"
import Image from "next/image";
import { useSearchParams } from "next/navigation";
export default function Home() {
const searchparms = useSearchParams()
return (
Hey this is our page and blog is {searchparms.get('blog')} and utm source is {searchparms.get('utm_source')}
);
}
================================================
FILE: Video 132/next-navigation-tutorial/components/Navbar.js
================================================
"use client"
import React from 'react'
import { usePathname } from "next/navigation";
const Navbar = () => {
const pathname = usePathname()
return (
Navbar
You are inside {pathname}
)
}
export default Navbar
================================================
FILE: Video 132/next-navigation-tutorial/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 132/next-navigation-tutorial/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 132/next-navigation-tutorial/package.json
================================================
{
"name": "next-navigation-tutorial",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.15"
},
"devDependencies": {
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8",
"eslint-config-next": "14.2.15"
}
}
================================================
FILE: Video 132/next-navigation-tutorial/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 132/next-navigation-tutorial/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 133/ssr-ssg-isr/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 133/ssr-ssg-isr/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 133/ssr-ssg-isr/README.md
================================================
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## SSR - Server Side Rendering
This is default behaviour
## SSG - Static Site Generation
Any content which does not have network calls is a static page by default
## ISG or ISR
fetch in next.js caches the response
To opt out use:
```
export const dynamic = 'force-dynamic';
```
However, there are exceptions, fetch requests are not cached when:
- Used inside a Server Action.
- Used inside a Route Handler that uses the POST method.
================================================
FILE: Video 133/ssr-ssg-isr/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: Video 133/ssr-ssg-isr/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 133/ssr-ssg-isr/app/page.js
================================================
import Image from "next/image";
export default async function Home() {
let data = await fetch('https://api.vercel.app/blog', { next: { revalidate: 3600 } })
let posts = await data.json()
return (
{posts.map((post) => (
{post.title}
))}
)
}
// export const dynamic = 'force-dynamic'
================================================
FILE: Video 133/ssr-ssg-isr/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 133/ssr-ssg-isr/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 133/ssr-ssg-isr/package.json
================================================
{
"name": "ssr-isg-isr",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.15"
},
"devDependencies": {
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8",
"eslint-config-next": "14.2.15"
}
}
================================================
FILE: Video 133/ssr-ssg-isr/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 133/ssr-ssg-isr/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 134/environment-variables/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 134/environment-variables/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 134/environment-variables/README.md
================================================
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
================================================
FILE: Video 134/environment-variables/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: Video 134/environment-variables/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 134/environment-variables/app/page.js
================================================
import Image from "next/image";
export default function Home() {
// console.log("The id is: ", process.env.ID)
// console.log("The secret is: ", process.env.SECRET)
return (
Hey this is home. The id is {process.env.NEXT_PUBLIC_ID} and secret is {process.env.SECRET} and name is {process.env.NAME}
);
}
================================================
FILE: Video 134/environment-variables/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 134/environment-variables/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 134/environment-variables/package.json
================================================
{
"name": "environment-variables",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.15"
},
"devDependencies": {
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8",
"eslint-config-next": "14.2.15"
}
}
================================================
FILE: Video 134/environment-variables/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 134/environment-variables/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 135/styles-in-nextjs/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 135/styles-in-nextjs/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 135/styles-in-nextjs/README.md
================================================
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
================================================
FILE: Video 135/styles-in-nextjs/app/about/page.js
================================================
"use client"
import React from 'react'
const About = () => {
return (
This is about me
Hey I am a good boy
Hey I am good
)
}
export default About
================================================
FILE: Video 135/styles-in-nextjs/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
color: var(--foreground);
background: var(--background);
font-family: Arial, Helvetica, sans-serif;
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
================================================
FILE: Video 135/styles-in-nextjs/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 135/styles-in-nextjs/app/page.js
================================================
import Image from "next/image";
import styles from "../styles/home.module.css"
export default function Home() {
return (
Hey
);
}
================================================
FILE: Video 135/styles-in-nextjs/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 135/styles-in-nextjs/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 135/styles-in-nextjs/package.json
================================================
{
"name": "styles-in-nextjs",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.15"
},
"devDependencies": {
"postcss": "^8",
"tailwindcss": "^3.4.1",
"eslint": "^8",
"eslint-config-next": "14.2.15"
}
}
================================================
FILE: Video 135/styles-in-nextjs/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 135/styles-in-nextjs/styles/Home.module.css
================================================
.red{
color: red;
}
================================================
FILE: Video 135/styles-in-nextjs/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 136/bitlinks/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 136/bitlinks/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# env files (can opt-in for commiting if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 136/bitlinks/BitLinks.postman_collection.json
================================================
{
"info": {
"_postman_id": "2f5d249a-7600-45b0-91e4-972d09030847",
"name": "BitLinks",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "24335059",
"_collection_link": "https://martian-station-78370.postman.co/workspace/Sigma-Web-Development-Express~5db32297-9967-4e1b-afb8-3d38caf12a97/collection/24335059-2f5d249a-7600-45b0-91e4-972d09030847?action=share&source=collection_link&creator=24335059"
},
"item": [
{
"name": "http://localhost:3000/api/generate",
"request": {
"method": "POST",
"header": [],
"body": {
"mode": "raw",
"raw": "{\r\n \"url\": \"https://facebook.com/codewithharry\",\r\n \"shorturl\": \"google2\"\r\n}",
"options": {
"raw": {
"language": "json"
}
}
},
"url": {
"raw": "http://localhost:3000/api/generate",
"protocol": "http",
"host": [
"localhost"
],
"port": "3000",
"path": [
"api",
"generate"
]
}
},
"response": []
},
{
"name": "http://localhost:3000",
"request": {
"method": "GET",
"header": [],
"url": {
"raw": "http://localhost:3000",
"protocol": "http",
"host": [
"localhost"
],
"port": "3000"
}
},
"response": []
}
]
}
================================================
FILE: Video 136/bitlinks/README.md
================================================
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
================================================
FILE: Video 136/bitlinks/app/[shorturl]/page.js
================================================
import { redirect } from "next/navigation"
import clientPromise from "@/lib/mongodb"
export default async function Page({ params }) {
const shorturl = (await params).shorturl
const client = await clientPromise;
const db = client.db("bitlinks")
const collection = db.collection("url")
const doc = await collection.findOne({shorturl: shorturl})
console.log(doc)
if(doc){
redirect(doc.url)
}
else{
redirect(`${process.env.NEXT_PUBLIC_HOST}`)
}
return My Post: {url}
}
================================================
FILE: Video 136/bitlinks/app/api/generate/route.js
================================================
import clientPromise from "@/lib/mongodb"
export async function POST(request) {
const body = await request.json()
const client = await clientPromise;
const db = client.db("bitlinks")
const collection = db.collection("url")
// Check if the short url exists
const doc = await collection.findOne({shorturl: body.shorturl})
if(doc){
return Response.json({success: false, error: true, message: 'URL already exists!' })
}
const result = await collection.insertOne({
url: body.url,
shorturl: body.shorturl
})
return Response.json({success: true, error: false, message: 'URL Generated Successfully' })
}
================================================
FILE: Video 136/bitlinks/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
================================================
FILE: Video 136/bitlinks/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
import Navbar from "@/components/Navbar";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "Bitlinks - Your trusted URL shortener",
description: "Bitlinks helps you shorten your Urls easily",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 136/bitlinks/app/page.js
================================================
import Image from "next/image";
import localFont from "next/font/local";
import Link from "next/link";
const poppins = localFont({
src: "./fonts/Poppins-ExtraBold.ttf",
variable: "--font-poppins",
weight: "100 900",
});
export default function Home() {
return (
The best URL shortener in the Market
We are the most straightfoward URL Shortener in the world. Most of the url shorteners will track you or ask you to give your details for login. We understand your needs and hence we have created this URL shortener
Try Now
GitHub
);
}
================================================
FILE: Video 136/bitlinks/app/shorten/page.js
================================================
"use client"
import Link from 'next/link'
import React, { useState } from 'react'
const Shorten = () => {
const [url, seturl] = useState("")
const [shorturl, setshorturl] = useState("")
const [generated, setGenerated] = useState("")
const generate = () => {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = JSON.stringify({
"url": url,
"shorturl": shorturl
});
const requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
fetch("/api/generate", requestOptions)
.then((response) => response.json())
.then((result) => {
setGenerated(`${process.env.NEXT_PUBLIC_HOST}/${shorturl}`)
seturl("")
setshorturl("")
console.log(result)
alert(result.message)
})
.catch((error) => console.error(error));
}
return (
)
}
export default Shorten
================================================
FILE: Video 136/bitlinks/components/Navbar.js
================================================
import React from 'react'
import Link from 'next/link'
const Navbar = () => {
return (
BitLinks
Home
About
Shorten
Contact Us
Try Now
GitHub
)
}
export default Navbar
================================================
FILE: Video 136/bitlinks/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 136/bitlinks/lib/mongodb.js
================================================
// https://www.codewithharry.com/blogpost/%60how-to-integrate-mongodb-into-your-nextjs-apps%60/
// lib/mongodb.js
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Add Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
================================================
FILE: Video 136/bitlinks/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 136/bitlinks/package.json
================================================
{
"name": "bitlinks",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"mongodb": "^6.10.0",
"next": "15.0.2",
"react": "19.0.0-rc-02c0e824-20241028",
"react-dom": "19.0.0-rc-02c0e824-20241028"
},
"devDependencies": {
"eslint": "^8",
"eslint-config-next": "15.0.2",
"postcss": "^8",
"tailwindcss": "^3.4.1"
}
}
================================================
FILE: Video 136/bitlinks/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 136/bitlinks/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 137/linktree-clone/.eslintrc.json
================================================
{
"extends": "next/core-web-vitals"
}
================================================
FILE: Video 137/linktree-clone/.gitignore
================================================
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# env files (can opt-in for commiting if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
================================================
FILE: Video 137/linktree-clone/README.md
================================================
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
================================================
FILE: Video 137/linktree-clone/app/[handle]/page.js
================================================
import Link from "next/link"
import clientPromise from "@/lib/mongodb"
import { notFound } from "next/navigation";
export default async function Page({ params }) {
const handle = (await params).handle
const client = await clientPromise;
const db = client.db("bittree")
const collection = db.collection("links")
// If the handle is already claimed, you cannot create the bittree
const item = await collection.findOne({handle: handle})
if(!item){
return notFound()
}
console.log(item)
const item2 = {
"_id": {
"$oid": "6729e97390cf30c8f66c4c68"
},
"links": [
{
"link": "https://www.instagram.com/codewithharry/?hl=en",
"linktext": "Instagram"
},
{
"link": "https://www.codewithharry.com",
"linktext": "Website"
},
{
"link": "https://www.YouTube.com/codewithharry/?hl=en",
"linktext": "YouTube"
}
],
"handle": "harry",
"pic": "https://avatars.githubusercontent.com/u/48705673?v=4"
}
return
{item &&
@{item.handle}
{item.desc}
{item.links.map((item, index)=>{
return
{item.linktext}
})}
}
}
================================================
FILE: Video 137/linktree-clone/app/api/add/route.js
================================================
import clientPromise from "@/lib/mongodb"
export async function POST(request) {
const body = await request.json()
const client = await clientPromise;
const db = client.db("bittree")
const collection = db.collection("links")
// If the handle is already claimed, you cannot create the bittree
const doc = await collection.findOne({handle: body.handle})
if (doc){
return Response.json({ success: false, error: true, message: 'This Bittree already exists!', result: null })
}
const result = await collection.insertOne(body)
return Response.json({ success: true, error: false, message: 'Your Bittree has been generated!', result: result, })
}
================================================
FILE: Video 137/linktree-clone/app/generate/page.js
================================================
"use client"
import React, { useState } from 'react'
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { useSearchParams } from 'next/navigation';
const Generate = () => {
const searchParams = useSearchParams()
// const [link, setlink] = useState("")
// const [linktext, setlinktext] = useState("")
const [links, setLinks] = useState([{link: "", linktext: ""}])
const [handle, sethandle] = useState(searchParams.get('handle'))
const [pic, setpic] = useState("")
const [desc, setdesc] = useState("")
const handleChange = (index, link, linktext) => {
setLinks((initialLinks)=>{
return initialLinks.map((item, i)=>{
if (i==index){
return {link, linktext}
}
else {
return item
}
})
})
}
const addLink = () => {
setLinks(links.concat([{link: "", linktext: ""}]))
}
const submitLinks = async () => {
const myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
const raw = JSON.stringify({
"links": links,
"handle": handle,
"pic": pic,
"desc": desc
});
console.log(raw)
const requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow"
};
const r = await fetch("http://localhost:3000/api/add", requestOptions)
const result = await r.json()
if(result.success){
toast.success(result.message)
setLinks([])
setpic("")
sethandle("")
}
else{
toast.error(result.message)
}
}
return (
)
}
export default Generate
================================================
FILE: Video 137/linktree-clone/app/globals.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
================================================
FILE: Video 137/linktree-clone/app/layout.js
================================================
import localFont from "next/font/local";
import "./globals.css";
import Navbar from "@/components/Navbar";
const geistSans = localFont({
src: "./fonts/GeistVF.woff",
variable: "--font-geist-sans",
weight: "100 900",
});
const geistMono = localFont({
src: "./fonts/GeistMonoVF.woff",
variable: "--font-geist-mono",
weight: "100 900",
});
export const metadata = {
title: "BitTree - Your favorite link sharing site",
description: "We brought a revolution in link sharing",
};
export default function RootLayout({ children }) {
return (
{children}
);
}
================================================
FILE: Video 137/linktree-clone/app/page.js
================================================
"use client"
import Image from "next/image";
import { useState } from "react";
import { useRouter } from "next/navigation";
export default function Home() {
const router = useRouter()
const [text, setText] = useState("")
const createTree = () => {
router.push(`/generate?handle=${text}`)
}
return (
Everything you
are. In one,
simple link in bio.
Join 50M+ people using Linktree for their link in bio. One link to help you share everything you create, curate and sell from your Instagram, TikTok, Twitter, YouTube and other social media profiles.
setText(e.target.value)} className="px-2 py-2 focus:outline-green-800 rounded-md" type="text" placeholder="Enter your Handle" />
createTree()} className="bg-pink-300 rounded-full px-4 py-4 font-semibold">Claim your Bittree
);
}
================================================
FILE: Video 137/linktree-clone/components/Navbar.js
================================================
"use client"
import React from 'react'
import Link from 'next/link'
import { usePathname } from "next/navigation";
const Navbar = () => {
const pathname = usePathname()
const showNavbar = ["/", "/generate"].includes(pathname)
return ( <>{showNavbar &&
Templates
Marketplace
Discover
Pricing
Learn
Log in
Sign up free
}
>
)
}
export default Navbar
================================================
FILE: Video 137/linktree-clone/jsconfig.json
================================================
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
================================================
FILE: Video 137/linktree-clone/lib/mongodb.js
================================================
// lib/mongodb.js
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Add Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
================================================
FILE: Video 137/linktree-clone/next.config.mjs
================================================
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
================================================
FILE: Video 137/linktree-clone/package.json
================================================
{
"name": "linktree-clone",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"mongodb": "^6.10.0",
"next": "15.0.2",
"react": "19.0.0-rc-02c0e824-20241028",
"react-dom": "19.0.0-rc-02c0e824-20241028",
"react-toastify": "^10.0.6"
},
"devDependencies": {
"eslint": "^8",
"eslint-config-next": "15.0.2",
"postcss": "^8",
"tailwindcss": "^3.4.1"
}
}
================================================
FILE: Video 137/linktree-clone/postcss.config.mjs
================================================
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
================================================
FILE: Video 137/linktree-clone/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
},
},
plugins: [],
};
================================================
FILE: Video 14/index.html
================================================
CSS
Hey I am harry and today I am in CSS Mood
I am good
I am also good
Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores tempora possimus molestiae doloremque quod. Recusandae laborum, laudantium cupiditate magni nostrum sit repellat dolorum ipsa vero aspernatur saepe autem, quod obcaecati, maxime quaerat! Praesentium culpa ipsam quasi odio sapiente nam, animi velit corporis nostrum!
================================================
FILE: Video 15/index.html
================================================
Document
Three ways to add CSS to HTML
Inline CSS
Internal CSS
External CSS
Everyone is good in some way or the other. Does this even make any sense?
================================================
FILE: Video 15/style.css
================================================
h1{
background-color: red;
color: yellow;
}
================================================
FILE: Video 16/index.html
================================================
Document
My Videos and Audios for the Day
Some Videos for the Day
Some Audios for the Day
================================================
FILE: Video 17/index.html
================================================
CSS Selectors
I am first
I am second
I am a div
I am a para inside div
I am another div
Go to Google
Go to Facebook
================================================
FILE: Video 18/index.html
================================================
CSS Boxmodel
I am a box
I am another box
================================================
FILE: Video 19/colors.html
================================================
Colors
Lets learn about colors
Color can be represented in:
Color Keywords
Hex Color Code
RGB
RGBA
HSL
================================================
FILE: Video 19/index.html
================================================
Fonts
Fonts
about Fonts
This is a video on fonts
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quos sequi accusamus quas itaque molestias dolorem quisquam quod, adipisci maxime dolore, mollitia illo officia deserunt voluptatem iure qui. Fugit aliquam possimus aperiam commodi eum amet veniam at vel. Necessitatibus asperiores eos amet laborum dolor, ipsum porro!
================================================
FILE: Video 20/index.html
================================================
Document
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita explicabo consectetur dicta fuga ea at vitae suscipit, repellendus illum deleniti laboriosam ipsa distinctio.
I am another para
I am also another para
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita explicabo consectetur dicta fuga ea at vitae suscipit, repellendus illum deleniti laboriosam ipsa distinctio.
I am another para
I am also another para
================================================
FILE: Video 21/index.html
================================================
Document
CSS Specificity
================================================
FILE: Video 22/index.html
================================================
Document
This is a box
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Perferendis necessitatibus quia quod iste dolorem
voluptatem fuga quidem aspernatur. Nihil ipsa sint quae, beatae explicabo saepe impedit laboriosam magni
cupiditate expedita voluptates consequatur odit veritatis dolorum doloribus. Iure nemo odit dicta, delectus,
modi reiciendis maiores ut quo adipisci libero quam laboriosam nihil voluptate natus nobis earum ad?
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero omnis voluptas est aliquam, dolores rem laudantium nulla maiores odio fugit, totam voluptatem saepe!
I am another container
================================================
FILE: Video 23/index.html
================================================
CSS Display Property
I am a box
also a nice box
I am a good
boy
================================================
FILE: Video 24/index.html
================================================
Document
I am a box
Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto, atque. Modi voluptatibus necessitatibus architecto quidem sit maiores, ad nesciunt et odit esse. Possimus, ipsam et molestiae eius quae nisi quisquam maiores fugiat aut fuga!
================================================
FILE: Video 25/index.html
================================================
CSS Lists
================================================
FILE: Video 26/index.html
================================================
Overflow
I am a good boy and I love to write Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dicta iure amet
unde voluptas nihil vero, maxime esse quis quos natus rem, earum aspernatur quasi aut ea commodi nostrum
voluptate! Sint rerum nostrum perferendis sapiente explicabo perspiciatis, ut magni? Aspernatur, provident
dolorum unde corporis doloribus rem!
================================================
FILE: Video 27/index.html
================================================
Document
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita explicabo consectetur dicta fuga ea at vitae suscipit, repellendus illum deleniti laboriosam ipsa distinctio.
I am another para
I am also another para
Lorem ipsum dolor sit amet consectetur adipisicing elit. Expedita explicabo consectetur dicta fuga ea at vitae suscipit, repellendus illum deleniti laboriosam ipsa distinctio.
I am another para
I am also another para
================================================
FILE: Video 28/index.html
================================================
CSS Position
================================================
FILE: Video 29/index.html
================================================
Document
================================================
FILE: Video 30/index.html
================================================
Css Variables
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Esse assumenda qui ad dolorem consequuntur facilis aliquam. Unde sapiente ipsam quaerat, at debitis nesciunt, totam nulla quae ad ipsum veniam sed eligendi rem deserunt quos maiores modi. Illo eaque expedita natus iusto nostrum dolorem quos est.
================================================
FILE: Video 31/index.html
================================================
CSS media query
Hey I am a red body guy!
================================================
FILE: Video 32/index.html
================================================
CSS Card Design
Nature
Lake
Harry
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas nemo numquam vel cumque ullam alias sequi suscipit velit! Enim cumque aperiam tempore tenetur?
Read More
Nature
Lake
Harry
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas nemo numquam vel cumque ullam alias sequi suscipit velit! Enim cumque aperiam tempore tenetur?
Read More
Nature
Lake
Harry
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quas nemo numquam vel cumque ullam alias sequi suscipit velit! Enim cumque aperiam tempore tenetur?
Read More
================================================
FILE: Video 33/index.html
================================================
Document
Create a multicolor website which can change color using CSS Variables
================================================
FILE: Video 34/index.html
================================================
CSS Float & Clear
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Commodi fugiat ab tenetur praesentium sequi, nisi nesciunt officiis magnam ut at voluptatibus sapiente ducimus deleniti esse alias nihil. Soluta iure ipsum voluptatibus assumenda ratione ut?
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Inventore explicabo dignissimos a et sapiente sunt assumenda cupiditate veniam cumque ipsa? Autem quod, id itaque velit cupiditate ea quia sit laudantium asperiores. Culpa fuga libero odio consequatur et totam ratione tempore eos ipsum, soluta omnis, fugiat facere? Quam neque a pariatur debitis quos vero maiores, porro, voluptatum earum corporis deserunt dolore ipsa! Explicabo ea ipsum possimus fugiat accusantium, incidunt ducimus. Assumenda nulla beatae dolores, recusandae voluptates non dolorem ut, obcaecati minus ducimus officiis in impedit. Quas cupiditate totam quis. Tempora praesentium similique cumque dolores ipsa commodi nobis itaque vero, est fugiat, accusantium maiores quos beatae quaerat quibusdam officia corrupti. Quaerat eaque magni error fugit nihil. Asperiores libero minus velit assumenda quo repellendus doloribus officia unde facere commodi a ab porro, repudiandae quidem! Officia, earum. Aliquam, id? Praesentium temporibus distinctio architecto asperiores consequatur provident reiciendis corrupti, nostrum nam hic voluptatem minima. Cum assumenda iste iusto. Adipisci quaerat labore suscipit minus libero ratione quidem recusandae neque. Eveniet amet animi quas quod facilis dicta, fugiat praesentium laborum, a delectus culpa cumque. Fugiat alias suscipit nostrum repellat nesciunt repudiandae enim provident iste a quo? Facere reiciendis ut illo quis blanditiis ipsa tempora, eos cupiditate corrupti ex alias laboriosam velit impedit eveniet asperiores sunt aperiam maxime earum explicabo? Modi cupiditate voluptatibus perspiciatis consequuntur quis, aut commodi, error libero, expedita debitis accusamus rem illo mollitia! Natus, repellat velit enim quaerat eius voluptate odio adipisci fuga accusantium officiis quidem perferendis qui fugiat amet! Nulla quisquam praesentium omnis excepturi officiis, quasi similique vero, unde, quos quo aperiam numquam! Dolorem, ea. Dignissimos blanditiis, quia quibusdam deserunt doloribus tempora perferendis pariatur dolore itaque voluptates mollitia fugiat deleniti tempore commodi. Doloribus facilis molestiae repellat possimus eligendi voluptatibus hic quos maiores architecto magni enim fugit, reiciendis, adipisci esse, illo exercitationem assumenda id? Laboriosam, temporibus odit? Facere ratione repellendus laudantium laborum incidunt voluptatibus explicabo deleniti iusto dolorum nisi dicta fugiat saepe qui molestias commodi non dolor aperiam unde provident optio, enim omnis quidem. Nulla molestias officia numquam.
Card 3
================================================
FILE: Video 35/index.html
================================================
More on CSS Selectors
I am first box
Hey I am a box
Hey I am a box
================================================
FILE: Video 36/index.html
================================================
CSS MultiColor Website
================================================
FILE: Video 38/index.html
================================================
CSS Flexbox
================================================
FILE: Video 39/grid-1.html
================================================
CSS Grid
================================================
FILE: Video 39/grid-2.html
================================================
CSS Grid
================================================
FILE: Video 40/index.html
================================================
Layout
Welcome to Sigma Web Development Express
================================================
FILE: Video 41/index.html
================================================
Document
================================================
FILE: Video 42/Demo.html
================================================
CSS Transform by CodeWithHarry
================================================
FILE: Video 42/index.html
================================================
Css Transform
================================================
FILE: Video 42/style.css
================================================
.wrap {
margin: 30px auto;
max-width: 1000px;
width: 90vw;
display: flex;
flex-flow: row wrap;
justify-content: center;
font-family: sans-serif;
}
.box {
width: calc(20%);
margin: 20px 20px;
background: #ddd;
cursor: pointer;
color: #FFF;
text-align: center;
line-height: 130px;
}
.blue {
background-color: rgba(56, 207, 248, 0.5);
}
.scaleX {
transform: scaleX(1);
transition: transform 0.5s ease;
}
.box:hover .scaleX {
transform: scaleX(2);
}
.scaleY {
transform: scaleY(1);
transition: transform 0.5s ease;
}
.box:hover .scaleY {
transform: scaleY(2);
}
.scale {
transform: scale(1, 1);
transition: transform 0.5s ease;
}
.box:hover .scale {
transform: scale(1.5, 1.5);
}
.translateX {
transform: translateX(1);
transition: transform 0.5s ease;
}
.box:hover .translateX {
transform: translateX(2em);
}
.translateY {
transform: translateY(1);
transition: transform 0.5s ease;
}
.box:hover .translateY {
transform: translateY(2em);
}
.translate {
transform: translate(1, 1);
transition: transform 0.5s ease;
}
.box:hover .translate {
transform: translate(2em, 2em);
}
.matrix {
transform: matrix(1, 1, 1, 1);
transition: transform 0.5s ease;
}
.box:hover .matrix {
transform: matrix(1, -1, 0, 1, 0, 0);
}
.rotate {
transform: rotate(0);
transition: transform 0.5s ease;
}
.box:hover .rotate {
transform: rotate(270deg);
}
.skew {
transform: skew(1, 1);
transition: transform 0.5s ease;
}
.box:hover .skew {
transform: skew(30deg, 20deg);
}
.skewX {
transform: skewX(1);
transition: transform 0.5s ease;
}
.box:hover .skewX {
transform: skewX(30deg);
}
.skewY {
transform: skewY(1);
transition: transform 0.5s ease;
}
.box:hover .skewY {
transform: skewY(30deg);
}
.matrix3d {
transform: matrix3d(1);
transition: transform 0.5s ease;
}
.box:hover .matrix3d {
transform: matrix3d(0.8535533905932737, 0.4999999999999999, 0.14644660940672619, 0, -0.4999999999999999, 0.7071067811865476, 0.4999999999999999, 0, 0.14644660940672619, -0.4999999999999999, 0.8535533905932737, 0, 22.62994231491119, -20.3223304703363, 101.3700576850888, 1)
}
.translate3d {
transform: translate3d(1px, 1px, 1);
transition: transform 0.5s ease;
}
.box:hover .translate3d {
transform: translate3d(1px, 1px, 50px) rotate3d(3, 2, 2, 90deg);
}
.rotateY {
transform: perspective(1) scaleZ(1) rotateY(0deg);
transition: transform 0.5s ease;
}
.box:hover .rotateY {
transform: perspective(500px) scaleZ(2) rotateY(45deg);
}
.rotateX {
transform: perspective(1) scaleZ(1) rotateX(0deg);
transition: transform 0.5s ease;
}
.box:hover .rotateX {
transform: perspective(500px) scaleZ(2) rotateX(45deg);
}
.translateZ {
transform: translateZ(1px);
transition: transform 0.5s ease;
}
.box:hover .translateZ {
transform: rotate3d(3, 2, 2, 90deg) translateZ(50px);
}
================================================
FILE: Video 43/index.html
================================================
Document
Products
Pricing
Resources
About Us
================================================
FILE: Video 44/index.html
================================================
Document
Download UE
================================================
FILE: Video 45/index.html
================================================
CSS Transitions
================================================
FILE: Video 46/index.html
================================================
CSS Animations
================================================
FILE: Video 47/index.html
================================================
Download UltraEdit text editor for Windows
Products
Pricing
Resources
About Us
Download UltraEdit for Windows
Download and try UltraEdit before you buy it! This download includes the full Windows version of the
text editor.
DOWNLOAD MAC OR LINUX VERSION
Download UltraEdit
v2023.1(released 08/16/2023) | Hotfix
================================================
FILE: Video 47/style.css
================================================
.logo {}
.logo img {
width: 164px;
}
nav {
display: flex;
justify-content: space-around;
align-items: center;
font-family: "Segoe UI";
}
.right ul {
display: flex;
gap: 34px;
}
.right ul li {
list-style: none;
display: flex;
align-items: center;
cursor: pointer;
}
.right ul li span {
padding: 0 5px;
}
.first {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 23px;
margin: 70px;
font-family: sans-serif;
}
.first span {
font-size: 40px;
}
section span img {
width: 82px;
margin: 0 23px;
}
.first p {
font-size: 23px;
width: 44vw;
text-align: center;
}
.btn {
background: #00b6d1;
padding: 14px 16px;
color: white;
border: none;
border-radius: 6px;
font-weight: 700;
margin: 12px 0;
cursor: pointer;
}
.btn a{
text-decoration: none;
color: white;
}
.green {
background-color: #5cb85c;
}
.flex {
display: flex;
}
.small {
font-size: 12px;
}
.second {
max-width: 50vw;
margin: auto;
}
.item {
padding: 23px;
background: #f9f9f9;
border-radius: 12px;
font-size: 20px;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
text-align: center;
}
.item-lang{
font-weight: 700;
text-align: center;
padding-bottom: 36px;
}
.grid{
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap:12px
}
.download :nth-child(2){
font-size: 23px;
}
.download img{
padding: 0px 12px;
}
.download{
display: flex;
font-family: sans-serif;
gap: 10px;
align-items: center;
}
@media screen and (max-width: 1145px) {
.grid{
grid-template-columns: 1fr;
}
}
================================================
FILE: Video 48/index.html
================================================
Document
================================================
FILE: Video 49/index.html
================================================
CSS object Fit and position
================================================
FILE: Video 50/index.html
================================================
CSS Filters
================================================
FILE: Video 51/index.html
================================================
Document
================================================
FILE: Video 52/index.html
================================================
Document
================================================
FILE: Video 53/index.html
================================================
Netflix India – Watch TV Shows Online, Watch Movies Online
English
Sign In
Enjoy on your TV
Watch on smart TVs, PlayStation, Xbox, Chromecast, Apple TV, Blu-ray players and more.
Download your shows to watch offline
Save your favourites easily and always have something to watch.
Watch everywhere
Stream unlimited movies and TV shows on your phone, tablet, laptop, and TV.
Create profiles for kids
Send children on adventures with their favourite characters in a space made just for them—free with
your membership.
Frequently Asked Questions
How much does Netflix cost?
What can I watch on Netflix?
================================================
FILE: Video 53/style.css
================================================
@import url('https://fonts.googleapis.com/css2?family=Martel+Sans:wght@600&family=Poppins:wght@300;400;700&display=swap');
* {
padding: 0;
margin: 0;
font-family: 'Poppins', sans-serif;
}
body {
background-color: black;
}
.main {
background-image: url("assets/images/bg.jpg");
background-position: center center;
background-size: max(1200px, 100vw);
background-repeat: no-repeat;
height: 644px;
position: relative;
}
.main .box {
height: 644px;
width: 100%;
opacity: 0.69;
position: absolute;
top: 0;
background-color: black;
}
nav {
max-width: 60vw;
justify-content: space-between;
margin: auto;
display: flex;
align-items: center;
height: 100px;
}
nav img {
color: red;
width: 130px;
position: relative;
z-index: 10;
}
nav button {
position: relative;
z-index: 10;
}
.hero {
font-family: 'Martel Sans', sans-serif;
height: calc(100% - 100px);
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
color: white;
position: relative;
gap: 23px;
padding: 0 30px;
}
.hero> :nth-child(1) {
font-family: 'Poppins', sans-serif;
font-weight: bolder;
font-size: 48px;
text-align: center;
}
.hero> :nth-child(2) {
font-weight: 400;
font-size: 24px;
text-align: center;
}
.hero> :nth-child(3) {
font-weight: 400;
font-size: 20px;
text-align: center;
}
.separation {
height: 7px;
background-color: rgb(46, 44, 44);
position: relative;
z-index: 20;
}
.btn {
padding: 3px 8px;
font-weight: 400;
color: white;
background-color: rgba(248, 243, 243, 0.021);
border-radius: 4px;
border: 1px solid white;
cursor: pointer;
}
.btn-red {
background-color: red;
color: white;
padding: 3px 24px;
font-size: 20px;
border-radius: 4px;
font-weight: 400;
}
.btn-red-sm {
background-color: red;
color: white;
}
.hero-buttons {
display: flex;
align-items: center;
justify-content: center;
gap: 16px;
}
.main input {
padding: 7px 101px 8px 14px;
color: white;
font-size: 12px;
border-radius: 4px;
background-color: rgba(23, 23, 23, 0.7);
border: 1px solid rgba(246, 238, 238, 0.5);
}
.first {
display: flex;
justify-content: center;
max-width: 70vw;
margin: auto;
color: white;
justify-content: center;
align-items: center;
}
.secImg {
position: relative;
}
.secImg img {
width: 555px;
position: relative;
z-index: 10;
}
.secImg video {
position: absolute;
top: 51px;
right: 0;
width: 555px;
}
section.first>div {
display: flex;
flex-direction: column;
padding: 34px 0;
}
section.first>div :nth-child(1) {
font-size: 48px;
font-weight: bolder;
}
section.first>div :nth-child(2) {
font-size: 24px;
}
.faq h2 {
text-align: center;
font-size: 48px;
}
.faq {
background: black;
color: white;
padding: 34px;
}
.faqbox:hover {
background-color: #414141;
color: white;
}
.faqbox svg {
filter: invert(1);
}
.faqbox {
transition: all 1s ease-out;
font-size: 24px;
display: flex;
justify-content: space-between;
background-color: #2d2d2d;
padding: 24px;
max-width: 60vw;
margin: 34px auto;
cursor: pointer;
}
footer {
color: white;
max-width: 60vw;
margin: auto;
padding: 60px;
}
footer .questions {
padding: 34px 0;
}
.footer {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
color: white;
}
@media screen and (max-width: 1300px) {
nav{
max-width: 90vw;
}
.first {
flex-wrap: wrap;
}
.secImg img {
width: 305px;
}
.secImg video {
width: 305px;
}
.hero> :nth-child(1) {
font-size: 32px;
}
.hero> :nth-child(2) {
font-size: 18px;
}
.hero> :nth-child(3) {
font-size: 18px;
}
.hero-buttons {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
}
.faq h2 {
text-align: center;
font-size: 32px;
}
footer {
max-width: 90vw;
padding: 75px 0;
}
.footer-item{
align-items: center;
}
}
@media screen and (max-width: 1300px) {
.footer {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 25px;
}
}
.footer a {
font-size: 14px;
color: white;
}
.footer-item {
display: flex;
flex-direction: column;
gap: 23px;
}
================================================
FILE: Video 54/index.html
================================================
JavaScript Introduction
Hey I am a Box
Submit
================================================
FILE: Video 54/new.js
================================================
console.log("Hello World")
console.log("Code is running...")
console.log("Code is also running...")
console.log("Code is looking like a wow...")
================================================
FILE: Video 54/script.js
================================================
alert("Hello World");
console.log("Code is running...")
console.log("Code is also running...")
console.log("Code is looking like a wow...")
var a = prompt("Enter your number")
var isTrue = confirm("Are you sure you want to leave this page and blast your computer ")
if(isTrue){
console.log("Computer is blasting")
}
else{
console.log("Computer is not blasting")
}
console.log("Your number is " + a)
document.title = "Hey I am good"
// document.body.style.backgroundColor = "red"
================================================
FILE: Video 55/index.html
================================================
JavaScript Variables
================================================
FILE: Video 55/script.js
================================================
console.log("Hey this is tutorial 55");
var a = 5;
// a = a + 1
let b = 6;
let c = "Harry";
let _a = "Shubham";
// var 55a = "Rohan"; // Not Allowed
// console.log(a + b + 8);
// console.log(typeof a, typeof b, typeof c);
{
// let a = 66;
console.log(a)
}
console.log(a)
// const a1 = 6;
// a1 = a1 + 1; // Not Allowed because a1 is constant
let x = "Harry bhai";
let y = 22;
let z = 3.55;
const p = true;
let q = undefined;
let r = null;
console.log(x, y, z, p, q, r)
console.log(typeof x, typeof y, typeof z, typeof p, typeof q, typeof r)
let o = {
"name": "Harry",
"job code": 5600,
"is_handsome": true
}
console.log(o);
o.salary = "100crores";
console.log(o);
o.salary = "500crores";
console.log(o);
================================================
FILE: Video 56/index.js
================================================
console.log("Hello I am conditional tutorial")
let age = 1;
// let grace = 2;
// age += grace
// console.log(age)
// console.log(age + grace)
// console.log(age - grace)
// console.log(age * grace)
// console.log(age / grace)
// console.log(age ** grace)
// console.log(age % grace)
/*
I am a
multiline
comment
*/
if (age == 18) {
console.log("You can drive");
}
else if (age == 0) {
console.log("Are you kidding?")
}
else if (age == 1) {
console.log("Are you again kidding?")
}
else {
console.log("You cannot drive");
}
a = 6;
b = 8;
let c = a > b ? (a - b) : (b - a);
/*
translates to:
if(a>b){
let c = a - b;
}
else {
let c = a - b;
}
*/
================================================
FILE: Video 57/index.js
================================================
console.log("I am a tutorial on Loops")
let a = 1;
// console.log(a)
// console.log(a+1)
// console.log(a+2)
// for (let i = 0; i < 100; i++) {
// console.log(a + i);
// }
// let obj = {
// name: "Harry",
// role: "Programmer",
// company: "CodeWithHarry AI"
// }
// for (const key in obj) {
// console.log(key)
// }
// for (const c of "Harry") {
// console.log(c)
// }
// let i = 0;
// while (i<60000) {
// console.log(i)
// i++;
// }
let i = 10;
do {
console.log(i)
i++;
} while (i<6);
================================================
FILE: Video 58/index.js
================================================
function nice(name) {
console.log("Hey " + name + " you are nice!")
console.log("Hey " + name + " you are good!")
console.log("Hey " + name + " your tshirt is nice!")
console.log("Hey " + name + " your course is good too!")
}
function sum(a, b, c = 3) {
// console.log(a + b)
console.log(a, b, c)
return a + b + c
}
result1 = sum(3, 2)
result2 = sum(7, 5)
result3 = sum(3, 13, 1)
console.log("The sum of these numbers is: ", result1)
console.log("The sum of these numbers is: ", result2)
console.log("The sum of these numbers is: ", result3)
const func1 = (x)=>{
console.log("I am an arrow function", x)
}
func1(34);
func1(66);
func1(84);
================================================
FILE: Video 59/index.js
================================================
/* Create a faulty calculator using JavaScript
This faulty calculator does following:
1. It takes two numbers as input from the user
2. It perfoms wrong operations as follows:
+ ---> -
* ---> +
- ---> /
/ ---> **
It performs wrong operation 10% of the times
*/
================================================
FILE: Video 60/index.js
================================================
console.log("This is strings tutorial")
let a = "Harry";
console.log(a[0]);
console.log(a[1]);
console.log(a[2]);
console.log(a[3]);
console.log(a[4]);
// console.log(a[5]);
console.log(a.length)
let real_name = "Harry"
let friend = "Rohan"
console.log("His name is " + real_name + " and his friends name is " + friend)
console.log(`His name is ${real_name} and his friends name is ${friend}`)
let b = "ShivamSh"
console.log(b.toUpperCase())
console.log(b.toLowerCase())
console.log(b.length)
console.log(b.slice(1, 5))
console.log(b.slice(1))
console.log(b.replace("Sh", "77"))
console.log(b.concat(a, "Aishwariya", "Rahul", "Priya"))
console.log(b)
================================================
FILE: Video 61/index.html
================================================
Document
================================================
FILE: Video 61/index.js
================================================
/* Create a faulty calculator using JavaScript
This faulty calculator does following:
1. It takes two numbers as input from the user
2. It perfoms wrong operations as follows:
+ ---> -
* ---> +
- ---> /
/ ---> **
It performs wrong operation 10% of the times
*/
let random = Math.random()
console.log(random)
let a = prompt("Enter first number")
let c = prompt("Enter operation")
let b = prompt("Enter second number")
let obj = {
"+": "-",
"*": "+",
"-": "/",
"/": "**",
}
if (random > 0.1) {
// Perform correct calculation
console.log(`The result is ${a} ${c} ${b}`)
alert(`The result is ${eval(`${a} ${c} ${b}`)}`)
}
else {
// Perform wrong calculation
c = obj[c]
alert(`The result is ${eval(`${a} ${c} ${b}`)}`)
}
================================================
FILE: Video 62/index.js
================================================
/* Create a business name generator by combining list of adjectives and shop name and another word
Adjectives:
Crazy
Amazing
Fire
Shop Name:
Engine
Foods
Garments
Another Word:
Bros
Limited
Hub
*/
================================================
FILE: Video 63/index.html
================================================
Document
================================================
FILE: Video 63/index.js
================================================
let arr = [1, 2, 4, 5, 7]
// Index 0, 1, 2, 3, 4
arr[0] = 5666;
// console.log(arr, typeof arr);
// console.log(arr.length)
// console.log(arr[0])
// console.log(arr[2])
// console.log(arr[4])
console.log(arr.toString())
console.log(arr.join(" and "))
// let numbers = [1, 2, 3, 4, 5]
// numbers.splice(1, 2)
// numbers.splice(1, 3)
// numbers.splice(1, 3, 222, 333)
// (4) [1, 222, 333, 5]
================================================
FILE: Video 63/loops.js
================================================
let a = [1, 93, 5, 6, 88]
// for (let index = 0; index < a.length; index++) {
// const element = a[index];
// console.log(element)
// }
// a.forEach((value, index, arr)=>{
// console.log(value, index, arr)
// })
// let obj = {
// a: 1,
// b: 2,
// c: 3
// }
// for (const key in obj) {
// if (Object.hasOwnProperty.call(obj, key)) {
// const element = obj[key];
// console.log(key, element)
// }
// }
for (const value of a) {
console.log(value)
}
================================================
FILE: Video 63/mfr.js
================================================
let arr = [1, 13, 5 ,7, 11];
// let newArr = []
// for (let index = 0; index < arr.length; index++) {
// const element = arr[index];
// newArr.push(element**2)
// }
let newArr = arr.map((e, index, array)=>{
return e**2
})
console.log(newArr)
const greaterThanSeven = (e)=>{
if(e>7){
return true
}
return false
}
console.log(arr.filter(greaterThanSeven))
let arr2 = [1,2,3,4,5,6]
const red = (a, b)=>{
return a+b
}
console.log(arr2.reduce(red))
================================================
FILE: Video 64/index.html
================================================
Document
================================================
FILE: Video 65/index.html
================================================
Document
================================================
FILE: Video 66/index.html
================================================
JavaScript DOM
================================================
FILE: Video 67/index.html
================================================
Document
================================================
FILE: Video 67/script.js
================================================
console.log("Hello world")
document.body.firstElementChild
document.body.firstElementChild.childNodes
document.body.firstElementChild.children
================================================
FILE: Video 68/index.html
================================================
Document
Bhupendra Jogi 1
Bhupendra Jogi 1.5
Bhupendra Jogi 2
Bhupendra Jogi 2.5
Bhupendra Jogi 3
Bhupendra Jogi 4
Bhupendra Jogi 5
================================================
FILE: Video 68/script.js
================================================
console.log("Harry")
// let boxes = document.getElementsByClassName("box")
// console.log(boxes)
// boxes[2].style.backgroundColor = "red"
// document.getElementById("redbox").style.backgroundColor = "red"
// document.querySelector(".box").style.backgroundColor = "green";
console.log(document.querySelectorAll(".box"))
document.querySelectorAll(".box").forEach(e =>{
e.style.backgroundColor = "green";
})
================================================
FILE: Video 69/index.html
================================================
Document
================================================
FILE: Video 69/script.js
================================================
let a = 7
function factorial(number){
let arr = Array.from(Array(number+1).keys())
let c = arr.slice(1,).reduce((a, b)=> a*b )
return c
}
function facFor(number){
let fac = 1;
for (let index = 1; index <= number; index++) {
fac = fac * index
}
return fac
}
console.log(factorial(a))
console.log(facFor(a))
================================================
FILE: Video 70/index.html
================================================
Document
================================================
FILE: Video 71/index.html
================================================
Document
Hey I am a box
Hey I am a box
================================================
FILE: Video 72/index.html
================================================
Document
================================================
FILE: Video 72/script.js
================================================
console.log("Script.js initializing")
// let boxes = document.getElementsByClassName("box")
let boxes = document.querySelector(".container").children
function getRandomColor(){
let val1 = Math.ceil(0 + Math.random()* 255);
let val2 = Math.ceil(0 + Math.random()* 255);
let val3 = Math.ceil(0 + Math.random()* 255);
return `rgb(${val1}, ${val2}, ${val3})`
}
Array.from(boxes).forEach(e=>{
e.style.backgroundColor = getRandomColor()
e.style.color = getRandomColor()
})
================================================
FILE: Video 73/index.html
================================================
Document
================================================
FILE: Video 73/script.js
================================================
function createCard(title, cName, views, monthsOld, duration, thumbnail){
// Finish this function
}
createCard("Introduction to Backend | Sigma Web Dev video #2", "CodeWithHarry", 560000, 7, "31:22", "https://i.ytimg.com/vi/tVzUXW6siu0/hqdefault.jpg?sqp=-oaymwEcCPYBEIoBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLACwWOixJVrKLFindK92kYMgTcQbw")
================================================
FILE: Video 74/eventBubbling.html
================================================
Event bubbling
================================================
FILE: Video 74/index.html
================================================
Document
Change Content
================================================
FILE: Video 74/script.js
================================================
let button = document.getElementById("btn")
// List of all mouse events
// https://developer.mozilla.org/en-US/docs/Web/API/Element#mouse_events
button.addEventListener("dblclick", ()=>{
document.querySelector(".box").innerHTML = "Yayy you were clicked Enjoy your click!"
})
button.addEventListener("contextmenu", ()=>{
alert("Dont hack us by Right click Please")
})
document.addEventListener("keydown", (e)=>{
console.log(e, e.key, e.keyCode)
})
================================================
FILE: Video 75/index.html
================================================
Document
================================================
FILE: Video 75/promise.js
================================================
console.log('This is Promises');
let prom1 = new Promise((resolve, reject) => {
let a = Math.random();
if (a < 0.5) {
reject("No random number was not supporting you")
}
else {
setTimeout(() => {
console.log("Yes I am done")
resolve("Harry")
}, 3000);
}
})
let prom2 = new Promise((resolve, reject) => {
let a = Math.random();
if (a < 0.5) {
reject("No random number was not supporting you 2")
}
else {
setTimeout(() => {
console.log("Yes I am done 2")
resolve("Harry 2")
}, 1000);
}
})
let p3 = Promise.race([prom1, prom2])
p3.then((a)=>{
console.log(a)
}).catch(err=>{
console.log(err)
})
================================================
FILE: Video 75/script.js
================================================
console.log("Harry is a hacker")
console.log("Rohan is a hecker")
setTimeout(() => {
console.log("I am inside settimeout")
}, 0);
setTimeout(() => {
console.log("I am inside settimeout 2")
}, 0);
console.log("The End")
const fn = () => {
console.log("Nothing")
}
const callback = (arg, fn) => {
console.log(arg)
fn()
}
const loadScript = (src, callback) => {
let sc = document.createElement("script");
sc.src = src;
sc.onload = callback("Harry", fn);
document.head.append(sc)
}
loadScript("https://cdnjs.cloudflare.com/ajax/libs/prism/9000.0.1/prism.min.js", callback )
================================================
FILE: Video 76/index.html
================================================
Document
================================================
FILE: Video 76/script.js
================================================
// async function getData() {
// // Simulate getting data from a server
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// resolve(455)
// }, 3500);
// })
// }
// settle means resolve or reject
// resolve means promise has settled successfully
// reject means promise has not settled successfully
async function getData() {
// Simulate getting data from a server
// let x = await fetch('https://jsonplaceholder.typicode.com/todos/1')
let x = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
let data = await x.json()
return data
}
async function main(){
console.log("Loading modules")
console.log("Do something else")
console.log("Load data")
let data = await getData()
console.log(data)
console.log("process data")
console.log("task 2")
}
main()
// data.then((v) => {
// console.log(data)
// console.log("process data")
// console.log("task 2")
// })
================================================
FILE: Video 77/index.html
================================================
Document
31:06
Introduction to Backend | Sigma Web Dev video #2
CodeWithHarry . 727K views . 2 months ago
================================================
FILE: Video 77/script.js
================================================
function createCard(title, cName, views, monthsOld, duration, thumbnail) {
// Finish this function
let viewStr
if (views < 1000) {
viewStr = views;
}
else if (views > 1000000) {
viewStr = views / 1000000 + "M";
}
else {
viewStr = views / 1000 + "K";
}
let html = `
${duration}
${title}
${cName} . ${viewStr} views . ${monthsOld} months ago
`
document.querySelector(".container").innerHTML = document.querySelector(".container").innerHTML + html
}
createCard("Introduction to Backend | Sigma Web Dev video #2", "CodeWithHarry", 560000, 7, "31:22", "https://i.ytimg.com/vi/tVzUXW6siu0/hqdefault.jpg?sqp=-oaymwEcCPYBEIoBSFXyq4qpAw4IARUAAIhCGAFwAcABBg==&rs=AOn4CLACwWOixJVrKLFindK92kYMgTcQbw")
function sum
================================================
FILE: Video 78/index.html
================================================
Document
================================================
FILE: Video 79/index.html
================================================
Document
================================================
FILE: Video 79/script.js
================================================
let a = prompt("Enter first number")
let b = prompt("Enter second number")
if (isNaN(a) || isNaN(b)) {
throw SyntaxError("Sorry this is not allowed")
}
let sum = parseInt(a) + parseInt(b)
function main(){
let x = 1;
try {
console.log("The sum is ", sum * x)
return true
} catch (error) {
console.log("Error aa gaya bhai")
return false
}
finally{
console.log("files are being closed and db connection is being closed")
}
}
let c = main()
================================================
FILE: Video 80/gs.js
================================================
class User {
constructor(name) {
// invokes the setter
this.name = name;
}
get name() {
return this._name;
}
set name(value) {
if (value.length < 4) {
console.log("Name is too short.");
return;
}
this._name = value;
}
}
let user = new User("John");
console.log(user.name); // John
user.name = "Harry" // Name is too short.
console.log(user.name)
================================================
FILE: Video 80/index.html
================================================
Document
================================================
FILE: Video 80/script.js
================================================
// let obj = {
// a: 1,
// b: "Harry"
// }
// console.log(obj)
// let animal = {
// eats: true
// };
// let rabbit = {
// jumps: true
// };
// rabbit.__proto__ = animal; // sets rabbit.[[Prototype]] = animal
class Animal{
constructor(name){
this.name = name
console.log("Object is created...")
}
eats(){
console.log("Kha raha hoon")
}
jumps(){
console.log("Kood raha hoon")
}
}
class Lion extends Animal {
constructor(name){
super(name)
console.log("Object is created and he is a lion...")
}
eats(){
super.eats()
console.log("Kha raha hoon roar")
}
}
let a = new Animal("Bunny");
console.log(a)
let l = new Lion("Shera")
console.log(l)
================================================
FILE: Video 81/index.html
================================================
Document
Initializing Hacking...
================================================
FILE: Video 82/index.html
================================================
Document
================================================
FILE: Video 82/script.js
================================================
console.log(a1);
(async function main(){
// let a = await sleep()
// console.log(a)
// let b = await sleep()
// console.log(b);
// let [x, y, rest] = [1, 5, 7, 8, 9, 10]
// console.log(x, y, rest)
let obj = {
a: 1,
b: 2,
c: 3
}
let {a, b} = obj
console.log(a, b)
let arr = [1, 4, 6]
console.log(sum(arr[0], arr[1], arr[2]))
console.log(sum(...arr))
})()
var a1 = 6;
const sleep = async ()=>{
return new Promise((resolve, reject)=>{
setTimeout(() => {
resolve(45)
}, 1000);
})
}
const sum = async (a, b, c)=>{
return a+b+c
}
================================================
FILE: Video 83/Problems.md
================================================
# Problems for Sigma Developers
1. The Magical Sorting Hat:
Imagine you are creating a magical sorting hat for a wizard school. Implement a JavaScript function that takes an array of student names and assigns them to one of the four houses (Gryffindor (length less than 6), Hufflepuff(length less than 8), Ravenclaw(length less than 12), or Slytherin(length greater than or equal to 12)) based on the length of their names.
2. The Double Trouble:
You are tasked with writing a function that doubles each element in an array. However, there's a catch: if the array contains consecutive duplicate elements, only double one of them.
3. The Mirror Mirror:
Imagine you have a string, and you need to create a new string that is a mirror image of the original. Write a function that appends the reversed version of the original string to itself.
4. The Password Validator:
You are building a password validation feature. Create a function that checks if a given password meets the following criteria: at least 8 characters long, contains both uppercase and lowercase letters, and includes at least one digit.
5. The Sum Selector:
You are working on a function that should sum all numbers in an array until it encounters a negative number. Write a function that performs this summation.
6. The Vowel Counter:
You need to create a function that counts the number of vowels in a given string. Consider both uppercase and lowercase vowels.
7. The Local Storage Manager:
You are working on a note-taking app, and you want to implement a function named saveNoteToLocalStorage that takes a note object and saves it to the browser's local storage.
8. Async Array Mapping:
Write an asynchronous function that takes an array of numbers and returns a new array of Promises where each number is multiplied by 2 after a delay of 500 milliseconds.
9. The Asynchronous Shopper:
Imagine you are building an online shopping application. Write an asynchronous function called placeOrder that simulates placing an order and returns a promise. The promise should resolve with an order confirmation message after a random delay.
10. The Coffee Machine:
In your coffee shop application, you need to simulate the process of brewing coffee asynchronously. Write an async function named brewCoffee that takes the type of coffee and returns a promise. The promise should resolve with a message indicating that the coffee is ready after a random delay.
11. The Array Filterer:
You are building a search feature for your e-commerce site. Write a function named filterProducts that takes an array of product objects and a filter criterion. The function should return a new array containing only the products that match the filter criterion.
12. The Token Manager:
You are developing a user authentication system, and you need to manage user authentication tokens. Implement a function named setAuthToken that takes an authentication token and sets it in localStorage with an expiration time.
13. The Shopping Cart Totalizer:
You are working on an e-commerce website, and you need to calculate the total cost of items in the shopping cart. Implement a function named calculateTotal that takes an array of products with prices and quantities and returns the total cost.
14. The Window Scroller:
You are developing a single-page application with a smooth scrolling effect. Implement a function named smoothScrollToTop that smoothly scrolls the window to the top when called.
================================================
FILE: Video 83/Solutions/01_houses.js
================================================
// The Magical Sorting Hat: Imagine you are creating a magical sorting hat for a wizard school. Implement a JavaScript function that takes an array of student names and assigns them to one of the four houses (Gryffindor (length less than 6), Hufflepuff(length less than 8), Ravenclaw(length less than 12), or Slytherin(length greater than or equal to 12)) based on the length of their names.
let students = ["shubh", "anajali", "Shivani", "Shivangi", "Annapurna", "Shubham", "Krishnanendu", "Ravindranathan", "Shivesh", "kaif", "Emanuel"]
let houses = []
for (const student of students) {
if(student.length < 6){
houses.push("Gryffindor")
}
else if(student.length < 8){
houses.push("Hufflepuff")
}
else if(student.length < 12){
houses.push("Ravenclaw")
}
else{
houses.push("Slytherin")
}
}
console.log(houses)
================================================
FILE: Video 83/Solutions/07_localStorage.html
================================================
Document
Add Note
================================================
FILE: Video 84 - Project 2 - Spotify Clone/css/style.css
================================================
@import url('https://fonts.googleapis.com/css2?family=Lato:wght@700&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
:root{
--a:0;
}
* {
margin: 0;
padding: 0;
font-family: 'Roboto', sans-serif;
}
.close {
display: none;
}
body {
background-color: black;
color: white;
}
.left {
width: 25vw;
padding: 10px;
}
.right {
width: 75vw;
}
.home ul li {
display: flex;
gap: 15px;
width: 14px;
list-style: none;
padding-top: 14px;
font-weight: bold;
}
.heading {
display: flex;
gap: 15px;
width: 100%;
padding-top: 14px;
padding: 23px 14px;
font-weight: bold;
align-items: center;
font-size: 13px;
}
.heading img {
width: 30px;
}
.library {
min-height: 80vh;
position: relative;
}
.footer {
display: flex;
font-size: 10px;
color: grey;
gap: 13px;
position: absolute;
bottom: 0;
padding: 10px 0;
}
.footer a {
color: grey;
}
.right {
margin: 16px 0;
position: relative;
}
.header {
display: flex;
justify-content: space-between;
background-color: rgb(34 34 34);
}
.header>* {
padding: 20px;
}
.spotifyPlaylists {
padding: 16px;
}
.spotifyPlaylists h1 {
padding: 16px;
}
.cardContainer {
margin: 30px;
display: flex;
gap: 10px;
flex-wrap: wrap;
overflow-y: auto;
max-height: 60vh;
}
.card {
width: 200px;
padding: 10px;
border-radius: 5px;
background-color: #252525;
position: relative;
transition: all .9s;
}
.card:hover{
background-color: rgb(105, 103, 103);
cursor: pointer;
--a: 1;
}
.card>* {
padding-top: 10px;
}
.card img {
width: 100%;
object-fit: contain;
}
.play {
width: 28px;
height: 28px;
background-color: #1fdf64;
border-radius: 50%;
padding: 4px;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
bottom: 88px;
right: 17px;
opacity: var(--a);
transition: all 1s ease-out;
}
.buttons>* {
margin: 0 12px;
}
.signupbtn {
background-color: rgb(34 34 34);
color: rgb(156, 148, 148);
font-weight: bold;
border: none;
outline: none;
cursor: pointer;
font-size: 16px;
}
.signupbtn:hover {
font-size: 17px;
color: white
}
.loginbtn {
background-color: white;
border-radius: 21px;
color: black;
padding: 10px;
width: 79px;
cursor: pointer;
font-size: 16px;
}
.loginbtn:hover {
font-weight: bold;
font-size: 17px;
}
.playbar {
display: flex;
justify-content: center;
align-items: center;
position: fixed;
bottom: 30px;
filter: invert(1);
background: #e2d9d9;
border-radius: 10px;
width: 90%;
padding: 12px;
width: 70vw;
min-height: 40px;
}
.songbuttons {
display: flex;
justify-content: center;
gap: 16px;
}
.songList {
height: 544px;
overflow: auto;
margin-bottom: 44px;
}
.hamburger {
display: none;
cursor: pointer;
}
.hamburgerContainer {
display: flex;
justify-content: center;
align-items: center;
gap: 14px;
}
.songList ul {
padding: 0 12px;
}
.songList ul li {
list-style-type: decimal;
display: flex;
justify-content: space-between;
gap: 12px;
cursor: pointer;
padding: 12px 0;
border: 1px solid rgba(146, 143, 143, 0.491);
margin: 12px 0;
padding: 13px;
border-radius: 5px;
}
.songList .info {
font-size: 13px;
width: 344px;
}
.info div {
word-break: break-all;
}
.playnow {
display: flex;
justify-content: center;
align-items: center;
}
.playnow span {
font-size: 15px;
width: 64px;
padding: 12px;
}
.seekbar {
height: 4px;
width: 98%;
background: black;
border-radius: 10px;
position: absolute;
bottom: 8px;
margin: 6px;
cursor: pointer;
}
.circle {
width: 13px;
height: 13px;
border-radius: 13px;
background-color: black;
position: relative;
bottom: 5px;
left: 0%;
transition: left 0.5s;
}
.songbuttons img {
cursor: pointer;
}
.timevol {
display: flex;
justify-content: space-evenly;
align-items: center;
}
.songinfo {
color: black;
padding: 0 12px;
width: 250px;
}
.songtime {
width: 125px;
color: black;
padding: 0 12px;
}
.volume {
display: flex;
justify-content: center;
align-items: center;
gap: 12px;
cursor: pointer;
}
.range input{
cursor: pointer;
}
.abovebar {
display: flex;
justify-content: space-between;
margin: 20px 0;
width: 100%;
}
@media (max-width: 1200px) {
.left {
position: absolute;
left: -130%;
transition: all .3s;
z-index: 1;
width: 373px;
background-color: black;
padding: 0;
height: 100vh;
position: fixed;
top: 0;
}
.songinfo,
.songtime {
width: auto;
}
.left .close {
position: absolute;
right: 31px;
top: 25px;
width: 29px;
}
.timevol {
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
gap: 13px;
}
.right {
width: 100vw;
}
.playbar {
width: calc(100vw - 75px);
}
.seekbar {
width: calc(100vw - 120px);
}
.hamburger {
display: block;
}
.right {
margin: 0;
}
.card {
width: 55vw;
}
.cardContainer {
margin: 0;
justify-content: center;
}
.close {
display: block;
}
.abovebar {
flex-direction: column;
gap: 23px;
align-items: center;
}
.cardContainer {
max-height: unset;
overflow-y: unset;
margin-bottom: 35vh;
}
.playbar{
right: 25px;
}
}
@media (max-width: 500px) {
.card {
width: 100%;
}
.header>* {
padding: 2px;
}
.buttons>* {
margin: 0 6px;
}
.header{
padding: 7px;
}
.spotifyPlaylists h1 {
padding: 4px;
}
.library{
height: 85vh;
}
.left{
width: 100vw;
}
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/css/utility.css
================================================
.border{
border: 2px solid red;
margin: 3px;
}
.flex{
display: flex;
}
.justify-center{
justify-content: center;
}
.items-center{
align-items: center;
}
.bg-black{
background-color: black;
color: white;
}
.invert{
filter: invert(1);
}
.bg-grey{
background-color: #121212;
}
.rounded{
border-radius: 7px;
}
.m-1{
margin: 5px;
}
.p-1{
padding: 10px;
}
/* For Webkit browsers (e.g., Chrome, Safari) */
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
background-color: #333; /* Dark color for the thumb */
border-radius: 6px;
}
::-webkit-scrollbar-track {
background-color: #222; /* Dark color for the track */
}
/* For Firefox */
scrollbar-color: #333 #222; /* Dark color for the thumb and track in Firefox */
================================================
FILE: Video 84 - Project 2 - Spotify Clone/index.html
================================================
Spotify - Web Player: Music for everyone
================================================
FILE: Video 84 - Project 2 - Spotify Clone/js/script.js
================================================
console.log('Lets write JavaScript');
let currentSong = new Audio();
let songs;
let currFolder;
function secondsToMinutesSeconds(seconds) {
if (isNaN(seconds) || seconds < 0) {
return "00:00";
}
const minutes = Math.floor(seconds / 60);
const remainingSeconds = Math.floor(seconds % 60);
const formattedMinutes = String(minutes).padStart(2, '0');
const formattedSeconds = String(remainingSeconds).padStart(2, '0');
return `${formattedMinutes}:${formattedSeconds}`;
}
async function getSongs(folder) {
currFolder = folder;
let a = await fetch(`/${folder}/`)
let response = await a.text();
let div = document.createElement("div")
div.innerHTML = response;
let as = div.getElementsByTagName("a")
songs = []
for (let index = 0; index < as.length; index++) {
const element = as[index];
if (element.href.endsWith(".mp3")) {
songs.push(element.href.split(`/${folder}/`)[1])
}
}
// Show all the songs in the playlist
let songUL = document.querySelector(".songList").getElementsByTagName("ul")[0]
songUL.innerHTML = ""
for (const song of songs) {
songUL.innerHTML = songUL.innerHTML + `
${song.replaceAll("%20", " ")}
Harry
Play Now
`;
}
// Attach an event listener to each song
Array.from(document.querySelector(".songList").getElementsByTagName("li")).forEach(e => {
e.addEventListener("click", element => {
playMusic(e.querySelector(".info").firstElementChild.innerHTML.trim())
})
})
return songs
}
const playMusic = (track, pause = false) => {
currentSong.src = `/${currFolder}/` + track
if (!pause) {
currentSong.play()
play.src = "img/pause.svg"
}
document.querySelector(".songinfo").innerHTML = decodeURI(track)
document.querySelector(".songtime").innerHTML = "00:00 / 00:00"
}
async function displayAlbums() {
console.log("displaying albums")
let a = await fetch(`/songs/`)
let response = await a.text();
let div = document.createElement("div")
div.innerHTML = response;
let anchors = div.getElementsByTagName("a")
let cardContainer = document.querySelector(".cardContainer")
let array = Array.from(anchors)
for (let index = 0; index < array.length; index++) {
const e = array[index];
if (e.href.includes("/songs") && !e.href.includes(".htaccess")) {
let folder = e.href.split("/").slice(-2)[0]
// Get the metadata of the folder
let a = await fetch(`/songs/${folder}/info.json`)
let response = await a.json();
cardContainer.innerHTML = cardContainer.innerHTML + `
${response.title}
${response.description}
`
}
}
// Load the playlist whenever card is clicked
Array.from(document.getElementsByClassName("card")).forEach(e => {
e.addEventListener("click", async item => {
console.log("Fetching Songs")
songs = await getSongs(`songs/${item.currentTarget.dataset.folder}`)
playMusic(songs[0])
})
})
}
async function main() {
// Get the list of all the songs
await getSongs("songs/ncs")
playMusic(songs[0], true)
// Display all the albums on the page
await displayAlbums()
// Attach an event listener to play, next and previous
play.addEventListener("click", () => {
if (currentSong.paused) {
currentSong.play()
play.src = "img/pause.svg"
}
else {
currentSong.pause()
play.src = "img/play.svg"
}
})
// Listen for timeupdate event
currentSong.addEventListener("timeupdate", () => {
document.querySelector(".songtime").innerHTML = `${secondsToMinutesSeconds(currentSong.currentTime)} / ${secondsToMinutesSeconds(currentSong.duration)}`
document.querySelector(".circle").style.left = (currentSong.currentTime / currentSong.duration) * 100 + "%";
})
// Add an event listener to seekbar
document.querySelector(".seekbar").addEventListener("click", e => {
let percent = (e.offsetX / e.target.getBoundingClientRect().width) * 100;
document.querySelector(".circle").style.left = percent + "%";
currentSong.currentTime = ((currentSong.duration) * percent) / 100
})
// Add an event listener for hamburger
document.querySelector(".hamburger").addEventListener("click", () => {
document.querySelector(".left").style.left = "0"
})
// Add an event listener for close button
document.querySelector(".close").addEventListener("click", () => {
document.querySelector(".left").style.left = "-120%"
})
// Add an event listener to previous
previous.addEventListener("click", () => {
currentSong.pause()
console.log("Previous clicked")
let index = songs.indexOf(currentSong.src.split("/").slice(-1)[0])
if ((index - 1) >= 0) {
playMusic(songs[index - 1])
}
})
// Add an event listener to next
next.addEventListener("click", () => {
currentSong.pause()
console.log("Next clicked")
let index = songs.indexOf(currentSong.src.split("/").slice(-1)[0])
if ((index + 1) < songs.length) {
playMusic(songs[index + 1])
}
})
// Add an event to volume
document.querySelector(".range").getElementsByTagName("input")[0].addEventListener("change", (e) => {
console.log("Setting volume to", e.target.value, "/ 100")
currentSong.volume = parseInt(e.target.value) / 100
if (currentSong.volume >0){
document.querySelector(".volume>img").src = document.querySelector(".volume>img").src.replace("mute.svg", "volume.svg")
}
})
// Add event listener to mute the track
document.querySelector(".volume>img").addEventListener("click", e=>{
if(e.target.src.includes("volume.svg")){
e.target.src = e.target.src.replace("volume.svg", "mute.svg")
currentSong.volume = 0;
document.querySelector(".range").getElementsByTagName("input")[0].value = 0;
}
else{
e.target.src = e.target.src.replace("mute.svg", "volume.svg")
currentSong.volume = .10;
document.querySelector(".range").getElementsByTagName("input")[0].value = 10;
}
})
}
main()
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/.htaccess
================================================
Options +Indexes
IndexOptions FancyIndexing NameWidth=* DescriptionWidth=*
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Angry_(mood)/info.json
================================================
{
"title": "Angry Mood",
"description": "Calm your Anger"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Bright_(mood)/info.json
================================================
{
"title": "Bright Songs",
"description": "Bright Songs for you"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Chill_(mood)/info.json
================================================
{
"title": "Just Chill",
"description": "Yes, Just Chill"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Dark_(mood)/info.json
================================================
{
"title": "Dark Horse",
"description": "Dark Songs for you"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Diljit/info.json
================================================
{
"title": "Diljit Dosanjh",
"description": "Diljit Dosanjh hits"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Funky_(mood)/info.json
================================================
{
"title": "Go Funky",
"description": "Lets go Funky"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Love_(mood)/info.json
================================================
{
"title": "I Love You",
"description": "Love is in the air"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/Uplifting_(mood)/info.json
================================================
{
"title": "Get up",
"description": "You can do it!"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/cs/info.json
================================================
{
"title": "Copyright Songs",
"description": "Cover Songs for you"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/karan aujla/info.json
================================================
{
"title": "Karan Aujla",
"description": "Karan Aujla for you"
}
================================================
FILE: Video 84 - Project 2 - Spotify Clone/songs/ncs/info.json
================================================
{
"title": "Sleep Songs",
"description": "Songs for you"
}
================================================
FILE: Video 85/myserver.js
================================================
// Further Reading: https://nodejs.org/en/learn/getting-started/introduction-to-nodejs
const http = require('node:http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
================================================
FILE: Video 85/package.json
================================================
{
"name": "spotify",
"version": "1.0.0",
"description": "This is a spotify clone for my app",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [
"spotify",
"music"
],
"author": "Harry",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"slugify": "^1.6.6"
}
}
================================================
FILE: Video 85/server.js
================================================
var slugify = require('slugify')
let a = slugify('some string') // some-string
console.log(a)
// if you prefer something other than '-' as separator
const b = slugify('some st&&*(^%$$^^&ring', '_') // some_string
console.log(b)
================================================
FILE: Video 86/index.html
================================================
Document
================================================
FILE: Video 86/main.js
================================================
// import {a, b, d} from "./mymodule.js"
// console.log(a, b, d)
// import harry from "./mymodule.js"
// console.log(harry)
// (function(exports, require, module, __filename, __dirname) {
// // Module code actually lives here
// });
const a = require("./mymodule2.js")
console.log(a, __dirname, __filename)
================================================
FILE: Video 86/mymodule.js
================================================
export const a = 1 // named export
export const b = 2 // named export
export const c = 3 // named export
export const d = 4 // named export
export const e = 5 // named export
const obj = {
x: 5,
y: 7
}
export default obj; // default export
================================================
FILE: Video 86/mymodule2.js
================================================
// module.exports = {
// a: 1,
// b:4
// }
let c = 56;
module.exports = c;
================================================
FILE: Video 86/package.json
================================================
{
"name": "video-86",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2"
}
}
================================================
FILE: Video 87/aboutpath.js
================================================
import path from "path"
let myPath = "C:\\Users\\iitia\\Downloads\\Sigma Web Development Course\\Sigma-Web-Dev-Course\\Video 87\\harry.txt"
console.log(path.extname(myPath))
console.log(path.dirname(myPath))
console.log(path.basename(myPath))
console.log(path.join("c:/", "programs\\harry.txt"))
================================================
FILE: Video 87/harry
================================================
harryroboharryrobo
================================================
FILE: Video 87/harry.txt
================================================
Harry is amazing and nice bouy
this is amazing promise
this is amazing promise
this is amazing promise
this is amazing promise
this is amazing promise
this is amazing promise
this is amazing promise
this is amazing promise
================================================
FILE: Video 87/harry2.txt
================================================
Harry is a good boy2
================================================
FILE: Video 87/main.js
================================================
const fs = require("fs")
// const fs = require("fs/promises")
console.log("starting")
// fs.writeFileSync("harry.txt", "Harry is a good boy")
fs.writeFile("harry2.txt", "Harry is a good boy2", ()=>{
console.log("done")
fs.readFile("harry2.txt", (error, data)=>{
console.log(error, data.toString())
})
})
fs.appendFile("harry.txt", "harryrobo", (e, d)=>{
console.log(d)
})
console.log("ending")
================================================
FILE: Video 87/mainpromise.js
================================================
import fs from "fs/promises"
let a = await fs.readFile("harry.txt")
let b = await fs.appendFile("harry.txt", "\n\n\n\nthis is amazing promise")
console.log(a.toString(), b)
================================================
FILE: Video 87/package.json
================================================
{
"name": "video-87",
"version": "1.0.0",
"description": "",
"main": "main.js",
"type":"module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
================================================
FILE: Video 88/Agenda.md
================================================
## Agenda:
1. Why should we use express?
2. Why Nodemon?
3. Installing Express@4
4. Request parameters and queries
5. Static Files
================================================
FILE: Video 88/main.js
================================================
const express = require('express')
const app = express()
const port = 3000
app.use(express.static('public'))
// app.get or app.post or app.put or app.delete(path, handler)
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/about', (req, res) => {
res.send('About us')
})
app.get('/contact', (req, res) => {
res.send('Hello contact me!')
})
app.get('/blog', (req, res) => {
res.send('Hello blog!')
})
app.get('/blog/:slug', (req, res) => {
// logic to fetch {slug} from the db
// For URL: http://localhost:3000/blog/intro-to-padosi?mode=dark®ion=in
console.log(req.params) // will output { slug: 'intro-to-padosi' }
console.log(req.query) // will output { mode: 'dark', region: 'in' }
res.send(`hello ${req.params.slug}`)
})
// app.get('/blog/intro-to-js', (req, res) => {
// // logic to fetch intro to js from the db
// res.send('Hello intro-to-js!')
// })
// app.get('/blog/intro-to-python', (req, res) => {
// // logic to fetch intro to python from the db
// res.send('Hello intro-to-python!')
// })
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 88/package.json
================================================
{
"name": "video-88",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
================================================
FILE: Video 88/public/harry.txt
================================================
This is a public file
================================================
FILE: Video 89/Agenda.md
================================================
## Response, Request and Routers
1. Handling post & other requests
2. Chaining of requests
3. Serving HTML files
4. Installing Postman
5. Express Router
================================================
FILE: Video 89/main.js
================================================
const express = require('express')
const blog = require('./routes/blog')
const shop = require('./routes/shop')
const app = express()
const port = 3000
app.use(express.static("public"))
app.use('/blog', blog)
app.use('/shop', shop)
app.get('/', (req, res) => {
console.log("Hey its a get request")
res.send('Hello World21!')
}).post('/', (req, res) => {
console.log("Hey its a post request")
res.send('Hello World post!')
})
app.put('/', (req, res) => {
console.log("Hey its a put request")
res.send('Hello World put!')
})
app.get("/index", (req, res) => {
console.log("Hey its index")
res.sendFile('templates/index.html', { root: __dirname })
})
app.get("/api", (req, res) => {
res.json({ a: 1, b: 2, c: 3, d: 4, name: ["harry", "jerry"] })
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 89/package.json
================================================
{
"name": "video-89",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
================================================
FILE: Video 89/public/mypage.html
================================================
Testing Post Request
================================================
FILE: Video 89/routes/blog.js
================================================
const express = require('express')
const router = express.Router()
// define the home page route
router.get('/', (req, res) => {
res.send('Blog home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About blog')
})
// define the about route
router.get('/blogpost/:slug', (req, res) => {
res.send(`fetch the blogpost for ${req.params.slug}`)
})
module.exports = router
================================================
FILE: Video 89/routes/shop.js
================================================
const express = require('express')
const router = express.Router()
// define the home page route
router.get('/', (req, res) => {
res.send('Shop home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About shop')
})
module.exports = router
================================================
FILE: Video 89/templates/index.html
================================================
Document
Hey I am bold
This is index.html
================================================
FILE: Video 90/logs.txt
================================================
1704316830132 is a GET1704316841989 is a GET1704316842152 is a GET1704316842312 is a GET1704316842481 is a GET1704316842626 is a GET1704316842785 is a GET1704316851270 is a GET
1704316851427 is a GET
1704316851586 is a GET
1704316851743 is a GET
1704316851897 is a GET
1704316852051 is a GET
1704316852202 is a GET
1704316852355 is a GET
1704316852510 is a GET
1704316852681 is a GET
1704316852876 is a GET
1704316891185 is a GET
1704316944655 is a GET
1704317127807 is a GET
1704317128091 is a GET
1704317128263 is a GET
1704317128432 is a GET
1704317128579 is a GET
================================================
FILE: Video 90/main.js
================================================
const express = require('express')
const app = express()
const port = 3000
const blog = require('./routes/blog')
const fs = require("fs")
// app.use(express.static("public"))
app.use('/blog', blog)
// Middleware 1 - Logger for our application
app.use((req, res, next) => {
console.log(req.headers)
req.harry = "I am harry bhai";
fs.appendFileSync("logs.txt", `${Date.now()} is a ${req.method}\n`)
console.log(`${Date.now()} is a ${req.method}`)
// res.send("Hacked by Middlware 1")
next()
})
// Middleware 2
app.use((req, res, next) => {
console.log('m2')
req.harry = "I am Rohan bhai";
next()
})
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get('/about', (req, res) => {
res.send('Hello about!' + req.harry)
})
app.get('/contact', (req, res) => {
res.send('Hello contact!')
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 90/package.json
================================================
{
"name": "video-90",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2"
}
}
================================================
FILE: Video 90/public/harry.txt
================================================
Harry
================================================
FILE: Video 90/routes/blog.js
================================================
const express = require('express')
const router = express.Router()
// Middleware that is specific to this router
router.use((req, res, next) => {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', (req, res) => {
res.send('Birds home page')
})
// define the about route
router.get('/about', (req, res) => {
res.send('About birds')
})
module.exports = router
================================================
FILE: Video 91/index.js
================================================
// You have to write a Node.js program to clear clutter inside of a directory and organize the contents of that directory into different folders
// for example, these files become:
// 1. name.jpg
// 2. name.png
// 3. this.pdf
// 4. harry.zip
// 5. Rohan.zip
// 6. cat.jpg
// 7. harry.pdf
// this:
// jpg/name.jpg, jpg/cat.jpg
// png/name.png
// pdf/this.pdf pdf/harry.pdf
// zip/harry.zip zip/Rohan.zip
================================================
FILE: Video 92/index.js
================================================
const express = require('express')
const app = express()
const port = 3000
app.set('view engine', 'ejs');
// https://github.com/mde/ejs/wiki/Using-EJS-with-Express
app.get('/', (req, res) => {
let siteName = "Adidas"
let searchText = "Search Now"
let arr = ["Hey", 54, 65]
res.render("index", { siteName: siteName, searchText: searchText, arr })
})
app.get('/blog/:slug', (req, res) => {
let blogTitle = "Adidas why and when?"
let blogContent = "Its a very good brand"
res.render("blogpost", {blogTitle: blogTitle, blogContent: blogContent})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 92/package.json
================================================
{
"name": "video-92",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2"
}
}
================================================
FILE: Video 92/views/index.ejs
================================================
Bootstrap demo
<%- include('navbar'); %>
================================================
FILE: Video 92/views/navbar.ejs
================================================
================================================
FILE: Video 93/index.js
================================================
// You have to write a Node.js program to clear clutter inside of a directory and organize the contents of that directory into different folders
// for example, these files become:
// 1. name.jpg
// 2. name.png
// 3. this.pdf
// 4. harry.zip
// 5. Rohan.zip
// 6. cat.jpg
// 7. harry.pdf
// this:
// jpg/name.jpg, jpg/cat.jpg
// png/name.png
// pdf/this.pdf pdf/harry.pdf
// zip/harry.zip zip/Rohan.zip
import fs from "fs/promises"
import fsn from "fs"
import path from "path"
const basepath = "C:\\Users\\iitia\\Downloads\\Sigma Web Development Course\\Sigma-Web-Dev-Course\\Video 93"
let files = await fs.readdir(basepath)
for (const item of files) {
console.log("running for ", item)
let ext = item.split(".")[item.split(".").length - 1]
if (ext != "js" && ext != "json" && item.split(".").length > 1) {
if (fsn.existsSync(path.join(basepath, ext))) {
// Move the file to this directory if its not a js or json file
fs.rename(path.join(basepath, item), path.join(basepath, ext, item))
}
else {
fs.mkdir(ext)
fs.rename(path.join(basepath, item), path.join(basepath, ext, item))
}
}
}
================================================
FILE: Video 93/package.json
================================================
{
"name": "video-93",
"version": "1.0.0",
"description": "",
"type":"module",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
================================================
FILE: Video 94/playground1.mongodb.js
================================================
use('SigmaDatabase');
// Insert a few documents into the courses collection.
db.getCollection('courses').insertMany([
{
"name": "Python",
"Price": 15000,
"Instructor": "Alice"
},
{
"name": "JavaScript",
"Price": 18000,
"Instructor": "Bob"
},
{
"name": "C++",
"Price": 22000,
"Instructor": "Charlie"
},
{
"name": "Ruby",
"Price": 17000,
"Instructor": "David"
},
{
"name": "C#",
"Price": 19000,
"Instructor": "Eva"
},
{
"name": "Swift",
"Price": 21000,
"Instructor": "Frank"
},
{
"name": "Kotlin",
"Price": 16000,
"Instructor": "Grace"
},
{
"name": "PHP",
"Price": 23000,
"Instructor": "Hank"
},
{
"name": "TypeScript",
"Price": 20000,
"Instructor": "Ivy"
},
{
"name": "Go",
"Price": 18000,
"Instructor": "Jack"
}
]
);
// Print a message to the output window.
console.log(`Done Inserting Data`);
================================================
FILE: Video 95/crud.mongodb.js
================================================
// CRUD Operation
use("CrudDb")
// Create Operation
db.createCollection("courses")
// db.courses.insertOne({
// name: "Harrys web dev free course",
// price: 0,
// assignments: 12,
// projects: 45
// })
// db.courses.insertMany([
// {
// "name": "Python Masterclass",
// "price": 0,
// "assignments": 10,
// "projects": 30
// },
// {
// "name": "JavaScript Basics",
// "price": 0,
// "assignments": 8,
// "projects": 20
// },
// {
// "name": "C# for Beginners",
// "price": 0,
// "assignments": 15,
// "projects": 40
// },
// {
// "name": "Web Development Fundamentals",
// "price": 0,
// "assignments": 12,
// "projects": 35
// },
// {
// "name": "Java Programming Essentials",
// "price": 0,
// "assignments": 14,
// "projects": 38
// },
// {
// "name": "ReactJS Crash Course",
// "price": 0,
// "assignments": 10,
// "projects": 25
// },
// {
// "name": "SQL Simplified",
// "price": 0,
// "assignments": 12,
// "projects": 30
// },
// {
// "name": "Responsive Web Design",
// "price": 0,
// "assignments": 10,
// "projects": 28
// },
// {
// "name": "Node.js for Beginners",
// "price": 0,
// "assignments": 13,
// "projects": 36
// },
// {
// "name": "Frontend Development with Vue.js",
// "price": 0,
// "assignments": 11,
// "projects": 32
// }
// ]
// )
// READ
// let a = db.courses.find({price: 0})
// console.log(a.toArray())
// let b = db.courses.findOne({price: 0})
// console.log(b)
// UPDATE
// db.courses.updateOne({price: 0}, {$set:{price: 100}})
// db.courses.updateMany({price: 0}, {$set:{price: 1000}})
// DELETE
db.courses.deleteOne({price: 1000})
db.courses.deleteMany({price: 1000})
// https://www.mongodb.com/docs/manual/reference/operator/query/
================================================
FILE: Video 96/main.js
================================================
// https://www.npmjs.com/package/mongodb
import mongoose from "mongoose";
import express from "express";
import { Todo } from "./models/Todo.js";
let conn = await mongoose.connect("mongodb://localhost:27017/todo")
const app = express()
const port = 3000
app.get('/', (req, res) => {
const todo = new Todo({ desc: "Description of this todo", isDone: false, days: Math.floor(Math.random() * 45 + 5* Math.random()) })
todo.save()
res.send('Hello World!')
})
app.get('/a', async (req, res) => {
let todo = await Todo.findOne({})
console.log(todo)
res.json({title: todo.title, desc: todo.desc})
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 96/models/Todo.js
================================================
import mongoose from "mongoose";
const TodoSchema = new mongoose.Schema({
title: {type: String, required: true, default: "Hey"},
desc: String,
isDone: Boolean,
days: Number
});
export const Todo = mongoose.model('Todo', TodoSchema);
================================================
FILE: Video 96/package.json
================================================
{
"name": "video-96",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon main.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"mongoose": "^8.0.4"
}
}
================================================
FILE: Video 97/main.js
================================================
// Generate a dummy data in this format in a collection called employees in a db called company
// {
// name: "Harry",
// salary: 45000000,
// language: "Python",
// city: "New York",
// isManager: true
// }
// Generate 10 such records when a button called generate data is clicked!
// Create an Express app with mongoose to acheive it
// Everytime the button is clicked, you should clear the collection
================================================
FILE: Video 98/index.html
================================================
Document
CodeWithHarry
================================================
FILE: Video 98/package.json
================================================
{
"name": "video-98",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "npx tailwindcss -i ./src/input.css -o ./src/output.css --watch"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"tailwindcss": "^3.4.1"
}
}
================================================
FILE: Video 98/setup.md
================================================
## How to setup Tailwind CSS
Step 1: Run the following commands
```
npm install -D tailwindcss
npx tailwindcss init
```
Step 2: Update tailwind.conf.js file to include this line:
```
content: ["*.html"],
```
Step 3: create src/input.css to include:
```
@tailwind base;
@tailwind components;
@tailwind utilities;
```
Step 4: Include the src/output.css file to your html
Step 5: Run the following command:
```
npx tailwindcss -i ./src/input.css -o ./src/output.css --watch
```
================================================
FILE: Video 98/src/input.css
================================================
@tailwind base;
@tailwind components;
@tailwind utilities;
================================================
FILE: Video 98/src/output.css
================================================
/*
! tailwindcss v3.4.1 | MIT License | https://tailwindcss.com
*/
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
6. Use the user's configured `sans` font-variation-settings by default.
7. Disable tap highlights on iOS
*/
html,
:host {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
-o-tab-size: 4;
tab-size: 4;
/* 3 */
font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
font-variation-settings: normal;
/* 6 */
-webkit-tap-highlight-color: transparent;
/* 7 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font-family by default.
2. Use the user's configured `mono` font-feature-settings by default.
3. Use the user's configured `mono` font-variation-settings by default.
4. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-feature-settings: normal;
/* 2 */
font-variation-settings: normal;
/* 3 */
font-size: 1em;
/* 4 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-feature-settings: inherit;
/* 1 */
font-variation-settings: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Reset default styling for dialogs.
*/
dialog {
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::-moz-placeholder, textarea::-moz-placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-gradient-from-position: ;
--tw-gradient-via-position: ;
--tw-gradient-to-position: ;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.container {
width: 100%;
}
@media (min-width: 640px) {
.container {
max-width: 640px;
}
}
@media (min-width: 768px) {
.container {
max-width: 768px;
}
}
@media (min-width: 1024px) {
.container {
max-width: 1024px;
}
}
@media (min-width: 1280px) {
.container {
max-width: 1280px;
}
}
@media (min-width: 1536px) {
.container {
max-width: 1536px;
}
}
.mx-auto {
margin-left: auto;
margin-right: auto;
}
.flex {
display: flex;
}
.h-6 {
height: 1.5rem;
}
.h-4 {
height: 1rem;
}
.h-40 {
height: 10rem;
}
.h-1 {
height: 0.25rem;
}
.h-10 {
height: 2.5rem;
}
.min-h-10 {
min-height: 2.5rem;
}
.flex-col {
flex-direction: column;
}
.items-center {
align-items: center;
}
.justify-center {
justify-content: center;
}
.justify-between {
justify-content: space-between;
}
.justify-around {
justify-content: space-around;
}
.space-x-3 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.75rem * var(--tw-space-x-reverse));
margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)));
}
.bg-red-600 {
--tw-bg-opacity: 1;
background-color: rgb(220 38 38 / var(--tw-bg-opacity));
}
.bg-purple-700 {
--tw-bg-opacity: 1;
background-color: rgb(126 34 206 / var(--tw-bg-opacity));
}
.text-purple-900 {
--tw-text-opacity: 1;
color: rgb(88 28 135 / var(--tw-text-opacity));
}
.text-white {
--tw-text-opacity: 1;
color: rgb(255 255 255 / var(--tw-text-opacity));
}
@media (min-width: 640px) {
.sm\:bg-purple-700 {
--tw-bg-opacity: 1;
background-color: rgb(126 34 206 / var(--tw-bg-opacity));
}
}
@media (min-width: 768px) {
.md\:mx-0 {
margin-left: 0px;
margin-right: 0px;
}
.md\:flex-row {
flex-direction: row;
}
.md\:justify-normal {
justify-content: normal;
}
.md\:justify-between {
justify-content: space-between;
}
.md\:bg-purple-700 {
--tw-bg-opacity: 1;
background-color: rgb(126 34 206 / var(--tw-bg-opacity));
}
.md\:bg-slate-600 {
--tw-bg-opacity: 1;
background-color: rgb(71 85 105 / var(--tw-bg-opacity));
}
}
================================================
FILE: Video 98/tailwind.config.js
================================================
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ["*.html"],
theme: {
extend: {},
},
plugins: [],
}
================================================
FILE: Video 99/main.js
================================================
const express = require('express')
const app = express()
const mongoose = require('mongoose');
const Employee = require("./models/Employee")
conn = mongoose.connect('mongodb://127.0.0.1:27017/company');
const port = 3000
app.set('view engine', 'ejs');
const getRandom = (arr)=>{
let rno = Math.floor(Math.random() * (arr.length - 1))
return arr[rno]
}
app.get('/', (req, res) => {
res.render('index', { foo: 'FOO' });
})
app.get('/generate', async (req, res) => {
// Clear the collection Employee
await Employee.deleteMany({})
// Generate random data
let randomNames = ['Rohan', "Sohan", "Mohan", "Sobhan"]
let randomLang = ["Python", "js", "C++", "Java"]
let randomCities = ["Bilaspur", "Moradabad", "Mysore", "Kolkata"]
for (let index = 0; index < 10; index++) {
let e = await Employee.create({
name: getRandom(randomNames),
salary: Math.floor(Math.random() * 22000),
language: getRandom(randomLang),
city: getRandom(randomCities),
isManager: (Math.random()>0.5)?true:false
})
console.log(e)
}
res.render('index', { foo: 'FOO' });
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
================================================
FILE: Video 99/models/Employee.js
================================================
const mongoose = require('mongoose');
const employeeSchema = new mongoose.Schema({
name: String,
salary: Number,
language: String,
city: String,
isManager: Boolean
});
const Employee = mongoose.model('Employee', employeeSchema);
module.exports = Employee
================================================
FILE: Video 99/package.json
================================================
{
"name": "video-99",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.2",
"mongoose": "^8.0.4"
}
}
================================================
FILE: Video 99/question.md
================================================
// Generate a dummy data in this format in a collection called employees in a db called company
// {
// name: "Harry",
// salary: 45000000,
// language: "Python",
// city: "New York",
// isManager: true
// }
// Generate 10 such records when a button called generate data is clicked!
// Create an Express app with mongoose to acheive it
// Everytime the button is clicked, you should clear the collection
================================================
FILE: Video 99/views/index.ejs
================================================
Bootstrap demo
Generate Now
================================================
FILE: video 117/.eslintrc.cjs
================================================
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react/jsx-no-target-blank': 'off',
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
================================================
FILE: video 117/.gitignore
================================================
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
================================================
FILE: video 117/README.md
================================================
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
================================================
FILE: video 117/index.html
================================================
Vite + React
================================================
FILE: video 117/package.json
================================================
{
"name": "video-117",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.2.55",
"@types/react-dom": "^18.2.19",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.56.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"vite": "^5.1.0"
}
}
================================================
FILE: video 117/src/App.css
================================================
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
================================================
FILE: video 117/src/App.jsx
================================================
import { useState, useMemo } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
const nums = new Array(30_000_000).fill(0).map((_, i)=>{
return {
index: i,
isMagical: i===29_000_000
}
})
function App() {
const [count, setCount] = useState(0)
const [numbers, setNumbers] = useState(nums)
// const magical = numbers.find(item=>item.isMagical===true) // Expensive Computation
const magical = useMemo(() => numbers.find(item=>item.isMagical===true), [numbers])
return (
<>
Magical number is {magical.index}
Vite + React
{
setCount((count) => count + 1);
if(count == 10){
setNumbers(new Array(10_000_000).fill(0).map((_, i)=>{
return {
index: i,
isMagical: i===9_000_000
}
}))
}
}}>
count is {count}
Edit src/App.jsx and save to test HMR
Click on the Vite and React logos to learn more
>
)
}
export default App
================================================
FILE: video 117/src/index.css
================================================
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
place-items: center;
min-width: 320px;
min-height: 100vh;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
================================================
FILE: video 117/src/main.jsx
================================================
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')).render(
,
)
================================================
FILE: video 117/vite.config.js
================================================
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
})