Slite3 Javascript SQL

This code creates a simple web server using the Express framework in Node.js, and it connects to a local SQLite database file named “bruh.db”. It first imports the necessary modules: Express for handling HTTP routes, CORS to allow cross-origin requests, and sqlite3 to interact with the database. The Express app is initialized, and middleware is added to enable CORS and to parse JSON request bodies. The server then starts listening on port 9000, and when it’s ready, it prints a confirmation message to the console.

The server defines several endpoints. The root endpoint (/) responds with a simple message indicating that the “Bruh database” is running. The /artists GET route queries all rows from the artists table in the database. If data is found, it sends it back in JSON format with a 200 status; if no data is found, it responds with a 404 and a “No Data!” message. If there is an error during the query, it returns the error in JSON format.

The POST route at /artists allows the client to insert a new artist into the database. It expects a JSON object in the request body containing a name field. If the insertion is successful, it returns a 201 status with a confirmation message; if there is an error, it sends the error back to the client.

Finally, the /genre-tracks GET route performs a join between the genres and tracks tables to retrieve a list of tracks along with their associated genre names. This data is returned as JSON. As with the other routes, if no data is found, it responds with a 404 and a “No Data!” message, and any query error is sent back in JSON format. This application provides basic read and write functionality for a music-related SQLite database using a RESTful API structure.

const cors = require('cors');
const app = express();
const sqlite3 = require('sqlite3');
const db = new sqlite3.Database("./bruh.db");


app.use(cors());
app.use(express.json());

app.listen(9000, () => {
    console.log("Nice");
});








app.get('/',(req,res)=>{
    res.send("Bruh database")
});



app.get('/artists',(req,res)=>{
    db.all("select * from artists",(error,rows)=>{
        if(error){
            res.json(error);
        } else {
            if(rows.length>0){
                res.status(200).json(rows);
            } else {
                res.status(404).json({message:"No Data!"});
            }
        }
    }
    );
});



app.post('/artists',(req,res)=>{
    const {name}=req.body;
    db.run("insert into artists (name) values(?)",[name],error=>{
        if(error) return res.send(error);
        return res.status(201).json({message:"Data upload!"});
    });

});




app.get('/genre-tracks',(req,res)=>{
    db.all("select genres.Name as 'Genre name',tracks.Name as 'Tracks name' from genres,tracks where genres.GenreId = tracks.GenreId",(error,rows)=>{
        if(error){
            res.json(error);
        } else {
            if(rows.length>0){
                res.status(200).json(rows);
            } else {
                res.status(404).json({message:"No Data!"});
            }
        }
    }
    );
});```

I’m trying to use a string code to send an email on a specific change and while debugging it doesn’t reconize the receipient, any suggestions?

This is a code I wrote, wether correct or not, it is’nt working to send email as while debugging it will not reconize the recipient.

Debug log

 function myFunction() {
  var sheet = SpreadsheetApp.getActive().getSheetByName("Backend");
  var range = sheet.getRange("C2:C23");
  var values = range.getValues();
  var lastRow = sheet.getLastRow();
  var emailSent = sheet.getRange("B2:O24").getValues();
  
  for (var i = 0; i < lastRow; i++) {
  if (values [i][0] === 0 && emailSent[i][0] !== "Sent")
  var recipient = '[email protected]';
  var subject = 'Ticker';
  var message = 'Buy_Sell_hold';

  MailApp.sendEmail(recipient, subject, message);
  }

How to programmatically generate fake profile pictures? [closed]

I’m building a chat application using the MERN stack for my portfolio project. To improve the UI, I want to populate user profiles with realistic-looking fake profile pictures.

Is there a way to programmatically generate or fetch fake profile pictures, ideally via an API or script, so I can automate adding them to my user data? The pictures should be:

  • Not real faces

  • Free to use (for personal portfolio and public demo)

  • Easy to integrate or download in bulk

Could anyone recommend an approach, tool, or API to generate or retrieve such fake profile pictures programmatically?

Import parent style into shadow DOM of custom element

I have a custom element, let’s say it’s called <cust-elem>. Assume that <cust-elem></cust-elem> renders to <a href="#">Foo</a>, but inside a shadow DOM.

Since my anchor a is styled in the surrounding environment (e.g., a lighter blue than the default), the links “outside” and “inside” the custom element look weird. I’ve searched a lot and found many workarounds, all of which are awful:

  • Don’t use a shadow DOM, render in light DOM. Out of the remaining options, probably the most sane, but obviously breaks encapsulation. I disklike this.
  • Use a shared CSS document that can be imported in the shadow DOM. Absolutely awful idea because it means my custom element has to have knowledge about the very file name where that style happens, breaking encapsulation even worse. Hard reject.
  • Use CSS --vars to communicate color. Rejected for the same reason as before, my custom element should have no need to know what variables contain the color and I do want to import the whole style (e.g., including text-decoration and such).

Ideally, in my shadow DOM CSS I would like to have a declaration like (imaginary syntax):

a {
    all: inherit-host(a);
}

Which would essentially answer the question: What style would a have if it replaced the custom element, then carry over all those properties into a of the shadow DOM.

I have not found a clean way to do this, not via Google nor a few LLMs I have asked. Is there a solution for this very obvious issue?

Why does referencing a this.function() in JavaScript not refer to the prototype element?

the below outputs true, meaning that new memory is not allocated for different objects, but they point to the same prototype Noob.

   function Noob(name, game) {
      this.name = name;
      this.game = game;
    }
    
    Noob.prototype.jersey = function () {
      console.log(this.game);
    };
    
    let p1 = new Noob("adam", "volleyball");
    let p2 = new Noob("eve", "cricket");
    
    p1.jersey();
    p2.jersey();
    
    console.log(p1.jersey === p2.jersey);

This one outputs false, meaning new memory is created for different objects. If I were to remove this keyword from the jersey function, then it returns true.

function Noob(name, game) {
  this.name = name;
  this.game = game;
  this.jersey = function () {
    console.log(this.game);
  };
}

let p1 = new Noob("adam", "volleyball");
let p2 = new Noob("eve", "cricket");

console.log(p1.jersey === p2.jersey);

I am confused whether this is related to the lexical scope of the this keyword or something with the new keyword.

How to type static getters in abstract classes in javascript using jsdoc

I’ve got a base class with some static getters that need to be overwritten by the inheriting classes.

class BaseClass {
    /**
     * @abstract
     * @returns {string}
     */
    static get prefix() { throw Error('must be overridden'); }

    /**
     * @abstract
     * @returns {string}
     */
    static get suffix() { throw Error('must be overridden'); }

    /**
     * @template {typeof BaseClass} T
     * @this T
     * @returns {`${T['prefix']}_${T['suffix']}`}
     */
    static get key() { return `${this.prefix}_${this.suffix}`; }
}

class Foo extends BaseClass {
    /** @override */
    static get prefix() { return /** @type {const} */ ('foo') };
    /** @override */
    static get suffix() { return /** @type {const} */ ('bar') };
}

Foo.key;
// `Foo.key` should be inferred as `'foo_bar'` but is only inferred as `${T['prefix']}_${T['suffix']}`.

The tooling can't infer the expected type here

Contrast this to a non static example that behaves exactly as I’d want, but my framework uses a lot of these static utility classes and thus this doesn’t work for my case.

class BaseClass {
    /**
     * @abstract
     * @returns {string}
     */
    get prefix() { throw Error('must be overridden'); }

    /**
     * @abstract
     * @returns {string}
     */
    get suffix() { throw Error('must be overridden'); }

    /**
     * @returns {`${this['prefix']}_${this['suffix']}`}
     */
    get key() { return `${this.prefix}_${this.suffix}`; }
}

class Foo extends BaseClass {
    /** @override */
    get prefix() { return /** @type {const} */ ('foo') };
    /** @override */
    get suffix() { return /** @type {const} */ ('bar') };
}

const foo = new Foo();
foo.key;
// the tooling correctly knows `foo.key` is `'foo_bar'`

the tooling correctly knows foo.key is 'foo_bar'

The goal is to type the static getters in such a way that directly referencing Foo.key (or any other inheriting class) has the proper constant type. Is there any way to do this with static classes via JSDoc?

BAT Job Compiles TypeScript File and Exits Without Running JS File

I have this BAT file, it is supposed to

  1. It takes any js or ts file as an argument
  2. Compile the file if its a .ts one
  3. Run the file using node – if its a ts file, it should create a .js file with the same name after compilation
  4. takes STDIN from input.in file, place STDOUT to output.out file
@echo off

REM Handle incoming file
set "FILE=%~1"
set "DIR=%~dp1"
set "NAME=%~n1"
set "EXT=%~x1"

cd /d "%DIR%"

REM Input/Output file paths
set "INPUT_FILE=%DIR%input.in"
set "OUTPUT_FILE=%DIR%output.out"

REM Compile TS if needed
if /I "%EXT%"==".ts" (
    echo Compiling TypeScript file...
    tsc "%FILE%"
    if errorlevel 1 (
        echo TypeScript compilation failed.
        exit /b %errorlevel%
    )
    set "RUNFILE=%DIR%%NAME%.js"
) else (
    set "RUNFILE=%FILE%"
)

echo Running: node "%RUNFILE%" < "%INPUT_FILE%" > "%OUTPUT_FILE%"
node "%RUNFILE%" < "%INPUT_FILE%" > "%OUTPUT_FILE%"
exit /b

But it

✅runs all js files
✅compiles ts file perfectly
❌exits the process after compilation step without executing the js created after execution

After adding some debuggers, I am sure that nothing truly executes after tsc command, I am also assured the js created after compilation is correct, and runs with node when invoked from cmd.

I need help here, I am not sure of why this is happening, and how can I get it to work.

How do I change the array values by getting multiple selected checkbox values?

I am try to use Ajax to Post value of an array at a time sequentially. There is working if the array values are fixed.But it is not working if the values are variable.
How could I change the array values of “startProcess” by getting multiple selected checkbox values? Deeply appreciated for the help.

function x_print() {
idx = 0;

var checkboxes = document.getElementsByName('multiple_id');
var spid = "";
for (var i=0, n=checkboxes.length;i<n;i++) 
{
    if (checkboxes[i].checked) 
    {
        spid += ',"'+checkboxes[i].value+'"';
    }
}
if (spid) spid = spid.substring(1);
///////////////////////
/// How to put "spid" into "startProcess" array?
//////////////////////

startProcess(["2505283JTS29U2","2505283FGSRJQ6","2505283E13UJJM"]); /// change values here

function startProcess(arg){
  if(typeof arg[idx] !== 'undefined'){
  
  $('.append-range_'+arg[idx]).html("<img src=img/loadinggraphic.gif>");

$.ajax({
      url: "loopok.php",
      method: 'post',
      query: arg[idx],
      data: {
            od_id: arg[idx],
        },
      success: function(resp){
        if(resp == "OK"){
          $('.append-range_'+arg[idx]).html('<strong>ID:</strong>'+arg[idx]+' <span style=color:blue;>OK</span><br>')
        }else{
          $('.append-range_'+arg[idx]).html('<strong>ID:</strong>'+arg[idx]+' <span style=color:red;>NG</span><br>')
        }
        idx++;
        startProcess(arg);
      }
    })
      }
}}

<div class="container">
    <div class="row">
        <h1>Range between two dates:</h1>
    </div>
    <br>
            <div class="row">
        <div class="append-range_111"></div>
        <div class="append-range_222"></div>
        <div class="append-range_333"></div>
    </div>
    <div class="row">
        <div class="append-range"><input type="checkbox" name="multiple_id" value="111"></div>
        <div class="append-range"><input type="checkbox" name="multiple_id" value="222"></div>
        <div class="append-range"><input type="checkbox" name="multiple_id" value="333"></div>
    </div>
    <div class="row">
        <input type="button" class="submit_button" onclick="x_print()" value=" PROCESS ">
    </div>
</div>

Regex for WhatsApp editor Italic [duplicate]

I my WhatsApp editor I have to write:

_text_

For italic.

My problem is, I also have to do a binding to replace tags like this:

_{{USER_CODE}}_

For the variable value.

In my editor preview this kind of variable are not showing correctly.

What I have so far:

.replace(/_([^_]+)_/g, "<i>$1</i>")
.replace(/(?:_)(?:(?!s))((?:(?!n|_).)+)(?:_)/g,'<i>$1</i>')

None of them work and the result is this:

{{USERCODE}}_

What would be the regex to achieve this?

key up event is not firing after key down and very fast key up

When the keys are pressed and released very quickly, the keyup event does not execute. Does anyone know how to fix this?

window.addEventListener("load", function (ev) {
    const samurai = document.querySelector(".samurai");
    let classes = null;

    const removeClasses = () => {
        classes.forEach((classe) => {
            if (classe !== "samurai") {
                samurai.classList.remove(classe);
            }
        });
    };

    window.addEventListener("keydown", function (ev) {
        classes = Array.from(samurai.classList);

        switch (ev.key) {
            case "d":
                removeClasses();
                samurai.style.transform = "scaleX(4) scaleY(4)";
                samurai.classList.add("run");
                break;
            case "a":
                removeClasses();
                samurai.style.transform = "scaleX(-4) scaleY(4)";
                samurai.classList.add("run");
        }
    });

    window.addEventListener("keyup", function (ev) {
        removeClasses();
        samurai.classList.add("idle");
    });
});

I hope that when a key is released quickly, the keyup event executes.

Is this a good structure for a basic Node.js + Express + MySQL + CORS API setup? [closed]

I’m building a simple Node.js server using Express, CORS, and MySQL. I also serve static files like index.html from the public folder.

Here’s my current code:

const express = require('express');
const cors = require('cors');
const path = require('path');
const mysql = require('mysql');

const app = express();
app.use(cors());

// MySQL connection
const con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "forum"
});

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// Test route
app.get('/test-connection', (req, res) => {
  con.connect(function(err) {
    if (err) {
      res.send('Connection failed: ' + err.message);
    } else {
      res.send('Connected!');
    }
  });
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
//

I have two main questions:

Is this structure reasonable for a simple backend?

Are there best practices I'm missing (especially regarding connection handling, CORS, or static file serving)?

I appreciate any advice or suggestions for improvement!

Is possible to use VS Code Intellisense with Sequelize + JS

I’m learning sequelize + other stuff and I’m using sequelize-cli to initialize the sequelize and generate the models. When I try to use the model in other file it doesn’t suggest anything related to Sequelize models.

If I understood the problem correctly the issue relies in the dynamic initialization of the modals in the models/index.js:

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (
      file.indexOf('.') !== 0 &&
      file !== basename &&
      file.slice(-3) === '.js' &&
      file.indexOf('.test.js') === -1
    );
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

I also tried using JSDoc to “activate” the intellisense, but unfortunately didn’t work(idk if I did anything wrong, or set the sequelize/models in the wrong way). So I’d like to know if there is any way to use Sequelize + JS with the autocomplete feature or if I should choose between migrate to TS or accept that with JS I won’t have the intellisense to help me.

How do I make my input text uppercase but the placeholder not using tailwind css

I want to make my input uppercase so when the user types its uppercase but then I want the placeholder to not be uppercase so it looks nicer and is separate

I know i will still have to extract the value in javascript and .toUpperCase it with this method but that’s okay because i only have to run that once rather than every keystroke if I uppercase the onChange

I tried to do uppercase classname in tailwind but that uppercases both