Why a string that has persian/arabic and English characters, was messed up in browser view?

I’m coding an ASP.NET core application. I read a record of SQL database and I want to show it in my html page through a Jquery function. It’s a part of my code:

//some code...

    <script charset="utf-8" type="text/javascript">
       $(document).ready(function () {
         var materialname = [];
         
         @if (Model.Count() != 0)
         {
            foreach (var item in Model)
            {
              @:console.log('name: ' + '@item.material.StoreName');
              @:materialname.push('@item.material.StoreName');

            } 
         }
       });
   </script>

When I run this code, it’s showed an incorrect string in console.
for example, StoreName in DB is:

enter image description here

but it is showed in console like this:

 name: &#x645;&#x62D;&#x635;&#x648;&#x644; &#x62F;&#x633;&#x62A;&#x647; AB &#x627;&#x646;&#x62F;&#x627;&#x632;&#x647; 5mm

How can I correct this and show a right encoding char?

react-pdf – production build produces minified JS file with improper require paths

I’m using react-pdf to render a PDF file from a web URL. The app works fine when doing local development, but fails to render when doing a production build. The root of the issue is that the pdf.min.worker.js file produced by the build has hard-coded file paths in its require statements that reference the file system of the machine that did the build. For example:

// Note: my local computer account is "administrator"
require("/Users/administrator/code/pdf-test/node_modules/@babel/runtime/helpers/defineProperty.js").default

Obviously, this causes the requires not to be found because they reference development paths in a production build. Does anyone know how to fix this?

Things I’ve tried

  • Everything mentioned in this issue and none of them have worked

Code

How do I get the data from an xhttp download to a string variable in Javascript and use it in my app

Here’s what I’m trying to do: NOAA offers data from public datasets on all kinds of climate data. What I am trying to do, in a javascript-only solution, is download the station and station metadata files from NOAA (plain text positional files), parse the metadata file for weather stations with the data I want (precipitation, daily max temps, min temps, and mean temps. From those data I can download the weather data from a station, and plot it using Plotly.

I’ve tried many different methods with xhttp, but I always end up in the same place. This is typical of my efforts:

<script>
    xhttpStation.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       stationData = xhttpStation.responseText;
    };

    xhttpStation.open("GET", "https://www.ncei.noaa.gov/pub/data/ghcn/daily/ghcnd-stations.txt", false);
    xhttpStation.send();
</script>

I can’t find a way to get from the .responseText to back outside the function and on my way with the data to make the dropdown select lists of the station ids. I have to be missing something, because the asynchronous nature of the xhttp call allows my code to fly on by without wating to get the data.

async function inside forEach [duplicate]

A newbie question – There is an async function inside a for loop and I want to keep collecting data and once done I want to use this information to do something. How do I perform this using a callback? I was able to achieve the same using async.whilist but I want to avoid it and understand basic callback better.

function kickoff() {
    xlData.forEach(function(data) {
                var ruleId = data.rule_id;
                asyncRequest(ruleId).then(function(result) {
                            results.push(result);
                });
    });
}

I want to avoid doing this

function kickoff() {
    async.whilst(
                function test(cb) {
                    cb(null, i<len);
                },
                function iter(callback) {
                    i++;
                    asyncRequest(ruleId).then(function(result) {
                                results.push(result);
                    });
                },
                function (err, result) {
                    //able to get stuff that I can work with
                    console.log(result.length);
                } 
    );  
}

How come the 2nd exit button is not fading in after clicking the 1st exit button?

The 1st exit button (.exitA) fades in without an issue.

The 2nd exit button (.exitB) should fade in after the curtain goes up.

It does not.

How do I fix this?

https://jsfiddle.net/8c4e129f/

.exitA,
.exitB {
  opacity: 0;
  transition: opacity 3s ease-in;
  transition-delay: 0s;
  pointer-events: none;
}

.exitA.visible,
.exitB.visible {
  opacity: 1;
  pointer-events: auto;
  cursor: pointer;
}




function showExit(containerSelector, exitSelector) {
    const container = document.querySelector(containerSelector);
    const closeButton = document.querySelector(exitSelector);
    container.classList.remove("hide");
    container.classList.add("slide");
    container.addEventListener("transitionend", function() {
      closeButton.classList.add("visible");
    });
  }


  function removePlayer() {
    videoPlayer.destroyPlayers();
  }

  function resetPage() {
    hideContainer(".video-containerA");
    // showContainer(".video-containerB");
    showExit(".video-containerB",".exitB");
    removePlayer();
  }

Javascript how to return native string symbol iterator when string not include “!”?

I have meet some problem , i want to return native string symbol iterator when string not include “!”

Object.defineProperty(
    String.prototype,Symbol.iterator,
                {
    writable: true, configurable: true, enumerable: false,
    value: function iterator(){
   
    var i, inc, done = false,str=this

    return {
   
    next() {

    if((str).includes("!")){
      do custom iterator
    }else {
        return native string iterator
    }
     } };
    } }
    ); 

Any pepole can help , thanks!

How to reload a site that was previously opened in js

im trying to refresh a url that is opened until it is canceled by the user manually

This is the actual code that i used – Used for an exploit in most chrome blocking extensions that unblock a website after cancel. your text

<html>
<script>

let site = prompt("Site?")
let open_site = window.open(site)
while (true)  {
window.open_site.reload()
}

</script>
</html>

Using Node.js, fetching a webpage is different from on the browser

I am trying to use fetch on Node.js, to fetch the page: https://finance.yahoo.com/quote/META

I can see on the browser it is at a price of $443.29

Also if I use view-source:https://finance.yahoo.com/quote/META on the browser and set Disable JavaScript to ON on Google Chrome’s dev tool, I can see the following content:

data-field="regularMarketPrice" data-trend="none" data-pricehint="2"
data-value="443.29" active><span>443.29

However, if I do a fetch using Node.js, or even if I go to Chrome’s dev tool and the Network tab, and reload the page, and then right click on the first network resource, and right click and choose

Copy -> as fetch (Node.js)

I can get the equivalent of what Google Chrome used:

    fetch("https://finance.yahoo.com/quote/META", {
          headers: {
            accept:
              "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language":
              "en",
            "cache-control": "max-age=0",
            "sec-ch-ua":
              '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"macOS"',
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1",
          },
          referrerPolicy: "no-referrer-when-downgrade",
          body: null,
          method: "GET",
          mode: "cors",
          credentials: "include",
        });

However, I tried to do a JS match, and cannot get the 443.29 string, but instead, keep on getting this:

Fz(36px) Mb(-4px) D(ib)" data-symbol="META" data-test="qsp-price" 
data-field="regularMarketPrice" data-trend="none" data-pricehint="2" 
value="511.9" active="">511.90

and $511.9 was the price as of 2, 3 days ago. What is the correct way to get the price (even if it is delayed 20 minutes or a couple of hours, but not for a couple of days).

The Node.js I am using is v20.10.0, which should be quite update.

P.S. to make it into a runnable program, the following can fetch the data and match the price:

const fetch = require("node-fetch");

fetch("https://finance.yahoo.com/quote/META", {
  headers: {
    accept:
      "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "accept-language": "en",
    "cache-control": "max-age=0",
    "sec-ch-ua":
      '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "sec-fetch-dest": "document",
    "sec-fetch-mode": "navigate",
    "sec-fetch-site": "same-origin",
    "sec-fetch-user": "?1",
    "upgrade-insecure-requests": "1",
  },
  referrerPolicy: "no-referrer-when-downgrade",
  body: null,
  method: "GET",
  mode: "cors",
  credentials: "include",
})
  .then((res) => res.text())
  .then((data) => console.log([...data.matchAll(/511..{30}/g)]));

and it will show the price match for 511. but not if I change the 511 to 443 — then it will not be able to match anything. (note that because the price change, so you may need to change to the prices later on, or you can change the last line to:

  .then((data) =>
    console.log([...data.matchAll(/36px.*regularMarketPrice.{80}/g)])
  );

instead.

Tring to build an autocomplete input for a weather desktop app

I am trying to build a weather app for a self-guided Vanilla JavaScript course. I have successfully fetched the code for the API from the accuWeather website, but I can’t figure out how to display it. I am trying to make it so that when the user types any letter onto the search bar, it’ll open a drop-down of some sort displaying cities that start with that letter. When I console.log it on the forecast.js file, I am able to get back those cities by applying this method:

data.forEach(city => console.log(`${city.AdministrativeArea.LocalizedName}, ${city.Country.LocalizedName}`))

and setting a random string-letter inside the function getAutoCities().

here is what I have so far:

forecast.js file (Here is where I fetch the information from the API):

    const key = 'P7USqIWPhyor91rmlvOTcRaMyMgwfrfrg'

//get Autocomplete List
const getAutoCities = async (search) => {
    const base = 'http://dataservice.accuweather.com/locations/v1/cities/autocomplete';
    const query = `?apikey=${key}&q=${search}`

    const response = await fetch(base + query);
    const data = await response.json();

    return data;
};

This top part is a separate JS file I made to fetch the API. The bottom one is my app code.

app.js (The code for the app):

const cityForm = document.querySelector('form');
const card = document.querySelector('.card');
const details = document.querySelector('.details');
const time = document.querySelector('.time');
const icon = document.querySelector('.icon img');
const inputField = document.querySelector('input');
const autofill = document.querySelector('.autocomplete')

const updateUI = (data) => {

    //destructure properties
    const {cityDets, weather} = data;
    

//update details template
    details.innerHTML = `
    <h5 class="my-3">${cityDets.EnglishName}</h5>
    <div class="my-3">${weather.WeatherText}</div>
    <div class="display-4 my-4">
        <span>${weather.Temperature.Imperial.Value}</span>
        <span>&deg;F</span>
    </div>
    `;


    //update day.night & icon images
    const iconSrc = `img/icons/${weather.WeatherIcon}.svg`;
    icon.setAttribute('src', iconSrc);

    let timeSrc = weather.IsDayTime ? 'img/day.svg' : 'img/night.svg';

    time.setAttribute('src', timeSrc);

    //remove the d-none if present
    if(card.classList.contains('d-none')) {
        card.classList.remove('d-none');
    }


}

const updateCity = async (city) => {

    const cityDets = await getCity(city);
    const weather = await getWeather(cityDets.Key);

return {cityDets, weather};

};


cityForm.addEventListener('submit', e => {
    e.preventDefault();

    //get city value
    const city = cityForm.city.value.trim();
    cityForm.reset();


    //update UI with new city
    updateCity(city)
     .then(data => updateUI(data))
     .catch(err => console.log(err));
});

Where and how would I insert the code to show the data I fetched from the api?

Why is JavaScript two-sided string literal interpolation not quadratic?

In JavaScript, why is this classic quadratic-append not O(n²)?

s = "";
for (i = 0; i < 1000000; i++) {
  s = `( ${s} )`
};
console.log(s.length)

It’s O(n) in both Firefox 124 and Chromium 123.

In Python, it’s O(n²) as expected:

s = ""
for i in range(50_000):  # increase by 2x, gets 4x slower
  s = f"( {s} )"
print(len(s))

What is this magic, how are browsers cheating here?
Is that behaviour guaranteed by the ECMAScript spec?

I wanted to get a array of objects in a flat sturcture for the parent it’s child and it’s grand child and it’s great grandchild and so on

I have an array of objects like below
[{Portfolio:”AMBAL”,
Level:1,
Immediate Parent:””},
{Portfolio:”AMBAL-PI”,
Level:2,
Immediate Parent:”AMBAL”},
{Portfolio:”AMBAL-FI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2213AMBAL”,
Level:3,
Immediate Parent:”AMBAL-FI”},
{Portfolio:”2132AMBAL”,
Level:3,
Immediate Parent:”AMBAL-PI”}….]

I have just gave example of level 3 but it could may have more also….

Expected o/p

[{Portfolio:”AMBAL”,
Level:1,
Immediate Parent:””},

{Portfolio:”AMBAL-FI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2213AMBAL”,
Level:3,
Immediate Parent:”AMBAL-FI”},

{Portfolio:”AMBAL-PI”,
Level:2,
Immediate Parent:”AMBAL”},

{Portfolio:”2132AMBAL”,
Level:3,
Immediate Parent:”AMBAL-PI”}

]
Return the above array of objects using javascript only

Why am I getting the error ‘Cannot read property ‘title’ of undefined’ after including a function in a useEffect hook?

I’m using a useEffect hook which includes a delete function in it. Before including the delete function in the useEffect hook my code was working fine and I was able to navigate between different object data without any worries. Since calling the function in the hook I get the error ‘Cannot read property ‘title’ of undefined’

I have tried to use a useCallBack hook incase the function variables change through user interaction and I’ve also included default values for the object, index for each object in the array and object properties in case some of these values were not accessible to the useEffect hook during the initial render. Both efforts still produce the same error. Here is the relevant code:

//Default Values
 //Note list index use state.
  const [index, setIndex] = useState(0);
  //List of notes use state.
  const [noteList, editNoteList] = useState([
    {
      title: 'First Note',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
    {
      title: 'Test 2',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
    {
      title: 'Test 3',
      text: 'This is my first note on the app :)',
      expiry: new Date(),
    },
  ]);


const Timer = () => {
  const [isDatePickerVisible, setDatePickerVisible] = useState(false);
  //Index use state.
  const { index, setIndex } = useContext(IndexContext);
  //List of notes use states.
  const { noteList, editNoteList } = useContext(NoteListContext);
  //Set inital value of noteList if undefined.
  const initialNote = noteList[index] || {};
  //Set initial expiryDate to current date if initialNote.expiry is undefined
  const initialExpiryDate = initialNote.expiry || new Date();
  const [expiryDate, setExpiryDate] = useState(initialExpiryDate);
  //Set other states dependent on noteList[index] conditionally. Set initial title to an empty string if initialNote.title is undefinedSet initial title to an empty string if initialNote.title is undefined
  const [title, setTitle] = useState(initialNote.title || '');
  const [content, setContent] = useState(initialNote.content || '');

//Delete function and useEffect hook.
  //Delete note function using useCallback.
  const deleteNote = useCallback(() => {
    const noteListToEdit = [...noteList];
    noteListToEdit.splice(index, 1);
    editNoteList(noteListToEdit);
    saveNotes(noteListToEdit);
  }, [index, noteList, editNoteList]);

  useEffect(() => {
    const calculateTimeUnits = (timeDifference) => {
      const seconds = Math.floor(timeDifference / 1000);
      setTimeUnits({
        days: Math.floor((seconds % (365 * 24 * 60 * 60)) / (24 * 60 * 60)),
        hours: Math.floor((seconds % (24 * 60 * 60)) / (60 * 60)),
        minutes: Math.floor((seconds % (60 * 60)) / 60),
        seconds: seconds % 60,
      });
    };

    const updateCountdown = () => {
      const currentDate = new Date().getTime();
      const expiryTime = expiryDate.getTime();
      const timeDifference = expiryTime - currentDate;

      if (timeDifference <= 0) {
        calculateTimeUnits(0);
        deleteNote();
        //navigation.navigate('Recent Notes');
      } else {
        calculateTimeUnits(timeDifference);
      }
    };

    updateCountdown();

    const interval = setInterval(updateCountdown, 1000);

    return () => clearInterval(interval);
  }, [expiryDate, deleteNote]);

Fetch works but http post doesn’t in Angular ts file, what am I doing wrong?

I have this fetch statement below that works fine in my .ts file.

const fileResult = await fetch(environment.stripeFileUrl, {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer ' + environment.stripePublishableKey
  },
  body: data,
});
const fileData = await fileResult.json();

But when I write it like this below I get a status 401, status Text Ok, but an error that says my API key is incorrect.
Am I plugging in the header incorrectly?

New code that doesn’t work

this.accountService.getStripeIdentityToken(data).subscribe(response => {
  if (response.error) {
    this.showError(response.error.message);
  } else {
    this.outputFile.emit({
      file: response.id,
      description: null
    });
  }
}, error => {
  console.log(error);
}).add(() => {
  this.loading(false);
});



getStripeIdentityToken(data: any) {
  let headers = new HttpHeaders();
  headers = headers.set('Authorization', `Bearer ${environment.stripePublishableKey}`);
  // I also tried below with same error about the incorrect API key
  // headers = headers.set('Authorization', `Bearer pk_test_fTr...BVLn9e6`);

  return this.http.post<any>(environment.stripeFileUrl, data, {
    headers
  });
}

Textarea + hidden div or content editable div to use the Rect API?

I am making a text editor and I need to detect where browsers create line breaks due to element’s width limits. I found that the Rect API can be used for this purpose but it’s not compatible with textarea since it is a replaced element.

I have come to a split: Do I go with a textarea + a hidden div or a content editable div?

Textarea + hidden div:

Pros:

  • Easier to maintain
  • I can simply replicate its content with a hidden div with the same styling to be able to use the Rect API

Content editable div

Pros:

  • No need to maintain two elements

Cons:

  • More complicated to maintain
    • Need to replace div tags created by the return key with br tags

SQLITE_BUSY: database is locked | Sequelize Node Javascript

router.post("/update-quiz", upload.single("file"), async (req, res) => {
    const transaction = await sequelize.transaction();

    try {
        const actions = {
            "Multiple Choice": async (questions, transaction) => {
                const data = await MultipleChoice.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            },
            "Identification": async (questions, transaction) => {
                const data = await Identification.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            },
            "True or False": async (questions, transaction) => {
                const data = await TrueOrFalse.bulkCreate(questions, {transaction: transaction});
                return data.map(question => question.question_id);
            }
        };

        const deleteActions = {
            "Multiple Choice": async (questions_id, transaction) => {
                await MultipleChoice.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            },
            "Identification": async (questions_id, transaction) => {
                await Identification.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            },
            "True or False": async (questions_id, transaction) => {
                await TrueOrFalse.destroy({
                    where: {
                        question_id: {
                            [Op.or]: questions_id
                        }
                    }
                }, {transaction: transaction});
            }
        };

        const quiz = JSON.parse(req.body.quiz);
        const questions = JSON.parse(req.body.questions);

        if (Object.keys(actions).includes(quiz.type)) {
            const validator = {
                "Multiple Choice": validateMultipleChoice,
                "Identification": validateIdentification,
                "True or False": validateTrueOrFalse
            };
            const validations = getValidations(questions, quiz, validator[quiz.type]);
            if (validations.every(v => v.isValid)) {
                const previousQuiz = await Quiz.findOne({where: {quiz_id: quiz.quiz_id}}, {transaction: transaction});
                await deleteActions[previousQuiz.type](previousQuiz.questions_id.split("|"), transaction);
                const newQuestions = await actions[quiz.type](questions, transaction);

                let fileName = "";

                if (!req.file) {
                    fileName = `${quizImagePath}/${createDateForFile()}.png`;
                    createImage(300, 200, fileName, 30, "quizzy-quest");
                } else {
                    fileName = `${quizImagePath}/${req.file.filename}`;
                }

                await Quiz.update(
                    {
                        name: quiz.name,
                        description: quiz.description,
                        topic: quiz.topic,
                        type: quiz.type,
                        visibility:quiz.visibility,
                        questions_id: newQuestions.join("|"),
                        image_path: fileName
                    },
                    {where: {quiz_id: quiz.quiz_id}},
                    {transaction: transaction}
                );

                await transaction.commit();
                return res.status(201).json({message: "Quiz successfully updated."});
            } else {
                return res.status(400).json(validations.filter(v => !v.isValid).map(v => v.message));
            }
        } else {
            return res.status(400).json(["Invalid quiz type"]);
        }
    } catch (error) {
        await transaction.rollback();
        return res.status(500).json({error: error.toString()});
    }
});

The route is about updating the quiz (sequelize model) then remove the previous questions
(sequelize model) and add the edited/updated questions. I add transaction for data integrity. I debug where the SQLITE_BUSY error come from and it is in the Quiz.update. Please explain to me what is happening here why I am getting that error, how could I handle this problem. Any help would be appreciated.