JSON.stringify returns empty- Google places API

I’m making a simple web dashboard where you can query different keywords for places, add them to a list, and download them as a json using the Google places API. I’m hitting a snag at the last step where I want to convert the collected data from an object to a json string using JSON.stringify and have the user download it.

I set it up that first you keep adding location ID’s to a global list with the nearbySearch() method. When you’re ready to download, you hit the download button and that sets off a second query for the location details, adds them to a js object, converts it to a json string, and has it download as a file.

let placeData = {places:[
        {name: 'place name', 
        price_level: 'price level: 0-no data, 1-4 rating',
        rating: 'user rating 1-5',
        user_ratings_total: 'number of user ratings'
    }
]}

function requestDetails(myCallback){

    for(const id of placeIDs){
        setTimeout(sendRequest(id),100)
    }
        myCallback(placeData);
}

function sendRequest(id){
    var request = {
        placeId: id,
        //fields: ['name'],
        fields: ['name', 'price_level', 'rating', 'reviews', 'user_ratings_total']
      };
      
      detService = new google.maps.places.PlacesService(map);
      detService.getDetails(request, detCallback);
      
      function detCallback(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          pushData(place);
        }
      }
}

function pushData(place){

    let priceLevel;
    let rating;
    let reviews;
    let userRatings;

    if(place.price_level== undefined){priceLevel= 0}
    else{priceLevel=place.price_level}
    if(place.rating== undefined){rating= 0}
    else{rating=place.rating}
    if(place.reviews== undefined){reviews= 'no data'}
    else{reviews=place.reviews}
    if(place.user_ratings_total== undefined){userRatings= 0}
    else{userRatings=place.user_ratings_total}

    placeData.places.push({
        name: place.name.toString(), 
        price_level: parseInt(priceLevel),
        rating: parseInt(rating),
        user_ratings_total: parseInt(userRatings)
    })
}

function download(content, fileName, contentType) {
    const a = document.createElement("a");
    const file = new Blob([content], { type: contentType });
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
  }

  function onDownload(data){
      download(JSON.stringify(data), "myfile.json", "text/plain");
  }

the html of the button is set up like this:
<button class="button" id="download" onclick="requestDetails(onDownload)">Download</button>

I had to set up the sendRequest() method with a timeout, because the places API allows you to make 10 calls at a time and that was a quick fix. I ruled out that the json isn’t written because of a wrong data format, the file is empty for any variable I give it if it’s being inserted in the same place as pushData().

If I print out the object before converting it to a string it looks like this;

{places: Array(1)}
places
: 
Array(11)
0
: 
{name: 'place name', price_level: 'price level: 0-no data, 1-4 rating', rating: 'user rating 1-5', user_ratings_total: 'number of user ratings'}
1
: 
{name: 'Bolaka Avoin yhtiö', price_level: 0, rating: 0, user_ratings_total: 0}
2
: 
{name: 'RAYAN Pizza Kebab', price_level: 1, rating: 3, user_ratings_total: 99}
3
: 
{name: 'Döner king', price_level: 0, rating: 3, user_ratings_total: 165}
4
: 
{name: 'Ravintola Ilano', price_level: 0, rating: 4, user_ratings_total: 117}
5
: 
{name: 'Yu Zi Ravintola', price_level: 0, rating: 4, user_ratings_total: 13}
6
: 
{name: 'Ravintola Wenla', price_level: 0, rating: 3, user_ratings_total: 28}
7
: 
{name: 'Shishkebab Helsinki Kontula', price_level: 1, rating: 4, user_ratings_total: 436}
8
: 
{name: 'Hesburger Helsinki Kontula', price_level: 2, rating: 3, user_ratings_total: 701}
9
: 
{name: 'Subway', price_level: 2, rating: 4, user_ratings_total: 279}
10
: 
{name: 'Kalkan Pizza-Kebab-Grilli (Entinen Pizzataxi Kontula)', price_level: 1, rating: 4, user_ratings_total: 249}
length
: 
11
[[Prototype]]
: 
Array(0)
[[Prototype]]
: 
Object

So they are being written, somehow, but on the top most level it registers the array as having only one item, the info item that the object was created with. After opening it, however, it shows that there are 11 items in the array with their data.

when I convert to a string I see only the first item;

{"places":[{"name":"place name","price_level":"price level: 0-no data, 1-4 rating","rating":"user rating 1-5","user_ratings_total":"number of user ratings"}]}

I’m guessing that the timeout is preventing the data to be written before I print it out so I tried putting the onDownload() function as a callback, but it still won’t work. I’m not sure if my syntax is wrong or I’ve missed the right approach here completely. Any advice would be great!

ES6 project documentation by jsDoc or whatever other tool

I have a Nodejs project made of several folders. Each folder is intended to be a java-like package of classes.

src
    folderA
        A.js
        ...

    folderB
        B.js
        ...
    ...

Each class A, B, ... is exported as a default export, as in:

/**
* 
* @class
*/
export default class A {
    constructor() {
        ...
    }
    ...
}
    ...

However, when I run jsDoc I get some module.exports.html page containing the documentation of all the classes in a single html page, whereas I whould like, of course, a documentation reflecting the structure of my project.

Reading from here it seems that the only way to go is creating my custom template, which is something I wish not to do. It appears to me unlikely that jsDoc does not support the documentation of an ES6 project, since jsDoc supports ES6 classes.

Is the structure of my project somehow wrong? How is it expected to be structured a project made of ES6 classes? Is there a way to reflect the project structure into the documentation by jsDoc? Is there a different tool which could do it instead of jsDoc?

cypress react testing a component where you have to be logged in

Hi first time trying to make test in cypress and I have a component called comments you are only allow to make comments if you are logged in as a user. So I what to test that, can I mock a user and set my useState/myCurrentUser? actually its though useContext my user is set.

import {Comments} from "../../src/app/risk-modules/risk-pattern-details/components/Comments";

 describe('LoginTest.cy.tsx', () => {

 // set userauth

 it('playground', () => {
   cy.mount(<Comments className={'test'} />)
   cy.get('#mybutton').click();
 })
})

how my comments component looks like, where is has a state called hasAccess, the “hasAccess is the one I want to mock, just set that state to true.

<div className={`card-toolbar ${!hasAccess && classes.isDisabled}`}>
    <button
       id='mybutton'
     
        data-bs-toggle='modal'
        data-bs-target='#kt_modal_comment'
        disabled={!hasAccess}
        onClick={() => setOpenDialog(!openDialog)}
       >
        New comment
        </button>
      </div>

So at the end I want to mock a useContext state called “hasAccess” to true

JS code interfere with CSS code transform animation

So I have this css code:

    width: 48%;
    max-width: 500px;
    position: relative;
    padding: 30px;
    margin-top: 20px;
    margin-left: 50px;
    margin-right: 50px;
    border-radius: 10px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.6);
    transform: translateY(-10px);
    transition: transform 0.55s ease;
    background-color: #ffffff;
}
  
.box:hover, .box1:hover {
    transform: translateY(-20px);
}

And this JS code using ScrollReveal libary:

sr1.reveal('.data-section .container .data .box', {delay: 150, origin: 'left'});
sr1.reveal('.data-section .container .data .box1', {delay: 150, origin: 'right'});

The JS code prevent the css from giving a hover animation, how do I fix this? Because I have another same element with hover animation combined with scrollreveal and it works just fine

Getting Unexpected token import for v16.18.0 node

I have created simple JS app(using npm init) to achieve absolute path but facing an import issue.

My package.json is like,

  "name": "test-abs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "dev": "nodemon src/index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "nodemon": "^2.0.22"
  },
  "devDependencies": {
    "basetag": "^2.1.0"
  }
}

I have index.js, test1.js in src folder

In /src/index.js,

import { app1 } from "$/src/test1.js";

app1();

In test1.js,

export const app1 = () => {
  console.log("app1");
};

When I start npm run dev server getting

(function (exports, require, module, __filename, __dirname) { import { app1 } from "$/src/test1.js";
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:617:28)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Function.Module.runMain (module.js:694:10)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3

My node is v16.18.0

Please let me know why I am facing this issue and how to fix this.

I can’t change my style.display attribute through javascript

So, I wrote a piece of functional code in html and css with no display values, but if I try to change them through javascript, it only works outside an if statement that I put it into, even if the if statement is true (tried checking it through console.log).

Here’s my js:

function toggleShowContact() {
  console.log(`${contactForm.style.display}`);
  contactForm.style.display = "flex";
}

html:

<div class="contact-form">
        <div style="font-size: 20px">
          <button class="btn-close" onclick="closeAll()">X</button>
          <h1 style="text-align: center">Contact Us</h1>
        </div>
        <form>
          <input
            name="name"
            type="text"
            class="feedback-input"
            placeholder="Name"
          />
          <input
            name="email"
            type="text"
            class="feedback-input"
            placeholder="Email"
          />
          <textarea
            name="text"
            class="feedback-input"
            placeholder="Comment"
          ></textarea>
          <div class="action">
            <button class="contact-submission-btn">SUBMIT</button>
          </div>
        </form>
      </div>

I tried going past it in numerous other ways, but didn’t work. As a matter of fact, the following code works:

function closeAll() {
  loginForm.style.display = "none";
  registrationForm.style.display = "none";
  contactForm.style.display = "none";
}


function toggleShowLogin() {
  closeAll();
  if (loginForm.style.display === "none" && loggedIn === false) {
    loginForm.style.display = "flex";
  }
}

function toggleShowRegistration() {
  closeAll();
  if (registrationForm.style.display === "none") {
    registrationForm.style.display = "flex";
  }
}

Shadow acne on castShadow & receiveShadow Mesh – Threlte/Three.js

When I try to create a Mesh that receives its own shadow, It always creates shadow acne.

For example, this code…

<script lang="ts">
  import { Canvas, OrbitControls, T, Three } from '@threlte/core';
  import { PointLight } from 'three';

  const light = new PointLight();
  light.shadow.mapSize.width = 4096;
  light.shadow.mapSize.height = 4096;
</script>

<Canvas>
  <T.PerspectiveCamera makeDefault fov={60} position={[0, 0, 7]}>
    <OrbitControls enableZoom={true} />
  </T.PerspectiveCamera>

  <T.AmbientLight intensity={0.2} />
  <Three
    type={light}
    intensity={1}
    distance={100}
    decay={2}
    position={[10, 0, 2]}
    bias={0.0001}
    castShadow
  />

  <T.Mesh castShadow receiveShadow>
    <T.TorusGeometry />
    <T.MeshStandardMaterial />
  </T.Mesh>
</Canvas>

…creates this scene

I’ve tried multiple values of bias, near and far. Anyone have any idea?

T level review – Please assist

As a part of the T level that I am currently undertaking, a task that needs to be complete is gathering feedback on the code that has been developed.

I am new to HTML and Js and have only just started so it may not be the best code ever.

I am kindly requesting others to open this link:

https://www.mediafire.com/folder/8mdkihc327xj7/Software

Which is the file for the software solution I have built and then once you have seen it please fill the survey in with this link:

https://www.mediafire.com/file/v8mr7u0tewu31s6/Survey.docx/file

you can also leave the name and age space blank if you so wish.

Once completed please email any responses to [email protected] and rename the feedback form with your username or name

Thank you so much for your time and help,

I just have to add 20 characters minimum here

How to parse json so that it’s the correct format?

I am trying to create a historical stock data graph and have followed a tutorial but that uses a json file that is already set meaning it only goes up to a certain time. I want to use an api so that it can be up until it is currently. How do I make the format the it to make it the same or to make it parse the json and know how to use the data.

This is the code so far, I have defined ticker and TDKEY as variables.

var dps = [];
var chart = new CanvasJS.Chart("chartContainer", {
    zoomEnabled: true,
    exportEnabled: true,
    title: {
        text: (ticker+" Stock Price")
    },
    
    axisX: {
        valueFormatString: "DD MMM"
    },
    axisY: {
        title: "Price",
        interval: 5,
        prefix: "$"
    },
    data: [{
        type: "candlestick",
        name: "Qualcomm Incorporated Stock Price",
        showInLegend: true,
        yValueFormatString: "$##0.00",
        xValueType: "dateTime",
        dataPoints: dps
    }]
});

$.getJSON("https://api.twelvedata.com/time_series?
   start_date=2020-05-06&outputsize=5&symbol="+ticker+"&interval=1day&
   apikey="+TDKEY, parseData
);

function parseData(result) {
    console.log(result.values);
    for (var i = 0; i < result.length; i++) {
        dps.push({
            x: result[i].datetime,
            y: result[i].open
        });
    }
    chart.render();
}

The format from my api call this retrieves historical stock data for aapl:

{
    "meta": {
        "symbol": "AAPL",
        "interval": "1day",
        "currency": "USD",
        "exchange_timezone": "America/New_York",
        "exchange": "NASDAQ",
        "mic_code": "XNGS",
        "type": "Common Stock"
    },
    "values": [
        {
            "datetime": "2023-04-19",
            "open": "165.80000",
            "high": "168.16000",
            "low": "165.53999",
            "close": "167.63000",
            "volume": "47644400"
        },
        {
            "datetime": "2023-04-18",
            "open": "166.10001",
            "high": "167.41000",
            "low": "165.64999",
            "close": "166.47000",
            "volume": "49923000"
        },
        {
            "datetime": "2023-04-17",
            "open": "165.09000",
            "high": "165.39000",
            "low": "164.03000",
            "close": "165.23000",
            "volume": "41516200"
        },
        {
            "datetime": "2023-04-14",
            "open": "164.59000",
            "high": "166.32001",
            "low": "163.82001",
            "close": "165.21001",
            "volume": "49337200"
        },
        {
            "datetime": "2023-04-13",
            "open": "161.63000",
            "high": "165.80000",
            "low": "161.42000",
            "close": "165.56000",
            "volume": "68445600"
        }
    ],
    "status": "ok"
}

the format of what the [original] (https://canvasjs.com/data/gallery/php/qualcomm-stock-price.json) tutorial had, this is the historical stock data for qualcomm inc in 2017:

`[
    {
        "x": 1483381800000,
        "y": [
            65.860001,
            66.139999,
            64.599998,
            65.400002
        ]
    },
    {
        "x": 1483468200000,
        "y": [
            65.669998,
            65.949997,
            65.260002,
            65.470001
        ]
    },
    {
        "x": 1483554600000,
        "y": [
            65.220001,
            65.980003,
            65.050003,
            65.550003
        ]
    }
]`

Couldn’t add an overlay div to each rendered react components using tailwind

Hi guys I’m using tailwind library for styling and was trying to add an overlay to each components that are rendered using array.map method in react. but the overlay is being overlayed on the outer most div(with id={slider} as u can see on the code below) instead of each components that are being rendered using the map function. Please help a beginner out. Here’s the code

 return (
<>
    <h2 className='text-gray-300 m-4'>{props.title}</h2>
    <div className='relative flex items-center'>
        <div id={'slider'}>
            {movies.map((item, id)  =>


                <div className='w-[160px] sm:w-[200px] md:w-[240px] lg:w-[280px] inline-block'>
                   
                    <img className='w-full h-auto block' src={`https://image.tmdb.org/t/p/w500/${item?.backdrop_path}`} alt={item?.title} />
                    <div className='absolute top-0 left-0 w-full h-full hover:bg-black/80 opacity-0 hover:opacity-100 text-white'> {/* this is the overlay div */}
                    <p className='white-space-normal text-xs md:text-sm font-bold flex justify-center h-full text-center'>{item?.title}</p>
                    </div>
                </div>
                  
            )}

           


        </div>

    </div>

</>

)

react router push isn’t redirecting to Home component

My react router push isn’t redirecting to Home component, while I’m passing with props the Home path. It seems that the code is correct though.

https://codesandbox.io/s/react-router-example-forked-rmfn5j?file=/src/components/UserDetails.js:0-526

import React, { Component } from "react";

const ErrorLogin = () => {
  let back = () => {
    this.props.history.push("/");
  };
  return (
    <div className="wrapper">
      <h1>Error</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
        veniam, quis nostrud exercitation ullamco laboris
      </p>
      <button onClick={() => back()}>Back</button>
    </div>
  );
};

export default ErrorLogin;

c# Make a ScriptBundle from a source that is not a *.js file

I want to be able to create a ScriptBundle from a source that is not a *.js file but rather from the contents of a string variable

My problem
I have a series of enums and constants from different classes in my source code.
I would like an equivalent of these enumerations and constants for use with javascript.
Currently 2 methods are available to me:

  • Manually write the equivalences in a *.js file then include it in the ScriptBundle
  • Do not use a *js file but use a method for dynamically creating these enumerations and constants from *.cshtml views

Method 1 is tedious and can generate oversights if the enumerations are changed.

Method 2 requires systematic regeneration at each page refresh.

Is there a solution to add the content of a variable to the ScriptBundle? Something that would look like this:

string myString = @"
const Direction = Object.freeze({
North: 'north',
East: 'east',
West: 'west',
South: 'south',
})
";

private static string GenerateJsEnum()
{
    string text = string.Empty;
    // convert enums 
    return text;
}
bundles.Add(new ScriptBundle("~/bundles/MyScript").IncludeString(myString, GenerateJsEnum());

Thank you for your answers

timing react.js for display content

i have a timing problem in react.js

i have a component that checks the user valid.token and user type and if is admin display content and if is not displays ” you don’t have premission “

but when the user is a admin at first component shows ” you don’t have permission” and immediately displays the content

i think its an asynchronous problem becuase it takes some time to get user type from backend, how to fix this in react.js

my component looks like this

export default function Component() {
  useEffect(() => {
    axios
      .post(`http://${process.env.REACT_APP_RUN}:3001/api/token/status`, {
        token,
      })
      .then((response) => {
        setvalidtoken(response.data);
      });
  }, []);

  if (!token || validtoken.valid === "false") {
    window.location.replace(`http://${process.env.REACT_APP_RUN}:3000/login`);
  } else if (validtoken.type !== "admin") {
    return (
      <>
        <Navbar />
        <div className="premission-denied-holder">
          <div className="premission-denied-ithed">
            <h6 className="text-premisson">you dont have premission</h6>
          </div>
        </div>
      </>
    );
  } else {
    return <h1>some content here</h1>;
  }
}

i tried to change the sequence