Connection error while installing react native cli via npm

I have been going step by step by the official instructions that are on react native site in the dev OS I have Windows and in the target OS I have Android. The installation via choco went well but when I try installing it with:

npm install -g react-native-cli

it starts normal like this:
[..................]  idealTree:npm: sill idealTree buildDeps
but then after a while it returns just these errors:
errors

I have already tried changing proxy and making it “the right way” but it just keeps crashing like this. Btw I have proxy on http://domain:8080/

Any ideas how to fix this pls?

replace all the special characters except numbers with javascript / node js

I am trying to replace all the special characters even space but not numbers with - but if there are multiple special characters like [/// then it should only replace -

I have added my expected output in snippet

const string= "![astronaut-lost-in-space-rk](//images.ctfassets.net/c8qz6f7npv42/fJd9r4N1eriItv5XNp0uv/4b46d52459ea20684c653a1c200b5aa1/astronaut-lost-in-space-rk.jpg)";

console.log(string.replace(/[^a-zA-Z ]/g, "-"));

console.log("Expected Output")

console.log("-astronaut-lost-in-space-rk-images-ctfassets-net-c8qz6f7npv42-fjd9r4n1eriitv5xnp0uv-4b46d52459ea20684c653a1c200b5aa1-astronaut-lost-in-space-rk-jpg-")

In snippet you can see I have 4 special characters present at like this ])\ and it getting replace by - by 4 times ---- I want to replace special characters but if it present more then 1 then it should replace every special character but show only one -

Creating a table with js

OK, I am very new to these things. I thought I got the DOM sense right but my code is not working. The task is to create a table like
this

This is the piece I did. Could you please help me out with pointing out at the mistake I made or parts missing in my code? Every help very much appreciated.

const tableValues = new Array(10).fill(false).map((x, i) => {
  return new Array(10).fill(1).map((y, i2) => {
    return (i + 1) * i2
  })
})

document.addEventListener('DOMContentLoaded', tableCreate, false);

function tableCreate() {
  const table = document.getElementById("table");
  tableValues.forEach((row) => {
    const row = document.createElement("tr")
    row.forEach(cell => {
        const cell = document.createElement("td");
        cell.innerHTML = cellText;
        cell.appendChild(cellText)
      }
      row.appendChild(cell))
  })
  table.appendChild(body)
}
<table>
  <tbody id="table"></tbody>
</table>

Node js SSR not rendering

I have a bit of code that should load a page and show an image(from server storage), that sometimes changes(is replaced by another image with the same name).

main.js:

const app = express();
const ejs = require('ejs');
var fs = require('fs');
const port = 8000;
   
// Render index.ejs file
app.get('/', function (req, res) {
   
    // Render page using renderFile method
    ejs.renderFile('index.ejs', {}, 
        {}, function (err, template) {
        if (err) {
            throw err;
        } else {
            res.end(template);
        }
    });
});
   
// Server setup
app.listen(port, function (error) {
    if (error)
        throw error;
    else
        console.log("Server is running");
});

index.ejs:

<html lang="en">
    <head>
        <title>Fasole LIVE</title>
        <link rel="stylesheet" href="styles.css">
        <meta charset="UTF-8">
        <meta name="viewport" content=
            "width=device-width, initial-scale=1.0">
    </head>
    <body>
        <img src="live.png" class="live" id="live">
        <script>
            while(true)
            {document.getElementById("live").src("live.png")}
        </script>
    </body>
</html>

What am I doing wrong?

requestanimationframe slows down when publish

I am building a game and i do the animations with requestanimationframe and when i run it locally on localhost everything goes smoothly and runs in the speed i want, but when i publish the game on github pages everything goes super slow. And I dont get any warning that the requestanimationframe took n secs to complete. Is it the speed of the server that the site is hosted on or should i check something else ?

The only thing i tried so far is increase the game speed but i didnt notice any changes in the final product

Google calendar api implemention troubles

I’ve been trying to implement the google calendar API into my website so the end-user can see easier when there’s an appointment already set up so they don’t have to go through the issue of getting the error message of there already being an appointment set up for that date and time, but, google’s being a bitch and their guide is as straight forward as a curvy road, so, someone for the love of god help me out cuz I genuinely have no idea what I’m doing wrong since its their code, the only thing that might be wrong is the credentials.json file but again, the own google tutorial is shite and doens’t say fuck all on how to get them.

Code:

require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
    $client->setAuthConfig(__DIR__ . '/credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:n%sn", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);

// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
  'maxResults' => 10,
  'orderBy' => 'startTime',
  'singleEvents' => true,
  'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();

if (empty($events)) {
    print "No upcoming events found.n";
} else {
    print "Upcoming events:n";
    foreach ($events as $event) {
        $start = $event->start->dateTime;
        if (empty($start)) {
            $start = $event->start->date;
        }
        printf("%s (%s)n", $event->getSummary(), $start);
    }
}?>

Thanks in advance

Error given:
PHP Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleauthsrcOAuth2.php:637
Stack trace:
#0 C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleapiclientsrcGoogleClient.php(328): GoogleAuthOAuth2->buildFullAuthorizationUri(Array)
#1 C:xampphtdocsprogramationsPAPIsrcuserStuffquickstart.php(38): Google_Client->createAuthUrl()
#2 C:xampphtdocsprogramationsPAPIsrcuserStuffquickstart.php(63): getClient()
#3 {main}
thrown in C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleauthsrcOAuth2.php on line 637

Fatal error: Uncaught InvalidArgumentException: missing the required redirect URI in C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleauthsrcOAuth2.php:637
Stack trace:
#0 C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleapiclientsrcGoogleClient.php(328): GoogleAuthOAuth2->buildFullAuthorizationUri(Array)
#1 C:xampphtdocsprogramationsPAPIsrcuserStuffquickstart.php(38): Google_Client->createAuthUrl()
#2 C:xampphtdocsprogramationsPAPIsrcuserStuffquickstart.php(63): getClient()
#3 {main}
thrown in C:xampphtdocsprogramationsPAPIsrcuserStuffvendorgoogleauthsrcOAuth2.php on line 637

Next/image doesn’t load my src image when I use a map

I use next/image to load my images in my app. It works fine except for a carousel with multiple images.
When I do like this I have that error :

Error: Image is missing required “src” property. Make sure you pass “src” in props to the next/image component. Received: {}

The problem is not because I have an entity without any file

image.js

import { getStrapiMedia } from "../utils/medias"
import NextImage from "next/image"

const Image = (props) => {
  if (!props.media) {
    return <NextImage {...props} />
  }

  const { url, alternativeText } = props.media

  const loader = ({ src }) => {
    return getStrapiMedia(src)
  }

  return (
    <NextImage
      loader={loader}
      layout="responsive"
      objectFit="contain"
      width={props.media.width}
      height={props.media.height}
      src={url}
      alt={alternativeText || ""}
    />
  )
}

export default Image

Carousel.js

import React, { useCallback } from "react"
import useEmblaCarousel from "embla-carousel-react"
import NextImage from "./Image"

export const EmblaCarousel = (product) => {
  const [emblaRef, emblaApi] = useEmblaCarousel()

  useEmblaCarousel.globalOptions = { loop: true }

  const scrollPrev = useCallback(() => {
    if (emblaApi) emblaApi.scrollPrev()
  }, [emblaApi])

  const scrollNext = useCallback(() => {
    if (emblaApi) emblaApi.scrollNext()
  }, [emblaApi])

  return (
    <div className="embla" ref={emblaRef}>
      <div className="embla__container">
        {product.gallery.map((_gallery) => (
          <div key={_gallery.id}>
            <NextImage media={_gallery.image} className="embla__slide" />
          </div>
        ))}
      </div>
      <button
        className="hidden md:inline embla__prev mr-2"
        onClick={scrollPrev}
      >
        Prev
      </button>
      <button
        className="hidden md:inline embla__next ml-2"
        onClick={scrollNext}
      >
        Next
      </button>
    </div>
  )
}

export default EmblaCarousel

How can I get Data from Localstorage when working with useContext , useReducer

I use the app from useContext , useReducer to State management and I want to save Data in the ProductList Comp on Localstorage, Save the successful Data, but I can not get the data …

const ProductsList = () => {
  const data = useProducts(); // get data with Custom hook
  const dispatch = useProductsAction(); 


  //GET localStorage
  useEffect(() => {
    console.log("get local");
    const items = JSON.parse(localStorage.getItem("products"));
    if (items) {
      return items;
    }
  }, []);

//SET localStorage
  useEffect(() => {
    localStorage.setItem("products", JSON.stringify(data));
  }, [data]);


  return (
    <div>
      {data.length > 0 ? (
        data.map((i) => {
          return (
            <Products
              key={i.id}
              name={i.name}
              onClick={() => dispatch({ type: "deleteProduct", id: i.id })}
            />
          );
        })
      ) : (
        <h3>Empty</h3>
      )}
    </div>
  );
};

export default ProductsList;

enter image description here

how to redirect admin to diffeerent child page in react router dom

I am facing an issue in using react-router-dom. I have an admin if admin click any particular option like ALL USER, add project
if admin clicks any particular option like ALL USER, add project then it will render the second page so my question is to how to do child specify redirect.

I tried using normal Link to but if click any option in admin then it will redirect to the whole different new page instant of under the admin/user. see the image

enter image description here

This is My App.js

import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './components/Home';
import Navbar from './components/Navbar';
import Contact from './components/Contact';
import Service from './components/Service'
import Login from './components/Login';
// Redirect to their dashboar
import Admin from './components/dashboard/Admin';
import Employee from './components/dashboard/Employee';
import Publisher from './components/dashboard/Publisher';
//Toast error message show
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Reset from './components/Reset';
import Newpassword from './components/Newpassword';

//admin Routes
import Project from './components/dashboard/AdminPages/Project'
import User from './components/dashboard/AdminPages/User';

function App() {

  return (
    <div>

      <Router>
        <Navbar />
        <Routes>

          <Route exact path="/" element={<Home />} />
          <Route exact path="/service" element={<Service />} />
          <Route exact path="/contact" element={<Contact />} />
          <Route exact path="/login" element={<Login />} />
          <Route exact path="/reset" element={<Reset />} />
          <Route exact path="/reset/:token" element={<Newpassword />} />
          {/* Redirect to their dashboard */}
          <Route exact path="/admin" element={<Admin />} />
          <Route exact path="/employee" element={<Employee />} />
          <Route exact path="/publisher" element={<Publisher />} />
          {/* admin pages */}
          <Route exact path="/publisher" element={<Project />} />
          <Route exact path="/user" element={<User />} />

        </Routes>
      </Router>

      <ToastContainer
        position="top-right"
        autoClose={4000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
      />
    </div>
  );
}

export default App;
Admin.js

import React from 'react'
import { CDBSidebar, CDBSidebarContent, CDBSidebarHeader, CDBSidebarFooter, CDBSidebarMenu, CDBSidebarMenuItem } from "cdbreact"
import { NavLink} from 'react-router-dom';
import "./AllStyle.css"

const Admin = () => {
 
  return (
    <div>
      <div style={{ display: 'flex', height: '100vh', overflow: 'scroll initial' }}>
        <CDBSidebar textColer="#fff" backgroundColor="rgb(0,7,61)">
          <CDBSidebarHeader prefix={<i className="fa fa-bars fa-large"></i>}>
            <h4>Admin</h4>
          </CDBSidebarHeader>
          <CDBSidebarContent className="sidebar-content">
            <CDBSidebarMenu>
              <NavLink  to="/user">
                <CDBSidebarMenuItem icon="portrait">
                  ALL USER
                </CDBSidebarMenuItem>
                <hr></hr>
              </NavLink>
              <NavLink  to="/">
                <CDBSidebarMenuItem icon="file-contract">
                  Add Project
                </CDBSidebarMenuItem>
                <hr></hr>
              </NavLink>
              <NavLink  to="/login">
                <CDBSidebarMenuItem icon="sign-out-alt">
                  Logout
                </CDBSidebarMenuItem>
                <hr></hr>
              </NavLink>
            </CDBSidebarMenu>
          </CDBSidebarContent>
          <hr></hr>
          <CDBSidebarFooter style={{ textAlign: 'center' }}>
            <div className="sidebar-btn-wrapper" style={{ padding: '20px 5px' }}>
              Evalue Content portal
            </div>
          </CDBSidebarFooter>
        </CDBSidebar>
      </div>
    </div>
  )
}

export default Admin

If anyone knows how to fix this please let me know

Why in React js Map() method is not working

If I use console.log it is printing all values perfectly and also if I pass these props one by one then it works perfectly fine but this map is not working her is my code:

` import Card from ‘./Components/Card’;
import ‘./App.css’

const data = [
  {
    id : "1",
    title : "DARK",
    image : require("./Images/potrait1.jpg")
  },
  {
    id : "2",
    title : "DARK",
    image : require("./Images/potrait8.jpg")
  },
  {
    id : "3",
    title : "DARK",
    image : require("./Images/potrait4.jpg")
  },
  {
    id : "4",
    title : "DARK",
    image : require("./Images/potrait5.jpg")
  },
  {
    id : "5",
    title : "DARK",
    image : require("./Images/potrait6.jpg")
  },
  {
    id : "6",
    title : "DARK",
    image : require("./Images/potrait7.jpg")
  }
]

let App = ()=>{

{data.map((val)=>{

      return(
            <Card
              key = {val.id} 
              title = {val.title}
              image = {val.image}
            />
        );

  })}
}

export default App;

`

Javascript Uncaught TypeError: Cannot read properties of undefined (reading ‘style’)

Below is the code snippet, on line number 18 and 22 where I have set the style property, it is giving the error cannot read property of undefined but I’m creating the element as div inside the constructor and appending the tile class still it is giving the error

export default class Tile {
  #tileElement
  #x
  #y
  #value
  contructor(tileContainer, value = Math.random() > 0.5 ? 2 : 4) {
    this.#tileElement = document.createElement('div')
    this.#tileElement.classList.add('tile')
    tileContainer.append(this.#tileElement)
    this.#value = value
  }
  set value(v) {
    this.#value = v
    this.#tileElement.textContent = v
  }
  set x(value) {
    this.#x = value
    this.#tileElement.style.setProperty('--x', value)
  }
  set y(value) {
    this.#y = value
    this.#tileElement.style.setProperty('--y', value)
  }
}

Revalidate on-demand a Next.js site from Django model’s save method

I have a next.js site deployed to Vercel, that fetches data from an API provided by Django. Next.js has this new feature (Incremental Static Regeneration On-Demand) where you can rebuild a specific page without need to rebuild the entire site with an url like this:

https://<my-site.com>/api/revalidate?secret=my-token

I need the next.js site rebuild some pages when the database changes, so it shows the new data, and i tried to make a request (with requests package) in the save method like this:

def save(self, *args, **kwargs):
    super(MyModel, self).save(*args, **kwargs)
    r = requests.get("https://<my-site.com>/api/revalidate?secret=<my-token>")

It seems to work when it trigger that url from my browser, but it doesn’t work when i trigger it from Django. The response of this Response object (r) is a 200 Status Code, as expected, with {“revalidated”:true} (r.text), but it doesn’t update the site anyways.

How can i implement this?

Security Concerns of Entirely Localized Password Manager

I’m creating a Chrome extension to autofill username and password for one specific site, “example.com”. I would like to make EVERYTHING localized to prevent any security concerns. My process is as follows:

  • on Options page, user can input username/password, which is saved in chrome.storage.local
  • on “example.com”, the extension autofills the username and password with chrome.storage.local.get(() => ...)

What are the security concerns of this?

What I’ve Considered

I’m concerned about

  1. Chrome says storage.local is not safe, but they do not provide reasons. Liability?
  2. Chrome also says storage.local is unique per chrome extension / site. So the ONLY way for an attacker to steal a password is by hacking me and / or my source code, and pushing malicious changes to my extension, correct? (if there’s any other way it’s a definite no-go)
  3. Ideally, I would have the password / username be encrypted, with e.g. AES-256. But if everything’s local, there’s either one master key (which any attacker could find) or a unique key that’s stored “securely somewhere” in the app, maybe created at install. << but where to store that? If there’s a “secure somewhere” in the app, I should just put the password / username there.

I’d like to do this without a server, however if that’s not possible I’m open to suggestions.

How can I improve this JS reduce?

So I have two different APIs that I’ve fetched from using await Promise.all(). They are assigned to a variable called items. API #1’s response is an object that would look like this:

{
    total: 3,
    items: [
        {…},
        {…},
        {…}
    ]
}

API #2’s response is just an array of objects.

Now I want to end up with an object looking like the response from API #1, using a reducer to add the length of API #2’s to the total and ’merge’ the response from API #2 into the items array.

This is what I’ve gone for:

const items = results.reduce((accumulator, { response }) => {
    const total = response?.total ?? response?.length

    if(!accumulator?.items) {
        accumulator.items = []
    }

    accumulator.items = [
        ...accumulator.items,
        ...(response?.items ?? response)
    ]

    return ({
        ...accumulator,
        total: (accumulator?.total ?? 0) + total
    })
}, {})

I’m quite a noob when it comes to reduce() and my gut feeling is that there could definitely be a cleaner/more structured way of accomplishing the same result. Any major hiccups that I should re/-consider?

Thanks!

Hello,I want the js function return the result but it show errorPromise {: undefined}

    if (window.ethereum) {
        const ethereum = window.ethereum;
        const web3 = new Web3(ethereum);
        const ethereum_account = ethereum.request({ method: 'eth_requestAccounts' });
        const ct = new web3.eth.Contract(abi, contract);

        try {
            await ethereum_account.then(accounts => {
                ct.methods.transfer(toaddress, web3.utils.toWei(value, "ether")).send({ 'from': ethereum.selectedAddress }).on('receipt', (receipt) => {
                    const result = {}
                    console.log(result) // I can see the result at console
                    return result //but I cannot get the return
                })
            });

        } catch (error) {
            console.log(error);
        }

Im new for code js,
I want the function return the result , but it shows undefine!