Why does my React Native camera feature give an ‘OpenCamera() does not work or load’ error on iOS simulator in Xcode?

So i’m making this application which has a feature of taking pictures using the phone’s camera but when i click on the button which opens the phone’s camera it displays an error which says that OpenCamera() does not work or load, idk if its because im using an ios simulator on xcode but i would appreciate any help.
Thanks.

I tried different methods provided by YouTube but sadly none worked

Change strings using script

I am on a site where I am looking for replacing 2 strings with each other.

I have 2 strings called Cart and Bag. I want to change where it is Cart, it’ll be replaced with Bag and where it is Bag, it’ll be replaced with Cart.

I have used the below PHP code to change strings:

add_filter( 'gettext', function ( $strings ) {
    $text = array(
        'Bag' => 'Cart',
        'Cart' => 'Bag',
    );
    $strings = str_ireplace( array_keys( $text ), $text, $strings );
    return $strings;
}, 20 );

Which as a result shows al the Cart and Bag strings as Bag.

Can anyone please guide me what correction can be done here?

Or any script that can help?

TIA.

Update all Chartjs instances in Chartjsv3 and v4 not working anymore

I used a nice method to update my darkmode color changes in chartjs which I got from here:
Update all Chart.js instances in order to apply changed defaults?

After updating to v3 or v4 the following line of code inside my darkmode.js doesn’t work anymore and the color changes are not applied because the charts are not updated anymore:

Chart.helpers.each(Chart.instances, function(instance){
    instance.chart.update();
});

I get the following console error: caught TypeError: Cannot read properties of undefined (reading ‘update’)

I read the docs about all the breaking changes but I was unable to find anything related to update() in combination with instance.

Any idea what went wrong?

How can I fix the ‘adddoc’ line on my Cloud Firestore code so the form on my HTML webpage successfully sends data to Firestore?

I was trying to make a HTML for which saves the response onto Firebase.

However, when it got to the adddoc line, the page appears to refresh only with nothing sent over.

Here is my code, i have used firefox’s debugging tool to find out which line is causing the issue.

const app = initializeApp(firebaseConfig);

// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);

document.getElementById("registration").onsubmit = async function() { submit(); };

async function submit() {
    const data = {
        name: document.getElementById("input-1").value,
        officialName: document.getElementById("input-2").value,
        universityID: document.getElementById("input-3").value,
        degree: document.getElementById("input-4").value,
        referral: document.getElementById("input-5").value,
        email: document.getElementById("input-6").value,
        phone: document.getElementById("input-7").value,
    };
    console.log(data);
    try {
        console.log("Attempting to send");
        const docRef = await addDoc(collection(db, "users"), data); // The Page Refreshes here
        console.log("Document written with ID: ", docRef.id);
        alert(docRef.id);
    } catch (e) {
        alert("Error adding document: ", e);
    }
};

The submit() function works perfectly okay when i call it alone on init, and with the data replaced with constants. However, i cant get the data from the form to send to firebase

Stuck trying to make my condition not case sensitive

I’ve have recently started to pick up JavaScript and trying to do some exercises and ran into a problem.

This condition does work but only when the prompt is entered in lowercases and I’m trying to filter it down without being case sensitive (sorry if it doesn’t make much sense)

    let userMonth = prompt('Enter the month: ')

    const autumn = ['september', 'october', 'november']
    const winter = ['december', 'january', 'february']
    const spring = ['march', 'april', 'may']
    const summer = ['june', 'july', 'august']

    if(autumn.includes(userMonth)){
      console.log(`${userMonth} is in Autumn`)

    } else if (winter.includes(userMonth)){
      console.log(`${userMonth} is in Winter`)

    } else if (spring.includes(userMonth)){
      console.log(`${userMonth} is in Spring`)

    } else {
      console.log(`${userMonth} is in Summer`)
    }

I tried writing another variable to define userMonth with .toLowerCase but the condition ignores the line and goes straight to the else console.log message

    let userMonth = prompt('Enter the month: ')
    const checkMonth = userMonth.toLowerCase

    const autumn = ['september', 'october', 'november']
    const winter = ['december', 'january', 'february']
    const spring = ['march', 'april', 'may']
    const summer = ['june', 'july', 'august'.t]

    if(autumn.includes(checkMonth)){
      console.log(`${userMonth} is in Autumn`)

    } else if (winter.includes(checkMonth)){
      console.log(`${userMonth} is in Winter`)

    } else if (spring.includes(checkMonth)){
      console.log(`${userMonth} is in Spring`)

    } else {
      console.log(`${userMonth} is in Summer`)
    }

Why is ‘createElement’ adding extra tags?

If I add a row to a table with an existing th row

y=document.createElement('tr');
z=document.createElement('td');
z.append(document.createTextNode('abc'));
y.append(z);
x.append(y);
console.log(x.innerHTML);
console.log(x.outerHTML);
<table id="x">
<th>
<td>xyz</td>
</th>
</table>

I get

<tbody><tr><th></th><td>xyz</td></tr></tbody><tr><td>abc

from innerHTML, but this has added a tbody tag and also changed the order of the existing tags to what looks like to me ill-formed HTML.

I wanted

<th><td>xyz</td></th></tr><tr><td>abc</td></tr>

How to calculate time difference between two dates in months, days, hours, minutes, and seconds using JavaScript and Node.js?

Subtraction of 2 dates

I have date1 and date2, I want them to the difference between the two, and the return value should be, in months days hours minutes seconds

const date1 = new Date("5/13/23");
const date2 = new Date();

const timeDifference = (date1, date2) => {
  return date2 - date1 //returns milli, but what I want is the result of "0month, 15days, 12hours, 26minutes, 10seconds"
};

Remove “content” CSS property “onclick” button for the entire website

function myFunction() {
  document.getElementById('img');
  const element = document.styleSheets[0].cssRules[0].style.removeProperty('content');
}
img {
  content: url("https://static.vecteezy.com/system/resources/previews/005/476/277/original/under-18-forbidden-round-icon-sign-illustration-eighteen-or-older-persons-adult-content-18-plus-only-rating-isolated-on-white-background-free-vector.jpg");
  max-width: 100%;
  height: auto;
}
<button onclick="myFunction()">Show pics</button>

<img src="https://m.media-amazon.com/images/I/81K2hJBAduL.png">

The point is that after clicking on the “delete” button, the “content” property for the entire website.

Keep selection when selected row is clicked with tabulator

Is there an option in tabulator to keep the selection of a row if it is clicked?

For example – assume we have a table of 3 rows. When I click the second row it selected. I would like that click on the second row again will not deselect it (but clicking other rows will deselect it when using selectable: 1).

How can I make a Shopify cart item popup stay visible indefinitely in a Google Optimize A/B test?

I am building an A/B test for a Shopify site through Google Optimize. When someone adds a product to the cart, a popup shows with the item added to cart for only 5 seconds. I am trying to make it so that it shows indefinitely.

I wish I could edit the theme.js file directly, because it would be very simple. There is a function called popdown that has a setTimeout of 5 seconds. The class “is-visible” that is being added simply changes the visibility property to none.

Does anyone know how I could change this using JavaScript or CSS running through Google Optimize?

Here is the JavaScript/jQuery from the theme.js file that defines the method I’m trying to change.

Product.prototype = _.assignIn({}, Product.prototype, {
    init: function () {
      theme.mediaInstances[this.id] = new theme.Media(this.container);
      theme.mediaInstances[this.id].init();
    },
    initAdd: function () {
      var $drawer = $(this.selectors.addDrawerWrapper),
        source = $(this.selectors.addDrawerTemplate).html(),
        template = Handlebars.compile(source),
        globalTimer;

      $("[data-add-to-cart]").on("click", function (e) {
        var isFocusEnabled = $("body").hasClass("focus-enabled");
        if (isFocusEnabled) {
          return;
        }
        e.preventDefault();
        var form = $(this).closest("form"),
          form_serialized = form.serializeArray();
        if (form.find('[type="file"]').length) {
          return;
        }
        var form_object = {};
        $.map(form_serialized, function (val, i) {
          form_object[val.name] = val.value;
        });
        ajaxAddItem(form_object);
      });
      var ajaxAddItem = function (data) {
        $.ajax({
          type: "POST",
          url: "/cart/add.js",
          dataType: "json",
          data: data,
          error: addError,
          success: addSuccess,
          complete: updateHeaderTotal,
        });
      };
      var updateHeaderTotal = function () {
        $.getJSON("/cart.js").done(function (cart) {
          var newTotal = slate.Currency.formatMoney(
            cart.total_price,
            theme.moneyFormat
          );
          $(".cartCost")
            .html("(<span class='money'>" + newTotal + "</span>)")
            .removeClass("hidden-count");
        });
      };
      var addError = function (object, status) {
        var errors =
          '<div class="errors">' + object.responseJSON.description + "</div>";
        $drawer.empty();
        $drawer.append(errors);
        $drawer.addClass("has-errors is-visible");
        popdown();
      };
      var addSuccess = function (product) {
        productObject = {
          product_title: product.product_title,
          product_image: product.image,
          variant:
            product.variant_title == "Default Title"
              ? false
              : product.variant_title,
          quantity: product.quantity,
          price: slate.Currency.formatMoney(product.price, theme.moneyFormat),
        };
        $drawer.empty();
        $drawer.append(template(productObject));

        // Popover should be just below header
        var topPosition =
          $(".site-header").outerHeight() + $(".info-bar").outerHeight();
        $drawer.attr("style", "");

        // If it is sticky, just put it at the header height with position: fixed
        if ($(".header__wrapper").hasClass("header--sticky")) {
          var topPosition = $(".site-header ").outerHeight();
          $drawer.css("top", topPosition);
        } else if ($(window).scrollTop() > topPosition) {
          // header is not visible pin to top
          $drawer.css("top", 0);
          $drawer.css("z-index", "2000");
        } else {
          // otherwise positon: absolute below header
          // or at top if scrolled below header
          topPosition = Math.max($(window).scrollTop(), topPosition);
          $drawer.css("position", "absolute");
          $drawer.css("top", topPosition);
        }

        $drawer.addClass("is-visible");
        popdown();
      };
      var popdown = function () {
        clearTimeout(globalTimer);
        globalTimer = setTimeout(function () {
          $drawer.removeClass("is-visible").removeClass("has-errors");
        }, 5000);
      };
      $drawer.on("click", ".close", function () {
        $drawer.removeClass("is-visible").removeClass("has-errors");
      });
    }

I’ve tried changing the CSS to “visible”, but it never shows. I tried changing it through added CSS as well as changing the visibility property through JS. In the dev tools on Chrome, the visibility for the object shows “visible” in the computed styles, but it’s not working.

I’ve also tried changing the “initAdd” method within the Product class that has the “popdown” function in it. But I think there’s a different instance of the Product class that’s being utilized that I can’t seem to get access to. I’ve also tried looking through the eventListeners on the add to cart button.

I haven’t had success with anything so far. I’m open to trying anything. It’s such a small thing that I thought would be so simple but it’s been such a pain.

How do I detect a change in a select element in React?

I have an HTML form with a select dropdown for users to select a color, and I’m trying to detect when a new color has been selected. I’ve added the onchange attribute with a console.log() function, but nothing is printed to console when I select a new color.

Here’s my select element which is contained in the return statement for the form:

<select id="color-selector"
        name="colors"
        onchange={() => console.log("Color has changed")}>
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="yellow">Yellow</option>
    <option value="orange">Orange</option>
    <option value="purple">Purple</option>
</select>

I’ve seen this is possible in vanilla JS from this question, but is there a way to do this by using the onchange attribute in the HTML in React?

how can I access my store from RTK-Query endpoints?

I want to access to my redux-toolkit store data inside of the rtk-query endpoints

how can I access my store from query or transformResponse methods?

import { createApi } from '@reduxjs/toolkit/query/react'
import customFetchBase from './customFetchBase.js'
import { setUserInfo, setUserPermissions } from '../features/userSlice.js'
import { aesDEC } from 'src/util/public.util.js'

export const authApi = createApi({
  reducerPath: 'authApi',
  baseQuery: customFetchBase,
  endpoints: builder => ({
    getUser: builder.mutation({
      query: () => ({
        url: '/Account/Login/GetUserInfo',
        method: 'POST',
        body: {
          RequestVerificationToken: salt //here I want the salt from my redux store
        }
      }),
      transformResponse: response => {
        return aesDEC(response.data, salt); //here I want the salt from my redux store
      },
    }),
})
export const { useGetUserMutation } = authApi

Why is ChatGPT API giving me an error about exceeding my API quota in Node.js code?

Here’s the node.js code in question:

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
    apiKey: 'sk-12345678',
});
const openai = new OpenAIApi(configuration);

const runner = async () => {
    const response = await openai.createCompletion({
        model: "gpt-3.5-turbo",
        prompt: "The following is a conversation with an AI assistant. The assistant is helpful, creative, clever, and very friendly.nnHuman: Hello, who are you?nAI: I am an AI created by OpenAI. How can I help you today?nHuman: I'd like to cancel my subscription.nAI:",
        temperature: 0.9,
        max_tokens: 150,
        top_p: 1,
        frequency_penalty: 0.0,
        presence_penalty: 0.6,
        stop: [" Human:", " AI:"],
    });
    console.log(response);
}

runner();

Boilerplate direct from their documentation. However, I keep seeing an error that I’m out of a quota. I have not touched the API in an entire day and according to OpenAI I should have at least a few requests per minute.

What am I missing here?

out of quota of chatGPT

I’ve simply used the ChatGPT API as per the documentation to test it out but I’m unable to even get one request in.

How to center text using Three.js

I’m trying to render text like the one in the picture. I can manually put line break to the text however the content will be dynamic so I don’t think creating new line manually is a great option.
enter image description here

Here is my code so far. I can display text in one line.

import React, { useEffect } from "react";
import * as THREE from "three";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry";
import { FontLoader } from "three/examples/jsm/loaders/FontLoader";
import { ThreeJSOverlayView } from "@googlemaps/three";

const Text = (props) => {
  useEffect(() => {
    props.map.setCenter(props.mapOptions.center);
    const overlay = new ThreeJSOverlayView({
      anchor: {
        lat: props.mapOptions.center.lat,
        lng: props.mapOptions.center.lng,
        altitude: 0,
      },
      upAxis: "Y",
    });
    overlay.setMap(props.map);

    const fontLoader = new FontLoader();

    fontLoader.load("./font.json", function (font) {
      const title = "HYATT HOTEL VANCOUVER";

      const geometry = new TextGeometry(title, {
        font: font,
        size: 60,
        height: 5,
      });

      const material = new THREE.MeshPhongMaterial({
        color: 0x4285f4,
        specular: 0xffffff,
      });

      const mesh = new THREE.Mesh(geometry, material);

      mesh.position.copy(
        overlay.latLngAltitudeToVector3({
          lat: props.mapOptions.center.lat,
          lng: props.mapOptions.center.lng,
        })
      );

      mesh.position.setY(130);
      mesh.scale.set(0.3, 0.3, 0.3);
      mesh.rotation.y = -Math.PI;

      overlay.scene.add(mesh);
    });
  }, []);
};

export default Text;

My questions are:

  1. How do I set the width of text so that lines will automatically break?
  2. How do I center the 3D text?