Unable to get required values from a regex match in javascript

I’m having some problems with regular expression

Here is the code:

var interpolate = /{ .* }/g

var data = "{ name } { roll } data { app }"

console.log(data.match(interpolate))

I expect the output to be ["{ name }", "{ roll }", "{ app }"]
But when I actually run it, I get the complete string as output,

i.e:

[Running] node "/home/mayukh/Desktop/Projects/tests/regular.js"
[ '{   } { roll } data { app }' ]

I don’t know what exactly is happening.

Reactjs Dynamically call components having cards under tabpanels using array

This is where Tab header and tab content is defined, expectation is Tabs_content has component name, and under tabpanel it should traverse array tabs_content and display component < AddQueueCard /> and call the component shown in image 3

let tabs_data= ['Add Queue','Edit Queue','Remove Queue'];
    let tabs_content= ['<AddQueueCard />','EditQueueCard','C content' ];
<div class="card-body">
        <div class="tab-content">
          <div class="tab-pane active">
          <div>
               <div  id="test">
        <Tabs>
          <ul>
            <TabList>
              
            {tabs_data.map(i => (
                <Tab>{i}</Tab>
                  ))}`***enter code here***`
            </TabList>
            </ul>
            {tabs_content.map(i => (
            
                <TabPanel>
              {i}   {/* here I want to call cards dynamically like <AddQueueCard /> <EditQueueCard> if clicked on 1st or 2nd tab respectively. How do I do that */}
               </TabPanel> 
            
              ))}
          </Tabs>
        </div>
        </div>
         </div>
          <div class="tab-pane">
      
          </div>
          
        </div>
      </div>

Currently cards are not called
enter image description here
Expected output

ArcGIS-JS-API – Custom Content in Popup Template is display nothing (Angular 11)

I want to display a hyperlink on the bottom of the popup template in arcgis esri map. I’ve added the code I’ve tried, but hyperlink is not displaying in the popup template. Only the fields table is displaying. Could you please have look into this code and let me know if I’ve missed something.

.ts file

const popUpTemplate = new PopupTemplate({
      title: "{name}",
      content: [
          {
              type: "fields",
              fieldInfos: [
                  {
                      fieldName: "PhysicianName",
                      label: "Physician Name"
                  },
                  {
                      fieldName: "PrimarySpecialty",
                      label: "Primary Specialty",
                  },
              ]
          },
    
        new CustomContent({
          outFields: ["*"],
          creator: (graphic) => {
              const a = document.createElement("a");
              a.href = graphic.attributes.url;
              a.target = "_blank";
              a.innerText = graphic.attributes.url;
              return a;
          }
      })
      ],
      outFields: ["*"]
    });
    
    const dataFeedLayer = new FeatureLayer({
        source: locationData.map((d,i)=>(
          {
              geometry: new Point({
                longitude: d.longitude,
                latitude: d.latitude
              }),
              attributes: {
                ObjectID: i,
                ...d
              }
          }
        )),
      objectIdField: 'ObjectID',
      popupTemplate : popUpTemplate,
    });

.html file

 <!-- Map Div -->
    <div #mapViewNode></div>

How to run custom made node.js commands inside of a running application?

I’m trying to make a Discord bot, I would like a way to reload commands or the client through the console white my application is running.

EG: When you type commands into a servers console or something similar to like that. Or I can type ‘reload’ and it will reload the client.

I could try doing something with readline https://www.npmjs.com/package/readline, but I’m mostly wondering what is the best way to achieve this.

Thanks in advance,
Luke.

Cannot Read The Properties of undefined (reading ‘addEventListener’) at [duplicate]

I am trying to create a modal window. I have successfully created an open button however, I’m trying to create a close button by clicking the close modal button and the overlay, however, it is displaying that “cannot read the properties of undefined (reading ‘addEventListener’) at .. . )please help, much appreciated.

const overlay = document.querySelector(".overlay");
const modal = document.querySelector(".modal");
const showModal = document.querySelectorAll(".show-modal");
const btnCloseModal = document.querySelectorAll(".close-modal");


for (let i = 0; i <= showModal.length; i++)
showModal[i].addEventListener("click", function () {
    modal.classList.remove("hidden");
    overlay.classList.remove("hidden");
})
btnCloseModal.addEventListener("click", function(){
    modal.classList.add("hidden");
    overlay.classList.add("hidden");
})



    

Why does React rerender when the state is set to the same value via an onClick event?

I have what I thought would be a simple test to prove state changes, I have another test which does the change by timer and it worked correctly (at least I am assuming so) but this one is trigged by a click event and it’s failing my rerender check.

  it("should not rerender when setting state to the same value via click", async () => {
    const callback = jest.fn();
    const baz = "baz";
    function MyComponent() {
      const [foo, setFoo] = useState("bar");
      callback();
      return (<div>
        <div data-testid="set1" onClick={() => { setFoo(baz); }} >FF</div>
        <div data-testid="test">{foo}</div>
      </div>)
    }

    const { getByTestId } = render(<MyComponent />)
    const testElement = getByTestId("test");
    const set1 = getByTestId("set1");
    expect(testElement.textContent).toEqual("bar");
    expect(callback).toBeCalledTimes(1)

    fireEvent.click(set1);
    await waitFor(() => expect(testElement.textContent).toEqual("baz"));
    expect(callback).toBeCalledTimes(2)

    fireEvent.click(set1);
    await waitFor(() => expect(testElement.textContent).toEqual("baz"));
    expect(callback).toBeCalledTimes(2) // getting 3 here.

  })

how to turn off viewport resizer when using Control+Shift+J to Open the Console panel on chrome?

I am using viewport resizer with chrome to see what happen with my code at some devices.

But, my problem is, when I use ctrl + shift + j to see the console on chrome, it open the viewport resizer. As you can see in this picturepicture about my problem

So, I want to use viewport resizer but I just want to see the console on chrome as usual.

Could you please help me to solve this problem ?
Thank you very much for your time.

How to fetch documents in a subcollection by their id in Firestore Database

I’m building a school managment system using HTML and Javascript in which, students must attend courses and I’m using this article as a guide: https://medium.com/firebase-tips-tricks/how-to-secure-many-to-many-relationships-in-firestore-d19f972fd4d3

I already have the Write part so I can associate courses with students, in the article this is
the code:

  const attendingRef = db.doc(`students/${studentId}/attending/${courseId}`);
  const attendeeRef = db.doc(`courses/${courseId}/attendees/${studentId}`);

  const batch = db.batch();
  batch.set(attendingRef, {});
  batch.set(attendeeRef, {});
  await batch.commit();
} 

But I had to make some changes to make it work in my project:

async function attendCourse() {
  
  
  const studentId = firebase.auth().currentUser.uid
  const courseId = "0O1OZOrtipgw8xlqNINc"
  const attendingRef = db.doc(`students/${studentId}/attending/${courseId}`);
  const attendeeRef = db.doc(`courses/${courseId}/attendees/${studentId}`);
  
  
  const batch = db.batch();
  batch.set(attendingRef, {});
  batch.set(attendeeRef, {});
  await batch.commit();
}

Now I want to fetch all the courses that a logged-in student attends and show them in a table, in the article it says that by using this I should be able to fetch the data:

async function fetchCourses(studentId) {
  const courseIds = await db.collection(`students/${studentId}/attending`).get();

  const courseDocs = await Promise.all(
    courseIds.docs.map(doc => db.doc(`courses/${doc.id}`).get())
  );

  return courseDocs.filter(doc => doc.exists).map(doc => ({ id: doc.id, ...doc.data() }));
} 

So I modified the code to make it work with my project aswell like this:

async function fetchCourses() {

  const studentId = firebase.auth().currentUser.uid
  const courseIds = await db.collection(`students/${studentId}/attending`).get();



  const courseDocs = await Promise.all(
    courseIds.docs.map(doc => db.doc(`courses/${doc.id}`).get())
  );
   
    console.log(courseDocs);

  return courseDocs.filter(doc => doc.exists).map(doc => ({ id: doc.id, ...doc.data() }));
  
}

Now, my console.log(courseDocs) shows a lot of things and amongst them is the id of the course that the student is attending but I want to show the title and content of that course in a table, any help is gladly appreciate.

Use “:not” pseudoclass within SASS nesting

I am trying to convert some plain CSS to SCSS so I can take advantage of nesting. The code below is an example of where I want to define styles for a bunch of form field input types. In the plain CSS below, I’m setting the default, plus the :focus state of the fields. Except for one particular form field (a search field in my global header), where I’m using the :not negation pseudo-class selector.

input.text, 
input.title, 
input[type=email], 
input[type=password], 
input[type=tel], 
input[type=text], 
select, 
textarea {
    border: 2px solid #c3cbd6;
}

input.text:focus, 
input.title:focus, 
input[type=email]:focus, 
input[type=password]:focus, 
input[type=tel]:focus, 
input[type=text]:not(div.global-search > form > div > input.et_pb_s):focus, 
select:focus, 
textarea:focus {
    border: 2px solid #008ed4;
}

And here is my conversion to nested SCSS for the first block:

input.text, 
input.title, 
input[type=email], 
input[type=password], 
input[type=tel], 
input[type=text], 
select, 
textarea {
    border: 2px solid #c3cbd6;
    
    &:focus {
        border: 2px solid #008ed4;
    }
}

But the second CSS block is trickier to convert to SCSS, because I’m making an exception using the :not selector to exclude the search field from having a focus state like all the other forms.

How can I do this in SCSS?

Get requested URL with params

I’m doing an API request with some params.

Example:

import Axios from 'axios';

const generator = Axios.create({
    baseURL: "https://some-api.com"
});

// Calling the API with GET method.
generator.get('/some/endpoint/', {
   params: {
      user: "user-test",
      password: "password-test"
   }
})

Can I get the entire URL, including the params? In this case, the answer to my question would be: “https://some-api.com/some/endpoint&user=user-test&password=password-test”.

Here I’m just mocking the params, but in my real application, it’s dynamic.

ReactJS – Cannot read property of undefined (only after clicking submit)

Following is my code to edit a form. This form is getting a bookDetails Object as props. I am storing the bookDetails that i get in props in a state variable bookDetailsObj. Now, this is working fine and even when I refresh the page the code does not break. But, when I click submit button, i’m getting the error “TypeError: Cannot read property ‘bookDetails’ of undefined”.

Another doubt is, even when I’m refreshing the page, the bookDetails data that im getting from props persists. That is, it is not undefined and I’m only setting the data in “componentDidMount”. I never need to get the data from local storage. What is the reason for that?

import {withRouter} from 'react-router-dom';
import LibNavbar from "./LibNavbar";
import swal from "sweetalert";


class EditBook extends Component{
    constructor(props) {
        super(props);
        this.state={
            // bookDetailsObj:[],
            bookDetailsObj:this.props.location.state.bookDetails,
            bookTitle: "",
            publisher: "",
            isbn: "",
            language: "",
            pages: 0,
            authors: [""],
            copies: 0,
            isReferenceOnly : 0,
            price: 0,
            purchaseDate:"1/1/1111",
            publicationYear : 0
        }
        this.handleChange = this.handleChange.bind(this)
        this.handleChangeArray = this.handleChangeArray.bind(this)
        this.fillForm=this.fillForm.bind(this)
        this.submitChanges=this.submitChanges.bind(this)
    }

    submitChanges(e){
        e.stopPropagation()
        e.preventDefault()

        swal("Submit Changes?","Once you submit older details cannot be revived","warning")
        
    }

    componentDidMount() {
        if(this.props.location.state===undefined)
        {
            console.log("getting item....",localStorage.getItem("bookDetailsObj"))

            this.setState({
                bookDetailsObj:localStorage.getItem("bookDetailsObj")
            }).then(()=>this.fillForm())
        }
        else
        {
            console.log("setting item....:" ,this.props.location.state.bookDetails)
            localStorage.setItem("bookDetailsObj",this.props.location.state.bookDetails)
            this.fillForm()
        }

        // console.log(this.state.bookDetailsObj)
    }

    fillForm(){
        console.log(this.state.bookDetailsObj)
        this.setState({
            bookTitle: this.state.bookDetailsObj["bookTitle"],
            publisher: this.state.bookDetailsObj["publisher"],
            isbn: this.state.bookDetailsObj["isbnNumber"],
            language: this.state.bookDetailsObj["language"],
            pages: this.state.bookDetailsObj["noOfPages"],
            authors: this.state.bookDetailsObj["authors"],
            copies: this.state.bookDetailsObj["copies"],
            isReferenceOnly : this.state.bookDetailsObj["isReferenceOnly"],
            price: this.state.bookDetailsObj["price"],
            purchaseDate: this.state.bookDetailsObj["purchaseDate"],
            publicationYear : this.state.bookDetailsObj["publicationYear"]
        })
    }
    handleChange(event) {
        console.log("Handle change called")
        const {name, value} = event.target;
        this.setState({
            [name]: value
        })
        console.log(this.state)
    }
    handleChangeArray(i, event) {
        let authors = [...this.state.authors];
        authors[i] = event.target.value;
        this.setState({ authors });
    }
    createUI(){
        return this.state.authors.map((el, i) =>
            <div key={i} className={"addBookContainer"}>
                <input type="text"  className="form-control authorName" value={el||''} onChange={this.handleChangeArray.bind(this, i)} />
                <input type='button' className="removeAuth" value='remove' onClick={this.removeClick.bind(this, i)}/>
                <p></p>
            </div>
        )
    }
    addClick(){
        this.setState(prevState => ({ authors: [...prevState.authors, '']}))
    }
    removeClick(i){
        let authors = [...this.state.authors];
        authors.splice(i,1);
        this.setState({ authors });
    }



    render() {
        return (
            <div>
                <LibNavbar/>

                <head>
                    <link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css"/>
                    <link rel="stylesheet"
                          href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
                          integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf"
                          crossOrigin="anonymous"/>
                    <title>Add Books</title>
                </head>
                <body>
                <div className="container mt-4">
                    <h1 className="display-4 text-center"><i className="fas fa-book-open text-primary"></i> <span
                        className="text-secondary">Edit</span> Books</h1>

                    <form id="register-book-form">
                        <div className="register-book">
                            <label htmlFor="title">Book Title</label>
                            <input type="text" id="bookTitle" name = "bookTitle" className="form-control" required="true" value={this.state.bookTitle} onChange={this.handleChange} />
                        </div>
                        <div className="register-book">
                            <label htmlFor="author">Publisher</label>
                            <input type="text" id="publisher" name="publisher" className="form-control " required="true" value={this.state.publisher} onChange={this.handleChange}/>
                        </div>
                        <br/>
                        <div className="register-book-set4">
                            <label htmlFor="title">ISBN#</label>
                            <label htmlFor="price">Price</label>
                            <input type="text" id="isbn" name="isbn" className="form-control addIsbn" required="true" value={this.state.isbn} onChange={this.handleChange}/>
                            <input type="number" id="price" name="price" className="form-control addPrice" required="true" value={this.state.price} onChange={this.handleChange}/>
                        </div>
                        <br/>
                        <div className="register-book-set">
                            <label htmlFor="title">Language</label>
                            <label htmlFor="title">Number of Pages</label>
                            <input type="text" id="language" name="language" className="form-control addIsbn" required="true" value={this.state.language} onChange={this.handleChange}/>
                            <input type="number" id="pages" name="pages" className="form-control addPages" required="true" value={this.state.pages} onChange={this.handleChange}/>
                        </div>
                        <br/>
                        <div className="register-book-set2">
                            <label htmlFor="Number of Copies">Number of Copies</label>
                            <label htmlFor="Reference only">Is Reference Only</label>
                            <input type="number" id="copies" name = "copies" className="form-control addCopies" required="true" value={this.state.copies} onChange={this.handleChange} />
                            <input type="number" id="isReferenceOnly" name = "isReferenceOnly" className="form-control addReference" min="0" max="1" required="true" value={this.state.isReferenceOnly} onChange={this.handleChange} />
                        </div>

                        <br/>

                        <div className="register-book-set3">
                            <label htmlFor="purchaseDate">Date of Purchase</label>
                            <label htmlFor="publicationYear">Year of Publication</label>
                            <input type="date" id="purchaseDate" name="purchaseDate" className="form-control addPurchase" required="true" value={this.state.purchaseDate} onChange={this.handleChange}/>
                            <input type="number" id="publicationYear" name="publicationYear" className="form-control addPublication" required="true" min="1000" max="9999" value={this.state.publicationYear} onChange={this.handleChange}/>
                        </div>

                        <div className="register-book">
                            <br/>
                            <label htmlFor="title">Authors</label>
                            {this.createUI()}
                            <input type='button' value='Add more authors' onClick={this.addClick.bind(this)}/>
                            {/*<input type="submit" value="Submit" />*/}
                        </div>
                        <br/>
                        <div className="register-book mb-3">
                            <button type="submit"  className="btn btn-primary btn-block" onSubmit={()=>this.submitChanges()}> Save</button>
                        </div>
                        <div className="register-book">
                            <button type="submit"  className="btn btn-primary btn-block"> Reset</button>
                        </div>
                        <br/><br/>
                    </form>

                </div>
                </body>
            </div>
        );
    }
}

export default withRouter(EditBook)

error while using custom html property tags

I am trying to make every HTML element in my project clickable. When it is clicked, it should take me to another webpage (other.html)
my JS:


let objs = document.querySelectorAll( 'body *' );
console.log(objs)
Array.from(objs).map(x => {
if (x.hasAttribute('loc') && x.hasAttribute('trig')){
let loc = x.getAttribute('loc')
let trig = x.getAttribute('trig')
let functionAtLast = function() {location.href = loc}
x.addEventListener(trig, functionAtLast)

}
})

my HTML:

<b loc = 'other.html' act = 'click'>hi</b>

When I click on the bold text, nothing happens.

What am I doing wrong here?

React doesn’t update when CSS File is changed

So I’m new to React.
I want to style a simple text and found out how to use styles, but when I want to change something in the CSS I have to restart my React App which always takes 3 Minutes.

I use npm start to start the React server that was created with create-react-app.

How can I let React update when the CSS file is changed?

I have an index.js that looks like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from  './Frontend/App.js';
import './Frontend/style/main.css';

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

And an App.js that looks like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './style/main.css';

class App extends Component {
    render() {
        var pageHeading = (
            <h1 className="pageHeading">bosleeir.it</h1>);
        return pageHeading;
    }
}

export default App;

Why is website not working on a live server?

I have built a website on Node.js, using Handlebars and Express.js connecting to MongoDB.
I am not sure why after I have uploaded it to the live hosting server it just show Files Directory..
Here is the snippet of what I see:
what i see right now on the live server

I understand I think that it is looking for index.html but I use templating Handlebars and my entry point is index.js as I stated in package.json here:
enter image description here