how can i pass the cps on this extension?

i am trying to develop a chrome extension for a website and for that i am trying to add jquary to the site.
but when I try to add the jquery library as cdn with dom, I get an error like this:

Refused to load the script ‘https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval’ ‘inline-speculation-rules’ http://localhost:* http://127.0.0.1:*”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

I tried changes to the manifest file.I tried to create meta tag and edit cps with this tag.But I did not succeed…

Why the value of the newly created text node changes in Chromium?

Just type any text, e.g. an “a”, the console.log(‘newTextNode: ‘, newTextNode) would return “a” as its value (not in Firefox or Stack Overflow Code Snippet).

        const para = document.querySelector('p')
        let range = document.createRange()
        // this won't automatically set the caret position in Firefox or Stack Overflow Code Snippet
        range.setStart(para.firstChild, 1)
        range.collapse()
        window.getSelection().addRange(range)
        document.addEventListener('keypress', (e) => {
            // has this changed anything in Chromium?
            range = window.getSelection().getRangeAt(0)
            const newTextNode = document.createTextNode('hello')
            // with Chromium, this simply returns the charater you just typed
            console.log('newTextNode: ', newTextNode)
            // in Edge/Chrome this changes the value of newTextNode
            // in Firefox and Stack Overflow Code Snippet, this works as expected
            range.insertNode(newTextNode)
        })
    <p contenteditable="true">text</p>

How does Node calculate sum of an array faster than Rust? [duplicate]

I wrote a basic sum array function in both JS and Rust. Size of the array was 1 million. Node gave me the result in 4 ms whereas Rust took 15.4 ms (both on my laptop).

Why such a significant difference, given all the advantages that Rust has?

JS Code

const calcSum = arr => {
    let sum = 0;
    let i = arr.length;

    while(i--) sum += arr[i];
    return sum;
};

const run = size => {
    const arr = Array.from(Array(size).keys());
    const start = Date.now();
    const sum = calcSum(arr);
    const dur = Date.now() - start;
    console.log(sum, dur);
};

run(1e6);

Rust Code

use std::time::Instant;
const SIZE: i64 = 1e6 as i64;

fn main() {
    let a = get_array(SIZE);    
    let now = Instant::now();
    let sum = calc_sum(&a);
    let tme = Instant::now().duration_since(now);
    println!("{}, {:?}", sum, tme);
}

fn calc_sum(a: &Vec<i64>) -> i64 {
    let mut sum = 0;
    
    for n in a {
        sum += n;
    }
    
    sum
}

fn get_array(size: i64) -> Vec<i64> {
    let mut a: Vec<i64> = Vec::new();

    for i in 0..size {
        a.push(i);
    }

    a
}

webpack-dev-server not showing content in localhost

webpack-dev-server not showing content in localhost. Here are some files and the output screenshots for better understanding, Please help me to find the solution. I have tried many ways to fix it but couldn’t find the solution.

webpack.config.js

const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const FaviconsWebpackPlugin = require("favicons-webpack-plugin");

module.exports = {
mode: "production",
entry: "./src/index.js",

output: {
 path: path.resolve(__dirname, "dist"),
 filename: "bundle.js",
 publicPath: "/dist/",
},
devServer: {
 port: 3000,
 contentBase: path.join(__dirname, "dist"),
 compress: true,
 open: true,
},

module: {
 rules: [
   {
     test: /.(js|jsx)$/,
     exclude: /nodeModules/,
     use: {
       loader: "babel-loader",
     },
   },
   {
     test: /.(css|scss)$/i,
     use: ["style-loader", "css-loader", "sass-loader"],
   },
   {
     test: /.svg$/,
     use: ["@svgr/webpack"],
   },
   {
     test: /.(png|jp(e*)g|svg|gif)$/,
     use: ["file-loader"],
   },

   {
     test: /.(jpe?g|png|gif|woff|woff2|otf|eot|ttf|svg)(?[a-z0-9=.]+)?$/,
     use: [
       {
         loader: "url-loader",
         options: {
           limit: 1000,
           name: "assets/img/[name].[ext]",
         },
       },
     ],
   },
 ],
},
resolve: {
 extensions: ["*", ".js", ".jsx", ".css"],
},

plugins: [
 new HtmlWebpackPlugin({
   template: "./public/index.html",
   favicon: "./public/favicon.ico",
 }),
],
};

webpack-dev-server not showing content in localhost. Here are some
files and the output screenshots for better understanding, Please help
me to find the solution. I have tried many ways to fix it but couldn’t
find the solution.

Package.json

"scripts": {
    "serve": "webpack serve --mode development",
    "build": "webpack --mode production",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }, 
 "devDependencies": {
    "@babel/core": "^7.13.10",
    "@babel/preset-env": "^7.13.10",
    "@babel/preset-react": "^7.12.13",
    "babel-loader": "^8.2.2",
    "css-loader": "^5.1.3",
    "file-loader": "^6.2.0",
    "html-webpack-plugin": "^5.3.1",
    "style-loader": "^2.0.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.27.0",
    "webpack-cli": "^4.5.0",
    "webpack-dev-server": "^3.11.2"
  }

webpack-dev-server not showing content in localhost. Here are some
files and the output screenshots for better understanding, Please help
me to find the solution. I have tried many ways to fix it but couldn’t
find the solution.

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>NvntriSystem</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta content="NvntriSystem" name="description" />
    <meta content="NvntriSystem" name="author" />
    <!-- <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> -->
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
    <!-- <link rel="manifest" href="/site.webmanifest" /> -->
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
    <meta name="msapplication-TileColor" content="#2b5797" />
    <meta name="theme-color" content="#ffffff" />
    <meta name="apple-mobile-web-app-title" content="NvntriSystem" />
    <meta name="application-name" content="NvntriSystem" />
    <script
      async
      src="https://www.googletagmanager.com/gtag/js?id=G-QT7YMPDNZN"
    ></script>
    <link
      href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css"
      rel="stylesheet"
    />
    <link
      href="https://unpkg.com/[email protected]/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.css"
      rel="stylesheet"
    />

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.tablednd.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/extensions/reorder-rows/bootstrap-table-reorder-rows.min.js"></script>
    <!--For Google Analytics-->

    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag() {
        dataLayer.push(arguments);
      }
      gtag("js", new Date());

      gtag("config", "G-QT7YMPDNZN");
    </script>
  </head>
  <body>
    <div id="root"></div>
    <script src="bundle.js"></script>
  </body>
</html>

npm run serve compiled successfully

Showing this output

Sorting group collection after query with aggregate

I use aggregate to get all users have same name, but whenever I query to this API, the results return are not sorted even thought I add $sort by ‘name’ field.
const aggregateQuery: any = [ { $group: { _id: '$name', count: { $sum: 1 }, users: { $push: '$$ROOT' } } }, { $match: { count: { $gt: 1 } } }, { $unwind: '$users' }, { $replaceRoot: { newRoot: '$users' } }, { $sort: { name: 1 } } ];

    const users = await this.userRepository.getModel().aggregate(aggregateQuery).exec();

The order of the records is not sorted

Unexpected end of JSON input and Cannot read properties of undefined (reading ‘length’) [closed]

I am running into this problem and can’t seem to find any solution for it. Hope this group can help.

I have a wordpress website and a maps pluggin, I added multiple maps on the same webpage. In the administrator account, I can view the page, maps loaded no problem. However, when I log out of the admin account or view the page as visitor, the maps can’t be loaded and says: “Error loading map (Unexpected end of JSON input)” plus “Error retrieving marker list (Cannot read properties of undefined (reading ‘length’))”.

I tried to clear all caches and disable all other plugins to find the problem but it’s still there. Anyone has experience this before?

Please suggest solution!
Thank you!
Julian

I tried to clear all caches and disable all other plugins to find the problem but it’s still there. Anyone has experience this before?

Turn on shelly with authentication via script

Shelly Plus 1 PM should turn on Shelly 1 that is protected with username and password.

I have a Shelly Plus 1 PM running a script. At some point another Shelly 1 should be turned on for 10 seconds. As long as the Shelly 1 is not protected with username and password this works as expected:

function turnOn() { Shelly.call("http.get", {url: 'http://' + Config.ip + '/relay/0?turn=on&timer=' + JSON.stringify(Config.duration * 60)}); }

However i am struggling while including authentication as well. I tried the following:

function turnOn() { Shelly.call("http.get", {url: 'http://' + Config.username + ':' + Config.password + '@' + Config.ip + '/relay/0?turn=on&timer=' + JSON.stringify(Config.duration * 60)}); }

If this is executed nothing happens, the Shelly 1 stays turned off. If i send the exact same request (http://USERNAME:PASSWORD@IP/relay/0?turn=on&timer=10) via Postman it works as expected.

Any suggestions?

Issue with RTL while using the combination of both english and hebrew language

We are using a combination of both english and hebrew language in our project and due to the javascript display functionality the ordering of the words is not displayed properly on UI.

Below is the output which is been displayed when we are using both languages where you can see the date is not displayed properly.
enter image description here

Do we have any option where we can stop this behavior or any solutions which can help make the format proper.

Any help is much appreciated. Thanks in advance.!!

Why do the buttons open the same component instead of opening each button each component?

I have one parent component with 3 buttons and 3 children components. Each button should open one component but with my code the 3 buttons open the same component when I click on the buttons.
The children components are in 3 different files and the parent component has one state. Can anyone tell me what’s wrong in my code.
I pasted one child component example but they’re 3 alerts.
Besides, my task for school specifies this: The state should have three values representing info, success and failed. How can I do it?

parent component

export const Messages = () => {

  const [showInfo, setShowInfo] = useState(false);
  

  return (
    <Stack>
       <Button
        onClick={() => setShowInfo(true)}
      >
        open info message
      </Button>
      <InfoMessage open={showInfo} onClose={()=> setShowInfo(false)} />
      <Button
        onClick={() =>  setShowInfo(true)}
      >
        open success message
      </Button>
      <SuccessMessage open={showInfo} onClose={()=>  setShowInfo(false)} />
      <Button
        onClick={()=>  setShowInfo(true)}
      >
        open error message
      </Button>
      <ErrorMessage open={showInfo} onClose={() =>  setShowInfo(false)} />
    </Stack>
  )
}

Child component (one example)

interface InfoMessageProps {
  open: boolean;
  onClose: () => void;
}

export const InfoMessage = ({ open, onClose }: InfoMessageProps) => {

  const handleClose = (): void => {
    onClose();
  };

 
  return (
    <Snackbar
      open={open}
      autoHideDuration={4000}
      anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      onClick={handleClose}
      // TransitionComponent={transition}
    >
      <Alert
        sx={{
              width: '487px',
              height: '104px',
              paddingTop: '20px',
              paddingLeft: '20px',
              backgroundColor: '#FDFDFD',
        }}
        icon={false}
        action={(
          <IconButton
            aria-label="close"
            color="inherit"
            size="small"
            onClick={handleClose}
          >
            <CloseIcon fontSize="inherit" />
          </IconButton>
        )}
      >
        <AlertTitle sx={{ paddingRight:'80px' }}>
          <Typography variant='headings.h4'>title</Typography>
        </AlertTitle>
        <Typography variant='captions.default'>Insert message here</Typography>
      </Alert>
    </Snackbar>
  );
};

Firebase 9.22 firebase-messaging-sw.js only onBackgroundMessage & onMessage event not working

Firebase 9.22 firebase-messaging-sw.js only onBackgroundMessage & onMessage event not working my service worker file given below:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.22.0/firebase-app.js";
import { getMessaging } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging-sw.js'
import { onBackgroundMessage  } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging-sw.js'
import { onMessage  } from 'https://www.gstatic.com/firebasejs/9.22.0/firebase-messaging.js'

const firebaseApp = initializeApp({
  apiKey: "AIzaSyCkrFDDHrhh-C3SRY47OTd7puysoJlFZ2Q",
  authDomain: "web-push-test-cc811.firebaseapp.com",
  projectId: "web-push-test-cc811",
  storageBucket: "web-push-test-cc811.appspot.com",
  messagingSenderId: "228880798813",
  appId: "1:228880798813:web:33102cb1b15baa5a4769b4",
  measurementId: "G-BL9BX4S59N"
});

// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
});

onMessage(messaging, (payload) => {
  console.log('Message received. ', payload);
});

Parsing {some_string} with any html tag or function in Javascript/PHP

Does anyone know how to or what method use to replace {some_text} with any function or html tag like markdown?

Here I’m trying to replace plain text from my database(SQL) to some function

{copy} - Websitename - Allights reserved

to replace copy with Date function

<script>document.write(new Date().getFullYear())</script>

so the final result in my Website will be

2023 - - Websitename - Allights reserved

Please anyone help?

How to call a parameterized tinymce.init from external js file?

I have searched a lot for finding answer how to create a separate .js file with javascript containing the following code:

tinymce.init({
    selector: '#tbInformation',
    plugins: 'lists advlist preview searchreplace',
    toolbar: 'preview | undo redo | blocks fontfamily fontsize | bold italic underline | bullist numlist | align lineheight' ,
    language: 'da',
    resize: false,
    branding: false
});

If I do the following in my aspx-file where the tinymce editor is placed – it works in this way:

<script type="text/javascript">
    tinymce.init({
        selector: '#tbInformation',
        plugins: 'lists advlist preview searchreplace',
        toolbar: 'preview | undo redo | blocks fontfamily fontsize | bold italic underline | bullist numlist | align lineheight' ,
        language: 'da',
        resize: false,
        branding: false
    });
</script>

My problem is that tinymce.init(); needs a selector which I have to provide – but as far as I can see I do not have this functionality provided by tinymce – so my question is: How to create a generel routine in a separate .js file with all the configuration for my tinymce editor and with a parameterized selector – a general routine which easy can be called from an several aspx-files?

Thanks in advance

Best regards,

Michael

Make an iterator from an array [duplicate]

I am currently modifying some code and trying to not mess with the initial structure. Having a for...of loop over an array, and having a second array with an identical structure, I am wondering if there is a quick way to make a generator over my second array to simulate a zip.

Here’s an example:

const firstArray = ["a", "b", "c"];
const myAdditionalArray = [1, 2, 3];
// const generatorOverMyAdditionalAray = ???
for (const item of firstArray) {
  // Initial code doing stuff with item
  const additionalItem = myAdditionalArray.next();  
  // More code doing stuff with item and additionalItem
}

For pythonistas, it would look something like that

>>> a = ["a", "b", "c"]
>>> b = [1, 2, 3]
>>> generator_over_b = (x for x in b)
>>> for item in a:
...     additional_item = next(generator_over_b)
...     print(item, additional_item)
... 
a 1
b 2
c 3