The geolocation pin is not displayed on the map

I’m a novice developer. The third day I can’t understand what the problem is, I created an Aure Map, then I need to link it to the dynamics 365 fields, but the whole problem is that the map does not display a pin with geolocation, tell me what the problem is. My Code:

<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Azure Map Integration</title>
    <style>
      #myMap {
        height: 400px;
        width: 100%;
      }
    </style>
    <!-- Azure Maps SDK -->
    <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.js"></script>
    <script src="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas-service.min.js"></script>
    <link
      rel="stylesheet"
      href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css"
      type="text/css"
    />
  </head>
  <body>
    <div id="myMap"></div>

    <script>
      let map, datasource, searchService, pushpin;

      // Initialize Azure Map
      function initMap() {
        map = new atlas.Map("myMap", {
          center: [-73.935242, 40.73061], // Default center (New York)
          zoom: 12,
          authOptions: {
            authType: "subscriptionKey",
            subscriptionKey:
              "api_key", // Replace with your Azure Maps key
          },
        });

        // Wait until the map resources are ready
        map.events.add("ready", function () {
          // Create a data source and add it to the map
          datasource = new atlas.source.DataSource();
          map.sources.add(datasource);

          // Create a search service for geocoding and reverse geocoding
          searchService = new atlas.service.SearchURL(map);

          // Try to get the user's current geolocation
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              function (position) {
                const userLocation = [
                  position.coords.longitude,
                  position.coords.latitude,
                ];

                // Center the map at the user's location
                map.setCamera({
                  center: userLocation,
                  zoom: 15,
                });

                // Add a draggable pushpin at the user's location
                pushpin = new atlas.data.Feature(
                  new atlas.data.Point(userLocation),
                  {
                    draggable: true,
                  }
                );
                datasource.add(pushpin);

                // Create a symbol layer to render the pushpin
                const symbolLayer = new atlas.layer.SymbolLayer(
                  datasource,
                  null,
                  {
                    iconOptions: {
                      image: "pin-blue", // Azure Maps default pin
                      anchor: "center",
                      allowOverlap: true,
                    },
                  }
                );
                map.layers.add(symbolLayer);

                // Add dragend event listener to update form fields when pushpin is moved
                map.events.add("dragend", pushpin, function () {
                  const location = pushpin.geometry.coordinates;
                  reverseGeocode(location);
                });
              },
              function (error) {
                console.error("Geolocation error: " + error.message);
              }
            );
          } else {
            console.error("Geolocation is not supported by this browser.");
          }
        });
      }

      // Function to reverse geocode the pushpin position to update the Dynamics 365 fields
      function reverseGeocode(location) {
        searchService
          .reverseSearch(atlas.service.Aborter.timeout(10000), {
            query: location,
          })
          .then((response) => {
            const result = response.geojson.getFeatures();
            if (result.features.length > 0) {
              const address = result.features[0].properties.address;
              fillFormFields(address);
            }
          })
          .catch((error) => {
            console.log("Reverse geocode was not successful: " + error.message);
          });
      }

      // Function to fill Dynamics 365 fields based on reverse geocoding results
      function fillFormFields(address) {
        setFieldValue(
          "address1_line1",
          (address.streetName || "") + " " + (address.streetNumber || "")
        );
        setFieldValue("address1_city", address.municipality || "");
        setFieldValue("address1_stateorprovince", address.adminDistrict || "");
        setFieldValue("address1_postalcode", address.postalCode || "");
        setFieldValue("address1_country", address.countryRegion || "");
      }

      // Initialize the map on page load
      initMap();
    </script>
  </body>
</html>

I tried different things from azure map documentation to gpt the problem was not solved, the key if something is there and is also inscribed

Problem with CSV export fom Google Earth Engine: final table is not what I want

I am trying to download a CSV file with a time series of Landsat 8 EVI2, and with the respective date and plot id from multiple points using GEE according to the following code:

var roi = ee.FeatureCollection([
 ee.Feature(ee.Geometry.Point([-43.8115,-16.6648]), {plot_id: 1}),
 ee.Feature(ee.Geometry.Point([-43.7923,-16.663]), {plot_id: 2}),
 ee.Feature(ee.Geometry.Point([-43.7794,-16.6596]), {plot_id: 3}),
 ee.Feature(ee.Geometry.Point([-43.8879,-16.7316]), {plot_id: 4}),
 ee.Feature(ee.Geometry.Point([-43.8487,-16.6756]), {plot_id: 5}),
 ee.Feature(ee.Geometry.Point([-43.8274,-16.6888]), {plot_id: 6}),
 ee.Feature(ee.Geometry.Point([-43.8946,-16.7579]), {plot_id: 7}),
 ee.Feature(ee.Geometry.Point([-48.3,-18.9833]), {plot_id: 8}),
 ee.Feature(ee.Geometry.Point([-44.1224,-16.3708]), {plot_id: 9}),
 ee.Feature(ee.Geometry.Point([-44.1134,-16.3687]), {plot_id: 10})
]);

// Intervalo de tempo da minha série temporal
var startdate = '2013-04-01'; 
var enddate = '2024-04-30'; 

var years = ee.List.sequence(ee.Date(startdate).get('year'), ee.Date(enddate).get('year'));


// This function masks clouds in Landsat 8 imagery.
 function maskL8(im) {
   var qa = im.select('QA_PIXEL');
   var mask = qa.eq(2720);
   return im.updateMask(mask).copyProperties(im);
 }

var ls8toa = ee.ImageCollection('LANDSAT/LC08/C02/T1_L2')
.filterBounds(roi)
  .filterDate(startdate, enddate)
  .filter(ee.Filter.lt('CLOUD_COVER',0.3))
    .map(function(im) {return maskL8(im)});

// Calcula EVI2 a partir do Landsat8

var ls8_evi2 = ls8toa.map(function(image) {
  var evi2 = image.expression(
    '2.5*(NIR-RED)/(NIR+2.4*RED+1)', {
      'NIR': image.select('SR_B5'),
      'RED': image.select('SR_B4')
}).rename('EVI2');
return image.addBands(evi2);
});

var landsat = ee.ImageCollection(ls8_evi2);
var EVI2 = ls8_evi2.select(['EVI2']);
print(EVI2, 'EVI2');
print('Quantas Imagens', EVI2.size());

//Função pra calcular valores médios para cada ponto
var pointsmean = function(image) {
  var means = image.reduceRegions({
    collection: roi.select(['plot_id']),
    reducer: ee.Reducer.mean(),
    scale: 30
  });
  
  // Atribuindo datas
  means = means.map(function(f) { return f.set({date: image.date().format("YYYY-MM-dd")}) });
  
  return means.copyProperties(image);
};

var finalEVI2 = EVI2.map(pointsmean).flatten()
.sort('date', false);

print(finalEVI2, 'final EVI2');

// Exportar tabela em csv direto pro Drive
Export.table.toDrive({
collection: finalEVI2,
  description: 'EVI2_walter_'+startdate+'_TO_'+enddate,
  folder: 'LS8_walter',
fileFormat: 'CSV'
});

Actually, I used 34 pairs of coordinates instead of 10 as shown in the code above. I simplified the sample in this Question.

The output shown in the console is:

Console output from the code above.

The CSV file is not what I expected (see figure below). I need columns named ‘date’, ‘plot_id’, and ‘EVI2’ with the values.

.csv file downloaded to Google Drive.

What is wrong and how to fix it?

How to validate and format large JSON files efficiently? [closed]

I’m working with very large JSON files (up to a few MBs in size) and need a tool or method to validate and format them efficiently. Most online JSON tools I’ve tried tend to crash or are too slow when processing such large files.

I’ve recently come across jsonmaster.com, which offers a JSON formatter, validator, and several other features, but I’m curious if anyone has any experience or recommendations on how to handle large JSON files in a more optimized way. Specifically:

Are there specific libraries or tools that are designed to handle large JSON files better than others?
How can I integrate such validation and formatting tools into a web-based app for large-scale use?
Is there any strategy for breaking down the JSON file into smaller chunks for validation, then recombining them?
Any advice on best practices or tools for this kind of scenario would be appreciated.

tried jsonlint.com but failed

Zod Validation for array of instance File

I am making post form for a social media project and I am using zod for validation

and this the solution in TypeScript but I am using JavaScript

z.object({
    file: z.custom<File[]>()
})

How can I write this in Js

I am not sure it my first time using zod

I’m starting to get my hands into web development, Should I learn React or Do projects on vanilla JavaScript in the beginning

I’m an aspiring full-stack developer currently enhancing my skills. I have a basic understanding of HTML and CSS, and I’m now looking to dive deeper into JavaScript and its frameworks. However, I’m at a crossroads and need some advice.

Should I start by mastering Vanilla JavaScript before moving on to React, or can I jump straight into learning React?

Here are a few points about my current situation:

I have some experience with basic programming concepts.
My ultimate goal is to build dynamic and responsive web applications.
I enjoy learning through practical projects and hands-on experience.
I’ve read that understanding the fundamentals of JavaScript is crucial, but I’ve also seen recommendations to start with React to quickly build real-world applications. What would be the best approach for someone in my position?

Any insights or personal experiences would be greatly appreciated!

Thanks in advance!

Unable to import any module for nextjs

I’m having some trouble with my Next.js project and I’m hoping someone here might be able to help. Here’s the situation:

Issue: I’m trying to import modules in my Next.js project, but I keep running into errors indicating that modules cannot be resolved. For instance, when trying to import react-chartjs-2, I get the error Module not found: Can’t resolve ‘react-chartjs-2’.

Setup:

Next.js Version: 14.2.12 (as indicated in package.json)

Error Message: Next.js (14.2.5) out of date when running the project, even though package.json lists version 14.2.12.

Folder Structure: I have two directories in my project: nextjs and fastapi. Inside nextjs, there’s a node_modules folder and a package.json file.

Questions:

Why is there a version mismatch between package.json and the build error message?

Are there any issues or steps I might have missed that could cause modules to not be resolved correctly?

How can I make sure that my Next.js environment is correctly set up and using the right version?

Steps Taken:

I ran npm install in the nextjs folder to install dependencies and have tried reinstalling the dependency as well.

I’ve tried deleting and reinstalling node_modules but still get the same errors.

I checked that the correct Next.js version is listed in package.json, but the build process seems to be using an outdated version.

I’ve also tried npm i next@latest as well

Laravel javascript variable get in blade file

I need get js var in view blade file.
I got this one in Controller and got success in console
in route file

Route::post('/some-route', [Controller::class, 'someMethod']);
Route::post('/some-route', 'Controller@someMethod');//this also work

in js file in $(“#applyBonus”).on(“click”, function () method

$.ajax({ 
    url: base_url + '/some-route', // The route to your Laravel controller 
    type: 'POST', 
    data: { 
        someVarName: someInput, // someInput is from blade file input value. got successfully 
         
    }, 
    success: function(response) { 
        console.log(response); //success
        alert("ssuccessss___" + someInput); //success
        
    }, 
    error: function(xhr) { 
        console.error(xhr.responseText); 
        alert("error___");
    } 
}); 

in Controller

public function yourMethod(Request $request) { 
    //$variable = 'someVarName'; //this also work
    $variable = $request->input('someVarName'); 
    
    //return view('frontend.checkout', compact('variable')); // this also work
    //return view('frontend.checkout')->with('variable'); //this also work
    return view('frontend.checkout')->with('variableName', $variable);//success in console and alert message
} 

and now I tried to get this $variable in view.blade.php

@foreach($variable as $varr) //undefined $variable
       <div class="row">{{ $variable }}</div>
       <div class="row">{{ $varr }}</div>
@endforeach

or

echo $variable;
//or next. also span tag
<div class="row">{{ $variable }}</div>

and all time I get error – $variable is undefined

with I want do is to get input value as php $variable.
maybe there other to get $variable from input value without page refresh?
or
How get this variable from controller in view blade file?
Thanks

try get input value via input value->js var -> controller -> blade file. on last step get error $variable undefined

How to add form elements to Dialog in Dojo dynamically

Please give me a code example on how to dynamically add any form elements to Dialog.

var myDialog = new Dialog({
    title: "Edit form",
    style: "width: 300px; height: 200px"
});
myDialog.show();

It seems I figured it out a little, but I need to somehow wrap the elements in a div since they go in the Dialog box in one line, I don’t know how to do this

var form = new Form();

var myDialog = new Dialog({
    content: form,
    title: "Dialog Box",
    style: "width: 300px; height: 200px"
});

new Select({
    name: "select2",
    options: [
        { label: "Item1", value: "1" },
        { label: "Item2", value: "2" },
        { label: "Item3", value: "3" }
    ]
}).placeAt(form.containerNode);

Cloud Application Programming Model OData v2 proxy

I am running a cap backend application with express.js and want to access the odata services with v2. In this project I used the @sap/cds-odata-v2-adapter-proxy which is now deprecated.
The recommended package is now @sap-js-community/odata-v2-adapter.

I tried to implement the proxy in the same way as the deprecated proxy. It did not work and I did not get any error messages.

This is my server.js

const express = require('express');
const proxy = require('@sap-js-community/odata-v2-adapter');
const cds = require('@sap/cds');
const app = express();

app.use(proxy());
app.use(bodyParser.json());

(async () => {
  await cds.serve('TestService').in(app).at('/test');

  app.listen(process.env.PORT || 4004);
})(); 

In React native, OnOpenWindow webview property is not triggering or working

In React Native, OnOpenWindow webview property is not triggering or listening when my webview source URI link have additonal query parameter.

not-working

In this stage onOpenwindow property is not triggering due to source URI link has additonal query params

<WebView

      source={{ uri: `https://example.com/?apk=1` }
          onOpenWindow={(syntenticEvent) => {
            const { nativeEvent } = syntenticEvent;
            const { targetUrl } = nativeEvent;
            console.log("target url of opened popup:::::::", targetUrl);

}
/>

working

<WebView

      source={{ uri: `https://example.com` }
          onOpenWindow={(syntenticEvent) => {
            const { nativeEvent } = syntenticEvent;
            const { targetUrl } = nativeEvent;
            console.log("target url of opened popup:::::::", targetUrl);

}
/>

javascript document.querySelector null = error / breaks other javascript [duplicate]

my javascript =

document.querySelector('#plus').addEventListener('click', () =>
tlshowhide.reversed() ? tlshowhide.play() : tlshowhide.reverse() );

Where my page has the #plus element this works fine but if the page does not have the #plus element then the console shows an error

 document.querySelector(...) is null

and other unrelated javascript breaks.

So is it expected that document.querySelector being null is an error that breaks other javascript, and if so how can I rewrite my javascript to say “if the element X is found on the page do Y, and if element X is not found on the page then don’t worry about it, just move on”?

Videos Stop Autoplaying After Navigating Away – Barbajs

I am using barba.js for page transitions. I have video element on my corporate page that are set to autoplay, loop, and muted. Work well when I initially load the corporate page. However, when I navigate away from the corporate page and then return (without refreshing the page), the video is no longer autoplaying. The video only start autoplaying again if I manually reload the page. Note: I’m not using any frameworks (like React, Vue, etc.), just plain JavaScript (vanilla JS).

 <video loop muted autoplay>
         <source src="VIDEO_LINK" type="video/mp4">
 </video>

I re-run all my JavaScript code on every page transition with Barba.js. What should i do for the video element ?

How I can ensure the video continue autoplaying when navigating back to the page, without requiring a page reload?

Thanks in advance!

How to mock a dependency of a dynamically imported module in jest

module-a.js

class Math {
  pi() {
    return 3.14;
  }
}

export default Math

module-b.js

import Math from './module-a';

const piVal = Math.pi();

export const doSomeCalc = (a) => {
  return piVal + a;
}

module-b.test.js

describe('module b', () => {
    it('should return correct value', () => {
        // I want to mock the return value of pi() here
        return import('./module-b').then(module => {
          expect(
            module.doSomeCalc(20)
          ).toBe(23.14);
        });
    });
})

How do I mock Math.pi() here?

I need to import the module dynamically as Math.pi() is evaluated as soon as I import the module.

Can not set httponly cookie using FastAPI

When user Log In I am creating Login using pyjwt and setting Httponly cookie but not able to set the cookie because of CROS.

When user Log In I am creating Login using pyjwt and setting httponly cookie like this.

def create_jwt(user_id: str, ip_address: str=None):
    payload = {
        "sub": str(user_id),
        "ip": ip_address,
        "iat": datetime.now(),
        "exp": datetime.now() + timedelta(minutes=30)
    }

    return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256)
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
database = self.client["test"]
@login_router.post("/login", response_model=SuccessResponse, tags=("Login",))
async def login(request: LoginRequest, response: Response):
    try:
        username = request.username
        password = request.password

        user = database.find_one(
            "user",
            filter={"username": username},
        )

        if not user or not login_instance.verify_password(
            password, user.get("password"), user.get("salt")
        ):
            raise InvalidUser()

        from ..authentication import create_jwt

        response.set_cookie(
            key="access_token",
            value=create_jwt(username),
            httponly=True,
            samesite="None",
            secure=False,
            path="/",
        )

        response_content = {
            "status": status.HTTP_200_OK,
            "success": True,
            "message": "User Logged In successfully",
            "data": {},
        }
        return response_content
    except InvalidUser:
        raise InvalidUser()
    except Exception as e:
        raise InternalServerError(e)

When i hit this API in frontend (my frontend is written in VueJS) it is saying not able to set the cookie.
Error Image

I have add CROS in FastAPI main.py
main.py

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8081"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

My front end is running on port **8081.

Frontend**
api.js

import axios from 'axios';

const apiURL = process.env.VUE_APP_BASE_URL;

const apiClient = axios.create({
    baseURL: apiURL,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true,
});

export const get = (endpoint, params = {}) => {
    return apiClient.get(endpoint, { params });
};

export const post = (endpoint, payload) => {
    return apiClient.post(endpoint, payload);
};