Javascript – Trouble With Multiple Special Characters In String Replace

I have a long JSON string that, when parsed, is getting hung up on the following 3-character string: "{

I can’t seem to generate a Regular Expression (I seem to consistently struggle to understand RegEx’s) that searches for this string, since the itself keeps being interpreted as an escape character, and the " is looking for a matching, ending “.

e.g. I’ve been trying something like: string.replace('"{','');

Next.js – API call from different page is not loading the data

Hello everyone I am extremely new at the Next.js world.

I am using the getStaticProps() to make an API call and in order to make it little organized, i have created a separate page “git” under “pages” folder and here is my code:

function Git({ stars }) {
    return <div>Next stars: {stars}</div>
  }

export async function getStaticProps() {
    const res = await fetch('https://api.github.com/repos/vercel/next.js')
    const json = await res.json()
    return { stars: json.stargazers_count }
}

export default Git

And i am trying to load the API data to the index.js file under the “pages” folder.

Inside the index.js file, i am using below to load the API data from the “Git” page

import fetch from "isomorphic-unfetch"
import Git from './Git'

And under the following

render () {
    return (
    <Git />

On the browser, i am not seeing the API data but i am seeing the HTML from the “Git” page

<div>Next stars: </div>

Is there any way if i can load the API data from different page to the index.js page?

How to run an Electron application from source (not bundle)

I’m new to Electron, and trying to help maintain an application whose developer has left. The resources/app folder consists of (at least) three things:

  • The app/lib/bundle.js, which contains the entire application, bundled and minified. This is what the app seems to actually run.
  • Node modules for all the code written by the developer. These are in TypeScript, and are in the structure node_modules/@mainmodule/submodule/src/.../something.ts. Each of these also has a node_modules/@mainmodule/submodule/package.json and node_modules/@mainmodule/submodule/tsconfig.json
  • Finally, for each of these, a corresponding lib folder: node_modules/@mainmodule/submodule/src/.../something.js. The lib folder has Javascript corresponding to each of the TypeScript, as well as map files showing how they correspond. It is these Javascript files that are minified and included in the bundle, which is actually run.

The source TypeScript is relatively clear and I can follow most of it. But to really understand it I need to set breakpoints on it and run it in a debugger (e.g. VS Code). However, when running the app, Electron doesn’t run it from the TypeScript (in src), or even the individual Javascript (in lib), but rather from bundle.js. Bundle.js is a giant file that, besides being minified, is too big to even load properly in my editor.

My question

How can I tell Electron to run the app not from the bundle.js, but from the individual src/...ts TypeScript, or, failing that, from the individual src/...js JavaScript?

If that’s not possible, what is the proper way to use a debugger, given the source, when the Electron application is bundled? I have full source but, when I invoke Electron, it runs out of the bundle: how I can change this?

I’m new to Electron and Node, so if I’m making an elementary mistake, please clarify.

element manipulation in react

So I have a series of code where a button in the Header.jsx file that if clicked, it will display the content of the Notification.jsx file. The problem here is, I don’t exactly know how can I display the content of Notification.jsx in index.js. I tried using conditional statements and is it possible to hide the h1 element once the button is clicked?

Header.jsx

import React from "react";
import { Button } from "@mui/material";
import { IconButton } from "@mui/material";
import NotificationsIcon from "@mui/icons-material/Notifications";
import SearchIcon from "@mui/icons-material/Search";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import FullNotifList from "./FullNotifList"
export default function Header() {
  const [anchorEl, setAnchorEl] = React.useState(null);
  const open = Boolean(anchorEl);
  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  return (
    <div>
      <Button
        id="basic-button"
        aria-controls={open ? "basic-menu" : undefined}
        aria-haspopup="true"
        aria-expanded={open ? "true" : undefined}
        onClick={handleClick}
      >
        <IconButton>
          <NotificationsIcon />
        </IconButton>
      </Button>
      <Menu
        id="basic-menu"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        MenuListProps={{
          "aria-labelledby": "basic-button",
        }}
      >
        {/* Button needs to be clicked in order to display Notification.jsx */}
        <Button variant="contained">Notification Center</Button> 
        <MenuItem onClick={handleClose}>Profile</MenuItem>
        <MenuItem onClick={handleClose}>My account</MenuItem>
        <MenuItem onClick={handleClose}>Logout</MenuItem>
      </Menu>

      <IconButton>
        <SearchIcon />
      </IconButton>
    </div>
  );
}

Notification.jsx

import React from "react";

export default function Notification(){
    return(
        <div>
            <ul>
                <li> Hello </li>
                <li> Hello </li>
                <li> Hello </li>
                <li> Hello </li>
            </ul>
        </div>
    )
}

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import Header from './Header'
import './index.css'
import Footer from './Footer';
import Notification from './Notification';

export default function Page(props) {
    const [isClicked, setIsClicked] = React.useState(false)
    function showHide(e) {
        setIsClicked(true)
    };

    return(
        <div className='main'>
            <Header onClick={showHide}/>
                {isClicked && <Notification />}
                <h1> Sample body </h1>
            <Footer />
        </div>
    )
}

ReactDOM.render(
    <Page />,
  document.getElementById('root')
);

Here is the sandbox link: https://codesandbox.io/s/friendly-darkness-9u5s22?file=/src/index.js

How to query/update a self-relation in Prisma?

I have some self-relation tables taken directly from one of Prisma’s examples.

model User {
  id         Int       @id @default(autoincrement())
  name       String?
  followedBy Follows[] @relation("follower")
  following  Follows[] @relation("following")
}

model Follows {
  follower    User @relation("follower", fields: [followerId], references: [id])
  followerId  Int
  following   User @relation("following", fields: [followingId], references: [id])
  followingId Int

  @@id([followerId, followingId])
}

I am wondering on the best/most idiomatic way to determine whether a user is following another user, as well as operations for following and unfollowing. I’m thinking the best way is to just query/update the Follows table directly, but I’m unsure whether the followedBy and following fields in the User model will automatically update themselves.

Javascript: using xml id attributes to getElementById

I’m trying to get getElementById to work with an XML structure. In this case, I am creating web pages based on two xml files: positions and personnel. I create a logical link between them by using a modified “person’s name” (with bl
anks replaced by underscores and apostrophes & periods removed) as the incumbent in the position file. The same thing is set as an id attribute in the personnel file.

The dtd for the personnel file is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE people [
   <!ELEMENT person (name, email?, bio, telephone*)>
        <!ATTLIST person id ID #REQUIRED > 
        <!ELEMENT name              (#PCDATA)>
        <!ELEMENT email (email-name, email-domain)>
            <!ELEMENT email-name    (#PCDATA)>
            <!ELEMENT email-domain  (#PCDATA)>
        <!ELEMENT bio (photo, p*, li*)>
            <!ELEMENT photo         (#PCDATA)>
            <!ELEMENT p             (#PCDATA)>
            <!ELEMENT li            (#PCDATA)>
        <!ELEMENT telephone (tel-type, tel-area, tel-num, tel-ext?)>
            <!ELEMENT tel-type      (#PCDATA)>
            <!ELEMENT tel-area      (#PCDATA)>
            <!ELEMENT tel-num       (#PCDATA)>
            <!ELEMENT tel-ext       (#PCDATA)>
 ]>

The data gets loaded into peopleList but

var incumbentDetails = peopleList.getElementById(curIncumbent);

fails. I’ve verified that curIncumbent contains the correct (and valid) information and checked for duplicate ids (there aren’t any). I’ve verified that I’ve loaded the correct number of “person” elements.

What I haven’t found in my searching is a sample DTD that actually shows an ID attribute in a full defined DTD. I suspect the issue may be in the DTD but it’s hard to tell if I’m making progress when the function only fails.

Any help would be appreciated.

A bookmarklet that floods the page with ants I tried to use failed to work

I was looking around to find some bookmarklets that would waste my time, and I came across this cool ants bookmarklet from here:

https://www.cs.huji.ac.il/~irush/projects/ants.html

However, when I tried to run it as a bookmarklet, the ants wouldn’t show up. Here is the bookmarklet below for reference:

javascript:document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).setAttribute('src','http://www.cs.huji.ac.il/~irush/scripts/antsbml.js');

svg stroke-dashoffset animation with percentage values

I have been successful in animating stroke-dashoffset with value as <length> as folllowing

const svg = document.querySelector("svg");

// variable for the namespace 
const svgns = "http://www.w3.org/2000/svg"

//assigning svg element attribute 
svg.setAttribute('class', 'layer1');
svg.setAttribute('xmlns', svgns);
svg.setAttribute('viewBox', '0 0 400 200');

//make background
var fill1 = '#e6e6e6';

let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('width', '400');
bg.setAttribute('height', '200');
bg.setAttribute('fill', fill1);

svg.appendChild(bg);

//wrapper dimension
var x = 20;
var y = 50;
var width = 200;
var height = 50;

let wrapper = document.createElementNS(svgns, 'rect');
wrapper.setAttribute('class', 'wrapper');
wrapper.setAttribute('id', 'wrapper');
wrapper.setAttribute('x', x);
wrapper.setAttribute('y', y);
wrapper.setAttribute('width', width);
wrapper.setAttribute('height', height);
wrapper.setAttribute('fill', 'none');
wrapper.setAttribute('stroke', 'black');
wrapper.setAttribute('stroke-width', '1');

svg.appendChild(wrapper);

let tube = document.createElementNS(svgns, 'line');
tube.setAttribute('class', 'tube');
tube.setAttribute('id', 'tube');
tube.setAttribute('x1', x);
tube.setAttribute('x2', x + width);
tube.setAttribute('y1', y + height / 2);
tube.setAttribute('y2', y + height / 2);
tube.setAttribute('stroke', 'brown');
tube.setAttribute('stroke-width', '1');

svg.appendChild(tube);

var possibleNumbers2 = [];

var ln = document.querySelector("#tube");
var path = ln.getTotalLength();
var halfPath = path / 2;
var temp = [];

ln.style.setProperty("--off", path + 'px');

var pct = 0.60;
var pxl = path - (path * pct);

ln.style.setProperty('--offset', pxl);

ln.style.setProperty('--v1', (path / svg.viewBox.baseVal.width) * 100 + '%');
ln.style.setProperty('--v2', (pxl / svg.viewBox.baseVal.width) * 100 + '%');

let mid = document.createElementNS(svgns, 'line');
mid.setAttribute('class', 'mid');
mid.setAttribute('id', 'mid');
mid.setAttribute('x1', x + width / 2);
mid.setAttribute('x2', x + width / 2);
mid.setAttribute('y1', y);
mid.setAttribute('y2', y + height);
mid.setAttribute('stroke', 'red');
mid.setAttribute('stroke-width', '.5');

svg.appendChild(mid);

var gridNum = 10;
var gridStart = width / gridNum;
var counter = gridStart;

for (var i = 0; i < gridNum; i++) {
    let ln = document.createElementNS(svgns, 'line');
    ln.setAttribute('class', 'axisLines' + i);
    ln.setAttribute('id', 'axisLines' + i);
    var x1 = x + counter;
    ln.setAttribute('x1', x1);
    ln.setAttribute('x2', x + counter);
    ln.setAttribute('y1', y);
    ln.setAttribute('y2', y + height);
    ((gridNum / 2) - 1) == i ? ln.setAttribute('stroke', 'red') : ln.setAttribute('stroke', 'green');
    ln.setAttribute('stroke-width', '1.5');
    svg.appendChild(ln);
    counter = counter + gridStart;

    let tl = document.createElementNS(svgns, 'title');
    ((gridNum / 2) - 1) == i ? tl.textContent = `Middle Coordinate ${x1-x},${y}` : tl.textContent = `Coordinate ${x1-x},${y}`;
    svg.appendChild(tl);
    ln.appendChild(tl);


}
.tube {
    stroke-dasharray: var(--off);
    stroke-dashoffset: var(--off);
    animation: effect 4s ease-out infinite forwards;
}

@keyframes effect {
    100% {
        stroke-dashoffset: var(--offset);
    }
}
<!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>Document</title>
</head>

<body>
    <link rel="stylesheet" href="style.css">
    </link>
    <svg>
    <script href="index.js"></script>
</svg>
</body>

</html>

However, I am trying to figure out how can I calculate the exact % value in css if I decide to use <percentage> instead of value.

I came to know from this post that percentages are calculated in respect to the current viewport, which I tried as
ln.style.setProperty('--v1', (path / svg.viewBox.baseVal.width) * 100 + '%');

and

ln.style.setProperty('--v2', (pxl / svg.viewBox.baseVal.width) * 100 + '%');

But passing on the above to CSS does not produce the same animation

.tube {
    stroke-dasharray: var(--v1);
    stroke-dashoffset: var(--v1);
    animation: effect 4s ease-out infinite forwards;
}

@keyframes effect {
    100% {
        stroke-dashoffset: var(--v2);
    }
}

FormData returning as empty object when trying to upload file in react

I am trying to send a file from my React client to my Flask server.

State that holds file

  const [fileToUpload, setFileToUpload] = useState(null)

form

          <React.Fragment>
            <p className='margin-top' style={pStyles}>Attach your file</p>
            <form onSubmit={handleFileUpload} encType='multipart/form-data'>
              <input
                multi='false'
                type='file'
                onChange={(e) => handleSetFileValues(e)}
              />
              {currentCheck === 'file-radio' ? (
                <button type='submit' className='btn-blue'>Upload</button>
              ) : (
                null
              )}
            </form>
          </React.Fragment>

handleSetFileValues

  const handleSetFileValues = (e) => {
    setFileToUpload(e.target.files[0])
    setFileUrlToUpload('')
  }

handleFileUpload

  const handleFileUpload = async (e) => {
    // if (fileTitle === '' || fileToUpload !== null) return;
    e.preventDefault()

    const formData = new FormData();
    formData.append("file", fileToUpload);

    const { data, success, errorMessage } = await addServiceFile(service.id, formData, fileTitle)
    if (success) {
      console.log('res', data)
    } else {
      console.log('ERROR', errorMessage)
    }
  }

Upon submision I recieve a 400 res from the server. Logging formData shows an empty object, and the file object in the req payload is an empty object as well. any advice here would be great.

addServiceFile

export async function addServiceFile(serviceId, fileToUpload, fileLabel) {
  try {
    const body = {
      file: fileToUpload,
      file_label: fileLabel
    };

    return await awsApiRequest({
      method: 'POST',
      path: `/service/${serviceId}/file-data`,
      params: {
        body: body,
      },
    });
  } catch (error) {
    return error;
  }

Cloudnary Product gallery widget does not render files and causes page to hang and freez

When I try to integrate the product gallery widget using plain JS, it causes the whole page and browser to freeze. Please, I need urgent help with this issue – we just deployed our App and all our image resources are using Cloudinary service.

I tried reading their documentation and it seems to work on their platforms – but yet fails when I run the code on my local machine or when deployed code runs on my website file.

Here is the code used [cloudname has been replaced for demo purposes]

<div id="gallery_div" style="max-width:90%;margin:auto"></div>
var myGallery = cloudinary.galleryWidget({
 container: "#gallery_div",
 cloudName: "myCloudNameHere",
 mediaAssets: [{ tag: "item_id_8" }],
 carouselStyle: "thumbnails",   // default value: included for clarity
 carouselLocation: "left",     // default value: included for clarity
 viewportBreakpoints: [
   { breakpoint: 600, carouselStyle: "thumbnails", carouselLocation: "bottom" },
   { breakpoint: 300, carouselStyle: "indicators", carouselLocation: "bottom", navigation: "always" } ]
});
myGallery.render();

Uncaught TypeError: Failed to execute ‘appendBuffer’ on ‘SourceBuffer’: Overload resolution failed

I want to make video streaming with vanilla js and websocket. I can easily create media recorder and get user video data as ArrayBuffer and send it but problem is I couldn’t append SourceBuffer due to this error
enter image description here

This is my code for getting arrayBuffer during websocket.onmessage and appending SourceBuffer. Error happens during append.

const video2 = document.getElementById('video2')
const mimeCodec = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';


if ('MediaSource'in window && MediaSource.isTypeSupported(mimeCodec)) {
    var mediaSource = new MediaSource();
    mediaSource.addEventListener('sourceopen', sourceOpen);
    video2.src = URL.createObjectURL(mediaSource);
    console.log("mediaSource.readyState"); // closed
} else {
    console.error('Unsupported MIME type or codec: ', mimeCodec);
}

function sourceOpen(_) {
    if (MediaSource.isTypeSupported(mimeCodec)) {
        console.log("yes it is supported")
    }
    const mediaSource = this;
    const sourceBuffer = mediaSource.addSourceBuffer(mimeCodec);
    sourceBuffer.mode = "sequence";
    
    streamsocket.onmessage =  (buf) => {
        sourceBuffer.addEventListener('updateend', function(_) {
            mediaSource.endOfStream();
            video2.play();
        });
        sourceBuffer.appendBuffer(buf);
    }
    
}

This is how i am sending array buffer in here everything works very well.

static registerStream =  (userdata , stream, streamsocket) => {
        const mediaRecorder = new MediaRecorder(stream)
        let countUploadChunk = 0
        console.log(stream)
        mediaRecorder.ondataavailable =  (data) => {
            Streaming.sendData(data.data, streamsocket, userdata, countUploadChunk)
            countUploadChunk++
        }
        
        mediaRecorder.start()

        setInterval(() => {
            mediaRecorder.requestData()
        }, 500)
    }

    static sendData = async (data, streamsocket, userdata, chunkNumber) =>{
        let reader = new FileReader();
        let rawData = new ArrayBuffer();            
        reader.loadend = function() {}
        reader.onload = function(e) {
            rawData = e.target.result;
            streamsocket.send(rawData)
        }
        reader.readAsArrayBuffer(data);
    }

best way to assign fetch response value to a variable [duplicate]

I searched entire stackoverflow for answer and almost all of them are either wrong or don’t work in a way I wanted (I mean actually assign to a variable).
Thanks to How to store fetch response in javascript variable I found the only real working solutions to question how to assign a fetch response to a variable.
But, Andrew provided two working answers:

import fetch from 'node-fetch'
------------------------------

async function fun() {
return fetch('https://api.exchangerate.host/2022-03-15?symbols=EUR&base=USD').then(res => res.json())
}
const data = await fun()
console.log(data)

//or

const fun = async () => {
const response = await fetch('https://api.exchangerate.host/2022-03-15?symbols=EUR&base=USD')
return response.json()
}
const data = await fun()
console.log(data)

So… which one is better? Which one should I use?

Saving a floating value to a google sheet using a script

I want to use google script to make a request and save some data on google sheet.
The problem is when I try to pass some non integer values as parameters in the request.
I think it’s something to do with the fact that sheets uses comma for separating decimal from integer while my program sends the numbers separated by a dot.

This is where I am now:


const doPost = (event) => {
  console.log(`doPost`, JSON.stringify(event));

  const { parameter } = event;
  const { temp, peso } = parameter;
  var date = new Date();

  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.appendRow([date, parseFloat(temp), peso]);
}

When I make a post request with parameters: { temp:1.234, peso:1.234 } the result on google sheet is a big mess.

Does someone have any idea how to fix this?

Shopify asset not loading

I am trying to include a JavaScript file (named StoreLocator.js) from my Shopify assets by using the URL filters as explained in the Shopify documentation (see https://shopify.dev/api/liquid/filters/url-filters).

First of all, I uploaded the JavaScript file to the assets folder. I noticed during debugging that the uploaded JavaScript file is accessible under the following URL:

https://cdn.shopify.com/s/files/1/0551/8009/9636/t/6/assets/StoreLocator.js

I was able to debug this, because I used the same JavaScript file and the same URL filter in a previous project and it worked just fine. Therefore I could see, that Shopify uses this URL to load the JavaScript file.

However, by using the following URL-filter in the new project.

{{ 'StoreLocator.js' | asset_url | script_tag }}

it generates the following URL which is incorrect (note the part /t/6 vs /t9.

https://cdn.shopify.com/s/files/1/0551/8009/9636/t/9/assets/StoreLocator.js

Unfortunately I could not find any documentation about the URLs that the Shopify CDN generates. In the present case it would be interesting to know why the URL changed from /t/6 to /t9.

Can someone explain why the URL filter does not point to the correct URL?