How does one pass an array with no fixed size into the vertex shader?

I have an array with no fixed size (let noise = [];) in my .js file where it stores the noise values for a point (noise[i] -> a single point).

I was wondering if I’m able to pass all the values inside the array into my vertex.shader by doing:

//.js
for(let i = 0; i < noise.length; i++) {
    const uNoise = gl.getUniformLocation(program, "uNoise[" + i + "]");
    gl.uniform3fv(uNoise, MV.flatten(noise[i]));
}

//vertex.shader
let uNoise[];

If not, how would it possible to do it?

isAuth is not defined

i defined isAuth in Line 14 but i got error “srcApp.js
Line 25:13: ‘isAuth’ is not defined no-undef”
idk, maybe i defined it wrong, looking up for your help, thanks

import React, { Component } from 'react';
import './css/main.css';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import Home from './pages/Home';
import CreatePost from './pages/CreatePost';
import Login from './pages/Login';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      isAuth: false,
      setIsAuth: false
    };
  }

  render() {
    return (
      <Router>
        <nav>
          <Link to="/">Home</Link>
          <Link to="/createpost"> Create New Post</Link>
          {!isAuth && <Link to="/login">Login</Link>}
        </nav>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login setIsAuth={this.state.setIsAuth} />} />
          <Route path="/createpost" element={<CreatePost />} />
        </Routes>
      </Router>
    );
  }
}

export default App;

How to find whether time ranges overlap?

I have the following time ranges 1pm to 3pm and 9am to 5pm. I know a doctor is available between 9am and 5pm. The patient is looking for doctors that are available from 1pm to 3pm. When he inputs that time range, he should be able to see the doctor in the list. For example, if the doctor is available from 9am to 12pm, and the patient input 3pm to 5pm, the doctor won’t show up. I’m trying to match doctors with appointments with patients where patients give a time range when they are available and so do doctors. How can I do this using javascript? Here’s my inefficient solution.

            // startDate and endDate is the time range for the doctor.
            const startDateTime = startDate.format('HH:mm');
            const endDateTime = endDate.format('HH:mm');

            const stimeParts = startDateTime.split(":");
            const stime1 = parseInt(stimeParts[0], 10);
            const stime2 = parseInt(stimeParts[1], 10);

            const etimeParts = endDateTime.split(":");
            const etime1 = parseInt(etimeParts[0], 10);
            const etime2 = parseInt(etimeParts[1], 10);

            const startminutes = (stime1 * 60) + stime2;
            const endminutes = (etime1 * 60) + etime2;

            // so patients can select times in a 3 hour range
            // for example from 0:00 to 3:00 or 12:00 to 15:00
            // key is the first number in the time range that the user selected
            // so if they select the time range 15:00 to 18:00, then key = 15
            const timeSelected = key;
            const fromMinutesSelected = timeSelected * 60;
            const toMinutesSelected = (timeSelected * 60) + (3 * 60);

            let timeStart = startminutes;

            while ( found === false && (timeStart < endminutes && ((timeStart + 30) <= endminutes))) {
                if (timeStart >= fromMinutesSelected && (timeStart + 30 < toMinutesSelected)) {
                    found = true;
                } else {
                    timeStart += 30;
                }
            }

if found == true then the two time ranges overlap. selectedTime

Math for combining two array’s values as notation for a large number

I am currently trying to write a part of my code that takes a large number, say, 1e31, and converts it to 1no where no is a units measure. I currently have my code set up as such:

function getNotation(num) {
  let firstArray = ["", "un", "du", "tr", "qa", "qi", "sx", "sp", "oc", "no"];
  let secondArray = ["", "Du", "Tr", "Qa", "Qi", "Sx", "Sp", "Oc", "No"];
  let output = "";
  console.log((Math.floor(Math.log10(num) / 3)) + " " + (Math.floor(Math.log10(num) / 3) % 11 - 1) + " " + (Math.floor(Math.floor(Math.log10(num) / 3) / 11)));
  output += firstArray[Math.floor(Math.log10(num) / 3) % 11 - 1];
  output += secondArray[Math.floor(Math.floor(Math.log10(num) / 3) / 11)];
  return output;
}

The issue that I am running into is that the index I use for firstArray works fine until it hits 9, then it jumps to -1. If anyone could give me some help that would be greatly appreciated. Let me know if you need any more of the code.

Pinterest Tag Health Make sure you are including Product IDs in your Add to Cart events. SHOPIFY

Make sure you are including Product IDs in your Add to Cart events. A Product ID can be any format that you choose as long as it matches the format used by your Catalog.

I am getting this error on Pinterest tag health and I don’t know how to fix it. I am using Shopify. I have tried to add this code to submit button:

onclick="pintrk('track', 'addtocart');"

But it is not working. Is this some kind of bug?

How do you click on this deeply nested class in javascript?

How can I access the class I marked blue on the screenshot below and click on it?
The “main class” and “section class” always got the same name. I have tried by starting at a class which I believe is the parent and find about its children step by step by using

var x = document.getElementsByClassName("_9eogI E3X2T")[0];
window.alert(x);

but that keeps giving me “undefined” and I don’t know how to get into the class I marked on the screenshot because the blue marked area in code always got a different name too :/

enter image description here

How debug Laravel 8 api call done in browser?

I have a project in Laravel 8 where I’ve created a controller with a update method.

    public function update(Product $product, Request $request)
    {
        $data = $request->all();

        $validator = Validator::make($data, [
            'name' => 'string',
            'quantity' => 'integer',
            //'image_path' => 'required|mimes:jpeg,bmp,png',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors(), 'error']);
        }

        $product->fill($data);
        $product->save();


        return new ProductResource($product);
       }

I’ve followed this answer to set up Phpstorm to debug Laravel and when I call that end-point with Postman the debug effectively starts.

Now, I am trying to use this endpoint, doing a js function that send the data of a html form.

From this answer, I wrote the following code

const productEditFormSubmit = async (e) => {
  let formData = new FormData();
  formData.append('fileData', e.target.elements.image.files[0]);
  formData.append('code', e.target.elements.name.value);
  formData.append('quantity', e.target.elements.code.value);
  formData.append('name', e.target.elements.quantity.value);

  try {
    const apiUrl = `http://localhost:8000/api/product/${e.target.elements.code.value}`;
    const options = {
      method: 'PATCH',
      body: formData
    };

    
    const response = await fetch(apiUrl, options);
    const body =  await response.json();

    return body;
  }
  catch (error) {
    console.log('(App) Error: ', error);
  }
  e.preventDefault();
}

However, the debug doesn’t start at all.
I’m sure the end-point is called and doesn’t crash midway, because if I alter it to send a “fake” response instead of return new ProductResource($product);, I find it in the browser network table:

call response

However, The update doesn’t do its logic – I mean, the product isn’t correctly updated as it happens with postman call.

Now, I am in the blind, as I can’t see what is actually happening inside that function.
Any idea why the debugger doesn’t start in this case? I’ve also installed and tried to enable the Xdebug helper extension but that doesn’t change anything.

By the way, any other ways to check what happens in that function when called in the browser? Log, dump function, whatever?

CSS/React My button moves out of place when minimizing window

Trying to make a generic search bar in React, having trouble preventing the search button from moving when minimizing the window. The arrow will always move out of position when I minimize the window even if just a bit, wondering what I am missing in my code. I want the search arrow button to maintain its place even when minimizing the window but it keeps moving.

Searchbar.js

import React from "react";
import './SearchBar.css';
import arrow from './arrow.png';

const SearchBar = ({placeholder,data}) => {
    return (
        <div className="search">
                <div className="searchInputs">
                    <input type="text" placeholder={placeholder}/>
                    <button className='button' style={{position: 'relative',
                                                right: 420, top: 15}}>
                    <img className='arrow' src={arrow} alt="logo" 
                        style={{position: 'relative', right: 15, bottom: 11}}
                    ></img>                            
                                                </button>
                    <div className="searchIcon"></div>
                </div>
                <div className="dataResult"></div>
        </div>
    );
}

export default SearchBar;

Searchbar.css

.searchInputs {
  margin-top: 55px;
  display: flex;
  position: relative;
}

.search input {
  background-color: white;
  border: 0;
  border-radius: 40px;
  font-size: 16px;
  height: 72px;
  width: 676px;
  margin: auto;
  font-family: Proxima Nova,Arial,sans-serif;
  font-weight: 700;
  line-height: 1.33;
  
  color: #414141;
}


input:focus {
  outline: none;
}

.searchIcon svg {
  font-size: 16px;
}

.button {
  display: flex;
  flex-direction: row;
  align-items: left;
  height: 10px;
  width: 10px;
  border-radius: 50%;
  border: none;
  padding: 20px;
  background-color: #428a13;
  transition: background-color .2s;
  
}

.arrow {
  height: 24px;
  width: 31px;
}

.button:hover {
  color: rgba(255, 255, 255, 1);
  box-shadow: 0 0px 22px orange;
}

How to get javascript value of html data with Jsoup in Java

I’ve been using Jsoup for a long time. I need to get values of a wheather conditions.

That’s the link i’m work on : https://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?il=ANKARA&ilce=

The problem here: I can’t directly access the values I want.

As you can see at below i need to access values which is showing in picture.enter image description here

The question is how can i access the data generated by javascript in html ?

How to write array elements to a rangelist using Google Apps Script?

I have this rangelist as the destination and a row of values that should be written to the destination.
I was thinking of iterating through the row of data and also through th rangelist and set value along the way, but I can’t find a way to iterate through the elements in the row of data.
Here’s the piece of code I’m working on:

let data = [];
  for (let i = 0; i < values.length; i++) {
    if (values[i][0] == ref && values[i][4] == variac) {
      data.push(values[i])
    }
  }
  const destRng = [
    "B5", "D5", "G5", "I5", "M5",
    "B7", "H7",
    "B9",
    "C12", "C14", "C16", "C18", "C20", "C22", "C24",
    "B27", "E27", "H27", "L27",
    "B29",
    "B32", "E32", "H32", "L32",
    "B34", "E34", "H34", "L34",
    "B36", "E36",
    "B40", "F40", "J40",
    "B42",
    "B44", "F44", "J44",
    "B46", "F46", "J46",
    "B48", "F48", "J48",
    "B50",
    "D53",
    "D55",
    "B58", "D58", "G58", "I58", "L58",
    "B61", "E61", "G61", "J61",
    "B65", "G65"
  ]

  Logger.log('Data: ' + data)

  const rngList = sheetCadProd.getRangeList(destRng).getRanges();
  for (let n = 0; n < data.length; n++) {
    for (let i = 0; i < rngList.length; i++) {
      let dado = data[n] 
      rngList[i].setValue(dado)//It sets the first value throughout the rngList
    }
  }
}

Now, this is getting the first element of data and writing it to all destination cells. How can I go through these data elements?

Thank you!

Why is a function I expect to be shaken from a tree still there on a create-react-app build?

Similar to Tree shaking create-react-app? but more of how to validate and fix.

So I have a created a library of react hooks. In there I added an example to help me understand how tree-shaking would work.

import { useClock, useDeepState } from '@trajano/react-hooks';
export function App(): JSX.Element {
  useClock();
  useDeepState("foo");
  return <div>Hello world</div>
}

However, there’s a function called useAsyncSetEffect that I added in my library code base, but tracing through the code for useClock and useDeepState I don’t hit that function at all, but when I look at the generated files I see a reference to useAsyncSetEffect.

Not really sure what’s causing it, the library isn’t large so the size is just a K gzipped, but I am curious as to why it is being included.

POST http://localhost:7500/api/users/posts 400 (Bad Request)

So I am trying to save some data into a mongodb data base using axios
I created a form to fill then when i click on save the data must be saved.

this is my try:

import auction1 from '../../Images/auction1.png'
import {useState} from 'react';
import './HomeScreen.css'
import {Button, Modal } from 'react-bootstrap';
import axios from 'axios';

const HomeScreen = ()=>{

    const [show, setShow] = useState(false);
    const handleClose = () => setShow(false);
    const handleShow = () => setShow(true);

    
    const [name, setName] = useState("");
    const [price, setPrice] = useState(null);
    const [deadline, setDeadLine] = useState("");
    const [description, setDescription] = useState("");

    const [img, setImg] = useState("");

    const [imgMessage, setImgMessage] = useState(null);
    const [error, setError] = useState(false);


    const handleSubmit = async(e)=>{

        e.preventDefault();

        try{
            const config = {
                headers: {
                    "Content-Type": "application/json",
                }
            }

            const {data} = await axios.post("http://localhost:7500/api/users/posts",
            {name, img, deadline, price, description}, 
            config
            );

            console.log(data);

        }catch(error){
            console.log(error.response.data.message);
        }
    };


    const postDetails = (pic)=>{

        if(!pic){
            return setImgMessage('Please select a picture');
        }

        setImgMessage(null);

        if(pic.type === 'images/jpeg' || pic.type==='image/png'){
            const data = new FormData();
            data.append('file', pic);
            data.append('upload_preset', 'battta');
            data.append('cloud_name', 'ChkounZed');
            fetch("https://api.cloudinary.com/v1_1/ChkounZed/upload", {
                method: 'post',
                body: data
            })
            .then((res)=> res.json())
            .then((data)=> {
                console.log(data);
                setImg(data.url.toString())
            })
            .catch((error)=>{
                console.log(error);
            });
        }else{
            return setImgMessage('Please select a picture');
        }
    };


    
    return(
        <div className="container bg">
            <img src ={auction1} className='landing-image' />
            <div style={{marginLeft:460}}> 
                <Button variant="primary" onClick={handleShow}>
                    Create Post
                </Button>
            </div> 
            <Modal show={show} onHide={handleClose}>
                <form onSubmit={handleSubmit}>
                    <Modal.Header closeButton>
                        <Modal.Title>Create Post</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <form >
                            <div className="form-group">
                                <label>Post Name:</label>
                                <input type="text" className="form-control" placeholder="Enter Name"
                                value={name} onChange={(e)=> setName(e.target.value)}/>
                            </div>

                            <div className="form-group">
                                <label>Post Images:</label>
                                <input type="file" className="form-control" multiple onChange="readURL(this)" accept="Image/*" 
                                onChange={(e)=> postDetails(e.target.files[0])}/>
                            </div>

                            <div>
                                <label>Price:</label>
                                <input type="number" className="form-control" placeholder="TND"
                                value={price} onChange={(e)=> setPrice(e.target.value)}/>
                            </div>
                            <div>
                                <label>DeadLine:</label>
                                <input type="datetime-local" className="form-control"
                                value={deadline} onChange={(e)=> setDeadLine(e.target.value)}/>
                            </div>
                            <div>
                                <label>Description:</label>
                                <textarea className="form-control" rows="3"
                                value={description} onChange={(e)=> setDescription(e.target.value)}/>
                            </div>
                        </form>
                    </Modal.Body>
                    <Modal.Footer>
                        <button type="submit" className="btn btn-primary" data-bs-dismiss="modal" onClick={handleClose} >
                            Save Post
                        </button>
                        <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" onClick={handleClose}>
                            Close
                        </button>
                    </Modal.Footer>
                </form>
            </Modal>
        </div>
    )

};

export default HomeScreen;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

that was my react component and the problem is that i keep getting a message that says the post already exists.

this is my postController from the backend side:

const Post = require("../Models/postModel");
const asyncHandler = require("express-async-handler");


const savePost = asyncHandler(async(req,res)=>{

    const {name, deadline, price, description, image} = req.body;
 

    const postExists = await Post.findOne({image});
    
    if(postExists){
        res.status(400);
        throw new Error('Post Already Exists');
    }

    const post = await Post.create({
        name,
        deadline,
        price,
        description,
        image
    });

    if(post){
        res.status(201).json({
            _id: post._id,
            name: post.name, 
            price: post.price, 
            image: post.image,
            deadline: post.deadline,
            description: post.description
        });
    }else{
        res.status(400);
        throw new Error('Error');
    }
});

module.exports = {savePost};

I would be so grateful if you can give me hand of this and by the way i wanna make my post unique using the images and still did not know how

JS password generator is only generating special characters

I’ve been working on a password generator website project and recently tried running the JS to check for any bugs. I noticed that it only generates and pushes out special characters from the special character list into the HTML text area. Could someone help me resolve this issue?

Generator code in question (without two of the trigger functions that just run the generators an increased number of times and the needed arrays):

var UpperGenVariable;
var LowerGenVariable;
var NumGenVariable;
var SpecialGenVariable;

function Basic () {
    for (var i = 1; i <= 4; i++) {
       let FUNNY = Math.floor(Math.random(1,4));

       if (FUNNY = 1) {
           UppercaseGenerate();
       } else if (FUNNY = 2) {
           LowercaseGenerate();
       } else if (FUNNY = 3) {
           NumGenerate();
       } else (FUNNY >= 4); {
           SpecialGenerate();
       }
    }
};

let passwordGen = document.getElementById("PasswordDisplay")

function UppercaseGenerate() {
    var Upperfiltered = [];
    UppergenVariable = Math.floor(Math.random() * LetterIDList.length);
    for (var i = 0; i < LetterIDList.length; i++) {
        if (LetterIDList[i] == UpperGenVariable) {
            UpperFiltered.push(UppercaseList[i]);
        }
    };
    console.log(UpperFiltered);
    passwordGen.value += UpperFiltered
};

function LowercaseGenerate() {
    var LowerFiltered = [];
    LowerGenVariable = Math.floor(Math.random() * LetterIDList.length);
    for (var i = 0; i < LetterIDList.length; i ++) {
        if (LetterIDList[i] == LowerGenVariable) {
            LowerFiltered.push(LowercasList[i]);
        }
    };
    console.log(LowerFiltered);
    passwordGen.value += LowerFiltered
};

function Numgenerate() {
    var NumFiltered = [];
    NumGenVariable = Math.floor(Math.random() * NumIDList.length);
    for (var i = 0; i < NumIDList.length; i++) {
        if (NumIDList[i] == NumGenVariable) {
            NumFiltered.push(NumList[i]);
        }
    };
    console.log(NumFiltered);
    passwordGen.value += NumFiltered
};

function SpecialGenerate() {
    var SpecialFiltered = [];
    SpecialGenVariable = Math.floor(Math.random() * SpecialIDList.length);
    for (var i = 0; i < SpecialIDList.length; i++) {
        if (SpecialIDList[i] == SpecialGenVariable) {
            SpecialFiltered.push(SpecialCharList[i]);
        }
    };
    console.log(SpecialFiltered);
    passwordGen.value += SpecialFiltered
};

React brokes up if builds as NPM package

I want to create an NPM package. The code I use is working – I tested it inside another project. But when I try to separate this code from my the project everything brokes up with error

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Here’s package.json

{
  "name": "some-name",
  "version": "0.0.1",
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "peerDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "dependencies": {
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "typescript": "^4.5.5"
  }
}

And the code of the package:

import { VFC, useMemo } from 'react';

export const someHOC = (Component: VFC) => {
    useMemo(() => [], []);

    return Component;
};

I build this code with tsc without any flags.


And for some reason I can’t use this package:

import React from 'react';
import ReactDOM from 'react-dom';
import { someHOC } from 'some-name';

const Some = someHOC(() => <div>asdasd1</div>);

ReactDOM.render(
    <Some/>,
    document.querySelector('#root'),
);

Could you please explain me where am I wrong?

Not able to call a method from InfoWindow in react js

I am trying to call a method on click of an element. The HTML is stored in a variable. It looks like below:

var cont = '<div class="infocontent" onClick="clickPoly('+index +')" style="width:100px;" >View More</div>';

const clickPoly = (index) => {
   var square = coordinates[index];
  
   if(square != undefined){
      square.dispatchEvent('click');
   }
}

clickPoly() should be called onclick of html above. But when I click on “View More”, it shows “clickPoly is not defined”.

Basically, I am showing multiple polygons on google map and on hover of each polygon I am showing infowindow. In infoWindow I need to show “View More” button and show relevant content.

You can see full code here