How to dinamically change the color of an element inside an SVG file, with Javascript?

I’m experimenting with HTML, CSS and SVG files.
I have an elaborate Illustration saved as SVG file. Inside this file, I have two elements with a unique ID: COLOR1 and COLOR2. As default they have a fill in Red (COLOR1) and Yellow (COLOR2).
I loaded the SVG file into the HTML page using the method. The SVG is too complicated to embed it inline and the page, after the experiment, can have more than only one SVG file of the same kind.

    <object id="Soldier" type="image/svg+xml" data="ProvaSVG.svg" width="400" height="400">
    <param name="src" value="ProvaSVG.svg">
    </object>

I want to change, at page load, the colors of these two elements, according to different values supplied by a database. For example COLOR1 to Green and COLOR2 to Blue.
This is what I did:

Soldier.COLOR1.fill='Green';
Soldier.COLOR2.fill='Blue';

How I correctly address the elements to change their fill values? I want to use plain Javascript, not JQuery or other dependencies.

How to use children array in React

My intention here is to create a search component page, that has a form and a table, that can vary on fields and result.

Let’s supose a component that receive a couple of children:

const SearchPage = ({title}) => {
    function handleSubmit() {...}
    
    return (
        <div>
            <div className="form">
                {chindren[0]}
            </div>
            
            <div className="table">
                {children[1]}
            </div>
        </div>
    )
}

and now using this component:

const MyPage = () => {
    return (
        <SearchPage title="Search for fruits">
            <form onSubmit={handleSubmit}>   <!--this is children[0]-->
                <input useSomethingFromSearchPageHere></input>
                ....
            </form>
            
            <table>                         <!--this is children[1]-->
                ....
            </table>
        </SearchPage>
    )
}

How access SearchPage variables and methods from children fragments?
This is the right way of doing this?

Custom fetch client called inside Next.js getServerSideProps() is returning data of a different user. Is it a memory leak? If yes, where?

Here is the implementation of a wrapper on top of fetch API that I use in one of the projects at work. This fetch wrapper is used specifically to fetch data from backend inside the getServerSideProps() of the page. The usage is strictly server-side and a hack is used to read authentication tokens via server-side signed cookie.

We have received complaints from customers seeing someone else’s details on their dashboard i.e. Someone else’s name and purchased items. However, a refresh of the page solves it and it is not reproducible.

After repeated review of the code on backend and failing to find anything even after 3 days of logs digging, I started believing that this might be a memory leak Next.js is known to have in older versions. So we switched to Next.js 14 and the issue went away.

Recently we had a situation where the server went into stress and the issue resurfaced till the load subsided. This time even my teammates could see the issue and performing a refresh brought random people’s data each time.

We shifted to client-side rendering for userdata related pages, which solved the issue. But I am curious what is exactly introducing the memory leak here. Since I have spent considerable effort in ensuring there should not be a memory leak by any means, to the best of my knowledge.

Is there any possibility of this happening in the code below?
I’m open to any other suggestion you might have about performance/readability/anything.


import { ACCESS_TOKEN } from "constants/cookie"; // cookie names for rotating
import { getCookie } from "cookies-next";

export function unstringify(value) {
  try {
    return JSON.parse(value);
  } catch (error) {
    return value;
  }
}

export function loadFromCookies(key, options) {
  return unstringify(getCookie(key, options) ?? null);
}

import { createLogger } from "logger/debug";
const debug = createLogger("fetchClient");
const verbose = debug.extend("verbose");

const isServer = typeof window === "undefined";

class FetchClient {
  constructor(defaultConfig) {
    this.defaultConfig = defaultConfig ?? {};
  }

  async request(method = "GET", endpoint, body, options) {
    const { baseURL, parseResponse, ...fetchOptions } = {
      ...this.defaultConfig,
      ...options,
      headers: {
        ...this.defaultConfig?.headers,
        ...options?.headers,
      },
      method,
    };

    if (body && !["HEAD", "GET", "DELETE"].includes(method)) {
      fetchOptions.body = typeof body === "string" ? body : JSON.stringify(body);
    }

    const target = (baseURL ?? "") + endpoint;
    debug("Q-> %s %s", method, target);
    verbose("Q-> %s %s %O", method, target, fetchOptions);

    const response = await fetch(target, fetchOptions);
    verbose("<-S %s %s %O", method, target, response.headers);

    if (!response.ok) console.error(`(${response.status}) ${response.statusText} | ${method} ${target}`);
    return this.responseParser({ response, parseResponse }).catch(this.errorCatcher);
  }

  async responseParser({ response, parseResponse }) {
    if (response.status === 204) return;
    if (parseResponse === false) return response;

    const contentType = response.headers.has("content-type") && response.headers.get("content-type");
    debug("<-S content-type %o", contentType);
    if (!contentType) return response;

    if (contentType.includes("application/json")) {
      const body = await response.json();
      verbose("<-S json %O", body);
      return body;
    }
  }

  head(endpoint, options) {
    return this.request("HEAD", endpoint, null, options);
  }

  get(endpoint, options) {
    return this.request("GET", endpoint, null, options);
  }

  delete(endpoint, options) {
    return this.request("DELETE", endpoint, null, options);
  }

  post(endpoint, body, options) {
    return this.request("POST", endpoint, body, options);
  }

  put(endpoint, body, options) {
    return this.request("PUT", endpoint, body, options);
  }

  patch(endpoint, body, options) {
    return this.request("PATCH", endpoint, body, options);
  }

  errorCatcher(error) {
    console.error(error);
    return {};
  }
}

const defaults = Object.freeze({
  headers: { "Content-Type": "application/json" },
});

const fetchClient = new FetchClient(defaults);
const fetchClientPrototype = Object.getPrototypeOf(fetchClient);

function SSR({ req, res }) {
  const context = Object.assign({}, this.defaultConfig);

  const token = loadFromCookies(ACCESS_TOKEN.KEY, { req, res }) ?? loadFromCookies(ACCESS_TOKEN.OLD_KEY, { req, res });
  if (token) {
    debug("fetchSSR token found", { isServer });
    context.headers = Object.assign(context.headers ?? {}, { Authorization: `Bearer ${token}` });
  }

  return Object.setPrototypeOf({ defaultConfig: context }, fetchClientPrototype);
}

const fetchSSR = SSR.bind(fetchClient);

export default fetchSSR;

Here’s how i call it.


export async function getServerSideProps(ctx) {
  const user = findUserFromRequest(ctx);
  const fetchClient = fetchSSR(ctx);

  const { data: purchasedItems = [] } = user ? await fetchClient.get("/path/to/purchased") : {};

  return withServerProps({ ctx, fetchClient, props: { purchasedItems } });
}

Slider with OwlCarousel 2 displays one slide instead of three

Today I’ve moved OwlCarousel 2 slider with one displayed image from half-a-page block to the full page block. Now it displays one image on full width at the time, even with items set to 3. I need it to display 3 elements at time and slide one-by-one using existing arrows. Moreover, I’ve rewriten owlcarousel settings so much time, so I don’t know the initial state of configuration.
I suppose, it may cause in width, but even when I’ve tried to fix it – nothing happened.

Here are my config and styles:

if (jQuery("body").find(".carousel1")) {
 var elements = jQuery(".carousel1").owlCarousel({
  loop: true,
  margin: 10,
  nav: false,
  dots: false,
  mouseDrag: false,
  touchDrag: false,
  items: 3
}
);
jQuery(".prev1").click(function (types) {
  types.preventDefault();
  elements.trigger("prev.owl.carousel");
});
jQuery(".next1").click(function (types) {
  types.preventDefault();
  elements.trigger("next.owl.carousel");
});
}

And CSS

.owl-carousel .owl-item img {
    display: inline;
}
.carousel1 img {
    height: auto!important;
    width: 100%!important;
}
.owl-carousel .owl-item img {
    height: 500px;
    width: auto;
    max-width: none;
}
/*.owl-carousel .owl-item {
    max-height: 500px;
    padding-bottom: 10px
}*/`

I’ve tried many ways, but when changing owl-item width in Edge Inspector to 1/3 of the initial width – this resulted in partially worked solution – items were displayed by 3, I was scrolling and the got an empty space.

After update react-native to 0.75.1 – react-native-fast-image gives error while running app on android

I have updated react-native to the latest 0.75.1 version and now have got the below error after running the application on Android.

node_modules/react-native-fast-image/android/src/main/java/com/dylanvann/fastimage/FastImageSource.java:14:
error: cannot inherit from final ImageSource public class
FastImageSource extends ImageSource {

Below are the versions used in the application

 "react": "18.3.1",
 "react-native": "0.75.1",
 "react-native-fast-image": "^8.6.3",

Accessing PokeAPI

I would like to access the PokeAPI to get all the moves learnt by a specific pokemon at level 1. At the moment,

Here is my js code:

let userPokemonName = "squirtle"
const pokeData = [];
const url = `https://pokeapi.co/api/v2/pokemon/${userPokemonName}`
pokeData.push(fetch(url).then(res => res.json()))

Promise.all(pokeData).then(results => {
  console.log(results)
  const userPokemonData = results.map(data => ({
    name: data.name,
    id: data.id,
    type: data.types.map(type => type.type.name).join(", "),
    moves: data.moves.map(move => {
      if (move.version_group_details.level_learned_at === 1) {
        return move.move.name
      }
    }).slice(0, 10).join(', ')
  }));
})

At the moment, I’m just getting an array of commas moves array is commas

but it should say [‘tackle’, ‘tail-whip’].

I have tried using .forEach instead of map :

 moves: data.moves.forEach(move => {
      if (move.version_group_details.level_learned_at === 1) {
        userPokemonData.push(move.move.name)
      }

but this has returned undefined.

Converting ingame coordinates to real life latitude and longitude

I need to convert in-game coordinates from the game Euro Truck Simulator 2 to real-world geographic coordinates. The game uses a coordinate system in meters with a scale of 1:19 compared to the real world, where coordinates 0 0 is approximately in originRealCoords lat and lng. Game provides a map of whole Europe.
The problem is that the longitude and latitude become less and less accurate as the point moves farther away from x: 0, z: 0. Maybe there is another way to convert in-game coordinates into real-life coordinates?

function convertGameCoordsToLatLong(gameCoords, originLat, originLong, originGameCoords, scale) {
   // Convert game coordinates to real-world meters
   const realX = (gameCoords.x - originGameCoords.x) / scale;
   const realZ = (gameCoords.z - originGameCoords.z) / scale;

   // Distances in degrees on Earth (approximately)
   const metersPerDegreeLat = 111320; // Average distance in meters per 1 degree of latitude
   const metersPerDegreeLong = 111320 * Math.cos(originLat * (Math.PI / 180));

   // Convert distance to degrees
   const deltaLat = realZ / metersPerDegreeLat;
   const deltaLong = realX / metersPerDegreeLong;

   // Calculate new coordinates
   const newLat = originLat - deltaLat;
   const newLong = originLong + deltaLong;

   return [newLat, newLong];
}

async function getCoords() {
   try {
       const res = await fetch("http://192.168.0.106:25555/api/ets2/telemetry");
       const json = await res.json();
       return { x: json.truck.placement.x, z: json.truck.placement.z };
   }
   catch (error) {
       console.error(error.message);
       return { x: NaN, z: NaN };
   }
}

async function convertCoords() {
   // Initial data
   const originGameCoords = { x: -5.121521, z: -14.6748238 };
   const originRealCoords = { lat: 50.746475, lng: 10.508655 };
   const scale = 1 / 19; // Ingame map scale

   // New game coordinates
   const gameCoords = await getCoords();

   // Convert coordinates
   return convertGameCoordsToLatLong(
       gameCoords,
       originRealCoords.lat, 
       originRealCoords.lng,
       originGameCoords,
       scale
   );
}

convertCoords();

Redux problem “from default-exporting module (only default export is available)”

I have update webpack (5.93.0) and react (18) and redux (5) to last version but now I have a lot of errors similar this:

Can’t import the named export ‘applyMiddleware’.’apply’ (imported as ‘applyMiddleware’) from default-exporting module (only default export is available)

and this is the relative class:

import React, { Component } from 'react';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createSagaMiddleware from 'redux-saga';
import { createLogger } from 'redux-logger';
import Provider from 'react-redux';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import { writeConfigurationSaga } from './sagas/writeConfigurationSaga';

import App from './App';
import reducers from './reducers';


const history = require("history").createHashHistory();

// create saga middleware
const sagaMiddleware = createSagaMiddleware();

const middlewares = [routerMiddleware(history), thunk, sagaMiddleware];
if (process.env.NODE_ENV !== 'production') {
  const logger = createLogger({ collapsed: true });
  middlewares.push(logger);
}

const store = createStore(reducers, applyMiddleware(...middlewares));

document.querySelector('#closeSwOnClick').onclick = function () {
  window.close();
};

// run sagas
sagaMiddleware.run(writeConfigurationSaga);

class SwTest extends Component {

  componentDidMount() {
    this.props.history.push('/sw-test/home'); 
  }

  render() {
return <Provider store={store} history={history}>
  <ConnectedRouter history={history} store={store}>
    <App />
  </ConnectedRouter>
</Provider>;
  }
}

export default SwTest;

I not able to undestand if the problem is on update of react/redux or if webpack is not configured correctly. Thanks in advanced

can’t embed Resdiary on my nuxt3 website without an Iframe

i’m having troubles trying to embed the Resdiary prenotation widget with multiple locations.

I would like to embed it just using these lines:

<div id="rd-widget-frame" style="max-width: 600px; margin: auto;"></div>

<input id="rdwidgeturl" name="rdwidgeturl" value="https://booking.resdiary.com/widget/Standard/LOCATION/IDNUMBER?includeJquery=false" type="hidden">

<script type="text/javascript" src="https://booking.resdiary.com/bundles/WidgetV2Loader.js"></script>

I inserted the script tag this way in the app.vue

<script setup lang="ts">
useHead({
  script: [
    {
      src: 'https://booking.resdiary.com/bundles/WidgetV2Loader.js',
      // valid options are: 'head' | 'bodyClose' | 'bodyOpen'
      tagPosition: 'bodyClose'
    }
  ]
})
</script>

and in the page where i wanted it to display, inside the template tag:

<div id="rd-widget-frame" style="max-width: 600px; margin: auto;"></div>

<input id="rdwidgeturl" name="rdwidgeturl" value="https://booking.resdiary.com/widget/Standard/LOCATION/IDNUMBER?includeJquery=false" type="hidden">

can’t get it to work, only thing i get is:

screenshot of result

I also tried on plain HTML page to check the widget but got the same result.

i would like to see the widget fully loaded like this one: https://booking.resdiary.com/widget/Standard/FraDiavoloMilanoSempione/37876

Date picker input element is not working as expected in ios devices. selects date without user select it manually on click of it

I’m experiencing an issue with a date picker that works as expected on most devices. However, on iOS devices (iPhone), I’m facing two specific problems:

Auto-Fill Without User Confirmation:
When the user clicks on the date picker, the input field is automatically filled with a date (AutoFill is off in ios settings), even if the user hasn’t clicked “Done.” This behavior is unexpected and differs from how the date picker works on other devices.

Date Overlaps with Calendar Icon:
The date value overlaps with the calendar icon within the input field. This overlap makes it difficult for the user to read the selected date clearly.

Here’s a simplified version of my js code:

 <div style="text-align: right; font-weight: bold;" class="sDiv1 date-width-sm">
 <span>text</span>
 <div class="date-width-sm">
     <input class="w-100 names" type="text" id="name" placeholder="">
     <div style="text-align: right; margin-top: 50px; direction: rtl;font-weight:bold;"> <span class="DatePicker">Demo</span></div>
     <div style="margin-top:20px;">
         <input class="textbox dateFilter px-3 py-0 date-picker-height-sm w-100" id="date" placeholder="DD/MM/YYYY" class="textbox" type="date">
     </div>
 </div>
.sDiv1 {
    order: 2;          
}
  .date-width-sm {
      width: 67%;
  }
  .dateFilter {
    border: .1px solid #c5c6c861;
    border-radius: .4rem;
    outline: none;
}

1 2

Questions:
1.How can I prevent the date picker on iOS devices from auto-filling the input field without user confirmation?
2.What can I do to stop the date value from overlapping with the calendar icon? Is there a CSS tweak or workaround that can solve this issue?

Any guidance or solutions would be greatly appreciated!

Does anyone have experience using expo to create an IOS app using windows and react native? [closed]

What is the best way to make an IOS app using windows? Would it be to learn react native and use a IOS simulator? Is that even allowed? Would you be able to actually use that app on your iphone? I have a windows laptop but an IOS phone so that’s the trouble!

I have found some sources say to use react native and Expo CLI and was wondering if anyone has tried this before and their feedback on it? It seems more hard than using Xcode (obviously, as Xcode is FOR IOS apps) but was it worth it?

I am trying to add BrowserPrintJs library into my wordPress site , but this library has NPM package and i don’t know how to add library into wordPress

Broprint.js helps JavaScript developers code visitors identifier more simply, readably, and securely. Whether you need to find a unique visitor, do analytics, browser fingerprinting, or do anything of the like while even preventing frauds, we’ve got you covered at a cryptographically strong level. The best part? Our library is extremely lightweight and developer friendly- which means it won’t take a toll on your project, and it’s uber-simple to implement. This library works on the concept of canvas fingerprint and audio fingerprint, the final result which a user get is the combination of audio and canvas fingerprint. We are using cryptojs under the hood for encryptions but you can easily tweek the library to remove the dependency.

⚡ Fast implementation
Step 1: Install using npm or yarn:

Using npm:

//Install:
npm i @rajesh896/broprint.js
Using Yarn:

//Install:
yarn add @rajesh896/broprint.js

But now the question is how i can install the library into the wordPress site

showing the even numbers between two numbers which the user has entered [closed]

I’ve done it to be honest but I feel like writing extra code. I want a shortcut

The code is:

let num1 = +prompt("enter a number");
let num2 = +prompt("enter a number");

if(isNaN(num1) || isNaN(num2) || num1 == num2) {
    alert("Error!")
} else{
    let smallnum = 0, bignum = 0;
    if (num1 > num2){
        smallnum = num2;
        bignum= num1;
    } else{
        smallnum = num1;
        bignum = num2;
    }
    i = smallnum + 1;
    while(i < bignum){
        if (i % 2 == 1){
            i++;
            console.log(i);
        } else {
            console.log(i);
        }
        i += 2;
    }
}

and please tell me whether I’ve written well or not.

Request header field istest is not allowed by Access-Control-Allow-Headers in preflight response in Codeigniter 3 [duplicate]

I have a problem here.

I am using Codeigniter 3.
So I created an api-builder application, well there is 1 external website that wants to use the api that has been created in the api-builder, let’s call it portal.

I created 1 javascript called global-ajax.js to call the api in the portal project like this

// ajax-global.js
const url = 'https://webserver.or.id/api/1.0/getSiswa';

$.ajax({
    url: url,
    type: "GET",
    beforeSend: function(request) {
          request.setRequestHeader("api_access_key", "xxxxxx"); // Ganti dengan API key Anda
          request.setRequestHeader("web_origin", "https://portal.or.id/");
    },
    success: function(response) {
        // Tampilkan data siswa di console
        console.log('Data Siswa:', response);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        $('#output').val('Error: ' + textStatus + 'n' + errorThrown);
    }
});

But when I look through the console, this error appears,

Access to XMLHttpRequest at ‘https://webserver.or.id/api/1.0/getSiswa’ from origin ‘https://portal.or.id’ has been blocked by CORS policy: Request header field web_origin is not allowed by Access-Control-Allow-Headers in preflight response.

So, how to get rid of the error and make the portal able to access the api created in api-builder (webserver)?

Because, in the api-builder controller, the requirement to be able to access the API is by providing api_access_key and web_origin for authentication.

Here is one function in the API controller (api-builder project)

private function isAuthorized()
    {
    $headers = getallheaders();
    error_log(print_r($headers, true));  // Log header yang diterima

    $api_key = $headers['api_access_key'] ?? '';
    $website_origin = $headers['web_origin'] ?? '';

    error_log("API Key: $api_key, Website Origin: $website_origin");  // Log nilai API Key dan Website Origin

    if (empty($api_key) || empty($website_origin)) {
        return false;
    }

    $is_key_valid = $this->M_api->validate_api_key($api_key, $website_origin);
    error_log("Is Key Valid: " . ($is_key_valid ? 'true' : 'false'));  // Log hasil validasi

    return $is_key_valid;
    }

Thank you very much

How to check if a result is a document?

I am using JavaScript that makes a call to a server (Java) to get documents. It has an Ajax call:

Client (JavaScript):

$.ajax({
    type: "get",
    url: urlStringCustomerInvoices,
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    success: function (result) {
        if (result.length > 0) {

The server (Java) sets a byte array representing the PDF document (can also be other document types):

OutputStream os = response.getOutputStream();
bos = new BufferedOutputStream(os);
bos.write(bytes);
bos.flush();
os.flush();
os.close();

This works as expected, i.e. a document, e.g. PDF can be downloaded sucessfully. However, when there is a problem, I want to be able handle it. If the returned result is not a valid document.

On the client in JavaScript, how do I validate if the returned result is a valid document?

Valid documents are file types .pdf, .doc and .docx

The type seems to always be String:

console.log(Object.prototype.toString.call(result));

prints:

[object String]

Also:

console.log(result.length);

prints (for a valid PDF):

66402