Snippets Collections
// importing
import ReactPaginate from 'react-paginate';

// handling the pagination
const [page, setPage] = useState(0);
const handlePageClick = (num) => {
  setPage(num);
};

// fetching all the employee details from the mongoDB database
const [loadedEmployees, setLoadedEmployees] = useState();
useEffect(() => {
  const fetchEmployees = async () => {
    try {
      const responseData = await sendRequest(
        `http://localhost:5000/api/employees/emp?page=${page}`
      );
      setLoadedEmployees(responseData.employees);
    } catch (err) {
      console.log("Error in fetching employees: "+err);
    }
  };
  fetchEmployees();
}, [sendRequest, page]);


// returning this component
<ReactPaginate
  containerClassName="flex gap-2 justify-center mt-4"
  pageClassName="text-gray-500"
  activeClassName="text-gray-900 border-2 border-black px-2"
  previousClassName="text-gray-500"
  nextClassName="text-gray-500"
  breakLabel="..."
  nextLabel="next >"
  onPageChange={(selected) => handlePageClick(selected.selected + 1)}
  pageRangeDisplayed={2}
  marginPagesDisplayed={1}
  pageCount={pageCount}
  previousLabel="< previous"
  renderOnZeroPageCount={null}
/>



// backend - controller methods
const getEmployeeCount = async (req, res, next) => {
  let employeeCount;
  try {
    employeeCount = await Employee.countDocuments();
  } catch (err) {
    const error = new HttpError(
      'Fetching employee count failed, please try again later.',
      500
    );
    return next(error);
  }

  res.json({ employeeCount });
  console.log("DEBUG -- Employee-Controller - Fetching employee count successful!");
};
const getEmployees = async (req, res, next) => {
  const page = req.query.page || 0;
  const employeesPerPage = 2; 

  let allEmployees;
  try {
    allEmployees = await Employee
      .find()
      .skip(page * employeesPerPage)
      .limit(employeesPerPage);
  } catch (err) {
    const error = new HttpError(
      'Fetching Employees failed, please try again later.',
      500
    );
    return next(error);
  }

  if (!allEmployees || allEmployees.length === 0) {
    return next(new HttpError('No employees found.', 404));
  }

  res.json({
    employees: allEmployees.map((emp) => emp.toObject({ getters: true })),
  });
  console.log("DEBUG -- Employee-Controller - Fetching employees successful!");
};
const passport = require('passport');

const jwtStrategy = require('passport-jwt').Strategy;

const ExtractStrategy = require('passport-jwt').ExtractJwt;

const Admin = require('../models/Admin');
const Faculty = require('../models/Faculty');

const opts = {
    jwtFromRequest : ExtractStrategy.fromAuthHeaderAsBearerToken(),
    secretOrKey : "secret"
}

passport.use(new jwtStrategy(opts,async function(payload,done){
      let AdminData = await Admin.findOne({email: payload.adminData.email});
      if(AdminData) {
         if(AdminData.password == payload.adminData.password){
            return done(null,AdminData);
         }
         else{
            return done(null,false);
         }
      }
      else{
        return done(null,false);
      }
}))



passport.serializeUser(function(user,done){
    console.log(user);
    return done(null,user.id);
})

passport.deserializeUser(async function(id,done){
    console.log("Deserialize");
    console.log(id);

    let AdminRecord = await Admin.findById(id);
    if(AdminRecord){
        return done(null,AdminRecord);
    }
    else{
        return done(null,false);
    }
})

module.exports = passport;
Segunda-feira - 9am ás 18pm
Quarta-feira - 9am ás 18pm
Sexta-feira - 9am ás 18pm
const { format } = require('date-fns');
const { v4: uuid } = require('uuid'); // import version 4 as uuid

const fs = require('fs');
const fsPromises = require('fs').promises;
const path = require('path');

const logEvents = async (message, logName) => {
  const dateTime = `${format(new Date(), 'yyyyMMdd\tHH:mm:ss')}`;
  const logItem = `${dateTime}\t${uuid()}\t${message}\n`;
  console.log(logItem);
  try {
    if (!fs.existsSync(path.join(__dirname, 'logs'))) {
      await fsPromises.mkdir(path.join(__dirname, 'logs'));
    } // if the logs folder does not exist, create it
    await fsPromises.appendFile(path.join(__dirname, 'logs', logName), logItem); 
  } catch (err) {
    console.error(err);
  }
}

module.exports = logEvents;
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Olá, Mundo!");
    }
}
{
  "commitizen": {
    "name": "cz_conventional_commits",
    "version": "0.1.0",
    "version_files": ["src/__version__.py", "pyproject.toml:version"],
    "style": [
      ["qmark", "fg:#ff9d00 bold"],
      ["question", "bold"],
      ["answer", "fg:#ff9d00 bold"],
      ["pointer", "fg:#ff9d00 bold"],
      ["highlighted", "fg:#ff9d00 bold"],
      ["selected", "fg:#cc5454"],
      ["separator", "fg:#cc5454"],
      ["instruction", ""],
      ["text", ""],
      ["disabled", "fg:#858585 italic"]
    ]
  }
}
  <div>
    <div id="content">
    </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollTrigger.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollToPlugin.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/MotionPathPlugin.min.js"></script>
  <script type="module">
    gsap.registerPlugin(ScrollTrigger, MotionPathPlugin);
    smoothScroll("#content");
    function smoothScroll(content, viewport, smoothness) {
      content = gsap.utils.toArray(content)[0];

      gsap.set(viewport || content.parentNode, {
        overflow: "hidden",
        position: "fixed",
        height: "100%",
        width: "100%",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0
      });
      gsap.set(content, { overflow: "visible", width: "100%" });

      let getProp = gsap.getProperty(content),
        setProp = gsap.quickSetter(content, "y", "px"),
        removeScroll = () => (content.style.overflow = "visible"),
        needsRefreshFix =
          parseFloat(
            ScrollTrigger.version
              .split(".")
              .map((n) => ("00" + n).substr(n.length - 1, 3))
              .join("")
          ) < 3006002,
        height;

      function onResize() {
        height = content.clientHeight;
        content.style.overflow = "visible";
        document.body.style.height = height + "px";
      }
      onResize();
      ScrollTrigger.addEventListener("refreshInit", onResize);
      ScrollTrigger.addEventListener("refresh", () => {
        removeScroll();
        requestAnimationFrame(removeScroll);
      });

      ScrollTrigger.defaults({ scroller: content });

      ScrollTrigger.prototype.update = (p) => p; // works around an issue in ScrollTrigger 3.6.1 and earlier (fixed in 3.6.2, so this line could be deleted if you're using 3.6.2 or later)

      ScrollTrigger.scrollerProxy(content, {
        scrollTop(value) {
          return arguments.length ? setProp(-value) : -getProp("y");
        },
        getBoundingClientRect() {
          return {
            top: 0,
            left: 0,
            width: window.innerWidth,
            height: window.innerHeight
          };
        }
      });

      gsap.fromTo(
        content,
        { y: 0 },
        {
          y: () => document.documentElement.clientHeight - height,
          ease: "none",
          onUpdate: ScrollTrigger.update,
          scrollTrigger: {
            scroller: window,
            invalidateOnRefresh: true,
            start: 0,
            end: () => height - document.documentElement.clientHeight,
            scrub: smoothness || 3,
            onRefresh: (self) => {
              // when the screen resizes, we just want the animation to immediately go to the appropriate spot rather than animating there, so basically kill the scrub.
              gsap.killTweensOf(self.animation);
              self.animation.progress(self.progress);
              if (needsRefreshFix) {
                let all = ScrollTrigger.getAll();
                all.slice(all.indexOf(self) + 1).forEach((t) => t.refresh());
              }
            }
          }
        }
      );
    }
    
    document.addEventListener("DOMContentLoaded", function () {
      smoothScroll();
    });


  </script>
$ fnm ls-remote # list remote Node.js versions
$ fnm install 16.5.0 # install a specific version
$ fnm use 14.17.5 # switch Node.js version
$ fnm ls # list installed versions
$ fnm default <version> # set a default version
npm install -g live-server

npx live-server
const axios = require('axios');

module.exports = {
  schedule: '0 8 * * 1-5', // runs at 8am Mon-Fri
  handler: async () => {
    try {
      // Make API call to turn on computer
      await axios.post('https://api.example.com/poweron');

      console.log('Computer turned on successfully!');
    } catch (error) {
      console.error(error);
    }
  }
};
import { jsPDF } from "jspdf";

export default async function lead({
}) {

  const doc = new jsPDF('p', 'pt', 'a4');
  doc.setFontSize(12)
  doc.html(document.getElementById("dream-house-full"),  {
    useCORS: true,
    autoPaging:'text',
    // html2canvas:
    callback: function (pdf) {
      pdf.save("12.pdf");
    },
    html2canvas: {
      scale: 0.5,
      // ignoreElements: element => element.id === autoTableConfig?.elementId,
    },
    x:10,
    y:10,
    width:1400,
  });
  // doc.save("a4.pdf");

  // htmlPdf.create(html, options).then((pdf) => pdf.toFile('test.png'));
}
async function formURLEncoded(url,params){
	const response = await axios.post ( 
      url ,
      new URLSearchParams(params)
    )
	return await response.data;
}
<form action="/overview.ejs" method="POST">
  <!-- Formulierinvoervelden -->
  <input type="text" name="naam">
  <input type="email" name="email">
  
  <!-- Formulierverzendknop -->
  <button type="submit">Verzenden</button>
</form>
//---------------------------------------------------------
// REST service to add an image to a PDF document
//---------------------------------------------------------
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const pdfLib = require('pdf-lib');

const app = express();
const port = process.env.PORT || 3000;

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

// Routes
app.post('/api/addImageToPDF', async function(req, res) {
	const { pdfPath, imagePath, outputName } = req.body;

	// Read PDF file
	const pdfData = await fs.promises.readFile(pdfPath);

	// Read image file
	const imageData = await fs.promises.readFile(imagePath);

	// Load PDF document
	const pdfDoc = await pdfLib.PDFDocument.load(pdfData);

	// Embed image in PDF
	const image = await pdfDoc.embedPng(imageData);
	const page = pdfDoc.getPages()[0];
	const { width, height } = page.getSize();
	page.drawImage(image, {
		x: 0,
		y: height - image.height,
		width: image.width,
		height: image.height,
	});

	// Save modified PDF
	const outputPath = path.join(__dirname, 'modified', outputName);
	const modifiedPdfBytes = await pdfDoc.save();
	await fs.promises.writeFile(outputPath, modifiedPdfBytes);

	// Send response
	res.json({ success: true, message: 'Image added to PDF', url: `http://localhost:${port}/api/getModifiedPDF/${outputName}` });
});

app.get('/api/getModifiedPDF/:fileName', async function(req, res) {
	const { fileName } = req.params;
	const filePath = path.join(__dirname, 'arhiviran', `${fileName}-arhivirano-${new Date().toISOString().replace(/[^\d]/g, '')}.pdf`);
	
	// Read modified PDF file
	const pdfData = await fs.promises.readFile(filePath);

	// Create blob from PDF data
	const blob = new Blob([pdfData], { type: 'application/pdf' });

	// Set response headers
	res.setHeader('Content-Type', 'application/pdf');
	res.setHeader('Content-Disposition', 'attachment; filename=modified.pdf');
	res.setHeader('Content-Length', pdfData.length);

	// Send response
	res.send(blob);
});

// Listen command
app.listen(port, function() {
	console.log(`Server is running on port ${port}`);
});
//---------------------------------------------------------


//---------------------------------------------------------
// How to call the service (client side) with a file name
//---------------------------------------------------------
// Create a FormData object to send the file data
var fileData = new FormData();
fileData.append('file', 'sample.pdf');

// Send the AJAX request to modify the PDF file
$.ajax({
	url: '/modify-pdf',
	method: 'POST',
	data: fileData,
	processData: false,
	contentType: false,
	success: function(data) {
		console.log('File modified successfully. Modified file URL:', data.url);
	},
	error: function() {
		console.error('Error modifying file.');
	}
});

//---------------------------------------------------------
// Send the AJAX request to get the modified PDF file as a blob
//---------------------------------------------------------
$.ajax({
	url: '/get-modified-pdf',
	method: 'GET',
	success: function(data) {
		// Create a blob URL from the received blob
		var blobUrl = URL.createObjectURL(data);
		
		// Create an anchor element to download the file
		var downloadLink = $('<a>')
			.attr('href', blobUrl)
			.attr('download', 'modified.pdf')
			.text('Download modified PDF file');
			
		// Add the anchor element to the page
		$('body').append(downloadLink);
	},
	error: function() {
		console.error('Error getting modified file.');
	}
});
//---------------------------------------------------------
const express = require("express");
const mysql = require("mysql2");
const cors = require("cors");

const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const session = require("express-session");

const bcrypt = require('bcrypt');
const saltRound = 10;
 
const app = express();
 
app.use(express.json());
app.use(
    cors({
        origin: ["http://localhost:3000"],
        methods: ["GET", "POST"],
        credentials: true,
    })
);
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use (
    session ({
        key: "userId",
        secret: "subscribe",
        resave: false,
        saveUninitialized: false,
        cookie: {
            expires: 60 * 60 * 24,
        },
    })
);
const db = mysql.createConnection({
    user: "username",
    host: "localhost",
    password: "PASSWORD-MYSQL",
    database: "usuarios",
});
 
app.post('/register', (req, res)=> {
    const username = req.body.username;
    const password = req.body.password;
    bcrypt.hash(password,saltRound, (err, hash) => {
    if (err) {
            console.log(err)
    }
   
    let insertQuery = 'INSERT INTO ?? (??,??) VALUES (?,?)';
    let query = mysql.format(insertQuery, ["usuarios", "username", "password", username, hash]);
    db.query(query, function(err, response,fields) {
        if (err) {
            console.log("Error: ");
            console.error(err);
        }
        // rows added
        console.log("Response: ");
        console.log(response);
        if  (response.affectedRows==1){
            res.send("OK");
        } else {
            res.send("NO");
        }
    });
    })
});
app.get("/login", (req, res) => {
  if (req.session.user) {
    res.send({ loggedIn: true, user: req.session.user });
  } else {
    res.send({ loggedIn: false });
  }
});
app.post('/login', (req, res) => {
 const username = req.body.username;
 const password = req.body.password;
 
 db.execute(
        "SELECT * FROM usuarios WHERE username = ?;",
        [username], 
        (err, result)=> {
            if (err) {
                res.send({err: err});
            }
            if (result.length > 0) {
                bcrypt.compare(password, result[0].password, (error, response) => {
                    if (response) {
                        req.session.user = result;
                        console.log(req.session.user[0].username);
                        if (req.session.user[0].username === username) {
                            res.send("OK");
                        } else {
                            res.send("NO");
                        }
                    } else{
                        res.send({message: "Wrong username/ password comination!"}); 
                    }
                });
            } else {
                res.send({ message: "User doesn't exists"});
            }
        }
    );
});
 
app.listen(3001, () => {
    console.log("running server");
});
SELECT EXISTS (
   SELECT FROM information_schema.tables 
   WHERE  table_schema = 'public'
   AND    table_name   = 'abcd'
   );
{
  "category": "test",
  "routes": ["route1", "route2"]
}
// app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const createLogger = require('./createLogger');
const adminRoutes = require('./adminRoutes');
const useRoutes = require('./useRoutes');

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

// Initialize the logger
const logger = createLogger();

// Add routes for the "admin" category
app.use('/admin/info', adminRoutes.info(logger));
app.use('/admin/warn', adminRoutes.warn(logger));
app.use('/admin/error', adminRoutes.error(logger));

// Add routes for the "use" category
app.use('/use/info', useRoutes.info(logger));
app.use('/use/warn', useRoutes.warn(logger));
app.use('/use/error', useRoutes.error(logger));

// Endpoint for adding a new category and routes dynamically
app.post('/addCategory', (req, res) => {
  const category = req.body.category;
  const routes = req.body.routes;

  // Create a new logger for the category
  const categoryLogger = createLogger(category);

  // Add routes for the category
  for (const route of routes) {
    app.use(`/${category}/${route}/info`, (req, res) => {
      categoryLogger.info({ message: req.query.message });
      res.send('Logged info message');
    });

    app.use(`/${category}/${route}/warn`, (req, res) => {
      categoryLogger.warn({ message: req.query.message });
      res.send('Logged warning message');
    });

    app.use(`/${category}/${route}/error`, (req, res) => {
      categoryLogger.error({ message: req.query.message });
      res.send('Logged error message');
    });
  }

  res.send(`Added category ${category} with routes ${routes.join(', ')}`);
});

app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
const createCategoryLogger = require('./createLogger');

const appLogger = createCategoryLogger('app');
const adminLogger = createCategoryLogger('admin');
const userLogger = createCategoryLogger('user');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, json } = format;

const getLogFileName = (category) => {
  const date = new Date().toISOString().slice(0, 10);
  return `logs/${category}/${category}-${date}.log`;
};

const createCategoryLogger = (category) => {
  return createLogger({
    level: 'info',
    format: combine(timestamp(), json()),
    transports: [
      new transports.File({
        filename: getLogFileName(category),
        level: 'info',
        maxsize: 1024 * 1024 * 10, // 10MB
        maxFiles: 5,
        tailable: true,
      }),
      new transports.Console({
        level: 'debug',
        format: format.combine(format.colorize(), format.simple()),
      }),
    ],
  });
};

module.exports = createCategoryLogger;


const express = require('express');
const router = express.Router();
const userLogger = require('../controllers/userLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  userLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  userLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  userLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const express = require('express');
const router = express.Router();
const adminLogger = require('../controllers/adminLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  adminLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  adminLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  adminLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const express = require('express');
const router = express.Router();
const appLogger = require('../controllers/appLogger');

// Route for info level logging
router.post('/info', (req, res) => {
  const { message } = req.body;
  appLogger.info(message);
  res.send('Info log successful');
});

// Route for warning level logging
router.post('/warning', (req, res) => {
  const { message } = req.body;
  appLogger.warning(message);
  res.send('Warning log successful');
});

// Route for error level logging
router.post('/error', (req, res) => {
  const { message } = req.body;
  appLogger.error(message);
  res.send('Error log successful');
});

module.exports = router;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const userLogRotate = new File({
  filename: path.join(__dirname, `../logs/users_${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const userLogger = createLogger({
  format: combine(
    label({ label: 'User' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    userLogRotate
  ]
});

module.exports = userLogger;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const adminLogRotate = new File({
  filename: path.join(__dirname, `../logs/admins_${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const adminLogger = createLogger({
  format: combine(
    label({ label: 'Admin' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    adminLogRotate
  ]
});

module.exports = adminLogger;
const winston = require('winston');
const path = require('path');
const { combine, timestamp, label, json } = winston.format;

// Log rotation configuration
const { createLogger, transports } = winston;
const { File } = transports;
const filename = (new Date()).toISOString().slice(0, 19).replace(/[-T]/g, '_');
const appLogRotate = new File({
  filename: path.join(__dirname, `../logs/${filename}.log`),
  level: 'info',
  maxsize: 1000000,
  maxFiles: 5,
  tailable: true,
});

// Winston logger configuration
const appLogger = createLogger({
  format: combine(
    label({ label: 'App' }),
    timestamp(),
    json()
  ),
  transports: [
    new winston.transports.Console(),
    appLogRotate
  ]
});

module.exports = appLogger;
├── controllers
│   ├── appLogger.js
│   ├── adminLogger.js
│   └── userLogger.js
├── logs
│   ├── app-2023-04-20.log
│   ├── admins-2023-04-20.log
│   └── users-2023-04-20.log
├── routes
│   ├── appRoutes.js
│   ├── adminRoutes.js
│   └── userRoutes.js
├── utils
│   └── createLogger.js
└── app.js
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import BleManager from 'react-native-ble-manager';

const App = () => {
  const [devices, setDevices] = useState([]);
  const [connectedDevice, setConnectedDevice] = useState(null);
  const [deviceData, setDeviceData] = useState(null);

  useEffect(() => {
    BleManager.start({ showAlert: false });
    BleManager.enableBluetooth();
  }, []);

  const scanDevices = () => {
    BleManager.scan([], 5, true)
      .then((results) => {
        setDevices(results);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const connectDevice = (device) => {
    BleManager.connect(device.id)
      .then(() => {
        setConnectedDevice(device);
        BleManager.startNotification(
          device.id,
          'serviceUUID',
          'characteristicUUID'
        ).then(() => {
          console.log('Notification started');
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const disconnectDevice = () => {
    BleManager.disconnect(connectedDevice.id)
      .then(() => {
        setConnectedDevice(null);
        setDeviceData(null);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const readDeviceData = () => {
    BleManager.read(
      connectedDevice.id,
      'serviceUUID',
      'characteristicUUID'
    )
      .then((data) => {
        setDeviceData(data);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Bluetooth Medical Devices Manager</Text>
      {connectedDevice ? (
        <View style={styles.connectedDevice}>
          <Text style={styles.deviceName}>{connectedDevice.name}</Text>
          <Button
            title="Disconnect"
            onPress={() => disconnectDevice()}
          />
          <Button title="Read Data" onPress={() => readDeviceData()} />
          {deviceData ? (
            <Text style={styles.deviceData}>{deviceData}</Text>
          ) : null}
        </View>
      ) : (
        <View style={styles.deviceList}>
          <Text style={styles.subtitle}>Available Devices:</Text>
          {devices.map((device) => (
            <View style={styles.deviceItem} key={device.id}>
              <Text>{device.name}</Text>
              <Button
                title="Connect"
                onPress={() => connectDevice(device)}
              />
            </View>
          ))}
          <Button title="Scan" onPress={() => scanDevices()} />
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#F5FCFF',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  subtitle: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  connectedDevice: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  deviceName: {
    fontSize: 18,
    fontWeight: '
const express = require("express");

const socket = require("socket.io");

// App setup

const app = express();

const server = app.listen(5000, function () {

  console.log(`server running!`);

});

// Static files

app.use(express.static("public"));

// Socket setup

const io = socket(server);

io.on("connection", function (socket) {

  console.log("socket connection on");

});
var path = require('path');
var http = require('http');
var fs = require('fs');

var dir = path.join(__dirname, 'public');

var mime = {
    html: 'text/html',
    txt: 'text/plain',
    css: 'text/css',
    gif: 'image/gif',
    jpg: 'image/jpeg',
    png: 'image/png',
    svg: 'image/svg+xml',
    js: 'application/javascript'
};

var server = http.createServer(function (req, res) {
    var reqpath = req.url.toString().split('?')[0];
    if (req.method !== 'GET') {
        res.statusCode = 501;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Method not implemented');
    }
    var file = path.join(dir, reqpath.replace(/\/$/, '/index.html'));
    if (file.indexOf(dir + path.sep) !== 0) {
        res.statusCode = 403;
        res.setHeader('Content-Type', 'text/plain');
        return res.end('Forbidden');
    }
    var type = mime[path.extname(file).slice(1)] || 'text/plain';
    var s = fs.createReadStream(file);
    s.on('open', function () {
        res.setHeader('Content-Type', type);
        s.pipe(res);
    });
    s.on('error', function () {
        res.setHeader('Content-Type', 'text/plain');
        res.statusCode = 404;
        res.end('Not found');
    });
});

server.listen(3000, function () {
    console.log('Listening on http://localhost:3000/');
});
db.timetable.updateMany(
   {},
   { $rename: { 'Train No': 'trainNo', 'Train Name': 'trainName', 'SEQ':'seq', 'Station Code':'stationCode', 'Station Name': 'stationName', 'Arrival time':'arrivalTime', 'Departure Time':'departureTime', 'Distance':'distance', 'Source Station':'sourceStation','Source Station Name':'sourceStationName', 'Destination Station':'destinationStation','Destination Station Name':'destinationStationName'  } }
)
<!doctype html>
<html lang="en">
<head>
    <title>Using the scripts in web pages</title>
    <meta charset="utf-8">
    <script type="module">
        import LatLon from 'https://cdn.jsdelivr.net/npm/geodesy@2/latlon-spherical.min.js';
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelector('#calc-dist').onclick = function() {
                calculateDistance();
            }
        });
        function calculateDistance() {
            const p1 = LatLon.parse(document.querySelector('#point1').value);
            const p2 = LatLon.parse(document.querySelector('#point2').value);
            const dist = parseFloat(p1.distanceTo(p2).toPrecision(4));
            document.querySelector('#result-distance').textContent = dist + ' metres';
        }
    </script>
</head>
<body>
<form>
    Point 1: <input type="text" name="point1" id="point1" placeholder="lat1,lon1">
    Point 2: <input type="text" name="point2" id="point2" placeholder="lat2,lon2">
    <button type="button" id="calc-dist">Calculate distance</button>
    <output id="result-distance"></output>
</form>
</body>
</html>
const Arithmetic = require("../arithmetic");
//tests arithmetic class
describe("Arithmetic", () => {
  //organizational tool containing tests
  describe("Initialization", () => {
    it("should set 'number' when created", () => {
      // Arrange
      const num = 108;
      // Act
      const obj = new Arithmetic(num);
      // Assert
      expect(obj.number).toEqual(num);
    });
  })
           })
           
// create a .nvmrc file in the project root directory and include node version u need to manage 
// ex: v16.16.0
// Execute following command in the root directory using a terminal

$ nvm use
Found '/path/to/project/.nvmrc' with version <5.9>
Now using node v5.9.1 (npm v3.7.3)
npm install typescript --save-dev
npm install @types/node --save-dev
npx tsc --init --rootDir src --outDir lib --esModuleInterop --resolveJsonModule --lib es6,dom --module commonjs
{
      tableName: tableName,
      paranoid: true,
      underscored: true,
      createdAt: 'created_at',
      updatedAt: 'updated_at',
      deletedAt: 'deleted_at',
      defaultScope: {
        attributes: {
          exclude: [
            'createdAt',
            'updatedAt',
            'createdBy',
            'updatedBy',
            'deletedAt',
            'deletedBy',
          ],
        },
      },
    },
UserDrinks.update({}, { $rename: { "creator" : "user" } }, { multi: true }, callback)
const schema = Joi.object({
    keyword_id: IdValidation()
      .when('keyword_ids', { not: Joi.exist(), then: Joi.optional(), otherwise: Joi.forbidden() }),
    keyword_ids: Joi.array().items(IdValidation().required()).min(1),
    keyword_value: Joi.string()
      .min(1)
      .max(constants.MAX_CHAR_LENGTH)
      .regex(constants.STRING_REGEX),
    class_ids: Joi.array().items(IdValidation().required()).min(1),
  });
expect(competitor.name).to.be.oneOf([
    competitorUnderReview.keyword_value,
    approvedCompetitor.keyword_value
]);
expect(body.response.topics).toEqual(expect.arrayContaining(topicList));
const dataUri = 'data:image/png;base64,iVBORw0KGg...';

const matches = dataUri.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
const type = matches[1];
const buffer = new Buffer.from(matches[2], 'base64');

fs.writeFileSync('image.png', buffer, { encoding: 'base64' });
expect(data.keyword_data).to.containSubset([
  {
    relationship_id: relationship.relationship_id,
    source_keyword: {
      keyword_id: keyword.keyword_id,
      keyword_value: keywordValue.keyword_value
    },
    target_keyword: {
      keyword_id: keyword2.keyword_id,
      keyword_value: keywordValue2.keyword_value
    }
  },
]);
//Installation
//Install the Rollbar rollbar.js package using npm:
// npm install --save rollbar


// include and initialize the rollbar library with your access token
var Rollbar = require('rollbar')
var rollbar = new Rollbar({
  accessToken: '<ACCESS_TOKEN>',
  captureUncaught: true,
  captureUnhandledRejections: true,
})

// record a generic message and send it to Rollbar
rollbar.log('Hello world!')
<script type="module" src="https://backspace.eco/b.js"></script>
const puppeteer = require('puppeteer-extra')
const pluginStealth = require('puppeteer-extra-plugin-stealth')
puppeteer.use(pluginStealth())


async function main() {
    const browser = await puppeteer.launch({
        headless: false,
        defaultViewport: null,
        executablePath: 'C:\\c-dev\\chrome.exe'
    })
    const [page] = await browser.pages()
    await page.goto('https://www.monotaro.id/s000009132.html', {timeout: 0, waitUntil: 'domcontentloaded'})
    await page.waitForSelector('#product-attribute-specs-table', {timeout: 0})
    const berat = await page.evaluate(() => {
        let b = 0
        const selector_head = '#product-attribute-specs-table tbody tr:nth-child({}) th'
        const selector_body = '#product-attribute-specs-table tbody tr:nth-child({}) td'
        let i = 1
        document.querySelectorAll('#product-attribute-specs-table tbody tr').forEach(el => {
            const data = {
                name: document.querySelector(selector_head.replace('{}', i)).innerText,
                value: document.querySelector(selector_body.replace('{}', i)).innerText
            }
            if(data.name == 'Berat (Kg)') b = data.value.match(/^[0-9]*\.?[0-9]*$/)[0]
            i+=1
        })
        return b
    })
    console.log(berat)
}

main()
const express = require("express");
const app = express();
const cors = require("cors");

require("dotenv").config({path:"./config.env"});

const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));

//get driver connection
const dbo = require("./db/conn");

app.listen(port,()=>{
    // perform a database connection when server starts
    dbo.connectToServer(function (err) {
        if(err) console.error(err);
    })
    console.log(`Server is running on port: ${port}`);
});
const express = require('express');
const cors = require('cors');

// env
const port = process.env.PORT || 3000;

// server
const app = express();

app.use(cors());

// routes
app.get('/', (req, res) => {
    res.send('Hello World!');
});

// start
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});



///////////////////////////////////////////
// https
/*
npm install -g mkcert
mkcert create-ca
mkcert create-cert

const https = require("https");
const fs = require("fs");

const options = {
    key: fs.readFileSync("./config/cert.key"),
    cert: fs.readFileSync("./config/cert.crt"),
};
https.createServer(options, app).listen(8080, () => {
    console.log(`HTTPS server started on port 8080`);
});

*/
//the main framework , express
var express = require('express');
//path , used for joining pathes
var path = require('path');
//cross origin resource sharing 
var cors= require('cors')
//body parser used to take data from forms , to be used later on
var bodyParser=require("body-parser");
//for security reasons , http security(not https)
var helmet= require('helmet')
//for parsing tokens and session cookies
var cookieParser= require('cookie-parser')
//assigning express functionaities as a global variable
const app = express()
//assigning cors functionaities as a global variable
app.use(cors())



//headers that will be sent to the browser
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Credentials', true);
  res.setHeader('Access-Control-Allow-Methods', ['PATCH', 'POST', 'GET', 'DELETE', 'PUT']);
  res.setHeader('Access-Control-Allow-Headers' , '*')
  res.setHeader('Access-Control-Expose-Headers' ,'content-type')
  next();
});

//body parser for form data
app.use(bodyParser.json())
app.use(bodyParser.json({ type: 'application/json' }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(cookieParser())
// secure apps by setting various HTTP headers
app.use(helmet())
// enable CORS - Cross Origin Resource Sharing
 app.options('*', cors()); 


//fetching index from react
app.use(express.static('./build/'));
app.use(express.static(path.join(__dirname, './client/build')));
app.get('*', (req, res) => {
  res.send(express.static(path.join(__dirname, './client/build/index.html')))  ;
});

//giving the functionalities of users.js to a variable users to be used later on
var Users = require('./routes/Users')
//using the functions assigned for users
app.use('/users', Users)

//exporting the app file 
 module.exports = app
import { useEffect, useMemo, useRef, useState } from 'react'
import { useWeb3React } from '@web3-react/core'
import Web3 from 'web3'

import { defaultEVMNetworkId } from '@contracts/networks'

import { web3NoAccountInstances } from '@utils/web3'

export const useWeb3 = () => {
  const { library, chainId } = useWeb3React()
  const web3NoAccount = useMemo(
    () =>
      web3NoAccountInstances[
        chainId ? chainId.toString() : defaultEVMNetworkId
      ],
    [chainId]
  )
  const refChainId = useRef(chainId)
  const refWeb3 = useRef(library)
  const [web3, setweb3] = useState(library ? new Web3(library) : web3NoAccount)

  useEffect(() => {
    if (library !== refWeb3.current || chainId !== refChainId.current) {
      setweb3(library ? new Web3(library) : web3NoAccount)
      refWeb3.current = library
      refChainId.current = chainId
    }
  }, [chainId, library, web3NoAccount])

  return web3
}
import { isMobile } from 'react-device-detect'
import { useWeb3 } from '@firestarter-private/firestarter-library'
import { UnsupportedChainIdError, useWeb3React } from '@web3-react/core'

import { injected, walletconnect } from '@/connectors'

export const useWalletConnect = (): { onClickWallet: () => void } => {
  const web3 = useWeb3()
  const { activate } = useWeb3React()

  const onClickWallet = () => {
    if (isMobile) {
      // if the connector is walletconnect and the user has already tried to connect, manually reset the connector
      if (
        // @ts-ignore
        walletconnect.walletConnectProvider?.wc?.uri
      ) {
        walletconnect.walletConnectProvider = undefined
      }
      activate(walletconnect, undefined, true).catch((error) => {
        if (error instanceof UnsupportedChainIdError) {
          activate(walletconnect) // a little janky...can't use setError because the connector isn't set
        }
      })
      // @ts-ignore
      web3.setProvider(window.ethereum)
    } else {
      activate(injected)
    }
  }

  return { onClickWallet }
}
DROP DATABASE IF EXISTS `sql_invoicing`;
CREATE DATABASE `sql_invoicing`; 
USE `sql_invoicing`;

SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;

CREATE TABLE `payment_methods` (
  `payment_method_id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payment_methods` VALUES (1,'Credit Card');
INSERT INTO `payment_methods` VALUES (2,'Cash');
INSERT INTO `payment_methods` VALUES (3,'PayPal');
INSERT INTO `payment_methods` VALUES (4,'Wire Transfer');

CREATE TABLE `clients` (
  `client_id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `phone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `clients` VALUES (1,'Vinte','3 Nevada Parkway','Syracuse','NY','315-252-7305');
INSERT INTO `clients` VALUES (2,'Myworks','34267 Glendale Parkway','Huntington','WV','304-659-1170');
INSERT INTO `clients` VALUES (3,'Yadel','096 Pawling Parkway','San Francisco','CA','415-144-6037');
INSERT INTO `clients` VALUES (4,'Kwideo','81674 Westerfield Circle','Waco','TX','254-750-0784');
INSERT INTO `clients` VALUES (5,'Topiclounge','0863 Farmco Road','Portland','OR','971-888-9129');

CREATE TABLE `invoices` (
  `invoice_id` int(11) NOT NULL,
  `number` varchar(50) NOT NULL,
  `client_id` int(11) NOT NULL,
  `invoice_total` decimal(9,2) NOT NULL,
  `payment_total` decimal(9,2) NOT NULL DEFAULT '0.00',
  `invoice_date` date NOT NULL,
  `due_date` date NOT NULL,
  `payment_date` date DEFAULT NULL,
  PRIMARY KEY (`invoice_id`),
  KEY `FK_client_id` (`client_id`),
  CONSTRAINT `FK_client_id` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `invoices` VALUES (1,'91-953-3396',2,101.79,0.00,'2019-03-09','2019-03-29',NULL);
INSERT INTO `invoices` VALUES (2,'03-898-6735',5,175.32,8.18,'2019-06-11','2019-07-01','2019-02-12');
INSERT INTO `invoices` VALUES (3,'20-228-0335',5,147.99,0.00,'2019-07-31','2019-08-20',NULL);
INSERT INTO `invoices` VALUES (4,'56-934-0748',3,152.21,0.00,'2019-03-08','2019-03-28',NULL);
INSERT INTO `invoices` VALUES (5,'87-052-3121',5,169.36,0.00,'2019-07-18','2019-08-07',NULL);
INSERT INTO `invoices` VALUES (6,'75-587-6626',1,157.78,74.55,'2019-01-29','2019-02-18','2019-01-03');
INSERT INTO `invoices` VALUES (7,'68-093-9863',3,133.87,0.00,'2019-09-04','2019-09-24',NULL);
INSERT INTO `invoices` VALUES (8,'78-145-1093',1,189.12,0.00,'2019-05-20','2019-06-09',NULL);
INSERT INTO `invoices` VALUES (9,'77-593-0081',5,172.17,0.00,'2019-07-09','2019-07-29',NULL);
INSERT INTO `invoices` VALUES (10,'48-266-1517',1,159.50,0.00,'2019-06-30','2019-07-20',NULL);
INSERT INTO `invoices` VALUES (11,'20-848-0181',3,126.15,0.03,'2019-01-07','2019-01-27','2019-01-11');
INSERT INTO `invoices` VALUES (13,'41-666-1035',5,135.01,87.44,'2019-06-25','2019-07-15','2019-01-26');
INSERT INTO `invoices` VALUES (15,'55-105-9605',3,167.29,80.31,'2019-11-25','2019-12-15','2019-01-15');
INSERT INTO `invoices` VALUES (16,'10-451-8824',1,162.02,0.00,'2019-03-30','2019-04-19',NULL);
INSERT INTO `invoices` VALUES (17,'33-615-4694',3,126.38,68.10,'2019-07-30','2019-08-19','2019-01-15');
INSERT INTO `invoices` VALUES (18,'52-269-9803',5,180.17,42.77,'2019-05-23','2019-06-12','2019-01-08');
INSERT INTO `invoices` VALUES (19,'83-559-4105',1,134.47,0.00,'2019-11-23','2019-12-13',NULL);

CREATE TABLE `payments` (
  `payment_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `amount` decimal(9,2) NOT NULL,
  `payment_method` tinyint(4) NOT NULL,
  PRIMARY KEY (`payment_id`),
  KEY `fk_client_id_idx` (`client_id`),
  KEY `fk_invoice_id_idx` (`invoice_id`),
  KEY `fk_payment_payment_method_idx` (`payment_method`),
  CONSTRAINT `fk_payment_client` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_invoice` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`invoice_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_payment_method` FOREIGN KEY (`payment_method`) REFERENCES `payment_methods` (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payments` VALUES (1,5,2,'2019-02-12',8.18,1);
INSERT INTO `payments` VALUES (2,1,6,'2019-01-03',74.55,1);
INSERT INTO `payments` VALUES (3,3,11,'2019-01-11',0.03,1);
INSERT INTO `payments` VALUES (4,5,13,'2019-01-26',87.44,1);
INSERT INTO `payments` VALUES (5,3,15,'2019-01-15',80.31,1);
INSERT INTO `payments` VALUES (6,3,17,'2019-01-15',68.10,1);
INSERT INTO `payments` VALUES (7,5,18,'2019-01-08',32.77,1);
INSERT INTO `payments` VALUES (8,5,18,'2019-01-08',10.00,2);


DROP DATABASE IF EXISTS `sql_store`;
CREATE DATABASE `sql_store`;
USE `sql_store`;

CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


CREATE TABLE `shippers` (
  `shipper_id` smallint(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`shipper_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `shippers` VALUES (1,'Hettinger LLC');
INSERT INTO `shippers` VALUES (2,'Schinner-Predovic');
INSERT INTO `shippers` VALUES (3,'Satterfield LLC');
INSERT INTO `shippers` VALUES (4,'Mraz, Renner and Nolan');
INSERT INTO `shippers` VALUES (5,'Waters, Mayert and Prohaska');


CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `birth_date` date DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `points` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `customers` VALUES (1,'Babara','MacCaffrey','1986-03-28','781-932-9754','0 Sage Terrace','Waltham','MA',2273);
INSERT INTO `customers` VALUES (2,'Ines','Brushfield','1986-04-13','804-427-9456','14187 Commercial Trail','Hampton','VA',947);
INSERT INTO `customers` VALUES (3,'Freddi','Boagey','1985-02-07','719-724-7869','251 Springs Junction','Colorado Springs','CO',2967);
INSERT INTO `customers` VALUES (4,'Ambur','Roseburgh','1974-04-14','407-231-8017','30 Arapahoe Terrace','Orlando','FL',457);
INSERT INTO `customers` VALUES (5,'Clemmie','Betchley','1973-11-07',NULL,'5 Spohn Circle','Arlington','TX',3675);
INSERT INTO `customers` VALUES (6,'Elka','Twiddell','1991-09-04','312-480-8498','7 Manley Drive','Chicago','IL',3073);
INSERT INTO `customers` VALUES (7,'Ilene','Dowson','1964-08-30','615-641-4759','50 Lillian Crossing','Nashville','TN',1672);
INSERT INTO `customers` VALUES (8,'Thacher','Naseby','1993-07-17','941-527-3977','538 Mosinee Center','Sarasota','FL',205);
INSERT INTO `customers` VALUES (9,'Romola','Rumgay','1992-05-23','559-181-3744','3520 Ohio Trail','Visalia','CA',1486);
INSERT INTO `customers` VALUES (10,'Levy','Mynett','1969-10-13','404-246-3370','68 Lawn Avenue','Atlanta','GA',796);


CREATE TABLE `order_statuses` (
  `order_status_id` tinyint(4) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`order_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_statuses` VALUES (1,'Processed');
INSERT INTO `order_statuses` VALUES (2,'Shipped');
INSERT INTO `order_statuses` VALUES (3,'Delivered');


CREATE TABLE `orders` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `order_date` date NOT NULL,
  `status` tinyint(4) NOT NULL DEFAULT '1',
  `comments` varchar(2000) DEFAULT NULL,
  `shipped_date` date DEFAULT NULL,
  `shipper_id` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`order_id`),
  KEY `fk_orders_customers_idx` (`customer_id`),
  KEY `fk_orders_shippers_idx` (`shipper_id`),
  KEY `fk_orders_order_statuses_idx` (`status`),
  CONSTRAINT `fk_orders_customers` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_order_statuses` FOREIGN KEY (`status`) REFERENCES `order_statuses` (`order_status_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_shippers` FOREIGN KEY (`shipper_id`) REFERENCES `shippers` (`shipper_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `orders` VALUES (1,6,'2019-01-30',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (2,7,'2018-08-02',2,NULL,'2018-08-03',4);
INSERT INTO `orders` VALUES (3,8,'2017-12-01',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (4,2,'2017-01-22',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (5,5,'2017-08-25',2,'','2017-08-26',3);
INSERT INTO `orders` VALUES (6,10,'2018-11-18',1,'Aliquam erat volutpat. In congue.',NULL,NULL);
INSERT INTO `orders` VALUES (7,2,'2018-09-22',2,NULL,'2018-09-23',4);
INSERT INTO `orders` VALUES (8,5,'2018-06-08',1,'Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis.',NULL,NULL);
INSERT INTO `orders` VALUES (9,10,'2017-07-05',2,'Nulla mollis molestie lorem. Quisque ut erat.','2017-07-06',1);
INSERT INTO `orders` VALUES (10,6,'2018-04-22',2,NULL,'2018-04-23',2);


CREATE TABLE `order_items` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`order_id`,`product_id`),
  KEY `fk_order_items_products_idx` (`product_id`),
  CONSTRAINT `fk_order_items_orders` FOREIGN KEY (`order_id`) REFERENCES `orders` (`order_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_order_items_products` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_items` VALUES (1,4,4,3.74);
INSERT INTO `order_items` VALUES (2,1,2,9.10);
INSERT INTO `order_items` VALUES (2,4,4,1.66);
INSERT INTO `order_items` VALUES (2,6,2,2.94);
INSERT INTO `order_items` VALUES (3,3,10,9.12);
INSERT INTO `order_items` VALUES (4,3,7,6.99);
INSERT INTO `order_items` VALUES (4,10,7,6.40);
INSERT INTO `order_items` VALUES (5,2,3,9.89);
INSERT INTO `order_items` VALUES (6,1,4,8.65);
INSERT INTO `order_items` VALUES (6,2,4,3.28);
INSERT INTO `order_items` VALUES (6,3,4,7.46);
INSERT INTO `order_items` VALUES (6,5,1,3.45);
INSERT INTO `order_items` VALUES (7,3,7,9.17);
INSERT INTO `order_items` VALUES (8,5,2,6.94);
INSERT INTO `order_items` VALUES (8,8,2,8.59);
INSERT INTO `order_items` VALUES (9,6,5,7.28);
INSERT INTO `order_items` VALUES (10,1,10,6.01);
INSERT INTO `order_items` VALUES (10,9,9,4.28);

CREATE TABLE `sql_store`.`order_item_notes` (
  `note_id` INT NOT NULL,
  `order_Id` INT NOT NULL,
  `product_id` INT NOT NULL,
  `note` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`note_id`));

INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('1', '1', '2', 'first note');
INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('2', '1', '2', 'second note');


DROP DATABASE IF EXISTS `sql_hr`;
CREATE DATABASE `sql_hr`;
USE `sql_hr`;


CREATE TABLE `offices` (
  `office_id` int(11) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` varchar(50) NOT NULL,
  PRIMARY KEY (`office_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `offices` VALUES (1,'03 Reinke Trail','Cincinnati','OH');
INSERT INTO `offices` VALUES (2,'5507 Becker Terrace','New York City','NY');
INSERT INTO `offices` VALUES (3,'54 Northland Court','Richmond','VA');
INSERT INTO `offices` VALUES (4,'08 South Crossing','Cincinnati','OH');
INSERT INTO `offices` VALUES (5,'553 Maple Drive','Minneapolis','MN');
INSERT INTO `offices` VALUES (6,'23 North Plaza','Aurora','CO');
INSERT INTO `offices` VALUES (7,'9658 Wayridge Court','Boise','ID');
INSERT INTO `offices` VALUES (8,'9 Grayhawk Trail','New York City','NY');
INSERT INTO `offices` VALUES (9,'16862 Westend Hill','Knoxville','TN');
INSERT INTO `offices` VALUES (10,'4 Bluestem Parkway','Savannah','GA');



CREATE TABLE `employees` (
  `employee_id` int(11) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `job_title` varchar(50) NOT NULL,
  `salary` int(11) NOT NULL,
  `reports_to` int(11) DEFAULT NULL,
  `office_id` int(11) NOT NULL,
  PRIMARY KEY (`employee_id`),
  KEY `fk_employees_offices_idx` (`office_id`),
  KEY `fk_employees_employees_idx` (`reports_to`),
  CONSTRAINT `fk_employees_managers` FOREIGN KEY (`reports_to`) REFERENCES `employees` (`employee_id`),
  CONSTRAINT `fk_employees_offices` FOREIGN KEY (`office_id`) REFERENCES `offices` (`office_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `employees` VALUES (37270,'Yovonnda','Magrannell','Executive Secretary',63996,NULL,10);
INSERT INTO `employees` VALUES (33391,'D\'arcy','Nortunen','Account Executive',62871,37270,1);
INSERT INTO `employees` VALUES (37851,'Sayer','Matterson','Statistician III',98926,37270,1);
INSERT INTO `employees` VALUES (40448,'Mindy','Crissil','Staff Scientist',94860,37270,1);
INSERT INTO `employees` VALUES (56274,'Keriann','Alloisi','VP Marketing',110150,37270,1);
INSERT INTO `employees` VALUES (63196,'Alaster','Scutchin','Assistant Professor',32179,37270,2);
INSERT INTO `employees` VALUES (67009,'North','de Clerc','VP Product Management',114257,37270,2);
INSERT INTO `employees` VALUES (67370,'Elladine','Rising','Social Worker',96767,37270,2);
INSERT INTO `employees` VALUES (68249,'Nisse','Voysey','Financial Advisor',52832,37270,2);
INSERT INTO `employees` VALUES (72540,'Guthrey','Iacopetti','Office Assistant I',117690,37270,3);
INSERT INTO `employees` VALUES (72913,'Kass','Hefferan','Computer Systems Analyst IV',96401,37270,3);
INSERT INTO `employees` VALUES (75900,'Virge','Goodrum','Information Systems Manager',54578,37270,3);
INSERT INTO `employees` VALUES (76196,'Mirilla','Janowski','Cost Accountant',119241,37270,3);
INSERT INTO `employees` VALUES (80529,'Lynde','Aronson','Junior Executive',77182,37270,4);
INSERT INTO `employees` VALUES (80679,'Mildrid','Sokale','Geologist II',67987,37270,4);
INSERT INTO `employees` VALUES (84791,'Hazel','Tarbert','General Manager',93760,37270,4);
INSERT INTO `employees` VALUES (95213,'Cole','Kesterton','Pharmacist',86119,37270,4);
INSERT INTO `employees` VALUES (96513,'Theresa','Binney','Food Chemist',47354,37270,5);
INSERT INTO `employees` VALUES (98374,'Estrellita','Daleman','Staff Accountant IV',70187,37270,5);
INSERT INTO `employees` VALUES (115357,'Ivy','Fearey','Structural Engineer',92710,37270,5);


DROP DATABASE IF EXISTS `sql_inventory`;
CREATE DATABASE `sql_inventory`;
USE `sql_inventory`;


CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


select 
	wr.start_datetime,
	wr.end_datetime,
	wr.object_id,
	wr.reserved_by_user,
	wr.reserved_for_user,
	wr.reservation_hash,
	wo.object_name as objectName,
	wo.object_type as objectType
from wmt_reservations wr

left join wmt_objects wo 
	on wr.object_id = wo.object_id and wr.org = wo.org and wr.org_path = wo.org_path

left join wmt_reservation_guests wrg 
	on wrg.reservation_id = wr.id

where wr.org = 'okku' and wr.org_path = '/demo' and wr.cancelled_at is null and wr.visible_to_others is true
UNION all
select DISTINCT on
	(wo2.regular_user)
	wr2.start_datetime,
	wr2.end_datetime,
	wr2.object_id,
	wr2.reserved_by_user,
	wr2.reserved_for_user,
	wr2.reservation_hash,
	wo2.object_name as objectName,
	wo2.object_type as objectType
from wmt_objects wo2

left join wmt_reservations wr2
	on wr2.org = wo2.org and wr2.org_path = wo2.org_path 
where wo2.regular_user is not null
const redisClient = require('redis')
const logger = require('../services/Logger')

const ENV = process.env.ENV ? process.env.ENV : 'DEV'

class Redis {
    constructor() {
        this.client = redisClient.createClient({
            url: process.env.REDIS_URL
        })

        // create connection
        this.client.connect()
        logger.info(`Redis connection opened`)
        // get some connection diagnostics
        this.client
            .sendCommand(['CLIENT', 'LIST'])
            .then(list => {
                const clients = list.split('\n')
                logger.info(
                    `Redis client count: ${
                        clients.filter(x => x?.length > 0).length
                    }`
                )
            })
            .catch(err => logger.error(err))
    }

    /**
     * Stores key value pair in redis
     * @param {String} key
     * @param {String} value JSON stringified value
     */
    async put(key, value, ttl) {
        const options = {}
        if (ttl) {
            options.EX = ttl
        }
        await this.client.set(
            `${ENV}:${key}`,
            JSON.stringify(value),
            options
        )
    }

    /**
     * Get redis data by key
     * @param {String} key
     * @returns
     */
    async get(key) {
        // logger.info(`getting redis key: ${ENV}:${key}`)
        let data = await this.client.get(`${ENV}:${key}`)

        data = data ? JSON.parse(data) : undefined
        if (data && Object.keys(data).length === 0) data = undefined

        if (!data) {
            logger.info(`Redis cache miss on key ${ENV}:${key}`)
        }
        return data
    }

    /**
     * Remove cache entry
     * @param {String} key
     */
    async clear(key) {
        await this.client.del(`${ENV}:${key}`)
        logger.info(`Redis key: ${key} deleted`)
    }

    /**
     * Delete keys in wild card fashion
     * @param {String} pattern Example: h?llo, h*llo
     */
    async deleteKeysViaWildCardPattern(pattern) {
        logger.info(`Deleting redis keys for pattern: ${pattern}`)
        let cursorIndex = '0'
        let running = true
        do {
            const { cursor, keys } = await this.client.scan(
                cursorIndex,
                {
                    MATCH: `${ENV}:${pattern}`
                }
            )
            logger.info(`Deleting redis keys: ${keys}`)
            // Delete redis key
            keys.forEach(async key => {
                await this.client.del(`${key}`)
                logger.info(`Redis key: ${key} deleted`)
            })

            // update cursor
            cursorIndex = cursor

            // loop control variable
            if (!cursor) running = false
        } while (running)
    }

    /**
     * Set expiry time of the key in milliseconds
     * @param {*} key
     * @param {*} expiryTime
     */
    async setKeyExpireTime(key, expiryTime) {
        await this.client.expire(`${ENV}:${key}`, expiryTime)
    }

    async quit() {
        await this.client?.quit()
    }
}

module.exports = new Redis()
arr.reduce((pre, cur)=> [].concat.apply([], pre.map(t => cur.map(g => t + g))));
const file = bucket.file(`${folderName}/${fileName}`)
const passThroughStream = new stream.PassThrough()
passThroughStream.write(fileTitle)
passThroughStream.write(fileHeader)
passThroughStream.write(convertArrayToCSV(accounts.map(mapRecords)))
passThroughStream.end()

passThroughStream
  .pipe(file.createWriteStream())
  .on('error', (err) => {
  console.error(makeLogEntry(err))
})
  .on('finish', () => {
  console.log('writed')
})
$ npm install typescript --save-dev
$ npm install express
$ npm install --save-dev eslint @types/express @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-config-prettier
$ npm install --save-dev ts-node-dev

// GENERATE TSCONFIG FILE FROM TERMINAL
$npm run tsc -- --init
$tsc --init

// PACKAGE.JSON
{
  // ..
  "scripts": {
    "start": "node dist/index.js",
    "build": "tsc --build",
    "clean": "tsc --build --clean",
    "tsc": "tsc",
    "dev": "ts-node-dev index.ts",
    "lint": "eslint src/**/*.ts",
     "format": "src/**/*.ts --fix",
  },
  // ..
}

// TSCONFIG.JSON
{
  "compilerOptions": {
    "target": "ES2018",
    "outDir": "dist",
    "sourceMap": true,
    "module": "commonjs",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": false,
    "noFallthroughCasesInSwitch": true,
    "esModuleInterop": true,
    "resolveJsonModule": true
  },
  "include": [
    "src/**/*.ts",
  ],
  "exclude": [
    "node_modules"
  ]
}

//.ESLINTRC
{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "plugins": [
    "@typescript-eslint"
  ],
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "env": {
    "browser": true,
    "es6": true,
    "node": true
  },
  "rules": {
    "indent": 0,
    "linebreak-style": 0,
    "quotes": [
      "error",
      "double"
    ]
  }
}
  
// PRETTIERRC
{
  "trailingComma": "all",
  "importOrder": [
    "<THIRD_PARTY_MODULES>",
    "next-seo.config",
    "^components/(.*)$",
    "^utils/(.*)$",
    "^assets/(.*)$",
    "^@fontsource/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}
 <Button component={Link} to='/auth' variant='contained'color='primary'>SignIn</Button>
require("dotenv").config();

const Discord = require("discord.js");

const Sequelize = require("sequelize");

const keep_alive = require("./keep_alive.js");

//const { MessageEmbed } = require('discord.js');

const token = process.env["DISCORD_BOT_SECRET"];

const prefix = "!";

​
require("dotenv").config();

const Discord = require("discord.js");

const Sequelize = require("sequelize");

const keep_alive = require("./keep_alive.js");

//const { MessageEmbed } = require('discord.js');

const token = process.env["DISCORD_BOT_SECRET"];

const prefix = "!";

​
 const {page}=req.query;
    console.log(page);
    try {
        const LIMIT=6; 
        // limit can be used dynamically
        const startIndex=(Number(page)-1 )* LIMIT;//getting the starting index of all the posts
        // converting page to Number because we get string as query

        const total=await PostMessage.countDocuments({});
        const posts = await PostMessage.find().sort({_id:-1}).limit(LIMIT).skip(startIndex); //skipping all the previous pages from loading
        
        res.status(200).json({data:posts,currentPage:Number(page),numberOfPages:Math.ceil(total/LIMIT)});
    }
    catch (error) {
        res.status(404).json({ message: error.message });

    }
/* 
Initialise node environment and install webpack as a dev dependency
$ npm init && npm install -D webpack webpack-cli webpack-dev-server

<dist> is the directory where built files are stored and <src/index.js> serves as the default entry file

In package.json "scripts", for the "build" script,
"scripts": {
	"build": "webpack",
	"dev": "webpack serve",
    "watch": "webpack --watch"
}


$ npm run build - to build
*/

/* 
Create a config file <webpack.config.js>. 
Install the HTML plugin as a dev dependency: $ npm i -D html-webpack-plugin
Install babel loader to maintain backwards compatibility with older browser versions: 
$ npm i -D babel-loader @babel/core @babel/preset-env
Install css loaders: $ npm i -D css-loader mini-css-extract-plugin
For sass: $ npm i -D sass-loader
*/

const path = require "path";
const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")

module.exports = {
  mode: "development", /* The environment. Other options include production */
  
  entry: {
    bundle: path.resolve(__dirname, "src/index.js"), /* The main file to be bundled */
  },
  
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "[name][contenthash].js", /* The created output file. By default <main.js>. The output file name depends on the property provided to "entry". Hence in this example, the output file will be called bundle.js. This file is served to the HTML file as a script. Adding the contentash will create a new output file after every build so */
    clean: true, /* Do not duplicate output files on each build. Maintain one file with changing hashes */
    assetModuleFilename: "[name][ext]" //Maitain filename after bundling
  },
  
  devtool: "source-map", /* Add source maps for debugging purposes */
  
  devServer: {
    static: {
      directory: path.resolve(__dirname, "dist"),
      port: 3000,
      open: true, //Open browser automatically on running $ npm run dev
      hot: true, //Hot reloading
      compress: true, //Enable gzip compression
      historyApiFallback: true,
    }
  },
  
  module: {
    rules: [
      /* The value of the test property refers to the file extension to be focused on, e.g. scsss, js, ts, etc. and the the value of the "use" property refers to the loaders needed to enable implementation of the specified files with the target extension */
      {
        test: /\s?.css$/i, //case insensitive
        use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"] //Read from LTR
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ["@babel/preset-env"]
          }
        }
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i, //case-insensitive
        type: "asset/resource"
      }
    ]
  },
  
  plugins: [
    new HtmlWebpackPlugin ({
    	title: "<Insert title of webapp>",
    	filename: "index.html",
      	template: "src/<insert template filename here>.html"
    }), /* Creates the HTML file with the necessary features based on the config. The template file serves as a boilerplate over which the plugin adds the other tags such as the title and script. The template is stored in the src directory */
    new MiniCssExtractPlugin()
  ]
  
}
//backend
//api

export const getPostsBySearch=async  (req,res)=>{
    const {searchQuery , tags}=req.query; 
    try {
       const title=new RegExp(searchQuery,'i');
       const posts=await PostMessage.find({$or:[{title},{tags:{$in:tags.split(',') }}]})
       //here we get tags as an array so finding the specific tag by spliting tags using array, because we get the array as an object here using ",". or = search by title or tags .RegExp = regex.

       res.json({data:posts})
    //    i for ignoring case 
    } catch (error) {
        
    }
}
//actions
 
export const getPostsBySearch=(searchQuery)=>async(dispatch)=>{
    try {
        
        const {data:{data}}=await api.fetchPostsBySearch(searchQuery);
        console.log(data);
    } catch (error) {
       console.log(error); 
    }
}
//action in front end

export const getPostsBySearch=(searchQuery)=>async(dispatch)=>{
    try {
        const {data:{data}}=await api.fetchPostsBySearch(searchQuery);
        console.log(data);
    } catch (error) {
       console.log(error); 
    }
}
///eta bahire\\\
function useQuery(){
    return new URLSearchParams(useLocation().search)
}
/// then vitore\\\
const query=useQuery();
    const page=query.get(page)
    /// page name e kono query thakle tar value dibe\\\
import jwt from 'jsonwebtoken'
const auth=async (req,res,next)=>{
    try {
       const token=req.headers.authorization.split(''[1]);
       const isCustomAuth=token.length<500;
       let decodedData;
       if(token && isCustomAuth){
               decodedData=jwt.verify(token,process.env.SECRET);
              req.userId=decodedData?.id;
       }
       else{
        decodedData=jwt.decode(token);
        req.userId=decodedData?.sub;
       }
       next();
    } catch (error) {
        console.log(error);
    }
}
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import user from '../models/user';

export const signin=async (res,req)=>{
 const {email,password} =req.body;
 try {
    const existingUser=await userfindOne({email: email});
    if(!existingUser) return res.status(404).json({message: 'user doesnot exist'});
    const isPasswordCorrect=await bcrypt.compare(password,existingUser.password);
    if(!isPasswordCorrect) return res.status(400).json({message: 'invalid credintials'});
    const token=jwt.sign({email:existingUser.email,id:existingUser._id},process.env.SECRET,{expiresIn:'1h'})
    res.status(200).json({result:existingUser,token})
 } catch (error) {
    res.status(500).json({message:'something went wrong'})
 }
}
export const signup=async (res,req)=>{

}
import cors from "cors"; //ES6
const cors = require("cors"); //commonjs

const corsOptions = {origin: "*", methods: ["GET, HEAD, PUT, PATCH, POST, DELETE"], credentails: true, optionsSuccessStatus: 200};
app.use(cors(corsOptions));
$npm install --save-dev eslint @babel/eslint-parser eslint-plugin-react eslint-plugin-react-native ...

// AUTOMATIC CONFIG FILE
$npm init @eslint/config

//GLOBAL INSTALLATION AND USE
$npm i -g eslint
$eslint --init

// PACKAGE.JSON
{ //...,
  
  "devDependencies": {
    "@babel/eslint-parser": "^7.18.9",
    "@trivago/prettier-plugin-sort-imports": "^3.3.0",
    "@typescript-eslint/eslint-plugin": "^5.32.0",
    "@typescript-eslint/parser": "^5.32.0",
    "eslint": "^8.21.0",
    "eslint-config-airbnb": "^19.0.4",
    "eslint-config-prettier": "^8.5.0",
    "eslint-plugin-import": "^2.26.0",
    "eslint-plugin-jsx-a11y": "^6.6.1",
    "eslint-plugin-react": "^7.30.1",
    "eslint-plugin-react-hooks": "^4.6.0"
  },
   //...
}

// TSCONFIG.JSON
{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src/**/*"
  ]
}


// .ESLINTRC
{
  "globals": {
    "module": true
  },
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "airbnb",
    "airbnb/hooks",
    "eslint:recommended",
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "prettier"
  ],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react",
    "@typescript-eslint"
  ],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": 0,
    "@typescript-eslint/explicit-module-boundary-types": 0,
    "react/react-in-jsx-scope": 0,
    "quotes": [
      "error",
      "double"
    ],
    "import/extensions": 0,
    "import/no-unresolved": 0,
    "linebreak-style": [
      "error",
      "windows"
    ],
    "operator-linebreak": "off",
    "react/jsx-filename-extension": 0,
    "no-shadow": "off",
    "jsx-a11y/label-has-associated-control": 0,
    "react/jsx-no-bind": 0,
    "no-unused-expressions": [
      "warn",
      {
        "allowShortCircuit": true,
        "allowTernary": true
      }
    ]
  }
}

// .PRETTIERRC
{
  "trailingComma": "all",
  "importOrder": [
    "^(next/(.*)$)|^(next$)",
    "<THIRD_PARTY_MODULES>",
    "next-seo.config",
    "^components/(.*)$",
    "^utils/(.*)$",
    "^assets/(.*)$",
    "^@fontsource/(.*)$",
    "^[./]"
  ],
  "importOrderSeparation": true,
  "importOrderSortSpecifiers": true
}
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
 if (typeId === 1) {
                // aca_book_list
                const deleteBook = await prisma.aca_book_list.update({
                    where: {
                        id: +productId,
                        // is_active: true,
                        // institution_id: +authData.institution_id,
                    },
                    data: {
                        is_active: false,
                    }
                })
                await BasicResponse(res, 1, 'Book Deleted', deleteBook)
                if (!deleteBook) {
                    await BasicResponse(res, 0, 'Book Not Found to Delete', [])
                    return
                }

            }

            if (typeId === 2 || typeId === 3) {
                // console.log(typeId, productId);
                let deleteProduct: any = await prisma.sm_products.findMany({
                    where: {
                        id: productId,
                        // is_active: true,

                    }
                    // data: {
                    //     is_active: false,
                    // },
                })
                console.log('deleteProduct ', deleteProduct)
                // if (!deleteProduct) {
                //     if (typeId === 2) {
                //         await BasicResponse(res, 0, 'A Copies Not Found to Delete', [])
                //         return
                //     }
                //     if (typeId === 3) {
                //         await BasicResponse(res, 0, 'A Stationery Not Found to Delete', [])
                //         return
                //     }
                // }

                // if (typeId === 2) {
                //     await BasicResponse(res, 1, 'A Copies Deleted', deleteProduct)
                // }
                // if (typeId === 3) {
                //     await BasicResponse(res, 1, 'A Stationery Deleted', deleteProduct)
                // }
            }
const fetch = require('node-fetch');

fetch("https://dink.ga/api/criarURL?url=SEU_URL").then(response => console.log(response)).catch(err => console.error(err));
const fs = require('fs');
const https = require('https');
const {Transform} = require('stream');

const transformGenerator = function() {
    let flushCallback = ()=>{};   
    const options = {
        host: <url>, //without protocol https://
        port: 443,
        path: </anything/after/slash>,
        method: 'POST' 
    };

    const transform = new Transform(); 
    const req = https.request(options, (res)=>{
        res.on('data', (d) => {
            transform.push(d);
        });

        res.on('end', () => {
            flushCallback();
            transform.destroy()
        });
    })

    transform._transform = (chunk, encoding, callback) => {
            req.write(chunk);
            callback()
    }

    transform.pipe(req);
    transform._flush = (cb)=>{
        req.end();
        flushCallback = cb;
    }
    return transform;
}

stream = fs.createReadStream('./example.txt');
stream.pipe(transformGenerator()).pipe(process.stdout);
//import this
const { check, validationResult } = require("express-validator/check");

//validate this
router.post(
  "/",
  [check("name", "Please add name").not().isEmpty(),
  check("email", "Please include a valid email").isEmail(),
  check("password", "Please enter a password with 6 or more characters").isLength({ min: 6 })
],
  (req, res) => {
       const errors = validationResult(req);
           if (!errors.isEmpty()) {
               return res.status(400).json({ errors: errors.array() });
           }
         res.send("passed");
  }
);
const multer = require("multer");
const path = require("path");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./server-side/public/uploads");
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(
      null,
      file.fieldname + "-" + uniqueSuffix + path.extname(file.originalname)
    );
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/jpeg" ||
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/gif"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 5, // max 5mb
  },
  fileFilter: fileFilter,
});

module.exports = upload;
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
    },
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },
  { timestamps: true }
);

module.exports = User = mongoose.model("User", userSchema);


// @routes  GET api/user/stats
// @desc    Get how many users are registered with in a year/month/week
// @access  Private - Admin
router.get("/stats", isAuthenticatedAndAdmin, async (req, res) => {
  User.aggregate([
    // { $match: { createdAt: { $gte: currentYear } } },
    {
      $project: {
        year: { $year: "$createdAt" },
        month: { $month: "$createdAt" },
        week: { $week: "$createdAt" },
      },
    },
    {
      $group: {
        _id: { year: "$year", month: "$month", week: "$week" },
        count: { $sum: 1 },
      },
    },
  ])
    .then((userStats) => res.status(200).json(userStats))
    .catch((err) => res.status(500).json(err));
});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const orderSchema = new Schema(
  {
    userId: {
      type: ObjectId,
      ref: "User",
    },
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    size: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      required: true,
    },
    quantity: {
      type: Number,
      default: 1,
    },
    totalPrice: {
      type: Number,
      required: true,
    },
    paymentMethod: {
      type: String,
      default: "Stripe",
    },
  },
  { timestamps: true }
);

module.exports = Order = mongoose.model("Order", orderSchema);


// @routes  GET api/order/income
// @desc    Get monthly income
// @access  Private - Admin
router.get("/income", isAuthenticatedAndAdmin, (req, res) => {
  const date = new Date();
  const lastMonth = new Date(date.setMonth(date.getMonth() - 1));
  const previousMonth = new Date(date.setMonth(lastMonth.getMonth() - 1));

  Order.aggregate([
    { $match: { createdAt: { $gte: previousMonth } } },
    { $project: { month: { $month: "$createdAt" }, sales: "$amount" } },
    { $group: { _id: "$month", total: { $sum: "$sales" } } },
  ])
    .then((income) => res.status(200).json(income))
    .catch((err) => res.status(500).json(err));
});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const { ObjectId } = mongoose.Schema.Types;

const reviewSchema = new Schema(
  {
    productId: {
      type: ObjectId,
      ref: "Product",
    },
    reviews: [
      {
        userId: {
          type: ObjectId,
          ref: "User",
        },
        rating: {
          type: Number,
          required: true,
        },
        comment: {
          type: String,
        },
      },
    ],
    totalRate: {
      type: Number,
      default: 0,
    },
  },
  { timestamps: true }
);

router.get("/:id", (req, res) => {
  Review.findOne({ productId: req.params.id })
    .populate({
      path: "reviews",
      populate: { path: "userId", select: "-_id username" },
    })        
    .then((reviews) => {      
        res.status(200).json(reviews);      
    })
    .catch((err) => res.status(500).json(err));
});
const request = require('supertest');
const assert = require('assert');

request('https://dog.ceo')
  .get('/api/breeds/image/random')
  .expect(200) // assert HTTP status code
  .expect('Content-Type', 'application/json') // assert content type
  .expect(function(res) { // assert body JSON structure
    assert(res.body.hasOwnProperty('status'));
    assert(res.body.hasOwnProperty('message'));
  })
  .end(function(err, res) {
    if (err) throw err;
  });
import { realpathSync as realpath, accessSync as access, existsSync as exists } from 'fs'
import { dirname } from 'path'

/**
 * IIFE to resolve Magento document root
 * @returns <string> Returns Magento document root
 */
export const mageRoot = (() => {
    let mageRoot = dirname(realpath(import.meta.url.slice(7)))

    while (!(exists(`${ mageRoot }/app/Mage.php`) || exists(`${ mageRoot }/bin/magento`))) {
        mageRoot = dirname(mageRoot)
    }

    return mageRoot
})()
FROM node:10.23.0-alpine3.10

RUN apk update && \
mkdir -p /app && chmod 0775 /app && \
rm -rf /var/lib/apt/lists/

#install nodemon 
RUN npm install -g nodemon --unsafe-perm=true --allow-root

#Aggiunta degli applicativi
RUN apk --no-cache add redis dcron procps

COPY entrypoint-dev.sh /entrypoint.sh

CMD ["/entrypoint.sh"]
res.status(404).render('your_template', your_data );
  const filteredData = datas[0].PostOffice.map(({ Name, State }) => {
    return { Name, State };
  });
 process.on('unhandledRejection', (error) => {
    throw error;
  });

  process.on('uncaughtException', (error) => {
    logError(error);

    if (!isOperationalError(error)) {
      process.exit(1);
    }
  });
db.customers.find({}).forEach(function (ch){db.customers.updateMany({},{$set:{"contact":ch.contact.toString()}})});
//Host Dosyası
sudo nano /etc/hosts 
Control+O
Control+X
Node Port Kill
lsof -i :3000
kill -9 PID
// From postman:
{
    "select": {"productName": "Skykick"}
}

// In file:
    req.body.select,
{
  "name": "frontend",
    // add proxy, so instead of looking at front end server, our api requests look at backend server
    // call it prox, then add the loopback address and the backend server port
  "proxy": "http://127.0.0.1:8080",
  "version": "0.1.0",
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
// require mongoose
const mongoose = require('mongoose');
// require config file to access mongoURI 
const config = require('config');
// make our db the mongoURI
const db = config.get('mongoURI');

const connectDB = async () => {
    try {
       await mongoose.connect(db, {
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true,
            useFindAndModify: false
        })
        console.log('mongo db connected')
    } catch (err) {
        console.error(err)
        //exit with failure
        process.exit(1)
    }
}

module.exports = connectDB;
//To see all versions of Node that are installed on your machine use the command:
$ npm -v

//To see versions installed on machine

$ nvm ls
->      v16.1.0
         system
default -> node (-> v16.1.0)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v16.1.0) (default)
stable -> 16.1 (-> v16.1.0) (default)

// add a new version
$ nvm install <version>
  
// to switch to a different verison
  
$ nvm use <version>
const getSourcesData = asyncHandler(async (req, res) => {
  const { dealership } = req.user;
  const month = parseInt(req.params.month);
  const customerData = await Customer.aggregate()
    .match({ dealership })
    .facet({
      fbCount: [
        {
          $match: {
            sourceOfEnquiry: "Facebook",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "fbCount" },
      ],
      googleCount: [
        {
          $match: {
            sourceOfEnquiry: "Google",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },

        { $count: "googleCount" },
      ],
      cardekhoCount: [
        {
          $match: {
            sourceOfEnquiry: "Cardekho",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "cardekhoCount" },
      ],
      carwaleCount: [
        {
          $match: {
            sourceOfEnquiry: "Carwale",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "carwaleCount" },
      ],
      instagramCount: [
        {
          $match: {
            sourceOfEnquiry: "Instagram",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "instagramCount" },
      ],
      newspaperAdsCount: [
        {
          $match: {
            sourceOfEnquiry: "Newspaper Ads",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "newspaperAdsCount" },
      ],
      websiteCount: [
        {
          $match: {
            sourceOfEnquiry: "Website",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "websiteCount" },
      ],
      hoardingsCount: [
        {
          $match: {
            sourceOfEnquiry: "Hoardings",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "hoardingsCount" },
      ],
      telephonicCount: [
        {
          $match: {
            sourceOfEnquiry: "Telephonic",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "telephonicCount" },
      ],
      referralCount: [
        {
          $match: {
            sourceOfEnquiry: "Referral",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "referralCount" },
      ],
      workshopCount: [
        {
          $match: {
            sourceOfEnquiry: "Workshop",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "workshopCount" },
      ],
      bushfireCount: [
        {
          $match: {
            sourceOfEnquiry: "Bushfire",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "bushfireCount" },
      ],
      managementCount: [
        {
          $match: {
            sourceOfEnquiry: "Management",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "managementCount" },
      ],
      walkInCount: [
        {
          $match: {
            sourceOfEnquiry: "Walk-in",
            $expr: { $eq: [{ $month: "$createdAt" }, month] },
          },
        },
        { $count: "walkInCount" },
      ],
    });
  

  return res.status(200).json({
    success: true,
    tableData: customerData,
  });
});
{
  sourceOfEnquiry:'Telephonic',
    createdAt: {
        $gte: ISODate("2021-06-01T00:00:00.000Z"),
        $lte: ISODate("2021-06-30T00:00:00.000Z")
    }
}
db.users.updateMany(
  { __t: "SE" },
  {
    $set: {
      targets: [
        {
          modelName: "rapid",
          targetCount: 15,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "superb",
          targetCount: 10,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "kushaq",
          targetCount: 5,
          bookingCount: 0,
          deliveredCount: 0,
        },
        {
          modelName: "octavia",
          targetCount: 0,
          bookingCount: 0,
          deliveredCount: 0,
        },
      ],
    },
  }
);
//create a file test.rest:
GET http://localhost:5000
# Push the commit and update the deployed version on Heroku
git push heroku main

# Open the app in the browser (from terminal)
heroku open

#fetch heroku logs
heroku logs

#specify number of logs
heroku logs -n 200

#find all your fucking heroku deployment errors then cry yourself to sleep
heroku logs --tail

# Open the terminal in the app dyno in Heroku
heroku run bash
 
# Run a file 
node seeds/index.js
# Open the terminal in the app dyno in Heroku

heroku run bash

 

# We may then run the seed file

node bin/seed.js
const dateFilter = asyncHandler(async (req, res) => {
  const month = 7;
  const day = 13;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $and: [
            { $eq: [{ $month: "$birthday" }, month] },
            { $eq: [{ $dayOfMonth: "$birthday" }, day] },
          ],
        },
        {
          $and: [
            { $eq: [{ $month: "$anniversary" }, month] },
            { $eq: [{ $dayOfMonth: "$anniversary" }, day] },
          ],
        },
      ],
    },
  });
  res.send(feedbacks);
});
const dateFilter = asyncHandler(async (req, res) => {
  const month = 6;
  const day = 10;
  const feedbacks = await Feedback.find({
    $expr: {
      $or: [
        {
          $eq: [{ $month: "$birthday" }, month],
          $eq: [{ $dayOfMonth: "$birthday" }, day],
        },
        {
          $eq: [{ $month: "$anniversary" }, month],
          $eq: [{ $dayOfMonth: "$anniversary" }, day],
        },
      ],
    },
  });
  console.log({ feedbacks });
});
hbs.registerHelper(`iff`, function (a, operator, b, opts) {
    let bool = false;
    a.toString();
    b.toString();
    switch (operator) {
        case `===`:
            bool = a === b;
            break;
        case `>`:
            bool = a > b;
            break;
        case `<`:
            bool = a < b;
            break;
        default:
            bool = a === b;
    }

    if (bool) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

{{#iff value1 '>' value2}}
do the thing
{{/iff}}
//cons name = 'me'

{{log 'author = ' name }}

//author = me
// in app.js
hbs.registerHelper(`ifEquals`, function (a, b, opts) {
    if (a.toString() === b.toString()) {
        return opts.fn(this);
    }
    return opts.inverse(this);
});

// in hbs template
{{#ifEquals name 'Foo'}}
      true
{{else}}
      false
{{/ifEquals}}
const comparePassword = async (password, hash) => {
    try {
        // Compare password
        return await bcrypt.compare(password, hash);
    } catch (error) {
        console.log(error);
    }

    // Return false if error
    return false;
};

//use case
(async () => {
    // Hash fetched from DB
    const hash = `$2b$10$5ysgXZUJi7MkJWhEhFcZTObGe18G1G.0rnXkewEtXq6ebVx1qpjYW`;

    // Check if password is correct
    const isValidPass = await comparePassword('123456', hash);

    // Print validation status
    console.log(`Password is ${!isValidPass ? 'not' : ''} valid!`);
    // => Password is valid!
})();
const mongoose = require('mongoose');

const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test';          // REPLACE WITH YOUR OWN DB NAME

const connectDB = async () => {
    try {
        await mongoose.connect(`mongodb://${server}/${database}`, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
            useFindAndModify: false,
            useCreateIndex: true
        });

        console.log('MongoDB connected!!');
    } catch (err) {
        console.log('Failed to connect to MongoDB', err);
    }
};

connectDB();
function promiseWrapper(fn) {
    return (req, res, next) => {
         fn(req, res).catch(next);
    };
}
Using Git and Heroku

1) In terminal - git init

This creates a hidden file .git

2) git add .

This will creating a new copy of the work. This is a staging area.

3) git commit -m "Initial Commit"

This will making a commit of the version

[ These stages can be done using GitHub Desktop]

4) Then on terminal: heroku login

This will offers to open a browser. On the window that opened log in and close the window. 

5) $ heroku git:remote -a <name> if already created on heroku - or -   heroku create

this will show something like this in terminal:

https://still-gorge-92777.herokuapp.com/ | https://git.heroku.com/still-gorge-92777.git

6) Create Procfile

$ touch Procfile 

7) Find Procfile (should be empty) and add: web: node app.js (same file as we use for starting the application with nodemon).

8) Need to change port address to heroku’s dynamic port:

let port = process.env.PORT;if (port == null || port == "") { port = 3000;};app.listen(port, function () { console.log("Server started successfully");});

9) Choose a database host - we already have that so ignore.

10) Language specific setup: 

Need to specify the version of node to heroku:

in terminal: $ node --version, 

then in package.json add: 

"engines": { "node": "12.x" } [or whatever version. No need to be totally specific hence the ‘x’]. Can insert before the dependencies start.

11) Create .gitingnore file:

touch .gitignore and in .gitignore: 

/node_modules

npm-debug.log.

DS_Store

/*.env

12) Deploy on heroku: 

Before deploying - push to git one more time for last changes to be added:

git add . 

git commit -m “<chanages made to go in here>”

$ git push heroku master

[note: at this point I had an error message: ‘error: src refspec master does not match any’.

I needed to change the branch from ‘main’ on the bottom left of vs code to ‘master’ by adding a branch master through vs code. I then pushed again and it worked.]

Committing directly to git:

https://stackoverflow.com/questions/46877667/how-to-add-a-new-project-to-github-using-vs-code - below is the relevant content:

1) Navigate to the local project directory and create a local git repository: (already done above)

 git init


2) Once that is successful, click on the 'Source Control' icon on the left navbar in VS-Code.One should be able to see files ready to be commit-ed. Press on 'Commit' button, provide comments, stage the changes and commit the files. Alternatively you can run from CLI (already done abovre)

git commit -m "Your comment"


3) Now you need to visit your GitHub account and create a new Repository. Exclude creating 'README.md', '.gitIgnore' files. Also do not add any License to the repo. Sometimes these settings cause issue while pushing in.

4) Copy the link to this newly created GitHub Repository.

5) Come back to the terminal in VS-CODE and type these commands in succession:

git remote add origin <Link to GitHub Repo>     //maps the remote repo link to local git repo

git remote -v                                  //this is to verify the link to the remote repo 

git push -u origin master // or main                      // pushes the commit-ed changes into the remote repo

 6) You can see the success message in the Terminal. You can also verify by refreshing the GitHub repo online.

Once done can change branch used from master to main: 

To switch the default branch used to deploy apps from master to main, first create a new branch locally:

git checkout -b main


Next, delete the old default branch locally:

git branch -D master


From there, the local environment only knows about the main branch.

Reset the GIT repository hosted on the Heroku Platform using the heroku-reset command from the heroku-repo CLI plugin. Doing so will not impact the running application. (Note: Please communicate this change with your team. If you are working with other developers who are not aware of the reset, they might push to "master" which will overwrite the reset).

Re-deploy the application using the new default branch:

git push heroku main

To push directly to github: 

The git push command takes two arguments:

A remote name, for example, origin

A branch name, for example, main

For example:

git push  <REMOTENAME> <BRANCHNAME> 

app.get('/downloadFile', function (req, res) {
  var file = path.join(__dirname, '/pdfs/');
  res.download(file, function (err) {
    if (err) {
      console.log('Error');
      console.log(err);
    } else {
      console.log('Success');
    }
  });
});
test('should verify typed', async () => {
  const browser = await puppeteer.launch({
    headless: false,
    slowMo: 10,
    args: ['--window-size=1920,1080']
  })
  const page = await browser.newPage()
  await page.goto(url)
  await page.type('.input-text', 'Hello World!')

  const finalText = await page.$eval('input.input-text', el => el.textContent)
  expect(finalText).toBe(finalText)
})
const bookingNumber = `${_.upperCase(modelName)}${_.random(1000000, 9999999)}
const {getIntroduction} = require('./util')

test('should output name and age', () => {
  const text = getIntroduction('Max', 20)
  expect(text).toBe('Max is 20 years old')
})
"scripts": {
  "test": "jest",
   "start": "node index.js"
},
"devDependencies": {
  "jest": "^26.6.3"
}
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
const updateStatus = asyncHandler(async (req, res) => {
  console.log("k");
  const { customer, stageFiveId, availableLoansId, status } = req.body;
  console.log(req.body);
  const customerData = await Customer.updateMany(
    {
      _id: customer,
    },
    // db.coll.update({}, {$set: {“a.$[i].c.$[j].d”: 2}}, {arrayFilters: [{“i.b”: 0}, {“j.d”: 0}]})
    {
      $set: { "stage5.$[i].availableLoans.$[j].status": status },
    },
    { arrayFilters: [{ "i._id": stageFiveId }, { "j._id": availableLoansId }] }
  );
  console.log(customerData);
  if (customerData)
    return res.status(200).json({
      success: true,
      message: "Status updated sucessfully!",
    });
  else
    return res.status(400).json({
      success: false,
      message: "Could not able to update Status!",
    });
});
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({}, {$unset:{"customerName":1}})
db.customers.updateMany({},
  [{ $set : { n : {$arrayElemAt:[{ $split: ["$customerName", " "] },1]}} }],

);
db.customers.updateMany({},
  [{ $set : { m : {$arrayElemAt:[{ $split: ["$customerName", " "] },0]}} }],

);
const fetch = require('isomorphic-fetch')


const query = fetch('https://www.freecodecamp.org/page-data/sq/d/4195245674.json')
    .then(resp => resp.json())
    .then(data => {
        // console.log(data)
        return data.data.allChallengeNode.edges.map(e => {
            // console.log(e.node)
            const url_pieces = e.node.fields.slug.split('/')
            return { 
                name: e.node.title, 
                cert: url_pieces[2], 
                section: url_pieces[3], 
                task: url_pieces[4] 
            }
        })
    }).then(q => console.log(q))
await new Promise(r => setTimeout(r, 5000));
const getModels = asyncHandler(async (req, res) => {
  const { modelName } = req.query;
  const dealership = await Dealership.aggregate([
    { $match: { _id: req.user.dealership } },
    {
      $project: {
        models: {
          $filter: {
            input: "$models",
            as: "models",
            cond: {
              $regexMatch: {
                input: "$$models.modelName",
                regex: `^${modelName}`,
                options: "i",
              },
            },
          },
        },
      },
    },
  ]);
  const models = dealership[0].models;
  return res.status(200).json({
    success: true,
    quesData: models,
  });
});
npx gsx-pdf-optimize raw_pdf.pdf optimized_pdf.pdf --dpi=150
// Script-wide timeout for wait and waitAndFind functions (in ms)
var startTime = new Date(),
  thisStep = 0,
  assert = require('assert'),
  Q = require('q'),
  ScriptTimeout = 0,
  MaintenanceMessage = "Script is running during maintenance window";

var log = function(msg) {
  if(typeof msg === "string")
  {
    var totalTimeElapsed = (new Date() - startTime);
    var elapsedSecs =  totalTimeElapsed / 1000;
    console.log('Step ' + thisStep + ': ' + elapsedSecs.toFixed(2) + 's: ' + msg);
    thisStep++;
    
    if(ScriptTimeout > 0 && totalTimeElapsed > ScriptTimeout)
    {
      throw Error('Script timed out. ' + totalTimeElapsed + 'ms is longer than script timeout threshold of ' + ScriptTimeout + 'ms.'); 
    }
  }
};

log("Initialising ...");

 // checks if this run is in within the maintenance window provided
 // @param {string} dayOfWeek - Monday, Tuesday, etc.
 // @param {string} startTime - UTC start time of window in 24hr format
 // @param {string} endTime - UTC end time of window in 24hr format
var checkInMaintenanceWindow = function(dayOfWeek, startTime, endTime)
{
  log("checkInMaintenanceWindow");
  var deferred = Q.defer();
  var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var now = new Date();
  var day = daysOfWeek[now.getUTCDay()];
  
  if(day != dayOfWeek)
  {
    log("Days do not match");
    deferred.resolve("Days do not match"); // not the specified day
  }
  else
  {
    log("Days match, checking times");
    startParts = startTime.split(":");
    var start = new Date(now);
    start.setUTCHours(parseInt(startParts[0]), parseInt(startParts[1]));

    endParts = endTime.split(":");
    var end = new Date(now);
    end.setUTCHours(parseInt(endParts[0]), parseInt(endParts[1]));

    // check if we are in the maintenance window
    if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime())
    {
      log("In maintenance window");
      $http.get("http://www.google.co.uk"); // workaround for monitor produced no traffic error
      deferred.reject(MaintenanceMessage);
    }
    else
    {
      deferred.resolve("Times do not match");
    }
  }  
  return deferred.promise;
};

function shouldDisplayError(message)
{
  return !(typeof message != "undefined" && message !== null && message.length > 0);
}

var buildSecurityOptions = function()
{
  var deferred = Q.defer();
  log("Building security options");
  // build your security options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "https://login.salesforce.com/services/oauth2/token",
    //Define body of POST request.
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    form: {
      grant_type: 'password',
      client_id: 'client ID',
      client_secret: 'Client Secret',
      username: 'username',
      password: 'password'
    }
  };
  
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var getSecurityToken = function(options){
  var deferred = Q.defer();
  log("Retrieving Security Token");
  $http.post(options, function(error, response, body)
  {
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }    
  });
  return deferred.promise; //promise is returned
};

var extractSecurityToken = function(data){
  log("Extracting Security Token");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(data);
  log("Security token retrieved successfully");
  deferred.resolve(info.access_token);
  return deferred.promise;
};

var buildApiOptions = function(securityToken){
  var deferred = Q.defer();
  log("Building API options");
  // build your api options here
  var options = {
    //Define endpoint URL.
    //url: "https://webhook.site/ddb04be2-8961-4771-b934-6dddfa40ab57",
    url: "http://url.com",
    //Define body of PATCH request.
    headers: {'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + securityToken},
    body: {
      "Description": "fooba3r"
    },
    json: true

  };
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var makeApiCall = function(options){
  var deferred = Q.defer();
  log("Making API call");

  //Make PATCH request, passing in options and callback.
  $http.patch(options, function(error, response, body){
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 204 (No Content) response code.
      assert.ok(response.statusCode == 204, 'Expected 204 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }
  });
  return deferred.promise; //promise is returned
};

var validateApiCall = function(body){
  log("Validating Api Call");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  //var info = JSON.parse(body);
  //assert.ok(shouldDisplayError(info.ErrorMessage), "Error Message: " + info.ErrorMessage);
	
  // perform any other validation here
  log("Completed successfully");
  deferred.resolve();
  return deferred.promise;
};

checkInMaintenanceWindow("Friday", "00:00", "01:30")
.then(function(){
  return buildSecurityOptions()
  .then(getSecurityToken)
  .then(extractSecurityToken)
  .then(buildApiOptions)
  .then(makeApiCall)
  .then(validateApiCall);
},
function(message){
  if(message != MaintenanceMessage)
  {
    throw new Error(MaintenanceMessage);
  }
  else
  {
    log(message);
  }
})
.done();
//Import the `assert` module to validate results.
var assert = require('assert');

var options = {
    url: "https://some_url.com",
        "headers": {
          "oauth_clientid": 123,
          
          },
        //"timeout": 15000
        };

$http.get(options, function(error, response, body) {
    console.log(response.statusCode + " status code")
    assert.ok(response.statusCode == 401, 'Expected 401 OK response');  
      });
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout});

var program = function(){
    rl.question("type question", function(answer) {
        switch (answer){
            case "option 1":
                //action 1;
                break;
            case "exit option":
            	//previous action
            	return rl.close();
            default:
                //default action
        }
        program();
    });
}

program();
app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
The following examples illustrate defining simple routes.

Respond with Hello World! on the homepage:
//get method for retrieving data.
app.get('/', function (req, res) {
  res.send('Hello World!')
})
 Save
Respond to POST request on the root route (/), the application’s home page:
//send method for sending data.
app.post('/', function (req, res) {
  res.send('Got a POST request')
})
 Save
Respond to a PUT request to the /user route:
//put request to 
app.put('/user', function (req, res) {
  res.send('Got a PUT request at /user')
})
 Save
Respond to a DELETE request to the /user route:

app.delete('/user', function (req, res) {
  res.send('Got a DELETE request at /user')
})
Basic routing
Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:

app.METHOD(PATH, HANDLER)
 Save
Where:

app is an instance of express.
METHOD is an HTTP request method, in lowercase.
PATH is a path on the server.
HANDLER is the function executed when the route is matched.
function processSQLFile(fileName) {

  // Extract SQL queries from files. Assumes no ';' in the fileNames
  var queries = fs.readFileSync(fileName).toString()
    .replace(/(\r\n|\n|\r)/gm," ") // remove newlines
    .replace(/\s+/g, ' ') // excess white space
    .split(";") // split into all statements
    .map(Function.prototype.call, String.prototype.trim)
    .filter(function(el) {return el.length != 0}); // remove any empty ones

  // Execute each SQL query sequentially
  queries.forEach(function(query) {
    batch.push(function(done) {
      if (query.indexOf("COPY") === 0) { // COPY - needs special treatment
        var regexp = /COPY\ (.*)\ FROM\ (.*)\ DELIMITERS/gmi;
        var matches = regexp.exec(query);
        var table = matches[1];
        var fileName = matches[2];
        var copyString = "COPY " + table + " FROM STDIN DELIMITERS ',' CSV HEADER";
        var stream = client.copyFrom(copyString);
        stream.on('close', function () {
          done();
        });
        var csvFile = __dirname + '/' + fileName;
        var str = fs.readFileSync(csvFile);
        stream.write(str);
        stream.end();
      } else { // Other queries don't need special treatment
        client.query(query, function(result) {
          done();
        });
      }
    });
  });
}
command line

npm init -y (creates the package for dependencies)

npm i [module]  (creates dependency key and module repository)
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      // "processId": "${command:PickProcess}",
      "protocol": "inspector",
      "restart": true,
      "name": "Launch Programa",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
$ sudo npm install --global cross-env
var express = require('express');
var app = express();

app.enable('trust proxy'); //to detect if req.secure is true/false

//Block http requests. Only allow https requests
app.use(function (req, res, next) {
	if (req.headers['x-forwarded-proto'] !== 'https'){
      return res.status(404).send('Not found');
    } else {
    next();
    }
})

exports = module.exports = app;
router.get("/search/:page", (req, res, next) => {
  const resultsPerPage = 5;
  const page = req.params.page >= 1 ? req.params.page : 1;
  const query = req.query.search;

  Product.find({ name: query })
    .select("name")
    .sort({ name: "asc" })
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((results) => {
      return res.status(200).send(results);
    })
    .catch((err) => {
      return res.status(500).send(err);
    });
});
userSchema.pre('save', async function(next){
    if (!this.isModified('password')) return next()
    this.password = await bcrypt.hash(this.password, 8)

    next()
})
//You must require fs and path before this action can be done
//set this on the top of the model
const imagePath = 'uploads/image'


//Create a virtual with the schema name e.g.
blogSchema.virual('imagePath').get(function(){
if(this.image != null){
return path.join('/', imagePath, this.image)
}
})

//exports the imagePath as like this
module.exports.imagePath = imagePath 


//go to the route and require it with the model name e.g.
const uploadPath = path.join("public", BlogModel.imagePath);

//set your function for unlink and call it on the delete route
function removeImage(image){
	fs.unlink(uploadPath, image), (err)=>{
    if(err) console.log(err)
    })
}

// Let generalize user data
app.use((req, res, next) => {
    res.locals.user = req.isAuthenticated() ? req.user : null
    return next()
})
const passport = require('passport')
const LocalStrategy = require("passport-local").Strategy;

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
const flashMsg = (req, res, next) => {
    if (req.session.flashData) {
        for (const key in req.session.flashData) {
            res.locals[key] = req.session.flashData[key]
        }

        req.session.flashData = null
    }
     
    next()
}

module.exports = flashMsg
const mongooseValidation = (theError) => {
    const errors = {}
    const details = errors.theError
    for (const key in details)
    {
        errors[key] = [details[key].message]
    }
    return errors
}

module.exports = mongooseValidation
var {src, dest, watch}        = require('gulp');
var browserSync = require('browser-sync').create();
var sass        = require('gulp-sass');

// Static server
  function bs() {
    serveSass();
  browserSync.init({
      server: {
          baseDir: "./"
      }
  });
  watch("./*.html").on('change', browserSync.reload);
  watch("./scss/**/*.scss", serveSass);
  watch("./js/*.js").on('change', browserSync.reload);
};

// Compile sass into CSS & auto-inject into browsers
 function serveSass() {
  return src("./scss/*.scss")
      .pipe(sass())
      .pipe(dest("./css"))
      .pipe(browserSync.stream());
};

exports.serve = bs;
var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
var stripe = require('stripe')('sk_test_LIPsyf7cwBv0pbWPbzjeqAhj009wgDByN7');

stripe.customers.create(
  {
    description: 'My First Test Customer (created for API docs)',
  },
  function(err, customer) {
    // asynchronously called
  }
);
var express = require("express");
var app = express();
const session = require('express-session');
var MemcachedStore = require('connect-memjs')(session);

// configure sessions
var store = new MemcachedStore({servers: [process.env.MEMCACHEDCLOUD_SERVERS], username: process.env.MEMCACHEDCLOUD_USERNAME, password: process.env.MEMCACHEDCLOUD_PASSWORD});
app.use(session({ secret: 'keyboard cat',
   resave: true,
   saveUninitialized: true,
   cookie: { secure: true }, 
   store: store
}))
                                exports.removeById = (req, res) => {
   UserModel.removeById(req.params.userId)
       .then((result)=>{
           res.status(204).send({});
       });
};

                                
                                var app = express()
var sess = {
  secret: 'keyboard cat',
  cookie: {}
}
 
if (app.get('env') === 'production') {
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}
 
app.use(session(sess))
                                
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function (result) {
       alert("The result is "+result);
	}
});
                                
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
router.post('/:id/edit', auth.requireLogin, (req, res, next) => {
  Post.findByIdAndUpdate(req.params.id, req.body, function(err, post) {
    if(err) { console.error(err) };

     res.redirect(`/`+req.params.id);
  });
});
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var slug = require('mongoose-slug-generator');

mongoose.plugin(slug);

const pageSchema = new Schema({
    title: { type: String , required: true},
    slug: { type: String, slug: "title" }
});

var Page = mongoose.model('Page', pageSchema);
module.exports = Page;
const songs[];
const results;

for (var i, i++, i<songs.length){
    if(song[i].artist == "Drake"){
      result.push(songs[i]);
    };

// OR

const songs [];
const result = songs.filter ( song => song.artist == "Drake");
<form action="/new" method="post">

  <input name="title" type="text">
  <input name="description" type="text">
  <input name="steps[0][text]" type="text">
  <input name="steps[0][ingredients]" type="text">
  <input name="steps[1][text]" type="text">
  <input name="steps[1][ingredients]" type="text">
  <button type="submit">Submit Form</button>

</form>
star

Sun Jan 21 2024 21:31:29 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/?__cf_chl_tk

#react.js #javascript #nodejs
star

Thu Dec 28 2023 17:55:06 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Dec 13 2023 19:39:36 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Nov 29 2023 16:32:25 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/how-to-send-email-using-mailgun-api-in-node-js/

#mailgun #javascript #nodejs
star

Mon Nov 20 2023 19:45:02 GMT+0000 (Coordinated Universal Time) https://youtu.be/f2EqECiTBL8

#nodejs
star

Thu Oct 26 2023 22:39:15 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Sun Oct 22 2023 18:25:48 GMT+0000 (Coordinated Universal Time) https://commitizen-tools.github.io/commitizen/config/

#nodejs #commit #commitizen #npm
star

Wed Oct 18 2023 06:42:04 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Mon Oct 09 2023 22:50:10 GMT+0000 (Coordinated Universal Time) https://bling2.com/

#json #mysql #react.js #nodejs
star

Thu Sep 14 2023 21:45:27 GMT+0000 (Coordinated Universal Time) https://www.honeybadger.io/blog/node-environment-managers/

#nodejs
star

Tue Aug 29 2023 03:25:55 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Thu Aug 10 2023 18:35:35 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Thu Aug 03 2023 17:51:43 GMT+0000 (Coordinated Universal Time) https://timmousk.com/blog/axios-timeout/

#nodejs #javascript
star

Tue Aug 01 2023 16:01:12 GMT+0000 (Coordinated Universal Time)

#database #postgresql #nodejs #indiafirst #javascript #pgadmin4
star

Thu Jul 20 2023 10:38:29 GMT+0000 (Coordinated Universal Time)

#nodejs #axios #form-urlencoded
star

Thu Jun 15 2023 11:23:39 GMT+0000 (Coordinated Universal Time) https://chat.openai.com/c/27bf8c3a-a183-4e84-aff6-85d425a92ab4

#nodejs
star

Mon May 29 2023 11:28:23 GMT+0000 (Coordinated Universal Time) https://www.kindacode.com/snippet/node-js-generate-images-from-text-using-canvas/

#nodejs #javascript
star

Fri May 12 2023 11:15:35 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #rest
star

Wed May 03 2023 19:43:05 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Fri Apr 14 2023 10:50:48 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:44:57 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:43:00 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:42:08 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:39:24 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:37:23 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:29:04 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:15:24 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:15:00 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:14:22 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Fri Apr 14 2023 10:10:37 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Tue Apr 04 2023 08:04:49 GMT+0000 (Coordinated Universal Time) https://www.opris.exchange/binance-clone-script/

#webassembly #javascript #nodejs
star

Sun Apr 02 2023 05:03:55 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Sun Mar 26 2023 15:17:28 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Tue Mar 07 2023 08:02:58 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/5823722/how-to-serve-an-image-using-nodejs

#javascript #nodejs
star

Mon Mar 06 2023 11:15:56 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Fri Mar 03 2023 08:46:46 GMT+0000 (Coordinated Universal Time) http://www.movable-type.co.uk/scripts/latlong.html

#html #distance #nodejs
star

Wed Feb 22 2023 19:28:16 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Sat Jan 21 2023 03:10:17 GMT+0000 (Coordinated Universal Time) https://github.com/nvm-sh/nvm#nvmrc

#commandline #nodejs
star

Wed Jan 18 2023 03:27:15 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #typescript
star

Tue Jan 03 2023 13:31:04 GMT+0000 (Coordinated Universal Time)

#nodejs #chai
star

Mon Jan 02 2023 07:10:19 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/43070692/update-schema-in-mongoose-to-add-new-property

#javascript #js #nodejs
star

Mon Dec 26 2022 14:34:53 GMT+0000 (Coordinated Universal Time)

#nodejs #chai
star

Fri Dec 23 2022 11:31:05 GMT+0000 (Coordinated Universal Time)

#nodejs #chai
star

Fri Dec 23 2022 07:09:53 GMT+0000 (Coordinated Universal Time)

#nodejs #chai
star

Fri Dec 16 2022 11:40:26 GMT+0000 (Coordinated Universal Time)

#nodejs #datauri
star

Tue Dec 06 2022 09:33:23 GMT+0000 (Coordinated Universal Time)

#nodejs #chai #mocha
star

Sat Dec 03 2022 10:37:21 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/erc721-token-development

#react.js #nodejs #mongoshell #jquery
star

Mon Nov 28 2022 04:12:19 GMT+0000 (Coordinated Universal Time) https://app.rollbar.com/onboarding/install/rb-node-js-default

#javascript #nodejs #rollbar
star

Wed Nov 23 2022 16:29:54 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/11/cloudfront-function-and-association.html

#aws-cdk #aws #cloudfront #nodejs #typescript
star

Mon Nov 21 2022 14:12:26 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/11/add-vpc-to-lambda-cdk.html

#aws-cdk #nodejs #typescript #vpc #lambda
star

Sat Nov 12 2022 08:43:12 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/11/cookies-same-site-and-lax-behavior.html

#typescript #nodejs #cookies
star

Wed Nov 09 2022 14:43:40 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Thu Nov 03 2022 01:34:23 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Fri Oct 28 2022 21:25:16 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Oct 26 2022 05:26:16 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #express
star

Wed Oct 26 2022 04:24:39 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/57005696/disallowing-concurrent-logins-for-same-user-at-once

#nodejs
star

Tue Oct 25 2022 07:05:26 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/10/unit-test-and-mocking-axios-jest.html

#aws #cdk #typescript #nodejs #axios #unittest
star

Sun Oct 23 2022 10:09:53 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/10/call-external-api-from-aws-lambda-using.html

#aws #cdk #typescript #nodejs
star

Wed Oct 19 2022 10:27:20 GMT+0000 (Coordinated Universal Time) https://maticz.com/token-development

#nodejs #angular #javascript #php #python #vue.js #react.js
star

Wed Oct 19 2022 10:19:52 GMT+0000 (Coordinated Universal Time) https://bit.ly/3GLa8p1

#javascript #java #php #laravel #angular #nodejs
star

Sun Oct 16 2022 16:44:02 GMT+0000 (Coordinated Universal Time) https://github.com/0x7c13/Notepads

#nodejs
star

Thu Oct 13 2022 12:35:44 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/10/find-security-group-based-on-name-aws.html

#aws #cdk #nodejs #typescript
star

Sat Oct 08 2022 08:35:55 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/10/pass-query-params-from-cloudfront-to.html

#aws #aws-cdk #nodejs #cloudfront
star

Fri Oct 07 2022 15:52:41 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/10/httpskuchbhilearning.blogspot.comimport-existing-vpc-in-aws-cdk.html

#aws #aws-cdk #vpc #nodejs #typescript
star

Tue Oct 04 2022 11:32:44 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/09/attaching-lambda-secret-manager.html

#aws #aws-cdk #secret-manager #lambda #nodejs
star

Tue Oct 04 2022 11:26:02 GMT+0000 (Coordinated Universal Time) https://kuchbhilearning.blogspot.com/2022/09/api-gateway-custom-domain-using-aws-cdk.html

#apigateway #aws-cdk #aws #lambda #route53 #nodejs #restapi
star

Fri Sep 23 2022 14:16:27 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #typescript
star

Fri Sep 23 2022 14:15:03 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #typescript
star

Thu Sep 15 2022 16:14:27 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Thu Sep 15 2022 05:44:35 GMT+0000 (Coordinated Universal Time) https://www.hivelance.com/binance-clone-script

#javascript #php #nodejs #laravel
star

Wed Sep 07 2022 16:45:41 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Mon Sep 05 2022 13:32:00 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Wed Aug 24 2022 04:59:02 GMT+0000 (Coordinated Universal Time) https://search.brave.com/search?q

#nodejs #react.js
star

Wed Aug 10 2022 09:47:51 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Wed Aug 10 2022 09:45:44 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Thu Jul 28 2022 22:53:13 GMT+0000 (Coordinated Universal Time) https://fullstackopen.com/en/part9/typing_the_express_app

#javascript #nodejs #typescript
star

Tue Jul 19 2022 21:52:09 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #jwt #login
star

Tue Jul 19 2022 09:36:21 GMT+0000 (Coordinated Universal Time) https://srcshare.io/?id

#nodejs
star

Tue Jul 19 2022 09:34:59 GMT+0000 (Coordinated Universal Time) https://srcshare.io/?id

#nodejs
star

Mon Jul 18 2022 20:50:42 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #jwt #login
star

Mon Jul 18 2022 19:58:59 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Sun Jul 17 2022 19:52:01 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #jwt #login
star

Sun Jul 17 2022 09:10:16 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #jwt #login
star

Sat Jul 16 2022 20:23:03 GMT+0000 (Coordinated Universal Time) https://www.youtube.com/watch?v=VsUzmlZfYNg&t=12191s

#javascript #nodejs #jwt #login
star

Sun Jul 10 2022 08:36:11 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Sun Jul 10 2022 08:19:18 GMT+0000 (Coordinated Universal Time) https://eslint.org/docs/latest/user-guide/getting-started

#javascript #nodejs #react.js
star

Sat Jul 09 2022 19:49:44 GMT+0000 (Coordinated Universal Time) https://affiliate.traforce.com/v2/statistics/countries?date_from

#nodejs
star

Wed Jun 29 2022 08:34:13 GMT+0000 (Coordinated Universal Time) https://github.com/nvm-sh/nvm

#nodejs
star

Mon Jun 06 2022 07:24:48 GMT+0000 (Coordinated Universal Time)

#nodejs #prisma
star

Sun Jun 05 2022 14:47:22 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Tue May 31 2022 16:49:23 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Tue Apr 19 2022 04:56:54 GMT+0000 (Coordinated Universal Time) https://github.com/jmerle/node-icecream

#nodejs
star

Sun Apr 17 2022 09:50:47 GMT+0000 (Coordinated Universal Time) express-validator

#express #javascript #nodejs
star

Thu Apr 07 2022 14:59:13 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Fri Mar 25 2022 08:01:16 GMT+0000 (Coordinated Universal Time) https://reactgo.com/nvm-set-default-node-version/

#nodejs
star

Sun Mar 20 2022 19:14:31 GMT+0000 (Coordinated Universal Time)

#mongo #nodejs
star

Sun Mar 20 2022 19:10:44 GMT+0000 (Coordinated Universal Time)

#mongo #nodejs
star

Sun Mar 20 2022 11:24:15 GMT+0000 (Coordinated Universal Time)

#mongo #nodejs
star

Fri Jan 14 2022 14:28:19 GMT+0000 (Coordinated Universal Time)

#api-testing #nodejs #supertest
star

Sat Jan 08 2022 06:00:50 GMT+0000 (Coordinated Universal Time) https://gist.github.com/juliyvchirkov/2c5c8d54b182528e39d4565d1632f8ee#file-magentodocumentroot-mjs

#javascript #nodejs #magento #document_root #resolve #module #mjs
star

Wed Nov 17 2021 13:19:30 GMT+0000 (Coordinated Universal Time)

#nodejs #redis #nodemon
star

Wed Nov 17 2021 13:16:18 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Tue Aug 24 2021 16:30:12 GMT+0000 (Coordinated Universal Time) https://sematext.com/blog/node-js-error-handling/

#nodejs #promises #unhandled
star

Fri Aug 20 2021 16:12:21 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Sat Aug 14 2021 22:15:34 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Sat Aug 14 2021 22:15:00 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Jul 21 2021 11:29:05 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript #postman
star

Thu Jul 15 2021 09:01:59 GMT+0000 (Coordinated Universal Time)

#nodejs #api #routing #rest
star

Thu Jul 15 2021 09:01:12 GMT+0000 (Coordinated Universal Time)

#mongodb #mongoose #nodejs
star

Mon Jul 05 2021 11:17:27 GMT+0000 (Coordinated Universal Time) https://dev.to/kowalevski/how-to-install-or-update-node-by-using-nvm-node-version-manager-1ip1

#javascript #nodejs #nvm #npm
star

Wed Jun 30 2021 11:07:26 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Wed Jun 30 2021 11:05:27 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Sat Jun 19 2021 09:25:48 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Wed Jun 16 2021 13:52:19 GMT+0000 (Coordinated Universal Time)

#nodejs #rest-client-extention
star

Mon Jun 14 2021 12:11:52 GMT+0000 (Coordinated Universal Time)

#heroku #nodejs #commandline
star

Mon Jun 14 2021 12:02:44 GMT+0000 (Coordinated Universal Time)

#heroku #seed #nodejs
star

Fri Jun 11 2021 05:17:27 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb #aggregate
star

Tue Jun 08 2021 16:48:15 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

Mon Jun 07 2021 08:25:51 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

Mon Jun 07 2021 08:20:41 GMT+0000 (Coordinated Universal Time)

#hbs #handlebars #express #nodejs
star

Sun Jun 06 2021 15:47:09 GMT+0000 (Coordinated Universal Time) https://attacomsian.com/blog/nodejs-password-hashing-with-bcrypt

#bcrypt #authentication #express #nodejs #password
star

Sun Jun 06 2021 15:41:09 GMT+0000 (Coordinated Universal Time) https://attacomsian.com/blog/mongoose-connect-async-await

#mongoose #mongodb #nodejs
star

Sun Jun 06 2021 15:34:43 GMT+0000 (Coordinated Universal Time)

#nodejs #async #promises #express #javas
star

Sun May 23 2021 14:30:42 GMT+0000 (Coordinated Universal Time)

#nodejs #heroku #github
star

Fri May 21 2021 20:09:05 GMT+0000 (Coordinated Universal Time)

#html #nodejs #pdf
star

Sat May 15 2021 10:50:38 GMT+0000 (Coordinated Universal Time)

#jest #nodejs #testing #puppeteer
star

Mon May 10 2021 10:21:30 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Sat May 08 2021 17:59:57 GMT+0000 (Coordinated Universal Time)

#jest #nodejs #testing
star

Sat May 08 2021 17:24:35 GMT+0000 (Coordinated Universal Time)

#jest #nodejs #testing
star

Sat May 08 2021 07:42:19 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Sat May 08 2021 07:38:30 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Wed May 05 2021 03:22:48 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Fri Apr 30 2021 12:17:40 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Fri Apr 30 2021 12:17:39 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose #mongodb
star

Tue Apr 27 2021 22:51:13 GMT+0000 (Coordinated Universal Time) wrote it myself

#nodejs
star

Wed Apr 21 2021 09:13:13 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Mar 31 2021 12:07:26 GMT+0000 (Coordinated Universal Time)

#nodejs #mongoose
star

Mon Mar 15 2021 13:40:38 GMT+0000 (Coordinated Universal Time) https://github.com/mattdesl/gsx-pdf-optimize

#nodejs #commandline #npx
star

Thu Mar 11 2021 13:05:11 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Tue Mar 09 2021 15:29:16 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Feb 24 2021 20:46:20 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/ip

#nodejs #javascript
star

Sat Feb 06 2021 13:36:11 GMT+0000 (Coordinated Universal Time)

#javascript #linux #nodejs
star

Sat Feb 06 2021 12:27:05 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Thu Jan 07 2021 22:05:21 GMT+0000 (Coordinated Universal Time) https://www.reddit.com/r/node/comments/4txqqw/how_to_track_email_opens_with_nodejs_app/

#nodejs #javascript #email
star

Fri Dec 04 2020 01:43:47 GMT+0000 (Coordinated Universal Time)

#nodejs,jquery #nodejs
star

Fri Dec 04 2020 01:42:13 GMT+0000 (Coordinated Universal Time)

#nodejs #jquery
star

Fri Nov 27 2020 18:42:18 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/22636388/import-sql-file-in-node-js-and-execute-against-postgresql

#sql #nodejs
star

Sat Nov 14 2020 17:51:41 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Wed Nov 11 2020 12:56:36 GMT+0000 (Coordinated Universal Time)

#json #nodejs #debug
star

Sat Oct 10 2020 17:41:42 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
star

Fri Oct 09 2020 23:22:52 GMT+0000 (Coordinated Universal Time) https://github.com/716green/graphql-express-setup/blob/main/server.js

#nodejs #javascript #graphql #express
star

Sun Oct 04 2020 06:48:54 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Sat Sep 26 2020 11:03:32 GMT+0000 (Coordinated Universal Time)

#nodejs #express #heroku
star

Wed Aug 26 2020 21:29:30 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Sat Aug 22 2020 23:06:10 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Tue Aug 18 2020 16:27:50 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs
star

Mon Aug 17 2020 16:22:15 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Mon Aug 17 2020 16:18:23 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Mon Aug 17 2020 15:53:41 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Mon Aug 17 2020 15:51:22 GMT+0000 (Coordinated Universal Time)

#nodejs #javascript
star

Tue Aug 04 2020 22:56:30 GMT+0000 (Coordinated Universal Time) https://flaviocopes.com/node-mass-rename-files/

#javascript #nodejs
star

Mon Jun 29 2020 22:48:29 GMT+0000 (Coordinated Universal Time)

#gulp #nodejs
star

Mon Jun 08 2020 10:15:25 GMT+0000 (Coordinated Universal Time) https://lavalite.org/blog/fastest-method-to-copy-file-in-nodejs

#nodejs #fs #javascript
star

Mon May 25 2020 10:06:38 GMT+0000 (Coordinated Universal Time) https://stripe.com/docs/api/customers/create

#nodejs
star

Fri May 08 2020 23:05:13 GMT+0000 (Coordinated Universal Time)

#nodejs
star

Thu Apr 30 2020 06:35:49 GMT+0000 (Coordinated Universal Time) https://www.toptal.com/nodejs/secure-rest-api-in-nodejs

#nodejs
star

Tue Apr 28 2020 19:40:32 GMT+0000 (Coordinated Universal Time) https://medium.com/javascript-in-plain-english/querying-sql-server-in-node-js-using-async-await-5cb68acf2144

#javascript #nodejs
star

Tue Apr 28 2020 19:22:18 GMT+0000 (Coordinated Universal Time) https://www.npmjs.com/package/express-session

#nodejs
star

Sun Apr 26 2020 20:50:22 GMT+0000 (Coordinated Universal Time) https://api.jquery.com/jquery.post/

#javascript #nodejs
star

Sun Mar 29 2020 07:06:35 GMT+0000 (Coordinated Universal Time) https://gist.github.com/trantorLiu/5924389

#javascript #nodejs #handlebars #express
star

https://medium.com/@thiscodeworks.com/how-to-redirect-your-node-js-app-hosted-on-heroku-from-http-to-https-50ef80130bff

#javascript #nodejs #commandline

Save snippets that work with our extensions

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