Get position of cursor when highlight the text

  • I need to create an Chrome Extension which people can use to look up words. And I have found that I use double click method like when I want to find meaning of a word I just double click and then the notification will appear. (The image below is my Chrome Extension.)

enter image description here.

  • However, I find it is difficult for user to find meaning of pharsal
    verb, collocation and sentence.
  • So come up with an idea that I can get the position of cursor when
    user select text and to the last letter of this text I get the
    position.

enter image description here

enter image description here

edit values in firestore database (firebase 9.6.11)

i have in issue to solve, in last days i tring update my DB in firestore but unfortunately i can’t, i read the documentation and i read anothers from stackoverflow questions, but don’t make my update funcionar, don’t know what i make wrong, bellow is my code.

here is my button who send to edit screen he is located in home Screen where i have a list of my informations he is inside a map

 <IconButton
   icon={<Icon as={AntDesign} name="edit" color="success.900" />}
   borderRadius="full"
   onPress={() =>
    navigation.navigate("EditScreen", { userId: user.id }) //here i passing a user id to 
    editing
   }
 />

here is code of my EditScreen

export const EditScreen = ({ navigation }) => {
  const [name, setName] = useState("");
  const [cep, setCep] = useState("");
  const [logradouro, setLogradouro] = useState("");
  const [numero, setNumero] = useState("");
  const [bairro, setBairro] = useState("");
  const [uf, setUf] = useState("");

  const usersCollectionRef = collection(db, "users");

  const handleChangeName = (value) => setName(value);
  const handleChangeCep = (number) => setCep(number);
  const handleChangeLogradouro = (value) => setLogradouro(value);
  const handleChangeNumero = (number) => setNumero(number);
  const handleChangeBairro = (value) => setBairro(value);
  const handleChangeUf = (value) => setUf(value);

  const updateUser = async (id) => {
    const userDoc = doc(usersCollectionRef, id);
    const newFields = {
      name: handleChangeName,
      cep: handleChangeCep,
      logradouro: handleChangeLogradouro,
      numero: setNuhandleChangeNumeromero,
      bairro: handleChangeBairro,
      uf: handleChangeUf,
    };
    await updateDoc(userDoc, newFields);
    navigation.navigate("HomeScreen");
  };

  return (
    <SafeAreaView style={{ backgroundColor: "#D4D4D8" }}>
      <Center h="100%" bg="dark.600">
        <Box ml="-300px" mb="80px" flexDirection="row" alignItems='center'>
          <IconButton
            size="lg"
            icon={<Icon as={AntDesign} name="left" color="orange.600" />}
            borderRadius="full"
            onPress={() => navigation.navigate("HomeScreen")}
          />
        </Box>
        <Box mb="25px" w="360px">
          <FormControl.Label ml="12px">
            <Text bold>Nome</Text>
          </FormControl.Label>
          <TextInput value={name} onChangeText={handleChangeName} />
        </Box>
        <Box w="360px">
          <FormControl.Label ml="12px">
            <Text bold>CEP</Text>
          </FormControl.Label>
          <TextInput value={cep} onChangeText={handleChangeCep} />
        </Box>
        <Text fontSize="12px">
          busque automaticamente seu edereço atraves do cep
        </Text>
        <Box flexDirection="row" mt="47px">
          <Box w="208px" mr="34px">
            <FormControl.Label ml="12px">
              <Text bold>Logradouro</Text>
            </FormControl.Label>
            <TextInput
              value={logradouro}
              onChangeText={handleChangeLogradouro}
            />
          </Box>
          <Box w="109px">
            <FormControl.Label ml="12px">
              <Text bold>Número</Text>
            </FormControl.Label>
            <TextInput value={numero} onChangeText={handleChangeNumero} />
          </Box>
        </Box>
        <Box flexDirection="row" mt="16px">
          <Box w="208px" mr="34px">
            <FormControl.Label ml="12px">
              <Text bold>Bairro</Text>
            </FormControl.Label>
            <TextInput value={bairro} onChangeText={handleChangeBairro} />
          </Box>
          <Box w="109px">
            <FormControl.Label ml="12px">
              <Text bold>UF</Text>
            </FormControl.Label>
            <TextInput value={uf} onChangeText={handleChangeUf} />
          </Box>
        </Box>
        <Box mt="50px">
          <PrimaryButton onPress={updateUser}>salvar</PrimaryButton>
        </Box>
      </Center>
    </SafeAreaView>
  );
};

Backfill the Dependent dropdown or operate dropdown in reverse

I have a requirement to use dependent Drop Down and autofill based on the selection of previous value, along with to backfill the dropdowns based on the value selected from other dropdown.
For example, I have School list based on city, so it narrows down the schools by city and I have completed this part, but if you don’t know the city and know the school, I want to be able to select the school and have the city automatically back fill.

Currently I did implemented it using many if else block, but this does not seems to be efficient.

is there a good and efficient way to do this?

How to tween view.center in paper.js

So I’m trying to give the feel of smooth movement when reassigning the paper.view.center coordinates. The center object doesn’t have a tweenTo() method. This is what I’ve tried using Tween.js:

let smooth = new TWEEN.Tween(paper.view.center).to({
    x: 650,
    y: 270
}, 900).easing(TWEEN.Easing.Cubic.Out).start();

Since it’s a Point object reassigning the x and y values don’t actually change the coordinates, because the proper way of reassiging it is to use another Point object (new paper.Point()). How could I tween the continuously new creation of a Point object?

Print string array have 10 char alphabet [closed]

I do not have any idea for create an array as title.
It mean an element in this array will have 10 characters from A-Z, a-z, 0-9

Ex:

arr = [
   "abaaaaaaaa",
   "abbaaaaaaa",
   "abbbaaaaaa",
   "abbbbaaaaa",
   "abbbbbaaaa",
   "abbbbbbaaa",
...
   "gDJnu3V04y",
...
]

Maybe have any solution, function or method can create an array like this ?
Thank you.

Just trying to get this reverse array function to work as I’m new to coding

const arr = [1, 2, 3, 4, 5, 6, 7];

function rev(arr) {
  var value;
  var nArr = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    value = arr[i];
    for (let j = 0; j < arr.length; j++) {
      nArr[j] = value;
    }
  }
  console.log(nArr);
}

rev(arr);

I thought this would work but i keep getting an output of the first index in the test array which means one, it’s not reversed at all and two, the new array is outputed [1,1,1,1,1,1,1]

How to delete document from mongodb?

I’ve been stuck on this problem a few days… Basically, I am trying to delete one document from collection in mongoDB. In index I have a map of items that are shown from database and a “DeleteTest” component that has certain object from map passed. In that component, I have a button which when clicked triggers a function(deleteTestFun) to call API. In API I try to delete it but it doesn’t seem to work…
Also here is git link in case something is not clear.
https://github.com/RennSter20/ReactStuff

Thanks 🙂

index

import React, { useState } from 'react';
import AppBar from '@mui/material/AppBar';
import Button from '@mui/material/Button';
import Card from '@mui/material/Card';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import CssBaseline from '@mui/material/CssBaseline';
import Grid from '@mui/material/Grid';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import Link from '@mui/material/Link';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import Form from '../components/form';
import DeleteIcon from '@mui/icons-material/Delete';
import connectMongo from '../utlis/connectMongo'
import Test from '../models/testModel';
import Checkbox from '@mui/material/Checkbox';
import DeleteTest from '../components/deleteTest';
const theme = createTheme();



export default function Album({tests}) {

  return (
<div>

<Form></Form>
    <div>
      {tests.map(test => (
        <a key={test._id}>
          <p>{test.name} {test.email}</p>
          <DeleteTest test={test}></DeleteTest>
        </a>
      ))}
    </div>
        
    

</div>
  );
}

export const getServerSideProps = async () => {
  try
    {
        console.log('CONNECTING TO MONGO');

        await connectMongo();
    
        console.log('CONNECTED TO MONGO');
        console.log('FETCHING DOCUMENTS');

        const tests = await Test.find();

        console.log('FETCHED DOCUMENTS');
    
        return {
          props:{
            tests: JSON.parse(JSON.stringify(tests))
          }
        }
    }
catch(error)
{
    console.log(error);
      return {
        notFound: true
      }
}
}

deleteComponent

import React, { useState } from 'react';
import Button from '@mui/material/Button';
import CardActions from '@mui/material/CardActions';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import CssBaseline from '@mui/material/CssBaseline';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import DeleteIcon from '@mui/icons-material/Delete';



export default function DeleteTest(props)
{
 

const postID = props.test._id;
const name = props.test.name;
const deleteTestFun = async (postID) => {

const response = await fetch('/api/delete/' + postID, {
  method:'DELETE'
})
const data = await response.json()
console.log(data)

}



    //{props.test._id}
    return(
      <div>
        <Button onClick={deleteTestFun}>
      Delete 
      </Button>
      </div>
    );
}

postID (API)

import connectMongo from "../../../utlis/connectMongo";
import Test from "../../../models/testModel";
import { MongoClient } from "mongodb";
import mongoose from 'mongoose'
/**
 * 
 * @param {import("next").NextApiRequest} req 
 * @param {import("next").NextApiResponse} res 
 */

export default async function deleteTest(req, res) {
    try{
      const object = Test.find({_id:req.query.postID})
      console.log(object.name)
      await Test.findOneAndDelete({name:req.query.name})
      res.send('Item deleted')
    }catch(error)
    {
      console.log(error)
    }
  }

How to pass a variable from a post request to a function that takes params as string or array of string in Node.js?

I would like to pass the variable below called query into the end of the prompt , I tried template literals but it doesn’t work

(async () => {
  const gbtResponse = await openai.createCompletion({
    model: "text-davinci-002",
    prompt:
      "Generate a product description explanation for the following product:  nn",
    temperature: 0.8,
    max_tokens: 256,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
  });
  console.log(`${gbtResponse.data.choices[0].text}`);
  // console.log(`${gbtResponse}.choices[0].text`);
  app.get("/api", (req, res) => {
    res.send(`${gbtResponse.data.choices[0].text}`);
  });
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));

  app.post("/api", (req, res) => {
    res.send(
      `I received your POST request. This is what you sent me: ${req.body.productName}`
    );
    const query = req.body.productName;
    console.log(`${query}`);
  });
})();

Radio button not working properly in react native

I am making custom radio button in react native.

Parent Component

const radioData = [
  { text: 'value A' },
  { text: 'value B' },
  { text: 'value C' },
];

<RadioButton
  dataText={radioData}
  isSelected={(selected) => {
    console.log('<><>', selected);
  }}
/>

Child Component

const RadioButton= (props) => {
 const [selected, setSelected] = useState(false);
 let { dataText, isSelected } = props;
 return (
  <>
   {dataText.map((item) => {
    return (
     <View
      style={{
       flexDirection: 'row',
       width: '50%',
       marginVertical: 10,
      }}
     >
      {selected ? (
       <TouchableOpacity
        onPress={() => {
          if (selected) {
            setSelected(false);
            isSelected(false);
           } else {
            setSelected(true);
            isSelected(true);
           }
        }}
       >
        <Image
         source={require('../../assets/img/checkFullColor.png')}
         style={{
          width: 20,
          height: 20,
          marginRight: 20,
         }}
         resizeMode={'contain'}
        />
       </TouchableOpacity>
      ) : (
       <TouchableOpacity
        onPress={() => {
          if (selected) {
            setSelected(false);
            isSelected(false);
           } else {
            setSelected(true);
            isSelected(true);
           }
        }}
       >
        <View
         style={{
          backgroundColor: Colors.accentDark,
          height: 20,
          width: 20,
          borderRadius: 50,
          marginRight: 20,
         }}
        />
       </TouchableOpacity>
      )}
      <Text style={{ color: Colors.accentDark }}>{item.text}</Text>
     </View>
    );
   })}
  </>
 );
};

The Problem is even I click on any one of the RadioButton, then all 3 are getting selected or unselected.

I wanted a feature where I click on one of them then other gets unselected and selected value is updated in parent component.

How to use .innerHTML with a class? [duplicate]

I tried to use .innerHTML with getElementsByClassName to change the text of one of my paragraph tags however when I do this nothing changes on the file. Any reason that the change is not being applied to the file?

document.getElementsByClassName("test").innerHTML = "Hello World";

discord bot keeps uploading attachment in a loop. everything else works but the uploading the thumbnail causes an uploading loop. thoughts?

`client.on(‘messageCreate’, async (message) => {
if (message.content && message.content.toLowerCase() === ‘!play radio’) {
if (!message.member.voice?.channel) return message.channel.send(‘You need to be a voice channel to execute this command’)
const connection = joinVoiceChannel({
channelId: message.member.voice.channelId,
guildId: message.guildId,
adapterCreator: message.guild.voiceAdapterCreator
})

    const player = createAudioPlayer()
    const resource = createAudioResource('https://nrf1.newradio.it:10328/alfaanime')

    connection.subscribe(player)

    message.channel.send({ content: "Now Playing", embeds: [embed2], files: ['./logo/bkrlogo.png'] }) + player.play(resource) 

}

})
});
`

variable is not initializing with the correct value, only after some action [closed]

I’m making a method that checks if my screen is in share mode, it works the way I check if the screen sharekey.

this is the code of the function

enter image description here

the problem that is happening is that when I load the screen, my variable has the value “`undefined“.

enter image description here

But when I perform some action, something like that, the variable returns the correct value.

enter image description here

How to set a property value based on other property in Mongoose

I have the following schema as exemple:

const categorySchema = new mongoose.Schema({
  categoryId: {type: Number},
  title: {type: String, default: "standard"},
})

I want that the category with categoryId equal 1, must always be “standard”, and if the title is not specified, it will assign the categoryId = 1. Is there any way to do that in Mongoose?

mapping within another map and printing multiple properties on object

In this code, everything prints out right except for my “flavors” is only returning one property value (the one at the index of 0] in the browser instead of the array it is supposed to. I should be showing 3 flavors per entry. I believe the answer would be to map that array within my current array of entries, but I am unsure as to how to write this out. Any help or tips are appreciated!

return (
  <>
    <article className="entries">
      {
        entries.map(entry => {
          return <section key={`entry--${entry.id}`} className="entry">
            <div>
              <ul>
                <div><img src={entry.image} height="300" /></div>
                <li>Name: {entry.name}</li>
                <li>Brewing Method: {entry.brewing_method.type}</li>
                <li>Grind Setting: {entry.grind_setting}</li>
                <li>Rating: {entry.rating}</li>
                <li>Flavors: {entry?.flavor_profile[0]?.name}</li>
                <li>Notes: {entry.notes}</li>
              </ul>

Cannot get useEffect to run when using React Router

I’m working on building a react app based on a REST API for practice and I cannot figure out why my useEffect function is never running and therefore item is never getting set. I am working on an Inventory Management application. Here is my code:

Item.jsx:

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
 
function Item() {
  const [item, setItem] = useState({});
  const id = useParams().id | 0;
  useEffect(() => {
    console.log("Fetching");
    fetch(`http://localhost:8080/item/${id}`)
      .then((res) => res.json())
      .then((data) => {
        setItem(data["Items"]);
      });
    console.log("Fetched");
  }, [id]);
 
  return (
    <div key={id}>
      <h1 className="">{item["name"]}</h1>
      <h2 className="px-3">Quantity: {item["quantity"]}</h2>
      <h2 className="px-3">Price: ${item["price"].toFixed(2)}</h2>
      <h2 className="px-3">Description: {item["description"]}</h2>
    </div>
  );
}
export default Item;

Index.js:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./Components/App";
import Item from "./Components/Item";
import "bootstrap/dist/js/bootstrap.min.js";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter, Route, Routes } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <div className="container">
      <Routes>
        <Route exact path="/" element={<App />} />
        <Route path="/item/:id" element={<Item />} />
      </Routes>
    </div>
  </BrowserRouter>
);

Full Repository here