How to prevent multiple window with url https://twitter.com/i/oauth2/authorize

I’m opening a new window with url https://twitter.com/i/oauth2/authorize?scope=tweet.read%20users.read%20follows.read%20follows.write&state=state&client_id=clientID&response_type=code&code_challenge=789089&code_challenge_method=plain&redirect_uri=http://localhost:4200/app/callback

But, when the url is loaded in new window, the popupWindow.closed property is getting set to true. Hence, leading to multiple windows getting open on button click. This doesn’t happen with linkedin’s oauth url

if (this.popupWindow == null || this.popupWindow.closed) {
      this.popupWindow = window.open(
        `${authUrl}?${params}`,
        'twitter',
        `menubar=no,location=no,resizable=no,scrollbars=no,status=no,toolbar=no, width=${width},height=${height},top=${top},left=${left}`
      );
    } else {
      this.popupWindow.focus();
    }

How do i prevent multiple window from opening?

Print out these counted values

I need answer ASAP
Given a set of five numbers that include both positive and negative data values. Create a program to read in these values one at a time and count the number of positive values (including zero) and the number of negative values found in the set. Print out these counted values.

Example:

Set of values: 1, -1, 0, 2, 4

Negative: 1

Positive: 4

Can I use uncontrolled inputs in React without ref?

I’ve a complex form (with over than 70 inputs) and it has many different inputs and children forms… I’ve decided to add a from tag then repeat all inputs inside that:

<form>
  <input name="email" />
  <input name="age" />
  <input name="address" />
  .
  .
  .
  { loop on state (Array) to render other re-usable form component for category or city etc. }
  { another loop on state (Array) to render file inputs and checkboxes etc. }
  .
  .
  .
</form>

I actually should get an API data then generate that form to collect data from user (we haven’t a fixed and common form, it depends on client and many things…). After that, I decided to forget controlled inputs, because I’ve to make a spaghetti and complex component to handle many states for this situation, I decided to use something like Formik, but that’s not really easy! because I’ve to pass many API methods to handle custom inputs onChange values…

Therefore, I’ve decided to get form values by onSubmit event (without ref):

const handleSubmit = (e) => {
  e.preventDefault();
  const values = new FormData(e.target);
  sendForm(values); // sending form by post method and formData
}

<form onSubmit={handleSubmit}>
.
.
.
</form>

But I’ve an important question, does effect uncontrolled input on React performance? or it’s not best practice and I’ve to find a solution to implement form by controlled inputs?

loop to check combination of dropdown & checkbox in pure javascript

Good morning!
I have a page with 1 dropdown menu that has 24 options to select.
As well There are 12 checkboxes to select.
Each dropdown option and each checkbox has a predefined variable.
i.e.:
dropdown value="utcValue0 -> var utc0 and
checkbox value id="gameCheck" -> var gameTag
desired output here is a new variable var a = utc0 + gameTag;

My current solution works, however it is very tedious and terrible to read and there must be a whole lot easier way to handle this. I’m at the moment just defining each scenario 1 by 1.
Considering it’s 24 dropdown menus and 12 checkboxes this can not be the way..
I think it can be done with a smart nested loop, but I can’t come up with how to actually write that.

I’d highly appreciate some help! Thank you so much!

    <select name="hourSelector" id="hourSelectorID">
      <option value="utcValue0">0 - 1 UTC</option>
      <option value="utcValue1">1 - 2 UTC</option>
      <option value="utcValue2">2 - 3 UTC</option>
      <option value="utcValue3">3 - 4 UTC</option>                
      <option value="utcValue4">4 - 5 UTC</option>
      <option value="utcValue5">5 - 6 UTC</option>
    </select>

       <input type="checkbox" class="custom-control-input" id="gameCheck">
       <input type="checkbox" class="custom-control-input" id="purchCheck">
       <input type="checkbox" class="custom-control-input" id="inputCheck">
    var utc0 = 'created>"' + todayUTC + 'T00:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T01:00:00Z"';
    var utc1 = 'created>"' + todayUTC + 'T01:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T02:00:00Z"';
    var utc2 = 'created>"' + todayUTC + 'T02:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T03:00:00Z"';
    var utc3 = 'created>"' + todayUTC + 'T03:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T04:00:00Z"';
    var utc4 = 'created>"' + todayUTC + 'T04:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T05:00:00Z"';
    var utc5 = 'created>"' + todayUTC + 'T05:00:00Z"' + ' ' + 'created<"' + todayUTC + 'T06:00:00Z"';
var gameTag = 'whatever';
var purchTag = 'otherwhatever';
var eventTag = 'morewhatver';

  // grab input Hour
  var hourDropdown = document.getElementById("hourSelectorID");
  var selectedHour = hourDropdown.options[hourDropdown.selectedIndex].value;

    if (document.getElementById('gameCheck').checked) {
      if (selectedHour == 'utcValue0' ) {
        var a = utc0 + standardStuff + eventTag
      }
      if (selectedHour == 'utcValue1') {
        var a = utc1 + standardStuff + eventTag
      }
      if (selectedHour == 'utcValue2') {
        var a = utc2 + standardStuff + eventTag
      }
      if (selectedHour == 'utcValue3') {
        var a = utc3 + standardStuff + eventTag
      }
      if (selectedHour == 'utcValue4') {
        var a = utc4 + standardStuff + eventTag
      }
      if (selectedHour == 'utcValue5') {
        var a = utc5 + standardStuff + eventTag
      }
    }  

JavaScript Password Generator Sometimes Not Including Character Selections?

Hello Stack Overflow!

This is my first time posting on the site so please bare with me and my question. My class was tasked with individually creating a password generator using JavaScript. Thankfully I had gotten most of the application operating correctly, but I’ve gotten stuck on a problem.

Example: The user chooses to have 8 characters in their password and chooses to include special, lowercase, and uppercase characters. When the password is generated sometimes it won’t include all of the character selections. (Sometimes it’ll generate a password with both special and uppercase characters, but not have a single lowercase character).

I’ve been finished with this assignment for a minute now, but my goal is to understand what I can do to fix this problem and complete this app anyway. I was thinking of potentially removing the passwordOptions object and turning each option into an array of their own, what are your thoughts?

Thank you so much for any suggestions! 😀

// passwordOptions contains all necessary string data needed to generate the password
const passwordOptions = {
  num: "1234567890",
  specialChar: "!@#$%&'()*+,^-./:;<=>?[]_`{~}|",
  lowerCase: "abcdefghijklmnopqrstuvwxyz",
  upperCase: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
};

// Executes when button is clicked
let generatePassword = function() {

  // initial state for password information
  let passInfo = "";

  // ask user for the length of their password
  let characterAmount = window.prompt("Enter the amount of characters you want for your password. NOTE: Must be between 8-128 characters");

  // If the character length doesn't match requirements, alert the user
  if (characterAmount >= 8 && characterAmount < 129) {

    // ask if user wants to include integers
    let getInteger = window.confirm("Would you like to include NUMBERS?");

    // if user wants to include numbers
    if (getInteger) {
      // add numerical characters to password data 
      passInfo = passInfo + passwordOptions.num;
    };

    // ask if user wants to include special characters
    let getSpecialCharacters = window.confirm("Would you like to include SPECIAL characters?");

    // if user wants to include special characters 
    if (getSpecialCharacters) {
      // add special characters to password data
      passInfo = passInfo + passwordOptions.specialChar;
    };

    // ask if user wants to include lowercase characters
    let getLowerCase = window.confirm("Would you like to include LOWERCASE characters?");

    // if user wants to include lowercase characters
    if (getLowerCase) {
      // add lowercase characters to password data
      passInfo = passInfo + passwordOptions.lowerCase;
    };

    // ask if user wants to include uppercase characters
    let getUpperCase = window.confirm("Would you like to include UPPERCASE characters?");

    // if user wants to include uppercase characters
    if (getUpperCase) {
      // add uppercase characters to password data 
      passInfo = passInfo + passwordOptions.upperCase;
    };

    // ensure user chooses at least one option
    if (getInteger !=true && getSpecialCharacters !=true && getLowerCase !=true && getUpperCase !=true) {
      // notify user needs to select at least one option
      window.alert("You need to select at least one option, please try again!");
      // return user back to their questions
      return generatePassword();
    };

    // randomPassword is an empty string that the for loop will pass information in
    let randomPassword = "";

    // for loop grabs characterAmount to use
    for (let i = 0; i < characterAmount; i++) {
      //passInfo connects to charAt that uses both Math.floor and random to take the length of passInfo and randomize the results
      randomPassword += passInfo[Math.floor(Math.random() * passInfo.length)];
    };

    // return password results
    return randomPassword;
  }
  // if user's response is invalid
  else {
    // alert user
    window.alert("You need to provide a valid length!");
    // return user back to their questions
    return generatePassword();
  }
};

JS Programming Patterns – Generalize a function vs split it

ORIGINAL CODE

Imagine this spaghetti method:

const useDeleteMedia = (media, { onSuccess, onError } = {}) => {
  const isMounted = useIsMounted();

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const deleteMedia = async () => {
    try {
      if (media.type === "audio") {
        await api.audios.delete();
      } else if (media.type === "video") {
        await api.videos.delete();
      } else if (media.type === "image") {
        await api.images.delete();
      } else {
        throw new Error("Invalid media type");
      }

      onSuccess?.();
    } catch (err) {
      if (!isMounted) return;

      setError(err);

      onError?.(err);
    }
  };

  return { error, deleteMedia };
};

REFACTORING USING OBJECT (FACTORY?)

In order to avoid the conditional chain etc. you may think about using some kind of factory of actions like:

const deleteAPI = Object.freeze({
  audio: api.audios.delete,
  video: api.videos.delete,
  image: api.images.delete,
});

I am not sure if this is considered an “object factory” (I know what a factory function is, but if I don’t remember bad, I heard about the “object factory pattern” some time ago).

And then refactor the original code to something like:

const useDeleteMedia = (media, { onSuccess, onError } = {}) => {
  const isMounted = useIsMounted();

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const deleteMedia = async () => {
    try {
      await deleteAPI[media.type]();

      onSuccess?.();
    } catch (err) {
      if (!isMounted) return;

      setError(err);

      onError?.(err);
    }
  };

  return { error, deleteMedia };
};

IS GENERALIZING BAD (sometimes)?

Another option could be to just make 3 different methods, in order to be more “flexible” and do different things in the future.

For example, imagine that after deleting each type of media, you have to update a context, decreasing “totalVideos”, “totalAudios”, or “totalImages”, depending on the media type.

This might look like:

const useDeleteMedia = (media, { onSuccess, onError } = {}) => {
  const isMounted = useIsMounted();

  const currentUser = useCurrentUser();

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const decreaseUserMedia = () => {
    currentUser.setData((prevData) => {
      if (media.type === "audio") {
        return {
          ...prevData,
          totalAudios: Math.max(prevData.totalAudios + 1, 0),
        };
      } else if (media.type === "video") {
        return {
          ...prevData,
          totalVideos: Math.max(prevData.totalVideos + 1, 0),
        };
      } else if (media.type === "audio") {
        return {
          ...prevData,
          totalImages: Math.max(prevData.totalImages + 1, 0),
        };
      }
    });
  };

  const deleteMedia = async () => {
    try {
      await deleteAPI[media.type]();

      onSuccess?.();
    } catch (err) {
      if (!isMounted) return;

      setError(err);

      onError?.(err);
    }
  };

  return { error, deleteMedia };
};

Then the spaghetti code comes again. And you may think: well, then just compute the keys like:

const decreaseUserMedia = () => {
  currentUser.setData((prevData) => {
    const computedKey = `total${capitalize(media.type)}`;

    return {
      ...prevData,
      [computedKey]: Math.max(prevData[computedKey] + 1, 0),
    };
  });
};

And that looks pro, yeah, but what if I keys could not be computed that simple? What if I need to add more stuff in the future? What if I only want to do different side effects for each type of media?

SPLITTING CODE

In the other hand, I can just make different methods: useDeleteAudio(), useDeleteVideo() and useDeleteImage().

With this, I am repeating my self. BUT… I have more flexibility in order to add new features for each different type of media.

Also, there is no need to compute keys, or using helpers like capitalize().

QUESTION

Is it considered, in terms of code quality, to repeat ourselves in this type of situation? Is there any pattern that can solve my life here?

jquery. update filelist after splice

i have my piece of code of removing items in filelist. first im done with converting my filelist to another array. and there i made my splice function. my problem here is how to get update the existing filelist after the splice function i made. i want to assign back the array i made to the filelist.

// existing filelist

var fileList = [];

var file_list = $('#fileupload').get(0).files;
var fileListArr = Array.from(file_list)

fileListArr.splice(i, 1)

for (var x = 0; x < fileListArr.length; x++)
{
    fileList.push($('#fileupload')[0].files[x]);
}

console.log($('#fileupload')[0], 'newFiles')

i want to update my existing filelist here. right now nothing happens. thank you folks

Iterate over an object to see which active days matches per id

Consider the array of objects below,

const resource = [
    {
        id: 'tony',
        shiftday: [
            {active: '1', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '1', code: 'Tue'},
            {active: '1', code: 'Wed'},
            {active: '1', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '1', code: 'Sat'},
        ]
    },
    {
        id: 'alex',
        shiftday: [
            {active: '0', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '1', code: 'Tue'},
            {active: '0', code: 'Wed'},
            {active: '1', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '0', code: 'Sat'},
        ]
    },
    {
        id: 'trey',
        shiftday: [
            {active: '0', code: 'Sun'},
            {active: '1', code: 'Mon'},
            {active: '0', code: 'Tue'},
            {active: '1', code: 'Wed'},
            {active: '0', code: 'Thu'},
            {active: '1', code: 'Fri'},
            {active: '0', code: 'Sat'},
        ]
    },
]

I need to get all values that has active day set to 1 (selected) and match it to the other id’s. And to be able to say that which id’s have matching active days.

Browser not displaying MP4 @webpack-dev-server @React.js @JS

I started a new React.js project in Visual Studio Pro 22 without CRA.
My react component renders accurately (minus a local .mp4 file).
The .mp4 file is contained inside a video element, inside a div, within my main component.
Edge developer tools shows the video element, and the .mp4 file (bundled by webpack).
However, the .mp4 file will not play or show in the browser.
I get this error.
localhost/:1

   GET http://localhost:8080/preview net::ERR_ABORTED 404 (Not Found)

Here is my webpack.config.js

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
    mode: 'development',
    entry: './src/index.js',
    output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
},
    resolve: {
        modules: [path.join(__dirname, 'src'), 'node_modules'],
        alias: { react: path.join(__dirname, 'node_modules', 'react') }
    },
    plugins: [new HtmlWebpackPlugin({ template: './src/index.html' })],
    module: {
        rules: [
            {
                test: /.css/i,
                use: ['style-loader', 'css-loader']
            },
            {
                test: /.js$/,
                exclude: /node_modules/,
                use:
                {
                 loader: "babel-loader",
                 options:
                    {
                        presets: ['@babel/preset-env', '@babel/preset-react']
                    }
                }
            },
            {
                test: /.(png|mp4)$/i,
                type: "asset/resource"
            },
            {
                test: /.txt$/i,
                type: 'asset/source'
            },
            {
                test: /.(woff|woff2|ttf)$/i,
                type: "asset/resource"
            },
            {
                test: /.html$/,
                use: ["html-loader"]
            }

          ]
       }
   }

here is my package.json

{
  "name": "tascticnodes",
  "version": "0.0.0",
  "description": "tascticnodes",
  "main": "index.js",
  "author": "",
  "presets": 
  [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "scripts": 
  {
  "build": "webpack --watch",
  "start": "webpack serve"
  },
  "keywords": [],
  "license": "ISC",
  "devDependencies": 
  {
   "@babel/core": "^7.16.5",
   "@babel/preset-env": "^7.16.5",
   "@babel/preset-react": "^7.16.5",
   "babel-loader": "^8.2.3",
   "css-loader": "^6.5.1",
   "file-loader": "^6.2.0",
   "html-loader": "^3.1.0",
   "html-webpack-plugin": "^5.5.0",
   "style-loader": "^3.3.1",
   "webpack": "^5.65.0",
   "webpack-cli": "^4.9.1",
   "webpack-dev-server": "^4.6.0"
  },
  "dependencies": 
  {
   "@aws-amplify/ui-react": "^2.1.5",
   "aws-amplify": "^4.3.11",
   "bootstrap": "^5.1.3",
   "react": "^17.0.2",
   "react-bootstrap": "^2.0.4",
   "react-dom": "^17.0.2",
   "typewriter-effect": "^2.18.2"
 }
}

here is my config.babelrc

{
  "presets": ["@babel/preset-env, "@babel/preset-react"]
}

here is my SRC directory
screen shot of my directory

here is my passIt.js(the standard app.js)

import React from 'react';
import Typewriter from 'typewriter-effect';
import './index.css';
import Amplify from 'aws-amplify';
import { API } from 'aws-amplify';
import { Button, Form } from 'react-bootstrap';
import preview from './preview.mp4';
import awsExports from './aws-exports';
Amplify.configure(awsExports);


async function addContact() 
{
  const data = 
              {
               body: 
                    {
                     name: formState.name,
                     email: formState.email,
                     message: formState.message
                    }
              }
  console.log(data);

  const apiData = await API.post('formapi', '/items', data);
  console.log({ apiData });
  alert('Mail sent');
};

const formState = { name: '', email: '', message: '' };

function updateFormState(key, value) 
{
  formState[key] = value;
};

const Hello = () => {
    return (
        <div>
            <div>
                <div>
                    <form>
                        <Typewriter
                            onInit={(typewriter) =>
                            typewriter
                            .typeString('Welcome to Anvil')
                            .start()} />
                    </form>
                    <Form>
                        <Form.Group>
                            <Form.Label>Name</Form.Label>
                            <Form.Control placeholder="Name" onChange={e => 
                                             updateFormState('name', e.target.value)} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>Email</Form.Label>
                            <Form.Control placeholder="Email" onChange={e => 
                                            updateFormState('email', e.target.value)} />
                        </Form.Group>
                        <Form.Group>
                            <Form.Label>Message</Form.Label>
                            <Form.Control placeholder="Message" onChange={e => 
                                          updateFormState('message', e.target.value)} />
                        </Form.Group>
                        <Button onClick={addContact}>Send a message</Button>
                    </Form>
                </div>
            </div>

            <video autoPlay muted loop>
                <source src="preview" type="video/mp4" />
            </video>

        </div>
    )
};



export default Hello;

here is my index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>Check my divs</title>
        <link href="index.css" rel="stylesheet" type="text/css">
        <link C:Userszacksourcerepostascticnodessrcpreview.mp4 />
    </head>
  <body id="body">
    <div id="root"></div>
  </body>
</html>

here is my index.js

import React from 'react';
import { render } from 'react-dom';
import Hello from './passIt';

render(<Hello />, document.getElementById('root'));

What’s wrong in my code ? in continuous count in JavaScript loop

I am trying to achieve 3,4,5 in output. But, am getting only 3,5 .its jumping/skipping one number. Donno why. Given my code below. Help me to fix the error and please let me know why its happening and what i am doing as error ?

Expected output,

3
4
5

output am getting,

3
5

my code,

var input1, input2;
input1 = Number(2);
input2 = Number(5);
for(let i=input1;i<input2;i++) {
    i=i+1;
    console.log(i);
  }

How to import js library using ed6 modules from browser client side?

I am trying to import this library

https://github.com/qiao/PathFinding.js/blob/master/README.md

the pathfinding-browser.min.js file can be retrieved from the latest release here

https://github.com/imor/pathfinding-bower/releases

I am importing it like this

import * as PF from '../js/pathfinding-browser.min.js';

But it doesn’t work. How can I import this?

Note: this is client side vanilla javascript (not node or webpack).

On safari browser, paste content programmably will show system paste menu sometimes

When you want paste something in a contenteditable element by using javascript, there are two ways.

  • Using the deprecated method document.execCommand('paste')
  • Or using the new Clipboard API navigator.clipboard.read()

On safari browser, paste content programmably will show system paste menu sometimes, not always. The above two methods’s behavior are same.

Is there anyway to disable this?

My safari browser: v15.0.

Test page ==> https://codepen.io/netsi1964/pen/QbLLGW?editors=0010

enter image description here