How can I get Javascript to ignore one of its built-in methods?

I am trying to parse through the JSON response from the OpenWeather API and I want to get the probability of precipitation, but the corresponding API response field is ‘pop’, so whenever I try to access it thinks that I am trying to use the .pop() method. How can I get Javascript to ignore the .pop() method and just let me use .pop to access the API?

My code:

ImageOfMyCodeThinkingPopIsACallToAMethod

The applicable portion of the JSON response:

TheApplicablePortionOfTheJSONResponse

Thank You

Can’t implement simple optional chaining

I am trying to implement a simple optional chaining state update. What I want is for the items to ONLY be changed IF the item is defined/exists; if not/is undefined, I want the item to keep the previous state (e.g userID should remain = 2 if not updated).

To test this out I created an object with three variables:

const userObj = {
  firstName: "",
  lastName: "",
  userID: 2,
};

Then I created a function to update state:

const updateState = (item) => {
  return {
    userObj.firstName = item?.firstName,
    userObj.lastName = item?.lastName,
    userObj.userID = item?.userID,
  };
};

Finally I pass the item which contains only one item to update (firstName) and I call the function:

const item = {
  firstName: "None",
};

console.log(updateState(item));

The output:

 userObj.firstName = item?.firstName,
           ^

SyntaxError: Unexpected token '.'

But when I hover over userObj I can see its properties:

enter image description here

How to Force a Function to Wait Until a bootbox Confirmation Result Arrives?

Following script reload the page before uploading all the files. I can manage to upload all the files if there is no duplicate. But not with bootbox confirmation box.

<script language="javascript">
        //This function is called on drop event to upload multiple files
        function file_uploads(files_obj, tocType) {
            if(files_obj != undefined) {
                var fileArr = [];
                for(i=0; i<files_obj.length; i++) {
                    var FName = files_obj[i].name.toUpperCase();
                    //validate_duplicate_file function make an ajax call to see if file already exist in Database
                    var IsDuplicate = validate_duplicate_file(files_obj[i], tocType);
                    if(IsDuplicate > 0){
                        //If file already exist it will ask for overwrite confirmation 
                        bootbox.confirm({
                            message: "<h3>Please Confirm...</h3><br> <p>Are you sure you want to overwrite <b>" + FName + " </b> ?</p>",
                            buttons: {
                                cancel: {label: 'No', className: 'btnBlack' },
                                confirm: {label: 'Yes', className: 'btnBlack'}
                                },
                            callback: function (result) {
                                if (result) {
                                    //If user allow to overwrite then upload the file to Database
                                    ajax_file_upload(files_obj[i])
                                }
                            }
                        });
                    }else{
                        //If not duplicate then upload the file to Database
                        ajax_file_upload(files_obj[i])
                    }
                }
                //Once all the files are uploaded reload the locations
                location.reload();
            }
        }
    </script>

How to solve react cors error upload images

I create mini social media app in MERN stack. In profile page I cannot get profile image backend. I use morgon and backend console show this: GET /uploads/[email protected]_monica.jpg 304 1.490 ms - - and console react show this: net::ERR_BLOCKED_BY_RESPONSE.NotSameOrigin. I use cors in backend:

app.use(cors({
    origin: process.env.FRONTEND_URL,
    credentials: true
}))

And my profile page this:

import axios from 'axios'
import {Auth} from '../../context'
import config from '../../config';
import AccountCircleRoundedIcon from '@material-ui/icons/AccountCircleRounded';
import {Button, Modal,Alert} from 'react-bootstrap'
import './Style.css'
import {EditOutlined} from '@ant-design/icons'
import {useParams, Link} from 'react-router-dom'
// import useSearch from './useUserSearch';
import {useState, useEffect} from 'react'
import ModulE from './Modul_e'


export default function UserSearch(){
    
    const [toggle, setToggle] = useState(false)
    const {username} = useParams()
    const {user, setUser} = Auth()
    const [data, setData] = useState(null)
    const [loading, setLoading] = useState(true)
    const [show, setShow] = useState(false)
    const [arr, setArr] = useState([])
    const [title, setTitle] = useState('')
    const [error, setError] = useState('');
    const [change, setChange] = useState(false)
    

    useEffect( ()=>{
        setLoading(true)
        axios({
            method: "GET",
            url: config+`/api/v1/friends/${username}`,
            withCredentials: true
        }).then(res=>{
            setData(res.data)
        }).catch(err=>{
            if(err.response) setError(err.response.data.message);
            else setError( 'Something wrong went! Try again!' );
        })
        setLoading(false)

    }, [username, change] )

    const unfollow = async ()=>{
        try {
            const res = await axios.post(config+`/api/v1/friends/unfollow`, {_id: data._id}, {withCredentials: true})
            setData(res.data)
        } catch (error) {
            console.error(error)
            alert(error)
        }
    }

    const follow = async ()=>{
        try {
            const res = await axios.post(config+`/api/v1/friends/follow`, {_id: data._id}, {withCredentials: true})
            setData(res.data)
        } catch (error) {
            console.error(error)
            alert(error)
        }
    }
    
    async function handleFollow(){
        setToggle(true)
        
        data.isFollow ? await unfollow(): await follow()
        
        setToggle(false)
    }
    return (
        <div style={{ marginTop: '3rem' }} className="_profile">
            { error.length>0 && <Alert variant="danger"> {error} </Alert> }
            {
                !loading && data && <div className="_body">
                <div className="_picture">
                    {  data.logo.length > 0 ?
                        <img src={`${config}/${data.logo}`} alt="Logo" />: // here I think wrong
                        <AccountCircleRoundedIcon style={{fontSize: '8rem'}} /> 
                    }
                </div>
                <div className="_user">
                    <div className="_first">
                        <h1> {data.username} </h1>
                        
                        {   data._id === user._id ?
                            <Link to="/settings"> <EditOutlined /> Edit Profile  </Link>
                            :  
                            <Button 
                                disabled={toggle} 
                                onClick={handleFollow} 
                                className=" _button " 
                                variant={ data.isFollow ? 'primary' : 'outline-primary' } 
                                > 
                                { data.isFollow ? `Unfollow${toggle?'...':''}`: `Follow${toggle?'...':''}` }  
                            </Button> 
                        }
                        {
                            data._id === user._id ?
                            <Button variant="primary" className="_btn"> Write New Blog </Button>
                            :
                            <Button variant="secondary" className="_btn"> Show Blogs </Button>
                        }
                    </div>
                    <div className="_second">
                        <Button variant="light" className="rounded-0 _fl" onClick={ ()=>{
                            setShow(true)
                            setArr( data.followers )
                            setTitle('Followers')
                        } } > {data.followers} followers </Button>
                        <Button variant="light" className="rounded-0 _fl" onClick={ ()=>{
                            setShow(true)
                            setArr( data.following )
                            setTitle('Followings')
                        } }> {data.following} following </Button>  
                    </div>
                    <div className="_third">
                        {data.firstName} {data.lastName}
                    </div>
                </div>
                
            </div>}
            
            { loading && <div> Loading... </div>}
               
            <Modal show={show} onHide={ ()=>{ setShow(false); setChange(prev=>!prev) } } >
                <ModulE setShow={setShow} userId={data ? data._id: null} title={title} setChange={setChange}/>    
            </Modal>         
        </div> 
    );
}

And image cannot show please help me! Backend successfully send data but not shown pictures

Alpine correct way of using key event handlers inside of the JavaScript

I’m trying to build a simple app where you can use the arrow keys to do certain things. And trying to get the front end to react appropriately. But so far, I’v not been able to update the data inside x-data.

Simple flow

  • Press ArrowUp key
  • keyDownHandler triggered
  • upPressed set to true
  • ArrowUp key released
  • keyUpHandler triggered
  • upPressed set to false
    again.

But this is not working since the event handler can’t set this.upPressed from where it is registered.

Any ideas?

HTML

<div x-data="loadComponent()" x-init="init">
    Right: <span x-text="rightPressed"></span><br>
    Left: <span x-text="leftPressed"></span><br>
    Up: <span x-text="upPressed"></span><br>
    Down: <span x-text="downPressed"></span>
</div>

JavaScript

function loadComponent() {
    return {
        rightPressed: false,
        leftPressed: false,
        upPressed: false,
        downPressed: false,
    init: function() {
        document.addEventListener("keydown", this.keyDownHandler, false)
            document.addEventListener("keyup", this.keyUpHandler, false)
    },
    keyUpHandler(e) {
      console.log(e.key) //loggin the key up event
      if(e.key == "Right" || e.key == "ArrowRight") {
        this.rightPressed = false
      }
      else if(e.key == "Left" || e.key == "ArrowLeft") {
        this.leftPressed = false
      }
      else if (e.key == "Up" || e.key == "ArrowUp") {
        this.upPressed = false
      }
      else if (e.key == "Down" || e.key == "ArrowDown") {
        this.downPressed = false
      }
        },
    keyDownHandler(e) {
      console.log(e.key) // login the key down event
      if(e.key == "Right" || e.key == "ArrowRight") {
        this.rightPressed = true
      }
      else if(e.key == "Left" || e.key == "ArrowLeft") {
        this.leftPressed = true
      }
      else if (e.key == "Up" || e.key == "ArrowUp") {
        this.upPressed = true
      }
      else if (e.key == "Down" || e.key == "ArrowDown") {
        this.downPressed = true
      }
        },
    }
}

How to grab js from a pastebin and run it?

im wondering if its possible to grab the code (which would be javascript) from a raw text in pastebin.

Basically, lets say I have some code I want to run. So I tell the program to go to this pastebin raw text and run whatever is in there.

Is it possible, and if it is. How do I do this?

Extract options from Javascript tree to insert into word document as a list

First things first, I am not a developer or programmer! But I like to be able to use developer tools to make my working life more efficient, even if I don’t fully understand what I’m doing!

Sometimes, I have to create a list in a Word document, from a website list, for other people to choose options without going to the website themselves. Using Firefox and Notepad++, I can do this for HTML dropdownlists.

But, how do I extract the text options from a Javascript tree? Please see the link to the example tree image

TypeError: Cannot read properties of undefined (reading ‘document’) GraphQL

I was using qraphql (javascript graphql-request library) in a project and ran into a typeError. Here’s the code:

import { request, gql } from 'graphql-request'
const graphqlAPI = process.env.NEXT_PUBLIC_GRAPHCMS_ENDPOINT
export const getPosts = async () => {
    const query = gql`
    query MyQuery {
        postsConnection {
          edges {
            node {
              author {
                bio
                name
                id
                photo {
                  url
                }
              }
              createdAt
              slug
              title
              excerpt
              featuredImage {
                url
              }
              categories {
                name
                slug
              }
            }
          }
        }
      }
 `     
    const result = await request(graphqlAPI, query)

    return result.postsConnection.edges
}

The error said there was a problem with the document parameter of the request.

Please help!

React OnBlur Input Fires Only Once

I have an input field where I initiate the field with an “Error” label.

Once the user types in “success” the input should change to show “Success” label.

This works the very first time, however if I go back and type something other than “success” it doesn’t appear to fire.

const [errState, SetErrState] = useState(true);
const [errValue, setErrValue] = useState("Error");

const handleChange = (e) => {
    setErrValue(e.target.value);
};

const handleBlur = (e) => {
    if (e.target.value === "success") {
      SetErrState(!errState);
    } else if (e.target.value !== "success") {
      SetErrState(!errState);
    }
};

return (

{errState ? (
     <input
          label="Error"
          value={errValue}
          onChange={handleChange}
          onBlur={handleBlur}
      />
     ) : (
     <input label="Success" value={errValue} onChange={handleChange} />
)}

)

Displaying weekly calendar by clicking a button > in React.tsx

I am trying to create a weekly calendar, so something like Fri, Feb 04 - Thu, Feb 10 which will be dynamic. The first Issue I am trying to solve is to instead of having Fri, Feb 04 - Thu, Feb 10, I want this to be Sun, Jan 30 - Sat, Feb 5 for the entire week, not matter if we are on Friday, it should be displaying that range of dates for the week, and once we reach a new Sunday, then calculate the next range of dates.

const today = new Date().toString();
const endOfWeek = new Date(Date.now() + 6 * 24 * 60 * 60 * 1000).toString();

This is what helps me calculate the end of the week date, I make it into an array by using .split() and then I am able to manipulate the rest of the info but, since it depends on what today’s date is and adding 6 days to it, that’s why it never stays as Sunday-Saturday.

The second thing I am trying to figure out is to be able to calculate the next week. For example, assuming that I got the Sun-Sat dates to work, how would I go about calculating Sun, Feb 6 - Sat, Feb 12, Sun, Feb 13 - Sat, Feb 19 and so on by just clicking a button that will look like this symbol >, or calculate the previous weeks by clicking <.

I will greatly appreciate if someone can help me figure out how to stay at a static Sun-Sat date instead of Fri-Thu like for example today that is Friday. And I would also appreciate if someone could give me an idea on how to calculate the next week Sun-Sat dates.
Thanks in advance!

How to focus a CKEditor 5 based Decoupled & Balloon Editors?

I’m working on creating a CKEditor 5 based Preact Custom component. I’m using a oj-text-area, as the base element to create my CKEditor Instance. I need to implement a focus mechanism for the editor instance.

Followed this documentation and used the focus method on the view.

 editor.editing.view.focus();
  

The above code works fine for a div element, but not working for the oj-text-area component.

Layout Calendar Events without overlap algorithm

I’m implementing an algorithm to position a list of events in a daily calendar without overlap them.

Event Schema is the following one:

{
  "date": {
     "start": Date,
     "finish": Date
   },
  "author": string,
  "color": string
}

Current code:

const handleEventsView = (date: Date): any => {
    const newDate = new Date(date)
    const startDay = new Date(date)
    const finishDay = new Date(newDate.setDate(newDate.getDate() + 1))
    const html = []

    // -----------------------------------------------------
    // 1. filter to get just events of selected date
    // 2. map to retreive duration and start as a blocks of 15 minutes.
    // 3. sort by start and then, if they have same start date, by duration. Because events with longer duration have to be in left place.

    const dailyEvents = events
      .filter((event) => new Date(event.date.start) >= startDay && new Date(event.date.finish) < finishDay && !event.date.isAllDay)
      .map((event) => {
        const startDate = new Date(event.date.start)
        const finishDate = new Date(event.date.finish)

        return {
          ...event,
          duration: ((finishDate.getTime() - startDate.getTime()) / 60000) / 15,
          start: (startDate.getHours() * 60 + startDate.getMinutes())/15
        }
      })
      .sort((a, b) => {          
        if (a.start === b.start) {
          return b.duration - a.duration;
        }
        
        return a.start - b.start;
      }
    )

    const eventMatrix: Array<Array<string | undefined>> = [];

    // -----------------------------------------------------
    // set an array of 96 rows (number of 15 minutes per 24 hours) with empty array columns

    for(let i = 0; i < 96; i++) {
      eventMatrix[i] = [];
    }

    // -----------------------------------------------------
    // 1. iterate over dailyEvents.
    // 2. For each duration time of event:
    // 3. Check if in first position there is an undefined or not and get the index where first event duration time is placed.
    // 4. If is not first position, next positions are filled with undefined until we get prev index position.
    // 5. index position is set with event.id
    // 6. Finally, we get if there is overlappDiff between current event and prev one and is filled with undefined until events durations are equal  

    let lastDailyEvent
    for (let i = 0; i < dailyEvents.length; i++) {
      if (dailyEvents[i].start < eventMatrix.length) {
        let index = 0
        let overlappingFinishDiff = 0

     for (let j = 0; j < dailyEvents[i].duration; j++) {
      if (j === 0) {
        if (eventMatrix[dailyEvents[i].start].indexOf(undefined) !== -1) {
          index = eventMatrix[dailyEvents[i].start].indexOf(undefined)
          eventMatrix[dailyEvents[i].start][index] = dailyEvents[i].id
        } else {
          eventMatrix[dailyEvents[i].start].push(dailyEvents[i].id)
          index = eventMatrix[dailyEvents[i].start].length - 1
        }
      } else {
        if (eventMatrix[dailyEvents[i].start + j].length < index + overlappingFinishDiff) {
          for (let k = eventMatrix[dailyEvents[i].start + j].length - 1; eventMatrix[dailyEvents[i].start + j].length < index; k++) {
            eventMatrix[dailyEvents[i].start + j].push(undefined)
          }
        }

        if (index <= eventMatrix[dailyEvents[i].start + j].length) {
          eventMatrix[dailyEvents[i].start + j][index] = dailyEvents[i].id
        } else {
          eventMatrix[dailyEvents[i].start + j].push(dailyEvents[i].id)
        }
      }

      if (overlappingFinishDiff === 0 && lastDailyEvent && eventMatrix[dailyEvents[i].start + j].indexOf(lastDailyEvent.id)) {
        const overLappDuration = lastDailyEvent.duration - (dailyEvents[i].start - lastDailyEvent.start + dailyEvents[i].duration)
        overlappingFinishDiff = overLappDuration > 0 ? overLappDuration : 0
      }
    }

        for (let j = 0; j < overlappingFinishDiff; j++) {
          eventMatrix[dailyEvents[i].start + dailyEvents[i].duration + j][index] = undefined
        }
      }

      lastDailyEvent = dailyEvents[i]
    }

    for (let i = dailyEvents.length - 1; i >= 0; i--) {
      const targetEvent = dailyEvents[i]
      let maxRowLength = 0

      for (let j = targetEvent.duration; j >= 0; j--) {
        if (targetEvent.start + j < eventMatrix.length) {
          const length = eventMatrix[targetEvent.start + j].length

          if (maxRowLength < length) maxRowLength = length
        }
      }

      const width = 100/maxRowLength
      const top = targetEvent.start * 50 + "px"
      const height = targetEvent.duration * 50 + "px"
      const position = eventMatrix[targetEvent.start].indexOf(targetEvent.id)

      html.push(<EventComponent key={i} event={dailyEvents[i]} style={{
        left: (width * position) + "%",
        top,
        width: width + "%",
        height
      }}/>)
    }

    return html
  }

Current result view: https://i.stack.imgur.com/dY8ZC.png

Errors:

  1. First event is overlapped with the second one because it gets the width when time is 16:30 (There are 3 events and result is 33.33%).

  2. I want to max all events so that they are as close together as possible without overlap.

I’m really convinced that algorithm can be much better implemented, correcting the errors mentioned above.

Any help is welcome.

Thank you very much in advance.

I wonder how to activate the click event of an element in the slider in the state of ‘pointer-event: none.’

I’m making a slider with JavaScript.

When implementing a slider, if you do not do pointer-events:none, the slider does not operate normally as follows.

enter image description here

Therefore, if you put pointer-events: none on the parent element, you can see that the slider is operating normally.

enter image description here

I want to make it possible to click on the elements in the slider.

However, if you do pointer-events: none in the parent element, it will not work even if you register a click event.

What I’m curious about is as follows.

  1. I wonder why the slider works strangely when I don’t do pointer-events: none.
  2. I wonder how the child elements can operate the click event with pointer-events: none on.

Here is my code (code sandbox)

cloneDeep recursively omit property key [duplicate]

I am trying to omit every property called “_sectionInfo” while cloneDeep an object and all it’s nested object.

This property should be omitted for the root object and all it’s nested objects as well.

My current code

const newModel = cloneDeep(omitBy(model, (val, key) => key === '_sectionInfo'))

Seems to only omit objects with this key at top level.