replace a string in json object inside a json object

I have a Json object

const mainString = {
  bool: {
    should: [{
      nested: {
        path: "employee",
        query: {
          bool: {
            must: [NAME_QUERIES]
          }
        }
      }
    }, NICK_NAME_QUERIES],
    minimum_should_match: 1
  }
}

where NAME_QUERIES and NICK_NAME_QUERIES are json object and is input from user.
for example:

NAME_QUERIES = [{
  multi_match: {
    query: "fname1 lname1",
    fields: ["employee.name"],
    type: "phrase"
  }
}, {
  multi_match: {
    query: "fname2 lname2",
    fields: ["employee.name"],
    type: "phrase"
  }
}]

NICK_NAME_QUERIES = [{
  multi_match: {
    query: "fname1 lname1",
    fields: ["employee.nickName"],
    type: "phrase"
  }
}, {
  multi_match: {
    query: "fname2 lname2",
    fields: ["employee.nickName"],
    type: "phrase"
  }
}]

How can i replace NAME_QUERIES and NICK_NAME_QUERIES in mainString ?

I want o/p of mainString like below

{
  bool: {
    should: [{
      nested: {
        path: "employee",
        query: {
          bool: {
            must: [{
              multi_match: {
                query: "fname1 lname1",
                fields: ["employee.name"],
                type: "phrase"
              }
            }, {
              multi_match: {
                query: "fname2 lname2",
                fields: ["employee.name"],
                type: "phrase"
              }
            }]
          }
        }
      }
    }, {
      multi_match: {
        query: "fname1 lname1",
        fields: ["employee.nickName"],
        type: "phrase"
      }
    }, {
      multi_match: {
        query: "fname2 lname2",
        fields: ["employee.nickName"],
        type: "phrase"
      }
    }],
    minimum_should_match: 1
  }
}

NAME_QUERIES can contain N number of multi_match’s, just added 2 for above example

I tried to directly add NAME_QUERIES and NICK_NAME_QUERIES in the string, but it adds [] .
Also I tried to use jsonStringify and then used the variable, then it added for all the fields double quotes like (“multi_match”) where as i want for keys no quotes.

Is there any simple way to replace them without [] in the main string ?

Modal window for all div’s with the same class

I tried to create a modal window for all div’s with the same class located in an associative array from php

Using an associative array, I displayed product cards, when I click on “More details” I want to get a modal window with a description of the product

Please help me, I’m just starting to learn programming languages, maybe my code is flawed, I’m sorry.

<div class="card">
  <div class="name"><?php echo $fish['name']; ?></div>
  <div class="price"><?php echo $fish['price']; ?></div>
  <button id="myBtn" class="button-intro">Подробнее</button>
  <div id="myModal" class="modal">
     <div class="modal-content">
         <div class="img-wrap"><img src="<?php echo $fish['img']; ?>"alt=""></div>
         <div class="wrapper-block">
             <div class="name-close">
                 <div class="name-block"><?php echo $fish['name']; ?></div>
                 <button id="close" class="btn-close">&times;</button>
             </div>
             <div class="description-shelf">
                 <div class="description-block"><p>Описание</p></div>
                 <div class="shelf-block"><p>Срок годности:<?php echo $fish['shelf']; ?></p></div>
             </div>
             <div class="description"><p><?php echo $fish['description']; ?></p></div>
         </div>
     </div>
  </div>
</div>

const mod = document.querySelectorAll('.modal');
const but = document.querySelectorAll('.button-intro');
const bclose = document.querySelectorAll('.btn-close');
but.onclick = () => {
    mod.style.display = "block";
}
bclose.onclick = () => {
    mod.style.display = "none";
}
window.onclick = function(event) {
    if (event.target == mod) {
        mod.style.display = "none";
    }
}

There are 6 products in my array, but when I click on the button, the function only works on one product

Button is not destroyed when class is deinstantiated

I’m using P5.js to create two scenes

A global variable currentScene instantiates the Scene to be rendered.

Then I have two scene classes:

  • A MainMenuScene, with a button New Game that instantiates CombatScene
  • A CombatScene where I will render my game.

Now, the button New Game is creates inside the class MainMenu, so when currentScene no longer points to MainMenuScene, I’d expect the instance to be garbage collected, and since the button is an attribute of the class, I’d expect it to also be garbage collected.

However, it looks like although the scene correctly changes to CombatScene (red background) the button remains there.

Why does it remain there, and how can I get rid of it?

class MainMenuScene {
  constructor() {

    // button is an attribute of the class, 
    //so when the instance of theclass is garbage collected 
    // it should disappear, but it doesn't
    this.button = createButton("New Game");
    this.button.position(100, 100);
    this.button.mousePressed(() => {

      // here currentScene changes to CombatScene, so the instance of
      // MainMenuScene should be garbage collected, right?
      currentScene = new CombatScene();
    });
  }
  show() {
    background("blue");
  }
}

class CombatScene {
  constructor() {}
  show() {
    background("red");
  }
}

let currentScene;


function setup() {
  createCanvas(400, 400);
  currentScene = new MainMenuScene();
}

function draw() {
  currentScene.show();
}

What are the general steps to setup/run a .js transpiled language in vs code?

Specifically, I would like to setup/run Neo, the educational, JavaScript transpiled language that Douglas Crockford introduced/implemented in his book “How JavaScript Works”.

He provides specific program files, e.g. ‘neo.tokenize.js’, ‘neo.parser.js’, ‘neo.codegen.js’, ‘neo.runtime.js’ and other files from the book at https://github.com/douglascrockford/howjavascriptworks.

I would appreciate any guidance and suggestions. Thank you!

How to add a help button to each option of select multiple?

I have a selectMultipleField from Flask WTForms. Each option is a user-specified group of multiple values, and right now the user only sees the group name. I would like to add a button on the right of each option, that would alert all the values of that group when clicked.

Creating a button and appending it to each respective option works, but the buttons are not clickable, I think because of being appended. Clicking the button just selects the option. Is there a way to make this work? Thanks.

Here’s what I have now:
SelectMultipleField with help buttons

I couldn’t publish the HTML code with the Javascript in WordPress [closed]

I have been trying to add Affiliate HTML code to my blog site. I copy pasted the code from Klook site and pasted in HTML code blocks. But after pasting the code, the wordpress editor shows the preview of the code within the block but not on the actual page. When I hit publish it throws errors such as – The response is not a valid JSON reponse, Server error(403 error), the firewall like cloudfare etc., in your site is’t allowing to publish.

I tried again by removing the script tag, by this way it allows me to publish the code. Kindly help to solve this issue. Fyi: I am not a pro in coding.

Django link table row to detail view with buttons to other views

Hey thanks in advance for any help its always much appropriated. So I found this post on here that help do this and it worked great. So i have my table and when you click a row it goes to the right detail view for that row. What i would also like to do is have a column in the table with a button for delete and one for edit for each row. I was able to add the buttons but it looks like the JS code that makes the rows clickable is overriding the buttons. without the JS code the buttons work. Any guidance on what to look up or helpful terms to make the rows clickable and and buttons not be lumped into it.

Sorry I’ve very new to this in general and especially inexperienced in javascript

I tested with the rows not clickable (no javascript) and the buttons that are in work and go to the intended view.

I also tried moving data-href="{% url 'detail' part.pk %}"the tag in the html the Table tag. this made a single cell clicked as expected (not what i want) but the buttons become clickable again but don’t route properly. I think this has to do with the JS code handling the routing for

Maps Advanced Markers – Change marker image after marker has been created

Has anyone managed to completely change the marker image ‘on-the-fly’, as in, after the marker has already been created.

I had this all working in the ‘normal’ addMarker situation, but due to the ‘informational message’ I got in my developer console about this function beind depricated starting from the 21st of Febuari, I’m trying my luck with the Advanced Markers.

I’ve got a map that has customized markers all over the place, and these marker images were changed ‘on-the-fly’ according to a situation as either a green dot as ‘everything ok’ or a red-pin with animated siren indicating a malfunction, which I used to change with the setIcon method. This method is not available with the Advanced Markers, and an instructional video mentions that the Advanced Markers are added as DOM HTML Elements, and one should be able to ‘manipulate it as one would do any DOM HTML Element’, but I seem to be unable to manage it.

All my markers are added to an array object, so accessing its properties shouldn’t be an issue.

I simply create an image object and feed the url to the image to its .src, the same way as instructed when creating a marker with a customized image.

const MarkerIcon = document.createElement("img");
MarkerIcon.src = <whatever url to img.png>;

if I take a sneekpeak with ‘console.log(MarkerIcon);’, I see that it has the exact same content as ‘console.log(marker.content’);’ in which the image has been stored during creation, but I simply don’t get how to feed it to the marker.

I’ve tried:

marker.content(MarkerIcon);
marker.content.InnerHTML = MarkerIcon;

and also, as a desperate attempt in the hopes it might use the same method as a new InfoWindow:

marker.content.SetContent(MarkerIcon);

The only thing so far that actually changes things up, but I know is not the way to do it, is:

marker.content = MarkerIcon;

This however changes every single marker to the ‘default redpin from google maps’, instead of my custom marker.

It might be something completely simple, and I might be overlooking it, but any assistance would be appriciated, as the documentation about the Advanced Marker is rather lacking in this aspect imo.

Thanks in advance.

I’ve read various documentation and crawled through an abundance of JSFiddles, which unfortunately all only showed the custom image during creation, no afterwards manipulation.

Images not showing up on Safari, and on IPhone

I am creating a photo gallery for a friend of mine and when I use safari to test my site, the images simply do not work. When I use any other web browser, the images show up. However, on iPhone every single browser I tried did not display the images. I am using Imagekit to store the images and to get the images to display them since the photos are very big.

Left side is chrome, right side is safari

The GitHub is https://github.com/jchin9607/photogalleryjs

I think image kit is the problem because when I just use local pngs it works regardless of the browser, However it could be anything.

how to set headers in axios for a single request?

Okay so i have a log in route on my backend that i am calling with axios on the frontend. I know how to set headers globally with axios, but i need to know how to set it for individual requests as the examples i’ve seen haven’t addressed my issue.

This is the axios request:

const {data} = await axios.post('/auth/login', {email,password}, {
  headers: {
    'Authorization': `Bearer ${the-token}`
  }
})

So i understand that this is how it goes, however, my dilemma is that i am sending the token from the backend through res.json() so the data i am receiving is the token. how can i still use it to set the authentication header at the same time? I am getting this error “Block-scoped variable ‘data’ used before its declaration” This is basically what i mean:

const {data  //this is the token} = await axios.post('/auth/login', {email,password}, {
   headers: {
     'Authorization': `Bearer ${the-token}`  //how can i still use the token here??
   }
 })

Catching a browser refresh button (React) [duplicate]

I’m trying to figure out a way how to detect if the user clicked the browser refresh button. I have a useEffect hook inside of which I call an async function that I got from my custom hook. I changed the function and variable names for this example

It looks like this;

    useEffect(() => {
        if (mode === Mode.Edit && updateFlag) {
            CalculateFunction(undefined, true);
            setUpdateFlag(false);
        }
    }, [randomDependency, mode]);

Now, what I would need here is to figure out if the user pressed the refresh button, and if he did I would call this function with the second parameter as false, like this:

if (mode === Mode.Edit && updateFlag) {
            CalculateFunction(undefined, false);
            setUpdateFlag(false);
}

javascript how to get cookie value with a leading dot on domain

A cookie “test” created by PHP appears in my console with a dot: .mydomain.com. How do I get its value?

    setcookie('test', $value, time()+(100 * 24 * 60 * 60), '/', 'mydomain.com', true, true);

I’ve tried a lot of scripts found here but none of them work:

    function getCookie1(name) {
        function escape(s) { return s.replace(/([.*+?^$(){}|[]/\])/g, '\$1'); }
        var match = document.cookie.match(RegExp('(?:^|;\s*)' + escape(name) + '=([^;]*)'));
        return match ? match[1] : null;
    }
    console.log('cookie 1 = '+getCookie1('test'))

    function getCookie2(name) {
          const regex = new RegExp(`(^| )${name}=([^;]+)`)
          const match = document.cookie.match(regex)
          if (match) {
            return match[2]
          }
       }
    console.log('cookie 2 = '+getCookie2('test'))

    function getCookie3(name) {
      let cookie = {};
      document.cookie.split(';').forEach(function(el) {
        let split = el.split('=');
        cookie[split[0].trim()] = split.slice(1).join("=");
      })
      return cookie[name];
    }
    console.log('cookie 3 = '+getCookie3('test'))

    function getCookie4(name){
      document.cookie.match('(^|;)\s*' + name + '\s*=\s*([^;]+)')?.pop() || ''
    }
    console.log('cookie 4 = '+getCookie4('test'))

    function getCookie5(name) {
        if(document.cookie.length>0) {
            start=document.cookie.indexOf(name+"=");
            pos = start+name.length+1;
            if(start!=0) {
                start=document.cookie.indexOf("; "+name+"=");
                pos = start+name.length+3;
            }
            if(start!=-1) { 
                start=pos;
                end=document.cookie.indexOf(";",start);
                if(end==-1) {
                    end=document.cookie.length;
                }
                return unescape(document.cookie.substring(start,end));
            } 
        }
        return '';
    }
    console.log('cookie 5 = '+getCookie5('test'))

Is it possible to recover it as it is, or do I have to rewrite PHP’s setcookie differently?

Scroll animation with toggling between fixed and absolute position

I have created html page with a corresponfing js file. I want to add specific animations on this page while scrolling through.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scroll Animation</title>
</head>
<body>
<!--Other contents-->

<div class="parent-bloc" style="height: 150em;">
    <a href="parent-bloc"></a>
    <div class="bloc" id="block4">
        <div class="content">
            <p>Text for Block 4</p>
            <img src="img-avant.png" alt="Image 1">
        </div>
    </div>
    <div class="bloc" id="block5" style="transform: translateY(100em);">
        <div class="content">
            <img src="img-avant.png" alt="Image 2">
            <p>Text for Block 5</p>
        </div>
    </div>
    <div class="bloc" id="block6" style="transform: translateY(100em);">
        <div class="content">
            <p>Text for Block 6</p>
            <img src="img-avant.png" alt="Image 3">
        </div>        
    </div>    
</div>

<!--Other contents-->
</body>

The animation concerns the 3 blocs having class=”bloc” that should follow these steps:

On page load, the block5 and block6 are not visible

1- When scrolling down, the bloc having id=”block4″ stays fixed when it arrives at the top of the page

2- While keep scrolling, the next block (block5) arrives 200px down from block4 with donw to top animation (translateY) and stays fixed too

3- Same thing for the block6, 200px down from block5

4- When the block6 is in viewport an we keep scrolling down, all those 3 blocks maintain their distance but souhldn’t be fixed anymore, so they go up together

5- When scrolling up and the block4 arrives at top of the page, block4 becomes fixed again and the block6 disappears by fading down as we keep scrolling up

6- Then the block5 disappears too by fading down and the block4 looses fixed position

I have provided some screenshots of the page so you can see the preview of what already works. The js code is a little longer so if you need to take a look at it, tell me I will provide here.

I have tried javascript scroll event listener with scroll position conditions and toggle between fixed and absolute position on each bloc but the behavior is not always the same depending on scroll position. The sticky position in css is a solution but the blocs will appear little by little,yet I want them to show on time like bottom to top. I’m stuck on the 5 and 6 steps so if anyone can help please I would be grateful. Thank you so much !!

Color coded Opportunities from Google API speed page test

I’m building my own dashboard, calling googleapis.com/pagespeedonline/v5/runPagespeed?url= on a site input by a user.
I can see the output its all running well, my question is about the Opportunities section.

When running a lighthouse report from the dev tools we get this nice color coordinated list of improvements.
enter image description here

I’ve found the opportunities returned from calling the Google API here’s an example of one:enter image description here

My question is how do I determine which opportunity is red, yellow, etc.
Any help will be appreciated.

Generic Key object same as value of other key

I’m trying to make type with same key of object as value of other key

I want to receive _Option type from data which has key same as a value of value key:

data = {
  asd: {
    value: "asd",
    label: "Asd",
    active: false,
  },
  qwe: {
    value: "qwe",
    label: "Qwe",
    active: true,
  },
};



const options = getOptionsFromDetails(data)

I want to force usage of this fn that key must be same as value of value key, below example with an warning: An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead. I tried to do it also using mapped object but get unknown on values 🙁

type _Option<TValue extends string> = {
  value: TValue;
  label: string;
};

export const getOptionsFromDetails = <TKey extends string>(
  details: {
    [key: TKey]: {
      value: TKey;
      label: string;
      active: boolean;
    };
  }, 
): _Option<TKey>[] =>