Is it safe to use url link to sort table rows using Django for backend?

I was asking my supervisor for an opinion to sort rows of a table.

When a table head column is clicked, I basically change the url to: /?order_by=price then check

if url == /?order_by=price:
    Inventory.objects.order_by('price')

He told me I could do this in frontend with css,because if someone enters a bad input or injects smth, they can access my whole table.

Is the backend logic with Django good for this problem, or should I do it as he said?

In Expo is there a way to disable a button depending on the current page?

I have created an Expo application with React Native and I am encountering an issue with disabling a button in my top Stack.

I have implemented my routes so that I have a /app/(main) /app/(main)/(tabs) and /app/(main)/(bannertabs).

My /app/(main)/_layout.tsx has a stack, where both the (tabs) and (bannertabs) have the same banner layout. I want to implement my right header as a button that leads to the user profile, which I have done with a button that calls router.push(‘/app/(main)/(bannertabs)/profile’) however, once on the profile page I want to disable the profile button so so the user cannot infinitely stack this page.

I attempted to do this with a Context Provider and it worked (setting isOnProfile to true on Profile page and false on (main)/layout.tsx) , however I ran into some js errors that lead me to believe this is not a good solution.

Are there any options so that I can disable the button when I am on a certain page? A better way to handle my context provider maybe?

prerender images when displayed out of the screen

i want to display a set of divs by moving them from translate-y=800px position to translate-y=0 when triggering scroll event
here is the html code:

                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>
                <div class='ml slider-elem translate-y-[800px]'></div>

and here is the js event handler

                for (i =0; i <sliderElems.length; i++) {
                    sliderElems[i].style.transform='translate(0px)'
                }

when the initial translate-y=200px or 100px (any value that let the element be rendered inside the screen) i have a smooth translation
but if the translation value throw the element out of the -above the fold- area i have a glitchy background image rendering when changing translation
consider that

body{
overflow:hidden;
}

is there a way to prepare the browser for a better rendering of the images

Jest reporting lines are uncovered when they actually are covered

I have a file reporting as only 48% covered, but when I looked at the report its very confusing because it seems like those lines are covered by tests. Example:

Settings.js

class Settings {

  general = {
      code: 'general',
      language: 'en-us',
      volume: 50,
      brightness: 75,
      notifications: true,
      autoUpdate: true,
  };
  ...

settings.test.js:

test('should initialize with default values', () => {
  const settings = new Settings();

  expect(settings.general).toEqual({
    code: 'general',
    language: 'en-us',
    volume: 50,
    brightness: 75,
    notifications: true,
    autoUpdate: true,
  });
});

The test passes and all appears to be well, except here is the resulting coverage report:

Test coverage report

Any idea what could cause this? If it matters, we are using the v8 coverageProvider in the jest setup.

How to dynamically inject/execute JavaScript in an iframe on a Wix site?

My Goal:
The goal is to dynamically load and execute different JavaScript code snippets within an iframe on a Wix website when users click between two buttons, with each button triggering the retrieval and injection of specific code from the backend into the iframe, ensuring the code is properly executed each time a button is clicked.

Frontend Setup:

  • There are two buttons (#button1 and #button2) on the Wix page.
  • Clicking these buttons triggers the corresponding backend method to retrieve the JavaScript code.
  • The retrieved code is then sent to an HTML iframe component (#htmlComponent) using the postMessage method.

The page code looks like this:

import { getTest1Content } from 'backend/Test1.web.js';
import { getTest2Content } from 'backend/Test2.web.js';

$w("#button1").onClick(async () => {
    const script1 = await getTest1Content();
    $w("#htmlComponent").postMessage({ action: "insertScript", content: script1 });
});

$w("#button2").onClick(async () => {
    const script2 = await getTest2Content();
    $w("#htmlComponent").postMessage({ action: "insertScript", content: script2 });
});

Backend Setup:
I have two backend methods (getTest1Content and getTest2Content) that return JavaScript code as strings. These methods are defined in Test1.web.js and Test2.web.js using webMethod from the Wix Velo API.

Test1.web.js looks like this:

import { webMethod, Permissions } from 'wix-web-module';

export const getTest1Content = webMethod(Permissions.Anyone, () => {
    return `document.write(unescape('%3C%21DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Cbody%3E%0A%0A%3Cbutton%20type%3D%22button%22%20onclick%3D%22alert%28%27Hello%20world%21%27%29%22%3EClick%20Now%21%3C/button%3E%0A%20%0A%3C/body%3E%0A%3C/html%3E%0A'));`;
});

Test2.web.js looks like this:

import { webMethod, Permissions } from 'wix-web-module';

export const getTest2Content = webMethod(Permissions.Anyone, () => {
    return `document.write(unescape('%3C%21DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Cbody%3E%0A%0A%3Cbutton%20type%3D%22button%22%20onclick%3D%22alert%28%27Hello%20world%21%27%29%22%3EClick%20Me%21%3C/button%3E%0A%20%0A%3C/body%3E%0A%3C/html%3E%0A'));`;
});

Iframe Setup:
The iframe listens for messages from the parent Wix page.
When a message is received, it attempts to inject the received JavaScript code into the iframe:

<!DOCTYPE html>
<html>
<body>
    <div id="content"></div>
    <script>
        //Taking messages from the parent Wix page
        window.onmessage = function(event) {
            if (event.data && event.data.action === "insertScript") {
                // Removing the old script
                var oldScript = document.getElementById('dynamicScript');
                if (oldScript) {
                    oldScript.remove();
                }

                // adding the new script
                var script = document.createElement('script');
                script.id = 'dynamicScript';
                script.type = 'text/javascript';
                script.text = event.data.content;

                // putting the new script in to the body
                document.body.appendChild(script);
            }
        };
    </script>
</body>
</html>

The Problem I am facing:
The script is not executed when switching between the two buttons (i.e., after one button is clicked, clicking the other button does not execute the new script).

Performance difference between Chrome and Firefox: Object.assign, spread, adding properties in loop

I’m currently looking into performance of creating objects in a data container that are initialized with a known list of properties that should intially be all null.

I was testing different approaches:

  • the code we had that iterates over the list of properties and adds
    each to an object that was initialized empty
  • Creating a template empty object and copying it with spread operator
  • Creating a template empty object and copying it with Object.assign

Testing this in a TS Playground showed that spread operator and Object.assign were fastest, but our code got slower actually when I did the change. I noticed that there was a big difference between Chrome (what I used to test our code) and Firefox (used to test on TS Playground).

I ended up creating a MeasureThat benchmark that did confirm this.

Differences are significant, where the performance of our original code is comparable, the other two are so much slower on Chrome that I can’t explain it. Anyone an idea what is happening here?

Timings from my machine:

Chrome results

Firefox results

How to use environment variables in client side js script

I have a html file and a javascript code file.

The js file has a fetch call which requires i add a secret key, I have put this secret key in a .env file, how do i make this js script work when i add it to a script tag on the html file. below is the js code and how i want to add it to the script tag on the html file.

document.getElementById('getstarted').addEventListener('click', () => {
  const applicanturl = 'https://api.sumsub.com/resources/applicants';
  const applicantoptions = {
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'X-App-Token': process.env.Token
    },
    body: JSON.stringify({
      externalUserId: '1234EERF', //Unique applicant identifier as registered on your side.
      email: '[email protected]'
    })
  };

fetch(applicanturl, applicantoptions)
  .then(res => {
    res.json()
  })
  .then(json => {
    console.log(json)
  })
  .catch(err => console.error('error:' + err));
})

here is what i want to do on the html file

<script src="../../applicant.js"></script>

This is what i have in my webpack.config.js file

const path = require('path');
const Dotenv = require('dotenv-webpack');

module.exports = {
  entry: './src/applicant.js',  // or wherever your entry file is
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  resolve: {
    fallback: {
      "path": require.resolve("path-browserify"), // add this line
    },
  },
  plugins: [
    new Dotenv(),
  ],
  mode: 'development', // or 'production'
};

Facing issue while migrating Jest@26 to Jest@27

I’m trying to migrate Jest from version 26 to 27 in my Next.js 13 project but facing the following error while running test after updating to Jest 27 version –

 FAIL  src/__tests__/app.test.tsx
  ● Test suite failed to run

    Cannot combine importAssertions and importAttributes plugins.

      at validatePlugins (node_modules/@babel/parser/src/plugin-utils.ts:130:11)
      at getParser (node_modules/@babel/parser/src/index.ts:106:5)
      at parse (node_modules/@babel/parser/src/index.ts:32:22)
      at parser (node_modules/@babel/core/src/parser/index.ts:28:19)
          at parser.next (<anonymous>)
      at normalizeFile (node_modules/@babel/core/src/transformation/normalize-file.ts:51:24)
          at normalizeFile.next (<anonymous>)
      at run (node_modules/@babel/core/src/transformation/index.ts:38:36)
          at run.next (<anonymous>)
      at transform (node_modules/@babel/core/src/transform.ts:29:20)
          at transform.next (<anonymous>)
      at evaluateSync (node_modules/gensync/index.js:251:28)
      at fn (node_modules/gensync/index.js:89:14)
      at stopHiding - secret - don't use this - v1 (node_modules/@babel/core/src/errors/rewrite-stack-trace.ts:97:14)
      at transformSync (node_modules/@babel/core/src/transform.ts:66:52)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.683 s

before updating the Jest, the test was passing so it’s not related to my code.
My jest.config.js looks like this –

module.exports = {
  collectCoverage: true,
  coverageProvider: 'babel',
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
    '!<rootDir>/out/**',
    '!<rootDir>/.next/**',
    '!<rootDir>/*.config.js',
    '!<rootDir>/coverage/**',
  ],
  moduleNameMapper: {
    '^.+\.module\.(css|sass|scss)$': 'identity-obj-proxy',
 
    '^.+\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
 
    '^.+\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,
 
    '^@/components/(.*)$': '<rootDir>/components/$1',
 
    '@next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
    'next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
    'server-only': `<rootDir>/__mocks__/empty.js`,
  },
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'jsdom',
  transform: {
    // Use babel-jest to transpile tests with the next/babel preset
    // https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
    '^.+\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
  },
  transformIgnorePatterns: [
    '/node_modules/',
    '^.+\.module\.(css|sass|scss)$',
  ],
}

and babel.config.js

module.exports = {
  presets: ["next/babel"],
  plugins: [
    [
      'react-css-modules',
      {
        autoResolveMultipleImports: true,
        generateScopedName: '[name]__[local]__[hash:base64:5]',
        handleMissingStyleName: 'throw',
        webpackHotModuleReloading: true,
      },
    ],
  ],
};

my package.json snapshot is here:

 {
    "dependencies": {
    "abortcontroller-polyfill": "^1.7.5",
    "babel-plugin-react-css-modules": "^5.2.6",
    "next": "13.1.0"
  },
  "devDependencies": {
    "@babel/core": "^7.22.0",
    "@testing-library/dom": "^10.4.0",
    "@testing-library/jest-dom": "^6.4.8",
    "@testing-library/react": "^16.0.0",
    "@types/jest": "^29.5.12",
    "babel-loader": "^8.2.2",
    "css-loader": "^3.4.2",
    "jest": "27.0.0",
    "jest-environment-jsdom": "^29.7.0",
    "node-fetch": "^2.6.1",
    "nodemon": "^2.0.7",
    "webpack": "^5.75.0"
  }
}

Please help me resolve this !

object.entries used with array as the object

please help me to understand the following code, it is an object of arrays (a grouping)

let groupArray = {"1":[{"id":"1","value": "13"},{"id":"1","value": "33"}],"2": [{"id":"2","value": "23"}],"3": [{"id":"3","value": "13"}]}
let resultArray = []
Object.entries(groupArray).forEach(g => {
  let sumValue = 0
  g[1].forEach(o => sumValue += parseFloat(o.value))
  resultArray.push({
    "id": g[0],
    "value": sumValue.toString()
  })
})
console.log(resultArray)

Am I correct in assuming that when an array is the object of the entries method then the return value will be an iterator? Then am I passing the next() value into the iterator object? In the above code we have g[1}.forEach. This is the part I am not understanding, thanks

I am passing the value 1 into the g object

How to check for an item not in an object

I have some borrowed code I’m trying to tweak for my needs. Ref. below code:

// Object that will contain all of the MRNs we want to keep
var assgnAuthToKeep = {};

for each(pid3 in PIDsegment['PID.3'])
{
    if(pid3['PID.3.4'].toString() in assgnAuthToKeep)
        delete PIDsegment[pid3.childIndex];
        
}

How can I check for the value NOT IN the object in the if statement?
!in doesn’t work nor does not in

Fetch and build a 2 dimensional array from json response [duplicate]

I am trying to figure out how to build a 2 dimensional array from a JSON response.

I am trying to capture two fields out of the json response name.common and name.official

This works to build a 1 dimensional array;

let names = [];
function fetchVendorName() {
    fetch("https://restcountries.com/v3.1/all")
        .then((response) => response.json())
        .then((data) => {
            names = data.map(x => x.name.common);
            names.sort();

        });
    return "done";
}

This does not work for a 2 dimensional array;

let names = [];
function fetchVendorName() {
    fetch("https://restcountries.com/v3.1/all")
        .then((response) => response.json())
        .then((data) => {
            names = data.map(x => x.name.common, x.name.official);
            names.sort();

        });
    return "done";
}

What is an easy way to accomplish this?

next js returns not-found.tsx when image path is broken

I have a question: I have a Next.js project on app router, there is a page on which there is an image from the public folder.
If you go to the url of the picture (open it in a new tab window) and intentionally break the path of the image – next js shows not-found.tsx page?

Is there any way to fix this so that it just shows the default not-found error from next on a black screen?

Counting Iterations in a While loop [closed]

We are doing an exercise where they have to pick up a stack of balls and place a stack that is double the original number in the same spot. It has to work with various numbers, so a for loop isn’t an option. I have a student that wants to use a while loop, return the number of iterations into a variable, and then use that variable * 2 to place the double stack in a function created to double the number.

haven’t tried anything because we can’t figure out how to create the counter to count iterations of a while loop

Encrypting and decrpting local storage data [closed]

I am new to Angular JS, I have requirement to encrypt local storage data.

I tried using few available libraries like encrypt-storage and localstorage-slim but they all are throwing a warning in the terminal saying these libraries are common JS libraries.

I tried in-built crypto-api methods but I am not able to properly handle the asynchronous calls in angular JS.

Can anyone suggest something and help me to achieve my goal?

Require data from MySQL to JS with 4 tables joins [closed]

Use MySQL subqueries, join, in and other things but didn’t get required output.
MySQL is structural based dbs and due to that i didn’t get the solution as required. Even use JS & jQuery with cell merge code but not getting solution from my end.

In PHP use json array, join multiple json array but not able to get result like explained in image.

So, please help me.

Require result as attached image