How to throw an error from API and catch it from client side?

I have two different projects. First one is the outer shell of the site, basically html+js. There is a registration function where you send data in the POST array:

const registerUser = async function(e) {
 e.preventDefault();

 let email = document.querySelector('#email').value;
 let password = document.querySelector('#password').value;
 let confirmPassword = document.querySelector('#confirm_password').value;

 const formData = new FormData();
 formData.append('email', email);
 formData.append('password', password);
 formData.append('confirm_password', confirmPassword);

 try {
   await fetch(`${API}/users`, {
   method: 'POST',
   body: formData,
   }).then((response) => {
     email = '';
     password = '';
     confirmPassword = '';
     console.log(response);
   })
 }
 catch(err) {
   console.log(err);
 }
}

The second one is a simple REST API on PHP where client side sends data to. It receives the POST array and registers the user.

function registerUser($db, $postData) {
 $email = mysqli_real_escape_string($db, $postData["email"]);
 $password = mysqli_real_escape_string($db, $postData["password"]);
 $confirm_password = mysqli_real_escape_string($db, $postData["confirm_password"]);

 if(empty($postData) || !isset($email) || empty($email) || !isset($password) || empty($password) 
 || !isset($confirm_password) || empty($confirm_password)) return false;

 if($password !== $confirm_password) {
   $_SESSION["error"] = "Passwords don't match!";
   return false;
 }

 $user = mysqliQuery($db, "SELECT * FROM `users` WHERE `email` = '$email';");

 if(mysqli_num_rows($user) > 0) {
   $_SESSION["error"] = 'User with such email already exists!';
   return false;
 };

 $date = date("Y-m-d H:i:s");
 $hashPass = password_hash($password, PASSWORD_DEFAULT);
 $nameFromEmail = strstr($email, '@', true); 

 if(mysqliQuery($db, "INSERT INTO `users` (`id`, `email`, `password`, `registered_at`, `name`) 
 VALUES (NULL, '$email', '$hashPass', '$date', '$nameFromEmail');")) {
   http_response_code(201);
 }

 else {
   http_response_code(401);
 }
}

But the problem is, I don’t know how to throw an error if received email already exists in the database. Is there any way to send an error from PHP server side in response to client side after fetching?

Can I use preventDefault to my event with passive equal true?

I’ve came across to the next article, there I found example with blocking scroll event:

document.body.addEventListener('pointermove', event => {
  if (event.cancelable) {
      event.preventDefault(); // block the native scroll
      /*
      *  do what you want the application to do here
      */
  }
}, {passive: true});

but, it doesn’t work, by the way I see illogicality using preventDefault in passive: true event. What is going on, anyone would explain to me?

How to replace query parameter only if it exists using string replace All regex

I have following urls :

https://test1.com/path?query1=value1

and

https://test2.com/path

I am trying to add additional query param to all urls, so i am trying something like

url.replaceAll(/(.*)[?]?(.*)/g,"$1?newquery=newvalue&$2")

let url = "https://test1.com/path?query1=value1"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))
url = "https://test1.com/path"
console.log(url.replaceAll(/^(.*)[?]?(.*)$/g,"$1?newquery=newvalue&$2"))

But it doesnt work as expected , could someone shed some light

Connect to game server using Discord Embed

I am trying to send a message to a channel when a client executes a specific slash command.
The command should send a embed that will contain a field. I want to make that field “clickable” so that people can join.

I want them to join a steam game server (CS:GO) that uses the protocol steam://connect/ip:port/password to connect.

I tried the following to send the message:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('stackoverflow')
        .setDescription('Question to stackoverflow'),

    async execute(interaction) {
        const embed = new MessageEmbed()
            .setColor('#ff0000')
            .setTitle('test')
            .setAuthor({ 
                name: 'Test'
            })
            .setDescription('Testing')
            .addField('Click below to join the server', '[Click here](steam://node1.spirtshop.cf:6002/TestesNexus!2022)')
            .addFields(
                { name: 'u200b', value: '[Join the server](steam://node1.spirtshop.cf:6002/TestesNexus!2022)'},
                { name: 'Connect through the console', value: 'connect node1.spirtshop.cf:6002; password TestesNexus!2022'}
            )
            .setTimestamp()
            .setFooter({
                 text: 'Just testing'
            });
        await interaction.reply({embeds: });
    },
};

Unfortunately, this doesn’t work: (output) -> https://i.imgur.com/D4xCCVm.png

I’ve found some bots written in python, however, I couldn’t take that into NodeJS. In my interpretation Discord just recognizes as a “clickable link” if I send it as the protocol(?).

The expected result is something like this: https://i.imgur.com/UcERDcM.png

From that screen shot, I just want to replace the steam://…. with some text.

Any idea of how I can make this?

(using nodejs v17.4.0, discordjs v13.6.0)

Search an element in an array component of a json file using JS

I am running this code snipped in React to search if there is a match with the user’s input. The json file goes as follows:

{
  "first":{
    "name": "Michael Jordan",
    "id": "mj"
    "image": ".../icon.png",
    "tags": [
      "Sportsman",
      "Tall",
      "Famous",
      "something",
      "etc"
    ]
  },
  "second":{
    "name": "Paul White",
    "id": "pw"
    "image": ".../icon.png",
    "tags": [
      "Engineer",
      "Small",
      "Famous",
      "Another characteristic",
      "likes apples"
      "something",
      "etc2"
    ]
  }
}

and here is the search function I made to search through all the names and tags if there is a matching “person”, and afterwards display all the “people” that share the same tags or names

function main_char_search(searchProp) {
    const tagssearch = searchProp[0].tags && Object.keys(searchProp[0].tags);
    return searchProp.filter(
      (new_items) => new_items.name.toLowerCase().indexOf(q) > -1 ||
      tagssearch.some((tagsearch)=>new_items[tagsearch].toString().toLowerCase().indexOf(q)) > -1
    );
  }

the trick is that the array that contains the tags varies in size sometimes.
Here is the errors that this code generates:
TypeError cannot read properties of undefined (reading ‘tags’)
Uncaught (in … promise)

Note: the code runs perfectly if I try to search through the names and other individual components.

Preventing form submission with dynamic nested forms

I have a set up where users can add answer options to quizzes with nested forms. Each quiz has a quiz_type which I’m using together with stimulus controller to let the user have the option to either add a multiple choice or long answer question. The way I’ve set this up is that the relevant part of the form is as follows

<%= f.fields_for :quiz do |quiz_form| %>
    <%= quiz_form.text_field :problem_statement %>
    <%= quiz_form.select :quiz_type, options_for_select(Quiz.quiz_type_select, selected: quiz_form.object.quiz_type), { } %>
    <div data-dynamic-select-target="choice">
        <div data-nested-form-target="add_item"></div>
        <template data-nested-form-target="template">
            <%= quiz_form.fields_for :answer_options, AnswerOption.new, child_index: 'ANSWER_RECORD' do |answer_option_fields| %>
              <%= render 'answer_option_form', f: answer_option_fields %>
            <% end %>
        </template>
        
        <%= quiz_form.fields_for :answer_options do |answer_option_fields| %>
          <%= render 'answer_option_form', f: answer_option_fields %>
        <% end %>
    </div>
    <div data-dynamic-select-target="long">
    <%= quiz_form.fields_for :answer_options, AnswerOption.new do |answer_option| %>
      <%= answer_option.hidden_field :correct_answer, value: true %>
       <%= answer_option.text_field :answer_text %>
      <% end %>
    </div>
.
.
.
.

and the stimulus controller is as follows

import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["select", "choice", "long"];

  connect() {
    this.selected();
  }

  selected() {
    this.hideFields();
    switch (this.selectTarget.value) {
      case "single_choice":
        this.choiceTarget.classList.remove("hidden");
        break;
      case "long_answer":
        this.longTarget.classList.remove("hidden");
        break;
    }
  }

  hideFields() {
    this.choiceTarget.classList.add("hidden");
    this.longTarget.classList.add("hidden");
  }
}

now the problem is that when choosing either one of the single_choice or long_answer options the form will still submit the other one causing it to submit empty records. So for example if I choose to add the singe_choice questions I can add multiple choices from which a single one is correct, but as the form is currently structured the part

<div data-dynamic-select-target="long">
    <%= quiz_form.fields_for :answer_options, AnswerOption.new do |answer_option| %>
      <%= answer_option.hidden_field :correct_answer, value: true %>
       <%= answer_option.text_field :answer_text %>
    <% end %>
</div>

will also be submitted as it’s only hidden, but not actually removed. I also cannot just remove this since there could be a scenario where the user will switch between the quiz_types.

Any suggestions on what can I do to make this work? It would seem that I should somehow render the forms conditionally with the dynamic select choices.

Clearing canvas “layers” separately?

I’ve been battling with <canvas> for a while. I want to create an animation/game with lots of different units on different layers.

Due to <canvas> limitation to just one context my approach is as follows:

  • have one <canvas> on the page,
  • create multiple “layers” using document.createElement("canvas"),
  • animate/rerender “layers” separately.

But this approach does not seem to work properly due to one quirk – in order to stack “layers” on my main canvas I’m doing realCanvas.drawImage(layerCanvas, 0, 0);. Otherwise the layers are not being rendered.

The issue here is ultimately it does not change a thing as everything is in being drawn on my main <canvas> and when I do clearRect on one of my layers it does nothing as the pixels are also drawn on the main canvas in addition to given layer. If I run clearRect on main canvas then the layers are useless as every layer is on main canvas so I’m back to starting point as I’m clearing the whole canvas and layers are not separated at all.

Is there a way to fix it easily? I feel like I’m missing something obvious.

Here’s an example, how do I clear blue ball trail without touching background rectangles here? There should be only one blue ball under your cursor. Note it’s a very simplified example, I’ll have multiple blue balls and multiple other layers. I just want to know how the heck do I clear only one layer in canvas. Note I don’t want to use multiple <canvas> elements and don’t want to use any libs/engines as I’m trying to learn canvas by this. I know many apps use just one canvas html element, many layers and somehow animate them separately.

Source: https://jsfiddle.net/rpmf4tsb/

Enum React multiple different child components

I have following functional component without any props with different children:

<Parent>
  <ChildA />
  <ChildB />
  ...
  <ChildG />
</Parent>

Is there any way to write all children in Parent component not manually, e.g. in loop like:

<Parent>
  {childrenArray.map(child => <Child>}
</Parent>

If yes, which way is correct?

TypeScript relative path does not resolve to index file

I’m working on a project and I set up absolute path imports in my project. But, it doesn’t resolve to the index file if I put only up to the folder name.

src
 |--modules
      |--search
           |--utils.ts
           |--index.ts

When I import,
import { something } from 'modules/search/index'
it works fine.

But, I when I import like
import { something } from 'modules/search'
It says, src/modules/search.ts not found.

Following is my tsconfig.json.

{
  "compileOnSave": false,
  "compilerOptions": {
    "rootDir": ".",
    "strict": true,
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "importHelpers": true,
    "target": "es2015",
    "module": "esnext",
    "lib": ["es2017", "dom"],
    "skipLibCheck": true,
    "skipDefaultLibCheck": true,
    "baseUrl": "src",
  },
  "exclude": ["node_modules", "tmp"]
}

How can I solve this problem?

The expected behavior is,
import { something } from 'modules/search' should resolve to src/modules/search/index.ts

import { something } from 'modules/search/utils' should resolve to src/modules/search/utils.ts

How can i add indirect referral earning?

please someone should assist below is what i want to achieve For example if I refer u I will be given 1,200 immediately

If you refer someone I will be given 100 naira immediately

While you be given 1,200

const { accountUnlockedMailer } = require("../../email/mails/accountUnlocked");
const asyncHandler = require("../../helpers/asyncHandler");
const { getCouponByKey, updateCouponByKey } = require("../../helpers/coupon");
const { openToken } = require("../../helpers/jwt");
const { creditReferrer } = require("../../helpers/referral");
const { editUserById, getUserById } = require("../../helpers/user");

exports.userUnlockUpgradePost = asyncHandler(async (req, res, next) => {
    const { id } = await openToken(req.signedCookies[process.env.TOKEN_NAME]);
    
    //Get The Coupon
    const coupon = await getCouponByKey(req.body.code);

    //Check If Available
    if (!coupon) return res.json({ status: false, message: "Coupon not found" });

    //Check If Is Used
    if (coupon.coupon_status === 1) return res.json({ status: false, message: "Coupon has been used" });
    
    //Then Upgrade User
    await editUserById(id, { can_earn: 1 });

    //Used Coupon
    await updateCouponByKey(coupon.coupon_id, { coupon_status: 1, coupon_used_by:id });

    //Credit His Referrer
    await creditReferrer(id);
   
    
    
    //Response Back
    res.json({ status: true, message: "Account has been unlocked successfully" });

    //Send Mail
    const user = await getUserById(id);
    accountUnlockedMailer({
        username: user.username,
        email: user.email
    });



})

Carousel 3element Help for createeeeeeeee [closed]

bootstrap 5 min.css latest version 5.1.3 carousel 3 element
lorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsumlorem ipsum

const elementUSD = document.querySelector('[data-value="USD"]')
const elementEUR = document.querySelector('[data-value="EUR"]')
const elementRUB = document.querySelector('[data-value="RUB"]')
const rates = []

const input = document.querySelector('#input')
const result = document.querySelector('#result')
const select = document.querySelector('#select')
const select2 = document.querySelector('#select2')


const getCourses = async() => {
    const response = await fetch('https://www.cbr-xml-daily.ru/daily_json.js')
    const data = await response.json()
    const result = await  data;
    result.Valute.AMD.Nominal = 1
    result.Valute.AMD.Value = 1
    result.Valute.AMD.Previous = 1
    result.Valute.RUB = {Previous:6.17625, Value: 6.15124}
    console.log(result);

    rates.USD = result.Valute.USD
    rates.EUR = result.Valute.EUR
    rates.AMD = result.Valute.AMD
    rates.RUB = result.Valute.RUB
    rates.USD.Value*=rates.RUB.Value
    rates.EUR.Value*=rates.RUB.Value
    rates.USD.Previous*=rates.RUB.Previous
    rates.EUR.Previous*=rates.RUB.Previous
    console.log(rates);
    elementUSD.textContent=(rates.USD.Value).toFixed(2)
    elementEUR.textContent=(rates.EUR.Value).toFixed(2)
    elementRUB.textContent=rates.RUB.Value.toFixed(2)

    if(rates.USD.Value > rates.USD.Previous){
        elementUSD.classList.add('bottom')
    }else{
        elementUSD.classList.add('top')
    }
    if(rates.EUR.Value > rates.EUR.Previous){
        elementEUR.classList.add('bottom')
    }else{
        elementEUR.classList.add('top')
    }
    if(rates.RUB.Value > rates.RUB.Previous){
        elementRUB.classList.add('bottom')
    }else{
        elementRUB.classList.add('top')
    }
}
getCourses()


const convertValue = () => {
result.value = (rates.AMD.Value * input.value / rates[select2.value].Value).toFixed(2)
}

input.oninput = convertValue

select.oninput = convertValue

select2.oninput = convertValue
*{
    font-family: 'Rubik', sans-serif;
}

.MTitle{
padding-bottom: 15px;
}
.courses{
    display: flex;
    align-items: center;
    margin-bottom: 40px;
}
.CBlock{
    border: 1px solid grey;
    padding: 10px 15px 10px 15px;
    margin-left: 10px;
    margin-right: 10px;
}
.CBTitle{
padding-bottom: 20px;
}
.CBCourse{
    text-align: center;
    font-size: 24px;
}
.bottom{
    color: red;
}
.top
{
    color: green;
}

.carousel-control-next{
height: 30%;
 margin-top: 80px;
}
.carousel-control-next-icon{
margin-left:55px;
}
.carousel-control-prev-icon{
margin-right:55px;
}
.carousel-control-prev{
height: 30%;
margin-top: 80px;
margin-right: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Valute Converter</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Rubik:wght@400;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./css/style.css">
    <link rel="stylesheet" href="./css/bootstrap.min.css">
</head>
<body style="background-color: #1b1b1b;">

<div class="container-xxl">
    <div class="row justify-content-center">
        <div class="col-6 p-5">
            <div class="card p-3" style="background-color: #18191a;">
                <form>
                <h2 class="MTitle" style="color: white;">Converter Valute</h2>

                <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
                <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                <span class="sr-only">Previous</span>
                </a>
                <div class="courses ">
                    <div class="col">
                    <div class="CBlock">    
                    <div class="CBTitle" style="color:white;">Course USD</div>
                    <div class="CBCourse" data-value="USD">--.--</div>
                    </div>
                    </div>
                    <div class="col">
                    <div class="CBlock">
                    <div class="CBTitle" style="color:white;">Course EUR</div>
                    <div class="CBCourse" data-value="EUR">--.--</div>
                    </div>
                    </div>
                    <div class="col">
                    <div class="CBlock">
                    <div class="CBTitle" style="color:white;">Course RUB</div>
                    <div class="CBCourse" data-value="RUB">--.--</div>
                    </div>
                    </div>
                </div>
                <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
                <span class="carousel-control-next-icon" aria-hidden="true"></span>
                <span class="sr-only">Next</span>
                </a>
                <div class="row mb-1">
                    <div class="col"><label style="color: white;" for="name">From:</label>
                    <select disabled class="form-control" id="select">
                        <option value="AMD" selected>AMD - Դրամ</option>
                    </select>
                    </div>
                    <div class="col"><label style="color: white;" for="name">To:</label>
                    <select style="cursor:pointer;" class="form-control" id="select2">
                        <option value="EUR">EUR - Եվրո</option>
                        <option value="USD">USD - Դոլլար</option>
                        <option value="RUB">RUB - Ռուբլի</option>
                    </select>
                    </div>
                </div>
                <div class="row">
                    <div class="col"><input type="number" id="input" class="form-control"></div>
                    <div class="col"><input type="number" class="form-control" id="result" disabled></div>
                </div>
                </form>
        </div>
            </div>


    </div>
    <h5 style="margin-left:60%;color: white;">Directed by: Me</h5>
</div>    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    <script src="./js/app.js">

    </script>
</body>
</html>

WebGL2 Instanced Drawing indexed

how can I order matrices for texture atlas by using Instanced Drawing in the 2D games?

https://webgl2fundamentals.org/webgl/lessons/webgl-instanced-drawing.html

#version 300 es

uniform mat4 u_projection;
uniform mat4 u_camera;

in mat4 u_matrix;//<--Instanced Drawing
in mat3 u_atlas;//<-- need to index 

out vec2 v_texcoord;
    
const float xp[6] = float[](0.0, 0.0, 1.0, 1.0, 1.0, 0.0);
const float yp[6] = float[](0.0, 1.0, 0.0, 1.0, 0.0, 1.0);

void main() {
    float x = xp[gl_VertexID];
    float y = yp[gl_VertexID];

    gl_Position = u_projection * -u_camera * u_matrix * vec4(x,y,1,1);
    v_texcoord = vec3(u_atlas * vec3(x,y,1)).xy;
}

Forgive me for my bad English

Syncing Two Google Drive Accounts Using Google Scripts

I have two Google Drive accounts that I would like them to be synced automatically using Google Scripts.

I need the script to do the following:

I need the whole folder and files (in the source Google Drive account) to be synced to the destination Google Drive account once there are any changes (new/modified/deleted files/folders).

It should notify me by email once there is an action made.

Please help me figure how to start doing this script as I had this script collected from others that I found in this forum:

function copyfile() {
  var sourceFolderName = "root";
  var destinationFolderName = "Folder 2 ID";
  var source_folder = DriveApp.getFoldersByName(sourceFolderName).next();
  var files = source_folder.getFiles();
  var dest_folder = DriveApp.getFoldersByName(destinationFolderName).next();

  var destination_files = [];
  var fileIterator = dest_folder.getFiles()
  while (fileIterator.hasNext())
    destination_files.push(fileIterator.next().getName());

  while (files.hasNext()) {
    var srcFile = files.next();
    var newName = srcFile.getName();
    if (destination_files.indexOf(newName) == -1) {
      srcFile.makeCopy(dest_folder);
    }
  }
}

How to add a 3rd party Jquery Library in React Functionnal component?

I want to use a 3rd library only for my homepage in a React application. The problem is : the library is developed with Jquery : www.npmjs.com/package/fullview

I need to import : Jquery, js file and css file.

so far, I haven’t found any way to import this type of library into a functionnal component. Only class components.

Can I import these files directly in index.html with or i need to import them in my component with import … from “…”

Thank you !