Dinamically populate Prisma Client CREATE query fields in explicite Many To Many relation

Assume I have a Recipe Model, an Ingredient Model, and a many to many mapped as:

model IngredientOnRecipes {
  recipe       Recipe     @relation(fields: [recipeId], references: [id], onDelete: Cascade)
  recipeId     String
  ingredient   Ingredient @relation(fields: [ingredientId], references: [id],onDelete: SetNull)
  ingredientId String
  textDescriptor String
  @@id([recipeId,ingredientId])
}

Now I need to populate a Recipe with many Ingredients reference, the second create example in the doc manually populate the 2 category (in my case the Ingredients) in the “create:[]” fields. I have many so I use the map function to create an object in the same form:

const test =  ingredients.map(
    (ing: { textDescriptor: any; id: any }) =>({
      textDescriptor: ing.textDescriptor,
      ingredient: {
        connect: {
          id: ing.id,
        },
      },
    })
  )
  console.log(test)

prints->

[
  { textDescriptor: '2g', ingredient: { connect: [Object] } },
  { textDescriptor: '5g', ingredient: { connect: [Object] } }
]

Now when i pass this test object in my data as:

const temp = {
        data: {
          ...
          ingredients: {
            create: test
          },
          category: recipeBody.category,
        },
      };

      const recipe = await prismaSharedCLient.recipe.create(temp);

a numeric index of each member is added to the list and I got this error

Invalid `prisma.recipe.create()` invocation:

{
  data: {
    ...
    ingredients: {
      create: {
        '0': {
          textDescriptor: '2g',
          ~~~~~~~~~~~~~~
          ingredient: {
          ~~~~~~~~~~
            connect: {
              id: '13'
            }
          },
+         id: String,
+         name: String,
?         IngredientOnRecipes?: {
?           create?: IngredientOnRecipesCreateWithoutIngredientInput | IngredientOnRecipesCreateWithoutIngredientInput | IngredientOnRecipesUncheckedCreateWithoutIngredientInput | IngredientOnRecipesUncheckedCreateWithoutIngredientInput,
?           connectOrCreate?: IngredientOnRecipesCreateOrConnectWithoutIngredientInput 
| IngredientOnRecipesCreateOrConnectWithoutIngredientInput,
?           createMany?: IngredientOnRecipesCreateManyIngredientInputEnvelope,
?           connect?: IngredientOnRecipesWhereUniqueInput | IngredientOnRecipesWhereUniqueInput
?         }
        },
        '1': {
          textDescriptor: '5g',
...
...
Unknown arg `textDescriptor` in data.ingredients.create.0.textDescriptor for type IngredientCreateWithoutRecipesInput.

What am I doing wrong?

how to return new array by using array.reduce

I want to return new array by using reduce. For example,

const product = [
  { color: 'orange', type: 'hat', count: 1 },
  { color: 'orange', type: 'hat', count: 1 },
  { color: 'orange', type: 'shoes', count: 1 },
  { color: 'blue', type: 'food', count: 1 },
];

the product list need to like below because there are two ‘hat’ therefore, the count should be 2 and one { color: ‘orange’, type: ‘hat’, count: 1 } should be removed.

const result = product.reduce((acc, curr) => {
// I want to make new array like
// const product = [
//  { color: 'orange', type: 'hat', count: 2 },
//  { color: 'orange', type: 'shoes', count: 1 },
//  { color: 'blue', type: 'food', count: 1 },
//];
 return acc
}

thank you!

how can i change a nested object ‘property value’ in React?

I want when the user start typing inside a input field age from and to property value to get update so i can send the information to the backend.

my onBlur eventhandler dosen’t work i get a undefiend: 43(user typed num for exam) property outside of age object on my state;

code

  const [advancedSearch, setAdvancedSearch] = useState({
    selectIdentify: "",
    type: "",
    gender: "",
    age: { from: "", to: "" },
  });

==========================
                   <TextField
                    label="Age From"
                    type="number"
                   onBlur={(e) =>
                      setAdvancedSearch((data) => ({
                        ...data,
                        ["age"["from"]]: e.target.value,
                      }))
                    }
                  />
                  <TextField
                    label="Age To"
                    type="number"
                   onBlur={(e) =>
                      setAdvancedSearch((data) => ({
                        ...data,
                        ["age"["to"]]: e.target.value,
                      }))
                    }
                  />

How to load google maps api using nextjs?

How do you load and use the google maps api using Nextjs?

1 – How do you load the api? I’ve tried to load it in _document.js:

import { Html, Head, Main, NextScript } from 'next/document'
import Script from 'next/script'

const source = `https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}&libraries=places`

const Document = () => {
  return (
    <Html>
      <Head>
        <Script type="text/javascript" src={source} strategy="beforeInteractive" />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

export default Document

2 – How do you reference the API?

Something like: ? window.google.maps.places.AutocompleteService().getPlacePredictions()

But I get an error that google is undefined

I have also tried using npm libraries but none seem to work.
react-places-autocomplete
use-places-autocomplete

How can i fix to make Axios post working in React?

I have a code to do login task:

                onSubmit() {
                    this.$q.loading.show();
                    this.$axios.post("http://localhost/adminision/api/usermanager/login.php", 
                    {
                        language: "vi",
                        instituteid: this.$store.state.mainState.istituto,
                        username: this.username,
                        password: this.passwd
                    }).then((t => {
                        1 == t.data.success ? (this.$store.commit("mainState/setLoginData", t.data.token), this.$store.commit("mainState/setFirstName", t.data.firstName), this.$store.commit("mainState/setLastName", t.data.lastName), this.$store.commit("mainState/setMatrixID", "login"), this.$q.sessionStorage.set("token", t.data.token), this.$router.push({
                            path: "/dashboard"
                        })) : (this.$q.loading.hide(), this.validatormessage = "Username or password not valid", this.mostraerrori = !0)
                    })).catch((t => {
                        this.validatormessage = t.response.data.error.description, this.mostraerrori = !0
                    }))
                },

But when i click submit button, this.$axios.post runs, but nothing happens. No login.php appear in Network tab of Chrome browser, with no js error. I’ve set breakpoint in catch body but it is unreachable.
So, please help, what can i do ?

What to do if the user has a reply ban (TELEGRAM BOT NODE JS)

a question about telegram bots (I have a feedback bot, its meaning is that the user writes to the bot and the message gets into the group and someone from the group can reply to the user i.e. admins everyone who is in the group), and the problem is that many users have a ban on forwarding messages, and therefore the SMS does not reach the user. when reply, there are no necessary user fields (for example, id, and there is only the forward_sender_name field), I need to somehow get around this moment, I get the user id only if the user writes to the group (I use the Telegraf library in the code) (I attach several attachments of answers )
message from user
reply from group

let isAdmin = userId => {
    return userId === admin;
};
let forwardToAdmin = ctx => {
    if (isAdmin(ctx.message.from.id)) {
        ctx.reply(replyText.replyWrong);
    } else {
        if (ctx.chat.id === admin) {
            return '';
        }
        ctx.forwardMessage(admin, ctx.from.id, ctx.message.id);
    }
};

function addMessageListeners () {
    bot.start(ctx => {
        ctx.reply(isAdmin(ctx.message.from.id) ? replyText.helloAdmin : replyText.helloUser);
    });
    bot.on('message', ctx => {
        if (ctx.message.reply_to_message && ctx.message.reply_to_message.forward_from) {
            ctx.telegram.sendCopy(ctx.message.reply_to_message.forward_from.id, ctx.message);
        } else {
            forwardToAdmin(ctx);
        }
    });
}

Add an multiple Element each Button clicked and remove element from the list of button

I have a 5 button click and each button will add each element. my concern is when I click back to previous button I click. I need a previous element only will be add and other will be remove..
example:
if click 5. it shows 5 add(element)
if then I click back to click3 it show only 3 element and remove element[5] and element[4].

      let clickItem;
            for (let c = 1; c < 6; c++){
                clickItem = document.getElementsByClassName('click-item-'+c);
                $(clickItem).on('click', function(){
                    $('.child-item').not(this).removeClass('active');
                    $(this).addClass('active')
                    $(".add-item").slice(0, c).removeClass("inactive");
                })
            }
<style>
.active{
 display:block;
background-color:blue;
}
.inactive{
 display:none;
}
</style>
<button class="child-item click-item-1">Click 1</button>
<button class="child-item click-item-2">Click 2</button>
<button class="child-item click-item-3">Click 3</button>
<button class="child-item click-item-4">Click 4</button>
<button class="child-item click-item-5">Click 5</button>

<div class="add-item inactive">Add 1</div>
<div class="add-item inactive">Add 2</div>
<div class="add-item inactive">Add 3</div>
<div class="add-item inactive">Add 4</div>
<div class="add-item inactive">Add 5</div>


<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

Hover over one element and select all elements with the same class

it is my first JavaScript project in school and I have no idea how to get a working solution.
Please see my HTML code. There is a green map and when hovering over it, it should change the color to yellow. The problem is, that there are separate SVG graphics (island), that not change their color.

    Is there a JavaScript solution, that all SVG paths change their color, when mouse is over only one SVG path?
    
    I would be so happy and thanful to get some help. 
    
    <pre>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Map</title>
    
        <style>
            .cls-4 {
            fill: #7ec353;
            stroke: #020202;
            stroke-width: 4px;
            transition: 0.3s;
        }
        
        .cls-4:hover {
            fill: #d1b308; 
        }
        </style>
    
    </head>
    <body>
        
        <div class="map">
    
            <svg id="Terrain" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 4280.57 5494.61">
        
                <g id="0-250m">
                    
                    <path class="cls-4"
                    d="M1237.03,239.22c4.1-5.74,1.62-16.81,0-26.24-1.64-9.41-2.05-6.54-8.6-8.6-6.57-2.05-11.08,.41-25.81,0-14.77-.41-32.79-4.52-34.86-4.9-2.03-.43-1.62,4.9-4.51,8.59-2.87,3.69-4.9,4.91-4.9,14.34s2.87,10.24,9.01,14.35c6.14,4.1,15.16,11.06,28.27,12.29,13.11,1.23,20.09,0,30.32,0s6.96-4.08,11.07-9.83Z" />
                <path class="cls-4"
                    d="M1142.37,233.9c-4.08-4.11-5.74-4.91-9.83,0-4.08,4.92-11.88,21.71-12.28,26.64-.43,4.9-2.06,15.96,2.24,21.3,4.3,5.32,6.76,12.7,11.69,15.57,4.92,2.87,4.92,9.43,11.05,0,6.16-9.44,7.39-6.57,2.87-13.11-4.51-6.57-13.5-10.67-12.91-16.4,.63-5.73-1.43-16.81,1.86-21.3,3.26-4.49,9.41-8.59,5.31-12.7Z" />
                <path class="cls-4"
                    d="M1239.27,361.34c1.45,6.54,1.4,11.49,5.11,15.16,3.73,3.69,16.83,12.27,20.93,7.79,4.11-4.51,10.24-15.57,9.85-20.48-.41-4.92,5.73-9.44,7.77-13.93,2.06-4.52,.84-9.03-5.31-8.61-6.16,.39-11.42,0-16.16,2.45-4.74,2.47-23.62,11.06-22.17,17.63Z" />
                <path class="cls-4"
                    d="M1255.47,332.24c3.7-2.87,6.78-.8,6.04-4.3-.7-3.47-1.21-8.4-6.51-8.81-5.26-.39-4.38-1.42-5.26-.39-2.43,2.74,2.05,16.37,5.73,13.5Z" />
                <path class="cls-4"
                    d="M1301.37,281.85c4.93-5.34,8.61-9.03,2.87-13.12-5.75-4.08-6.27,.43-7.62,0-1.39-.41-13.27,10.67-8.76,15.58,4.51,4.92,8.61,2.87,13.52-2.46Z" />
                <path class="cls-4"
                    d="M1177.6,316.67c-3.67-.82-4.08-2.46-5.73,0-1.62,2.46-5.72,23.35,2.06,22.53,7.79-.8,10.24-2.38,7.79-8.37-2.46-5.97-.39-13.35-4.11-14.16Z" />
                <path class="cls-4"
                    d="M1223.51,341.22c6.54-.38,7.37-3.39,6.54-8.63-.8-5.27-1.23-8.54-6.96-8.96-5.74-.39-11.06,0-13.93,0s7.82,17.99,14.36,17.6Z" />
                <path class="cls-4"
                    d="M1175.98,351.51c-3.69,1.62-2.46,22.12,2.05,23.34,4.51,1.23,11.47,3.7,10.26-3.67-1.23-7.37,0-12.29-3.72-16.4-3.67-4.1-4.9-4.9-8.59-3.26Z" />
                <path class="cls-4"
                    d="M1198.81,418.28c-3.99-5.32-6.55-7.36-10.39-13.09-3.86-5.75-9.58-8.21-12.45-8.62-2.87-.41-2.05-4.08-2.87-.41-.82,3.69,1.23,20.48,4.91,24.17s7.39,7.8,12.27,7.39c4.95-.43,12.5-4.1,8.51-9.44Z" />
                <path class="cls-4"
                    d="M1281.7,396.89c-.43,2.14,8.18,8.3,11.47,5.01,3.28-3.29,.08-12.7-4.68-12.29-4.74,.41-6.38,5.14-6.79,7.28Z" />
                <path class="cls-4"
                    d="M1265.32,684.23c3.28-10.26,6.13-14.75,1.64-18.86-4.51-4.1-6.98-6.14-10.67-4.9-3.69,1.23-7.79,24.98-.41,28.27,7.38,3.28,6.16,5.73,9.44-4.51Z" />
                <path class="cls-4"
                    d="M3026.95,335.07c3.15-11.8,7.07-11,7.07-22.79s-.8-12.32,0-21.07c.77-8.76,1.58-7.2,5.48-15.84,3.92-8.63,4.73-13.34,0-18.83-4.71-5.5-2.13-14.13,3.26-12.57,5.39,1.57,10.89,.77,5.39-8.64-5.52-9.41-1.96-11.77-11.58-3.92-9.63,7.85-9.63,3.14-9.63,7.85s-4.71,32.99-3.15,41.61c1.58,8.62,1.72,26.69-.3,35.33-2.04,8.63,.3,30.63,3.45,18.86Z" />
                <path class="cls-4"
                    d="M1147.69,745.43c5.58,5.59,11.16,5.59,17.43,3.48,6.29-2.08,14.66,.6,8.37-6.34-6.27-6.9,4.19-6.21-6.27-6.9-10.46-.68-25.1,4.17-19.52,9.75Z" />
                <path class="cls-4"
                    d="M1138.63,827.73c10.46-2.1,16.04-.35,16.04-6.45s-3.17-11-8.21-12.4c-5.04-1.39-18.29,20.93-7.83,18.85Z" />

        
        </div>
    
    </body>
    </html>
    </pre>

Send keypresses through Nodejs to another program

I am using a custom app running on a Windows machine which is used for recording and showing SQL data to user but it has terrible UI so I wrote my own Nodejs Electron app to do same purpose.

However, I can’t close the custom app and run only my Electron app because the custom app creates and inserts data to SQL and requires password by key entry for every 10 minutes to continue recording data.

When you open the custom app and type password anywhere of the program, there is no special window or input field for it. Program start creating and inserting data. After 10 minutes it doesn’t matter you are focus or not focused to the app, app stops and want you to type password again to continue.

So I want to stay always in my Electron app, while the custom app is running background. Every 10 minutes Electron app should send password 1234 keypress to the custom app to keep session alive in the custom app.

If there is a way to do that with Nodejs, it would be perfect for me but If not I am okay to try different solutions.

I am also okay to hang notepad.exe and send keypress via another program to understand principles.

Thanks.

How to pass value in Function to another Function with JS?

https://codepen.io/dogukanhanifi/pen/zYRMvva

i selected color. But I can’t pull this value from the function.
I used “return” it doesn’t work.

var btn = document.querySelector('#btn');
var fontColor = document.querySelector('#color')
var paragraf = document.querySelector('p');


fontColor.addEventListener('change', colors)
function colors(e) {
    var color = e.target.value;
    console.log(color)

    return color
}

btn.addEventListener('click', myFunction);

function myFunction() {
    var renk = colors();

    console.log(renk)
    /* paragraf.style.color = `${colors()}`; */
}
     <form>
        <input type="color" name="" id="color">
        <input type="button" value="Onayla" id="btn">
    </form>
<div>
        <h1>Js Css </h1>
        <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Recusandae laboriosam voluptatibus, quos quae nesciunt blanditiis. Minus magni quod quos rem quidem sed ipsum cum molestias necessitatibus. Provident tempore quisquam molestias error perspiciatis alias impedit qui!</p>
    </div>

enter image description here

Ajax FormData return null

I created a form. I am sending the data in this form as JSON.

If I just submit the formData (I also change the controller to [FromBody] Image request) and set the contentType and processData to false, the formData is not null.

I think “document” returns null because I am sending the data as JSON. How can I solve this issue I’m stuck in this issue.

Ajax Request

   let myProfile = {
        id: 0,
        title: "",
        text: "",
        document: File,
    };
    
        myProfile.title = "Lorem ipsum"; 
        myProfile.text = "Lorem ipsum"; 

        var formData = new FormData();
        formData.append('file', $('#file').get(0).files[0]);
        formData.append('fileName', $("#fileName").val());

        var myFile = formData.get('file');
        myProfile.document = myFile;

    $.ajax({
       url: `/admin/myprofile`,
       type: "POST",
       data: JSON.stringify(myProfile),
       contentType: "application/json",
       dataType: 'json',
       success: ....

Cshtml

    <div class="form-group">
        <input type="file" name="document" asp-for="document" id="file" />
    </div>

Controller

    [HttpPost("myprofile")]
    public IActionResult MyProfile([FromBody] MyProfileDTO request)
    {
        return ...
    }

Class

    public class Image
    {
      public IFormFile file { get; set; }
      public string fileName { get; set; }
    }

    public class MyProfileDTO 
    {
        public string Title { get; set; }
        public string Text { get; set; }
        public Image Document{ get; set; }
    }

How to draw a chart with highcharts.js once I retrieved all the data from firebase database?

I get data from my Firebase database every ten seconds. I want to plot a graph with highcharts.js, but when I access the web page, I get all the data prior to the moment the page is loaded. At this point, my web page freezes and crashes after a few minutes while the data is being recovered. (I also have a second piece of code that retrieves the new data each time it is added to the database but the web page crashes before).

I think it’s my plotvalue function that is crashing the page. When I suppress plotValue(…) I can read my data in a few seconds even if there’s 15k+. Indeed, it may be because i’m redrawing the chart each time I receive a data instead of waiting to retrieve it all.

I would like to know how to draw the chart once all of my data is retrieved from my database.

I thank you in advance for your answers.

Here is the code:

setInterval(test, 10000);
function test() {
 if (it === 0) {
  console.log("it=", it);
  dbRef.orderByKey().once('value', snapshot => { //"value" to have all existing data
    var jsonData = snapshot.toJSON();
    //console.log(jsonData); // Test purpose
    var coco = Object.values(jsonData); //Extract the numerical values of the object
    // Save values on variables
    //console.log(Défaut_communication_automate); //Test purpose
    coco.forEach(elt => { //Choose in coco for each element 
            var Puissance_batterie = elt.Puissance_batterie; //Choose all the values 
           of the element named "Puissance_batterie"
            var Puissance_AC_Onduleurs = elt.Puissance_AC_Onduleurs;
            var Tension_réseau = elt.Tension_réseau;
            var timestamp = elt.timestamp;
            //console.log(Puissance_batterie);
            plotValues(chartALM, timestamp, Puissance_batterie, 0);
            plotValues(chartALM, timestamp, Puissance_AC_Onduleurs, 1);
            plotValues(chartALM, timestamp, Tension_réseau, 2);
        })
        ++it;
    console.log("it=", it);
})
}
//function to plot values on charts
function plotValues(chart, timestamp, value, series) {
  var x = epochToJsDate(timestamp).getTime();
  var y = Number(value);
  chart.series[series].addPoint([x, y], false, false);
  chart.redraw();
}

 // Create the charts when the web page loads
 window.addEventListener('load', onload);

 function onload(event) {
   chartALM = createALMChart();
   barALM = createALMBar();
 }

 // Create Chart
 function createALMChart() {

  var chart = new Highcharts.Chart({
   chart: {
      renderTo: 'chart-ALM',
      type: 'spline'
   }
   //The following is only about the visual aspect
  }

How do I change the background of an image using javascript, htms and css?

I have been trying to write a program that removes an image’s original background and allows the user to add different colour backgrounds. I’m able to accomplish the first part by using the removebg API. But I’m unable to add background to the image. All I can find online is how to add a background to a div element or a form element. Please help.
This is the code until now:

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = 'ctive.png';
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
        method: 'post',
        url: 'https://api.remove.bg/v1.0/removebg',
        data: formData,
        responseType: 'arraybuffer',
        headers: {
            ...formData.getHeaders(),
            'X-Api-Key': 'YUCKwSujDYGm2z1FpVHgxxo8',
        },
        encoding: null
    })
    .then((response) => {
        if (response.status != 200) return console.error('Error:', response.status, response.statusText);
        fs.writeFileSync("no-bg-pingu.png", response.data);
    })
    .catch((error) => {
        return console.error('Request failed:', error);
    });

How do i download a file using AJAX in javascript?

I need to download a file from a different server (from Documentum) through a VBCS application. If i put the URL of the document into postman and provide basic authentication and then click on send and download, I am able to download the document but when i try to do it through AJAX and javascript, the document does not get downloaded but i can see the contents of the document in the response of my GET call. Following is the code that i have written –

     var xhrdoc = new XMLHttpRequest();
     xhrdoc.open("GET", docURL1);
 


     xhrdoc.setRequestHeader("Accept", "*/*");
    // xhrdoc.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     xhrdoc.setRequestHeader("Content-Type","application/octet-stream");
     xhrdoc.setRequestHeader("Content-Disposition", "attachment");
     xhrdoc.setRequestHeader("Authorization","Basic "+btoa(username+":"+password));
     console.log("Log:docURL",xhrdoc.status);
    
 // window.location.href = docURL1;

     xhrdoc.send();

    

    xhrdoc.onload = function () {
  console.log("inside onload for get doc");
   console.log("Log: inside getdoc",xhrdoc.status, "Status");
  console.log("Log: inside getdoc",xhrdoc.responseURL,"ResponseURL");
  console.log("Log inside get doc response text",xhrdoc.responseText);
  console.log("log inside response ", xhrdoc.response);

Any help will be really appreciated. Thank you!