I can’t change the text of an element using textContent on Reddit

I need to highlight the text in the comment form and change the highlighted part to another word

But reddit won’t let me change the comment form in any way, the text just doesn’t change, I don’t know what to do anymore

I’m making a plugin for chrome and this functionality will be in my plugin.

I also tried to change the text in the form via the console, nothing works either

enter image description here

Polymorphic associations when you are not sure what the Datatype will be?

I am setting up a database for a CRM project. I’m trying to set-up polymorphic one-to-many associations with mySQL and Sequelize, following this tutorial, where the example is a Comment that can belong to an Image or a Video.

I have Reunions, Clients, Projects, Tasks, and possibly later other elements, where I want the user to be able to leave a Note, a Link, or a Document. I debated putting the Notes/Link/Document into one table but I think it might make it very chaotic and take a long time to filter?

The problem is our Clients and Projects have UUIDs for primary keys, but Tasks and Reunions have integers. From what I gather it’s not possible to have a column that accepts two types of Datatypes, so I’m thinking my options are:
– Change everything to have UUIDs
– Give an int ID number to the Clients and Projects
– Scratch everything because I am thinking about it wrong
– …???

Could you just point me in the right direction of what would be good practice in this case?

I am junior developer working with another junior on a huge project so we’re only slightly overwhelmed, ya kno

This is the first time I do something like this, so I am pretty sure I am missing a lot of elements moving forward.

Duplicating dialog box on the same html page won’t work

hope you’re all having a wonderful day.

code on codepen

<dialog></dialog><button></button>
<dialog></dialog><button></button>

I have this code set with its css and javascript to show a dialog by clicking a button to select the site’s language.

When I duplicate this dialog to the site’s footer it doesnt work anymore and when clicking the dialog on the footer it does nothing but the first dialog still works.

I tried adding ids for the javascript code but I didn’t get anything working.

validate and transform a field value using ajv in nodejs

I want to validate and change field json_data.childOrder.Order.triggerPrice using ajv. But my customKeyword function is never called.

I want to update it to 10% of json_data.ltp

I tried to read the documentation but its not very clear how to do this. And moany examples on stackoverflow are referring to old version of ajv library.

const Ajv = require('ajv')
const ajv = new Ajv({ coerceTypes: true }) // options can be passed, e.g. {allErrors: true}

const OrderSchema = {
    type: 'object',
    properties: {
        childOrder: {
            type: 'object',
            additionalProperties: true,
            properties: {
                Order: {
                    type: 'object',

                    additionalProperties: true,

                    properties: {
                        qty: {
                            type: 'string'
                        },
                        triggerPrice: {
                            type: 'number'
                        }

                    },
                    required: ['triggerPrice', 'qty']

                }

            }
        }

    },
    additionalProperties: true

}

json_data = {
    childOrder: {
        Order: {
            buy: 'true',
            orderType: '3',
            price: 3999,
            qty: '10',
            triggerPrice: 3400
        }
    },
    duration: 'DAY',
    ltp: 3435,
    orderType: '3',
    price: 0,
    product: 'wood',
    qty: '10',
}

ajv.addKeyword({
    keyword: 'triggerPrice',
    type: 'number',
    compile: (a, b) => {
        // logic to transaform trigger price
        console.log(a, b)
    }
})
const validateOrder = ajv.compile(OrderSchema)

const _validate = validateOrder(json_data)

are there any other alternate ways of doing validatin in nodejs like there are in python marshmallow and django DRF.

Mongo DB is failing to fetch data from the request in Next js

I have a POST request in my Nextjs app, file path is app/api/gigs/new. The request is supposed to check for data in the request body, take that data and add it to the mongo db schema, then save it to the database. When I try sending the request via thunderclient(a tool like postman), I get the following error:

Data has not been saved successfully: ValidationError: GigTitle: Path GigTitle is required., GigDesc: Path GigDesc is required., BasicPrice: Path BasicPrice is required., StandardPrice: Path StandardPrice is required., BasicFeatures: Path BasicFeatures is required., StandardFeatures: Path StandardFeatures is required.“.

The kind of payload that I am sending through thunder client is like this:
{
“gigtitle”: “Gigger”,
“gigdesc”: “Desc”,
“basicprice”: “20”,
“basicfeatures”: “Unlimited revisions”,
“stdprice”: “50”,
“stdfeatures”: “three revisions”
}

        Here is my route.js file through which I am trying to send the request:
        import { connectToDB } from "../../../../lib/mongo.js";
        import Gig from "../../../../lib/models/Gigs.model.js";

        export const POST = async (req) => {
        try {
            await connectToDB();

            const {
            gigtitle,
            gigdesc,
            basicprice,
            basicfeatures,
            stdprice,
            stdfeatures,
            } = req.body;

            const gig = await new Gig({
            GigTitle: gigtitle,
            GigDesc: gigdesc,
            // GigTags: tags,
            BasicPrice: basicprice,
            BasicFeatures: basicfeatures,
            StandardPrice: stdprice,
            StandardFeatures: stdfeatures,
            });

            await gig.save();
            return new Response("Data saved successfully", { status: 200 });
        } catch (error) {
            console.log(error);
            return new Response(`Data has not been saved successfully: ${error}`, {
            status: 500,
            });
        }
        };


    Here is the mongo db schema: 
    import mongoose from "mongoose";

    const GigSchema = new mongoose.Schema(
      {
        GigTitle: {
          type: String,
          required: true,
        },
        GigDesc: {
          type: String,
          required: true,
        },
        GigTags: {
          type: Array,
        },
        BasicPrice: {
          type: Number,
          required: true,
        },
        StandardPrice: {
          type: Number,
          required: true,
        },
        BasicFeatures: {
            type: String,
            required: true
        },
        StandardFeatures: {
            type: String,
            required: true
        },
        Sales: {
            type: Number,
            default: 1
        }
      },
      { timestamps: true }
    );

    const Gig = mongoose.models.Gig || mongoose.model("Gig", GigSchema);
    export default Gig;

What am i doing wrong here? Please someone advice.

Error 500 when I called webservice with AJAX

I have web service solution in Visual Studio with one parameter :

Public Function CheckPalletInLocation(location As String) As String

       Dim ScaleConnnection As New SqlClient.SqlConnection("MYCONNEXION")
       Dim ScaleCommand As New SqlClient.SqlCommand
       ScaleCommand.Connection = ScaleConnnection
       ScaleConnnection.Open()
       ScaleCommand.CommandText = "SELECT DISTINCT LOGISTICS_UNIT FROM LOCATION_INVENTORY WHERE LOCATION = '" &
       location & "'"
       Return ScaleCommand.ExecuteScalar()
       ScaleConnnection.Close()

       'Return "True"
   End Function

When I launch solution, webservice works. It return value.
Now I want to call it in HTML page with ajax code :

<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
        <title>TEST WEB SERVICE</title>
        <script type="text/javascript" src="jquery-3.4.1.js"></script>
</HEAD>

    <BODY onload="Click_BB();">PAGE
    <script>

    function Click_BB()
    {
        $.ajax({
          type: 'post',
          url: 'https://localhost:44341/WebService1.asmx?op=CheckPalletInLocation',
          contentType: "application/xml",
          data: { location: '110-01-03-10' },
          success: function (d) 
              {
                alert(d);
              },
          failure: function (response) 
              {
                debugger;
                alert(response.d);
              }
        });
    }
    
    </script>
    </BODY>
</HTML>

I always have this error in the response page :

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="fr">System.Web.Services.Protocols.SoapException: Le serveur n'a pas pu traiter la demande. ---> System.Xml.XmlException: Données non valides au niveau racine. Ligne 1, position 1.

I transale : server cannot process. Invalid data root, line 1 position 1

Can someone help please ?

Thanks

I tried to change AJAX code, I would like to have the result of my web service in HTML page. Until now I have error 500

Is it possible to automatically get the main color of an element in css / javascript? [duplicate]

Can css or javascript pick automatically the main color of an image for example? like on spotify where the website /app automatically adapts to whatever is the color of the artwork of an album

As for now i’m using a var that I set individually in each html pages:

    <style>:root {
  --primary-color: #9dff00;</style>

and indeed then in my css:

    color: var(--primary-color);

Javascript loop goes too fast and does not change the api call [closed]

I am executing in the google chrome console the following script:

source code
the button click suppose to call an API, but in the API call, I see alwazs the some ID, insted of getting the other two:

Google chrome network result

I did similar code with a foreach, this time I am using a promise with timeout.
Not sure what to do to resolve this, looks like the foreach goes too fast before the changes are applied to the html and the click even is triggered 3 times with the first ID of the array and it suppose to to have 3 different calls.

Any suggestion?

Node Hapi.js bulk update to mariaDB

I’m looking for a way to do a bulk update on my MariaDB. I use the Node.js mariaDB plugin and HAPI.js with Handlebars. I’m very new at javascript but got already a far way on my little project to do some research on working dogs (Belgium Malinois). It’s for myself to learn working with Javascript, Node and MariaDB.

My issue:
I have a webpage with multiple parameters to edit through a form.

The database: aped_db.parameters

TABLE `parameters` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_general_ci',
    `description` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_general_ci',
    `opt0` VARCHAR(50) NOT NULL DEFAULT 'Unknown' COLLATE 'utf8mb4_general_ci',
    `opt1` VARCHAR(50) NOT NULL DEFAULT 'Very bad' COLLATE 'utf8mb4_general_ci',
    `opt2` VARCHAR(50) NOT NULL DEFAULT 'Bad' COLLATE 'utf8mb4_general_ci',
    `opt3` VARCHAR(50) NOT NULL DEFAULT 'Ok' COLLATE 'utf8mb4_general_ci',
    `opt4` VARCHAR(50) NOT NULL DEFAULT 'Good' COLLATE 'utf8mb4_general_ci',
    `opt5` VARCHAR(50) NOT NULL DEFAULT 'Very good' COLLATE 'utf8mb4_general_ci',
    `multiplier` FLOAT NULL DEFAULT '1',
    PRIMARY KEY (`id`) USING BTREE,
    UNIQUE INDEX `name` (`name`) USING BTREE
)

The HTML code in short

{{#each parlist}}
    <input type="hidden" name="id" value="{{this.id}}" form="form-edit">
    <td style="text-align:center;">{{this.id}}</td>
    <td><input type="text" name="name" value="{{this.name}}" form="form-edit"></td>
    <td><input type="text" name="description" value="{{this.description}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt0}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt1}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt2}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt3}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt4}}" form="form-edit"></td>
    <td><input type="text" name="opt0" value="{{this.opt5}}" form="form-edit"></td>
    <td><input type="text" name="multiplier" value="{{this.multiplier}}" form="form-edit"></td>
{{/each}}

The received payload to process into the table parameters:

req.payload = {
   id: [ '1', '3', '' ],
   name: [ 'Social', 'Work ethic', 'Dominance' ],
   description: [ 'Desc 1', 'Desc 2', 'Desc 3'],
   opt0: [ 'Unknown', 'Unknown', 'Unknown' ],
   opt1: [ 'Very bad', 'Very bad', 'Very bad' ],
   opt2: [ 'Bad', 'Bad', 'Bad' ],
   opt3: [ 'Ok', 'Ok', 'Ok' ],
   opt4: [ 'Good', 'Good', 'Good' ],
   opt5: [ 'Very good', 'Very good', 'Very good' ],
   multiplier: [ '1', '1', '1' ]
}

In the above payload 2 parameters are existing ones, and the third one needs to be a new INSERT.
The issue I have is, that for each key there is an array. I would have expected an array for each row.

Parameters id ‘1’ & ‘3’ are existing ones to update, par id ” is a new one to insert.

Because the payload gives an array for each key, I’m not sure how to proceed. How to convert the payload to something more usable.

I tried looking on google, but didn’t find a good example that I could follow (that I understand). I’m very new at this.

Anyone can put me on the right track?

Thx

In html page onclick and console.log is not working

I created a button on my html page
So, In index.html:

<button class="btn btn-sm btn-remove delete-product" data-product="{{product_id}}"><i class="fas fa-trash-alt" ></i></button>

When I am clicking on this button it is not working In function.js:

$(".delete_product").on("click",function(){
    let product_id=$(this).attr("data_product")
    let this_val=$(this)


    console.log("Product ID:", product_id);
}

and the html page is also linked with js file

So that’s it… What is wrong here???

how to add top margin to the download pdf file using JSPDF

enter image description here
-> In this pdf the content is starting without any top margin, looking for an solution to add top margin.

-> I tried the below code and i’m looking for a solution to add “top_left_margin= 15” to the downloaded pdf file.but the margin is not getting added.

HTML :-

paragraph 1

paragraph 2

paragraph 3

paragraph 4

paragraph 5

SCRIPT:-

const section: any = document.getElementById(‘summaryId’);

var HTML_Width = section.scrollWidth;
        var HTML_Height = section.scrollHeight;
        var top_left_margin = 35;
        var PDF_Width = HTML_Width + (top_left_margin * 2);
        var PDF_Height = (PDF_Width * 1.2) + (top_left_margin * 2);
        var canvas_image_width = HTML_Width;
        var canvas_image_height = HTML_Height;

        var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
     
        html2canvas(section, { allowTaint: true }).then(function (canvas) {
          var imgData = canvas.toDataURL('image/png');
          var imgWidth = 210;
          var pageHeight = 299;
          var imgHeight = canvas.height * imgWidth / canvas.width;
          var heightLeft = imgHeight;
          var top_left_margin = 15;
          var doc = new jspdf.jsPDF();
          var position = 0;
     
          doc.addImage(imgData, 'PNG',0, position, imgWidth, imgHeight+30);
          heightLeft -= pageHeight;
    
          while (heightLeft >= 0) {
              position = heightLeft - imgHeight; 
              doc.addPage();
              doc.addImage(imgData, 'PNG',0,position, imgWidth, imgHeight+30);
              heightLeft -= pageHeight;
          }
        doc.save("Dashboard.pdf");
        });
         
      }

Sort HTML row’s cells

I am trying to sort the <td>‘s inside a <tr> based on the text content.

sortedCells = Array.from(tr.cells).sort((a,b) => b.textContent - a.textContent);
const cellsLength = tr.cells.length;
for(i = 0; i < cellsLength; i++) {
  const cell = tr.cells[i];
  tr.replaceChild(sortedCells[i], cell);
}

When this code is executed, it will shorten the tr.cells by one, so in one of the replaceChild() calls, something goes wrong, as a result, i will get a shorter <tr> i cant figure out why.

NextJS Client component not receiving props until rendering props.children?

Super strange one that I can’t quite figure out…

I have a server side component, which gets data and then passes it down to the client component – pretty standard.

Heres the strange thing… if I log the data on the server side it’s all fine as expected. I then pass it down to the client, which weirdly receives only “children” props (which aren’t passed anyway..). If I render the children, then I actually get passed the props which I passed down, and children are no longer passed? It’s obviously not intentional, and I end up with my component being rendered twice as I assume one time its being fed to itself? Super strange

Here’s my code

Server side component:

// SERVER SIDE COMPONENT

'user server';

const Page = async () => {
    const news = await getAllNews();
    console.log(news)
    //correctly logs news in the server console
    return <Template news={news}/>
}

export default Page;


//CLIENT SIDE COMPONENT WHERE NEWS IS NOT PASSED

'use client';

const PageTemplate = (props: any) => {
    console.log(props);
    // console logs children, which is a React component
    return (
        <S.PageTemplateWrapper>
            Template
        </S.PageTemplateWrapper>
    )
}

export default PageTemplate;


//CLIENT SIDE COMPONENT WHERE NEWS IS  PASSED

'use client';

const PageTemplate = (props: any) => {
    console.log(props);
    // console logs children, then news (separately). Renders two instances of "Template"
    return (
        <S.PageTemplateWrapper>
            Template
            {props.children}
        </S.PageTemplateWrapper>
    )
}

export default PageTemplate;

So where is props.children coming from?
Why is my data only passed when I render props.children?

Without rendering props.children

With rendering props.children

Moving Anchor Point for Framer Motion

I want to create an animation for an .svg component using the React Framer Motion library so that it rotates 360 degrees. However, I don’t want the anchor point to be in the center of the .svg, I want it to be a custom point “x% y%” off the top left corner. I have tried something like the following (inside the .svg file), however it doesn’t work (it still just rotates about the center). What are other methods to try, or what might be missing from the current implementation?

  <motion.path
    id="Needle"
    d=...
    fill=...
    initial={{ opacity: 1, rotate: 0, transformOrigin: "9% 75%" }} // Initial animation state
    animate={{ opacity: 1, rotate: 360 }} // Target animation state
    transition={{ rotate: { duration: 2, delay: 0 } }} // Animation duration and delay
  />

Mock multiple capsuled GraphQL requests in JEST

I will test my redux-sagas, and stuck by mocking my api requests.
The scenario is like this:

I have a GraphQL API and each request is capsuled (axios) in a requestApiUtil.

like

/path/api/sampleOneApiRequest.js

import { requestApi } from 'utils';

export const sampleOneApiRequest = ({ arg1 }) => requestApi.query(`
  sampleData {
    id
  }
`)

/path/api/sampleTwoApiRequest.js

import { requestApi } from 'utils';

export const sampleTwoApiRequest = ({ arg1 }) => requestApi.query(`
  otherSampleData {
    id
  }
`)

/path/api/index.js

export * from './sampleOneApiRequest';
export * from './sampleTwoApiRequest';

the saga that i like to test, looks like this

/path/redux/saga/sampleSaga/sampleSaga.js


import { all, put } from 'redux-saga/effects';
import { successAction, failureAction } from 'path/redux/action';
import { sampleOneApiRequest, sampleTwoApiRequest } from 'path/api';

export function* sampleSaga({ payload }) {
  const switch = payload ? payload.switch : false;
  try {
    let response;
    if (switch) {
      response = (yield sampleOneApiRequest());
    } else {
      response = (yield sampleTwoApiRequest());
    }

    if (response.errors) {
      return yield put(failureAction(response.errors));
    }

    yield put(successAction(response.data));
  } catch (error) {
    yield put(failureAction(error));
  }
}

Now to the problem, my test to the saga looks like this:

/path/redux/saga/sampleSaga/sampleSaga.test.js

import { sampleSaga } from './sampleSaga;
import { sampleOneApiRequest, sampleTwoApiRequest } from 'path/api';
import { successAction } from 'path/redux/action';
import { put } from 'redux-saga/effects';

jest.mock('path/api', () => ({
  sampleOneApiRequest: async () => { id: 'sample1' },
  sampleTwoApiRequest: async () => { id: 'sample2' }
}));

descripe('test sampleSaga', () => {
  
  if('test sampleSaga switch false', () => {
    const generator   = sampleSaga({ payload: { switch: false } });
    const apiResponse = { data: { id: 'sample1' } };
    
    expect(generator.next().value).toEqual(sampleOneApiRequest());
    expect(generator.next(apiResponse).value).toEqual(put(successAction(apiResponse)))
  });
  
  if('test sampleSaga switch true', () => {
    const generator   = sampleSaga({ payload: { switch: true } });
    const apiResponse = { data: { id: 'sample2' } };
    
    expect(generator.next().value).toEqual(sampleTwoApiRequest());
    expect(generator.next(apiResponse).value).toEqual(put(successAction(apiResponse)))
  });

});

The problem is, that the second triggert saga, generate a request to the backend, but i aspect the the request to the backend will be mocked. The frist one will mocked perfectly, when i change the order of both tests, always still the second one (in order) will be call to the backend. When i comment out the first test, the second works fine.

I don’t know what its wrong.