React : How use ogp tags on differents components

I’m trying to implements meta ogp tags on my app :
I want to do something like this :

If I post on discord, www.myurl.com/, I want “Homepage” in my embed title
If I post www.myurl.com/about, i want “About” in my embed title

I’ve already looked around helmet, and something called react-meta-tags, but It’s wasn’t really working.. the url were duplicated and never updated, and after when i’ve fixed this, url in discord was every time the same..

maybe i’ve messed up something ?

How do transitions work when fading in and out using css classes and javascript

I am trying to find out how transitions work. I am trying to make a thumbs up appear using a fade in fade out transition for a recycling simulator program, however, I do not know how understand how transitions work.
Here is a snippet of my html

<div class="thumbs-up-bg">
    <i  class="fas fa-thumbs-up" id="thumbs-up"></i>
</div>

<div class="thumbs-down-bg">
    <i class="fas fa-thumbs-down" id="thumbs-down"></i>
</div>

Here is the CSS

.thumbs-up-bg {
  position: absolute;
  visibility: hidden;
  background-color: green;
  display: inline-block;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  text-align: center;
  opacity: 0;
  transition: opacity 0.1s ease-in-out;
}

#thumbs-up-bg.visible {
  opacity: 1;
}

#thumbs-up {
  font-size: 50px;
  color: white;
}

.thumbs-down-bg {
  position: absolute;
  visibility: hidden;
  background-color: red;
  display: inline-block;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  text-align: center;
  opacity: 0;
  transition: opacity 0.1s ease-in-out;
}

#thumbs-down {
  font-size: 50px;
  color: white;
}

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 2s linear;
}

.hidden {
  opacity: 0;
  transition: visibility 5s, opacity 2s linear;
}

Are transitions supposed to be set on the selector that is going to be changed? Is there a simpler way to complete this task?

Here is the Javascript

if (drop === trashDropZone){
    if(!isRecyclable(draggable)){
        alert("Success, it is garbage");
        thumbsUp.classList.toggle("visible");
        setTimeout(() =>{
        thumbsUp.classList.toggle("visible");
        thumbsUp.classList.toggle("hidden"); 
     }, 1000);
     makeInvisible(draggable);
     } else{
     //show thumbs down
     alert("Thumbs down");
     thumbsDown.classList.toggle("visible");
     setTimeout(() =>{
     thumbsDown.classList.toggle("visible");
     thumbsDown.classList.toggle("hidden"); 
     }, 1000);

Onclick requires two clicks for element, when clicking friend element, it requires 2 clicks for it to become true

When I click friend button, it takes 2 clicks to become true I want to click just once and for isFriend to be set true

function FriendChoice({friend, index}) {
    const [showHobbies, setShowHobbies] = useState(false);
    const [friendClicked, setFriendClicked] = useState(false);
    // const[isFriend, setIsFriend] = useState(false);
    // const[showActivity, setShowActivity] = useState(false);
    const db = getDatabase();
    let friendClass = "friend-card";
    const handleClick = async () => {
        try {
            const path = "Friends/" + index + "/isFriend";
            const friendRef = ref(db, path);
            setFriendClicked(!friendClicked);
            await firebaseSet(friendRef, friendClicked);
        } catch (error) {
            console.log(error);
        }
    }

   if(friend.isFriend) {
   friendClass = "friend-card friend-card-clicked";
 }

return (
<div className={friendClass} onClick={handleClick} onMouseEnter={() => setShowHobbies(true)} onMouseLeave={() => setShowHobbies(false)}>
  <img src={friend.img} alt={friend.alt} />
  <div className="d-flex flex-column friend-font">
    {!showHobbies && (
      <p><strong>{friend.name}</strong></p>
    )}
    {showHobbies && (
      <p>
        A:{friend.activity} H:{friend.hobby}
      </p>
    )}
  </div>
</div>
);
}

Thank you for your help javascript class have around 2 hours to submit

Is it possible to getImageData on Firefox without enabling Cors?

I’d like to do this simple task of taking a local file and checking its RGB value. But Firefox’s security makes it difficult… First, getImageData gives an insecure warning, to get around it, I set crossOrigin as “anonymous”, however, this results in “Cross-Origin Request Blocked”.

var ctx = document.getElementById("canvas").getContext("2d");
var img = new Image();
img.crossOrigin = "anonymous";

img.onload = function() {
     var d = ctx.getImageData(0, 0, 1, 1).data;

}
img.src = 'picture.jpeg';

I realize that I could around this by enabling Cors or doing a localhost, but I prefer neither. Are there are any other choices?

Porting php code that extracts public key from certificate and encrypt data to javascript

I wrote these two methods in PHP.
The first method, get_pubkey, extracts the public key from a certificate (certnew.cer) and the second method, encryptit(info) returns the encrypted information using the public key extracted by the first function.
I need to port these 2 functions to their Javascript equivalent. Does anyone know how to do it?

class Assdig 
{

   private $pubkey;

   /* (... )*/

   public function get_pubkey()
   {
       $certificado = __DIR__ . '/certnew.cer';

       $fp=fopen($certificado,"r"); 

       $this->pubkey=fread($fp,8192);

       fclose($fp);

       openssl_get_publickey($this->pubkey);
   }

   public function encryptit($info)
   {
     openssl_public_encrypt($info, $infoencrypted, $this->pubkey);

     return base64_encode($infoencrypted);
   }

}

How to access response body as text in https module

I am trying to do the following to parse an html document:

function process_url_handler(res) {
     // ...
     const node = xpath.fromPageSource(res);
}

for (const url of urls) {
    console.log(`${'-'.repeat(10)} ${url} ${'-'.repeat(10)}`);
    let request = https.get(url, (res) => process_url_handler(res));

Res is of type IncomingMessage. How would I get that as raw text so I can grab the html node?

Wait for For loop to finish – Angular

I have this code that formats the parameters and submits to api.

                for (let a = 0; a < perfCriteria.length; a++) {
                    const element = perfCriteria[a];
                    let newObject = Object.assign({}, paramObject)
                    newObject.performanceCriteria = element.performanceCriteriaId
                    for (let b = 0; b < element.performanceIndicators.length; b++) {
                        const element2 = element.performanceIndicators[b];
                        let newObject2 = Object.assign({}, newObject)
                        newObject2.performanceIndicator = element2.performanceIndicatorId
                        newObject2.numberTarget = element2.divisionTarget ? element2.divisionTarget : ""
                        newObject2.targetDetails = element2.targetDetails
                        for (let c = 0; c < element2.targetDetails.length; c++) {
                            const element = element2.targetDetails[c];
                            element2.targetDetails[c].individualAccountable = element.individualAccountable.map(function(row){
                                return row._id
                            })
                        }

                        divTargetArray.push(newObject2)
                    }
                }

                this.DivisionTarget.create(divTargetArray).subscribe(result =>{
                    console.log('result', result)
                    if(result.success){
                        this.appComponent.showLoadingIndicator = false;
                        this.router.navigate(['/index/app/performanceManagement/divisionTargets']);
                        this.toastService.openSnackBar(result.message, "success");
                    }else{
                        this.appComponent.showLoadingIndicator = false;
                        this.toastService.openSnackBar(result.message, "danger");
                    }
                }, error => {
                    this.appComponent.showLoadingIndicator = false;
                    this.toastService.openSnackBar(error, "danger");
                });

But sometimes, it will not wait for the For loop to finish. Is there a way that I can wait for the For loop to finish before proceeding to submit it to API?

Conditional rendering of svg files in react native

I have an app for buying and selling dogs. In my app each dog breed has its own svg file stored in my assets folder (around 150 svg files). When fetching post data from the backend, I get different information about a the post, including the dogBreed, e.g. {dogBreed: golden-retriver}. I want to render the corresponding svg to each post of dogs, but I am unsure about what the best way to deal with this is.
Should my app import all svg files?
Should I convert all the svg files into JSX files? I have done this in other parts of the application.
If i’m going for the JSX solution, should I render the JSX conditionally based on the name like: <${dogBreed}/> (if it is possible), or should I have one component take in the dog breed as a prop and have logic within for conditional rendering? . This would create a huge file, and I’m not sure if 150 if else/switch statements is the way to go. I feel really stuck here.

vue.runtime.esm.js?TypeError: Cannot read properties of undefined

I create this component from the vuetify documentation.

https://github.com/vuetifyjs/vuetify/blob/master/packages/docs/src/examples/v-card/prop-outlined.vue

<template>
    <v-card class="mx-auto" max-width="344" outlined>
        <v-list-item three-line>
            <v-list-item-content>
                <div class="text-overline mb-4">OVERLINE</div>
                <v-list-item-title class="text-h5 mb-1"> {{ person.name }} </v-list-item-title>
                <v-list-item-subtitle> {{ person.role }} </v-list-item-subtitle>
            </v-list-item-content>

            <v-list-item-avatar tile size="80" color="grey"></v-list-item-avatar>
        </v-list-item>

        <v-card-actions>
            <v-btn outlined rounded text> Message </v-btn>
        </v-card-actions>
    </v-card>
</template>

<script>
export default {
    name: 'Person',
    props: {
        person: Object
    }
}
</script>

I import them like so… was intended to use it in a loop 5 times.

<template>
    <div class="teams">
        <h1 class="subtitle-1 grey--text">Teams</h1>
        <v-container class="my-5">
            <v-card class="mx-12 my-12">
                <v-row>
                    <v-flex xs12 sm6 md4 lg3 v-for="person in team" :key="person.name">
                        <Person :name="person" :role="person" />
                    </v-flex>
                </v-row>
                <v-divider></v-divider>
            </v-card>
        </v-container>
    </div>
</template>
<script>
import Person from '@/components/Person.vue'

export default {
    name: 'Team',
    components: {
        Person
    },
    data() {
        return {
            team: [
                { name: 'The Net Ninja', role: 'Web developer' },
                { name: 'Ryu', role: 'Graphic designer' },
                { name: 'Chun Li', role: 'Web developer' },
                { name: 'Gouken', role: 'Social media maverick' },
                { name: 'Yoshi', role: 'Sales guru' }
            ]
        }
    }
}
</script>

However, it is not compiling… I kept getting

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of undefined (reading ‘name’)

What did I forget to do ??

If I comment out the

 <Person :name="person" :role="person" />

enter image description here

Result

enter image description here

{{ person.name }} seems accessible…

SQLITE_CANTOPEN: unable to open database file

I’m trying to open SQLite3 database for my node.js app, but it does not seem to work there is the code I wrote to open the database:

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database("./Users/home/Desktop/webscraping/database.db", sqlite3.OPEN_READWRITE, (err) => {
    if (err) return console.error(err.message);

    console.log("Conncetion succesful");
});

After running it the following message pops up:

SQLITE_CANTOPEN: unable to open database file

TypeError: Cannot read properties of undefined (reading ‘createMessageCollector’)

I’ve been following CodeLyon’s tutorial on how to make an economy system for a discord bot and usually have managed to get things working. However, the MessageCollector has been giving me issues and I don’t know what exactly the error means. Am I missing something before the createMessageCollector?

const profileModel = require("../models/profileSchema");

module.exports = {
    name: "search",
    aliases: [],
    permissions: [],
    description: "Search for some coin!",
    async execute(message, args, cmd, client, discord, profileData) {

        const locations = [
            "car",
            "bathroom",
            "park",
            "truck",
            "pocket",
            "computer"
        ];

        const chosenLocations = locations.sort(() => Math.random() - Math.random()).slice(0, 3);

        const filter = ({ author, content }) => message.author == author && chosenLocations.some((location) => location.toLowerCase() == content.toLowerCase());

        const collector = message.channel.createMessageCollector({ filter, time: 15000 });

        const earnings = Math.floor(Math.random() * (1000 - 100 + 1)) + 100;

        collector.on('collect', async (m) => {
            message.channel.send(`You found ${earnings} coins!`);

            await profileModel.findOneAndUpdate(
                {
                    userID: message.author.id,
                },
                {
                    $inc: {
                        reputation: earnings,
                    },
                }
            );
        });

        collector.on('end', (collected, reason) => {
            if (reason == "time") {
                message.channel.send('You ran out of time!');
            }
        });


        message.channel.send(`<@${message.author.id}> Which location would you like to search?n Type the location in this channeln `${chosenLocations.join('` `')}``);
    }
}

I’m going to be honest, I’m not very familiar with Javascript. This bot is mostly for fun.

Possible to share global variable between two functions without a file?

With the below code, I get

{ test1: 'aaa', test2: 'bbb' }

which is what I want. Ie. being able to have a global variable between t2.js and t3.js.

In this PoC is t3() only called once, but in the real case, if will be ~100 instances of t3() that never ends, because they collect data in an infinite loop. t2.js won’t need to modify c.

Question

Is it possible to be the same, but without a third file (t1.js in this case)?

t1.js

module.exports = {};

t2.js

const express = require('express');
const app = express();

let c = require('./t1');
const t3 = require('./t3');

c.test1 = "aaa";
t3();
console.log(c);

app.get('/test.json', (req, res) => {
  res.send(JSON.stringify(c, null, 2));
});    

app.listen(1900, () => {});

t3.js

let c = require('./t1');
module.exports = () => {
  c.test2 = "bbb";
};

React – redirect to login page when not authenticated

This is my primary react file:

// App.tsx
const App: FC = () => {

  const isLoggedIn: boolean = localStorage.getItem('logged_user') !== null;

  return (
    <BrowserRouter>
        <Routes>
          <Route path="/main" element={isLoggedIn ? <Main/> : <Navigate to='/login'/>}/>
          <Route path="/about" element={isLoggedIn ? <About/> : <Navigate to='/login'/>}/>
          <Route path="/login" element={<Login/>}/>
        </Routes>
    </BrowserRouter>
  );
}

export default App;

After logging in, I store the user in local storage.

I want to achieve the behaviour of redirections to the /login page when the user is not authenticated (when it is not stored in localstorage).

Generally, the above approach works but only sometimes. Sometimes, when I go to ‘/main’, I would get redirected to ‘/login’ even though I was logged in. I assume this is caused by React’s nature of re-renders.

How can I approach this?

Find path to an imported element

I am mocking a component using jest.mock("../path/to/file").

If that mocked component moves around, Webstorm will fix all my imports. But it will not fix the path in the mock. I am trying to see if there is any way to solve this!

Something like…


import Component from "../../Component"

const pathToComponent = pathToFile(Component) // returns "../../Component", but this will change if the file moves.

Does such a function exist? Seems like it might be too meta…

(by the way, including the actual import to the component does not appear to break Jest’s mocking)

highlight one value in plotly.js boxplot

I have a plotly boxplot chart with array of many values and all works well, but I want to highlight one value.

this is my code

var ebitda_margin_plotly = {
                      x: data.plotly_data.ebitda_margin,
                      type: 'box',
                      name: 'E-MARGIN',
                      marker: {
                      color: 'rgba(255, 202, 3, 0.7)',
                      outliercolor: 'rgba(219, 64, 82, 0.6)',
                      line: {
                        outliercolor: 'rgba(219, 64, 82, 1.0)',
                        outlierwidth: 2
                      }
                    },
                    boxpoints: 'suspectedoutliers'
                    };

                    var ebitda_margin_config = {
                    responsive: true,
                    modeBarButtonsToRemove: ['pan2d','select2d','lasso2d','resetScale2d'],
                    displaylogo: false,
                    autosizable: true

                    }
                     var layout_ebitda_margin = {
                      title: ('EBITDA MARGIN: ' + data.data.ebitda_margin + "%")
                    };
Plotly.newPlot('ebitda_margin_plotly', [ebitda_margin_plotly], layout_ebitda_margin,ebitda_margin_config);

how can I add line like this blue which will represent my custom value ? in thiscase 11.7% I have from backend

enter image description here