VS 2022 Could not Create React App with error message the sdk microsoft.visualstudio.javascript.sdk/1.0.1184077 specified could not be found

I try to make a ReactJS as Frontend with .Net Core 6 as API Application, but as soon as I click create button there is a popup with error message like this :

The sdk microsoft.visualstudio.javascript.sdk/1.0.1184077 specified could not be found

I have try to install the SDK, but the .nupkg file seems need to be install on a react project.
Also when I try to install microsoft.visualstudio.javascript.sdk on my solution that currently only has .Net API part, it refuse to install because it is not compatible with existing project..

So it is a chicken and egg situation now..

How to return only one result using match() [duplicate]

I try to filter text using regular expressions

var regExpDouble = new RegExp(/[0-9]+([.,][0-9]{0,3})?/)
var someText = "0.33 mm"
var result = someText.match(regExpDouble)
console.log("match:", result)

I get result in output as array

match: [0.33,.33]

How to get only one result (first) without parsing array?

I want to create smoother “swipe functionality” only for mobile on click buttons. Buttons are also in different languages for different Countries

Code to review here:

/* Styling for buttons */
.....
}

/* Button hover effect */
.button:hover {
  background-color: #f1f1f1;
}

/* Styling for the swipeable container */
.swipe-container {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow-x: auto; /* Enable horizontal scrolling */
  scroll-snap-type: x mandatory; /* Smooth snap effect */
  -webkit-overflow-scrolling: touch; /* Enable smooth scrolling on mobile devices */
  padding: 10px;
}

/* Flexbox items alignment */
.swipe-container a {
  flex-shrink: 0; /* Prevent shrinking */
  margin: 4px 10px; /* Spacing between buttons */
  scroll-snap-align: center; /* Ensure snapping happens in the center */
}

/* Centering buttons and making the swipe responsive on smaller screens */
@media (max-width: 768px) {
  .swipe-container {
    justify-content: flex-start; /* Align buttons to the start */
  }
}

My requests:
I want to have a smoother and stable swipe functionality without the container around. Buttons should show on desktops in the centre as well and stay fixed, not swiping like for the mobile version. Moreover, I want to eliminate the slight “up and down” sensibility with the swipe motion.

How to filter JavaScript data?

I have a search function which works good, but I want to modify it little bit. Let say I have some search query:

  1. XXX

It should show the series which contains the input XXX

  1. XXX 130

It should show the families which contains XXX130 in its name

  1. XXX 130 6 W

It should show both families with name including XXX130 and families which has wattage: 6.

  1. 111-1935

It should show the families with that productCode.

const series = [{
    id: 1,
    name: 'XXX100 MARKER',
  },
  {
    id: 2,
    name: 'XXX100',
  },
  // and etc
];

const families = [{
    id: 1,
    wattage: 6,
    seriesId: 1,
    productCode: '111-1935',
    name: 'XXX120-GB LED',
  },
  {
    id: 2,
    seriesId: 1,
    wattage: 6,
    productCode: '111-1947',
    name: 'XXX130-GB LED',
  },
  {
    id: 3,
    seriesId: 1,
    wattage: 6,
    productCode: '111-1950',
    name: 'XXX130-GB-TW LED',
  },
  {
    id: 4,
    seriesId: 1,
    wattage: 6,
    productCode: '111-1970',
    name: 'XXX130-GB-CC LED',
  },
];


let filteredFamilies = [];
let matchingSeries = [];
let terms = [];

const handleSearch = () => {
  console.clear();
  let searchText = document.getElementById('term').value;
  terms = searchText.split(' ').map(term => term.toLowerCase());
  matchingSeries = series.filter(s => {
    return terms.every(term => s.name.toLowerCase().includes(term));
  });

  filteredFamilies = families.filter(family => {
    let seriesName = series.find(s => s.id === family.seriesId).name.toLowerCase();
    return terms.every(term => {
      const wattageStr = family.wattage.toString();
      const wattageWithW = wattageStr + 'w';

      return (
        seriesName.includes(term) ||
        family.name.toLowerCase().includes(term) ||
        wattageStr.includes(term) ||
        wattageWithW.includes(term) ||
        family.productCode.toLowerCase().includes(term)
      );
    });
  });

  console.log(filteredFamilies);
};
<input type="text" id="term" />
<button onclick="handleSearch()">Search</button>

So, if user types XXX 130 6 (or XXX 130 6W) it should show results which include XXX, 130 and 6 in it. How can I achieve it?

Python alternative to Javascripts toFixed, round not working [duplicate]

Pythons default round function uses bankers algorithm to round of number.
(uses rounding to the nearest even number when the value is exactly halfway between two numbers).

JS toFixed used standard rounding( It always rounds up when the next digit is 5 or greater, regardless of whether it’s odd or even.)

My backend application is in python and Frontend in JS, due to this validations are failing.

69.125.toFixed(2)
'69.13'

>>> round(69.125,2)
69.12

Is there any way i can match JS output using python.
I thought numpy will do the job but it uses same algorithm

Jquery offset returns inconsistent values [closed]

Using jquery offset(), i’m finding that when called in a function, the values returned are different to what is returned if i get the same offset in the console.

I’m trying to plot points on an image using offset, and currently trying to get this points to redraw correctly when the window is resized.

I’ve currently got a function being called on window resize, that replots the points.

The issue here is that when getting the offset of the image in the function, it may return

{top: 771.21875, left: 391.984375}

but without resizing the window, calling the same offset call in the console will return

{top: 412.53125, left: 391.984375}

This doesn’t seem to be an issue for the left value, but the top value seems inconsistent.

EDIT:

I have the following bound to the resize event

$(window).resize(function(){resequenceDamage();});

function resequenceDamage() {
                var seq = 1;

                damage.map(
                    function ( _e ) {
                        if( _e.sequence != seq ) {
                            _e.sequence = seq;
                            serverUpdateDamage( _e );
                        }
                        seq += 1;
                    }
                )

                // And repaint
                damage.map( removeDamagePointerAndPill );
                damage.map( removeDamageRow )
                damage.map( addDamage );
            }

The resequenceDamage function essentially goes over an array of damage, that removes each one and then readds them, as well as updating any changes we need to record (for this example, serverUpdateDamage isn’t needed).

                function addDamage( _damage ) {
                // Draw pointer on damage diagram
                var offset = $('#damageDiagram').offset();

                var div = $( '<div></div>' );

                div.attr( 'id', 'damagePointer' + _damage.pk );
                div.html( _damage.sequence );
                div.addClass('damageItem');
                div.addClass( _damage.severityLabel );
                div.css( 'left', _damage.x + offset.left + 'px');
                div.css( 'top', _damage.y + offset.top + 'px');
                div.mousedown(
                    function( _e ) {
                        editDamage( _damage )
                    }
                );
                if (_damage.sequence == 1 ){
                console.log('Sequence: ' + _damage.sequence + ' X:' + _damage.x + ' Y: ' + _damage.y);
                console.log(offset);
                console.log($('#damageDiagram').offset());
                }

                $( 'body' ).append( div );

            }

The console.log within this function will return

{top: 771.21875, left: 391.984375}

when the window has been resized, with the above being the last console log out.

Without resizing the window, running

$('#damageDiagram').offset();

in the console will return

{top: 412.53125, left: 391.984375}

Unable to authenticate users based on their roles using session management via Node

I have a single form that I want to authenticate users (doctors, patients, and admins). I am using Node for the backend and MySQL for the database.

Backend Server setup:

// import neccessary packages
const db = require('./config/db') // database conn
const express = require('express') // web server
const cors = require('cors')
const bodyParser = require('body-parser') // capture form data
const session = require('express-session');  // session-management
const MySQLStore = require('express-mysql-session')(session); // session-management storage
require('dotenv').config() // manage environment variables
const path = require('path')

const app = express()

// middleware
app.use(cors({
    origin: ['http://127.0.0.1:5500', 'http://localhost:5500'],
    methods: ['GET', 'POST', 'PUT', 'DELETE'], 
    credentials: true 
}));

app.use(express.static(path.join(__dirname, '../client/index.html')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true })) // capture form data

// sesssion store
const sessionStore = new MySQLStore({}, db)

// configure session middleware
app.use(session({
    secret: process.env.SESSION_SECRET,
    store: sessionStore,
    resave: false,
    saveUninitialized: false,
    cookie: {
        maxAge: 1000 * 60 * 60 // 1 hour
    }
}))

// routes
app.use('/telemedicine/api/patients', require('./routes/patientRoutes'))
app.use('/telemedicine/api/providers', require('./routes/providerRoutes.js'))
app.use('/telemedicine/api/admin', require('./routes/adminRoutes.js'))

// fetch for the html file
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../client/', 'index.html'))
})

// Patient Dashboard
app.get('/dashoard', (req, res) => {
    res.sendFile(path.join(__dirname, '../client/patient', 'dashboard.html'))
})

// Provider Dashboard
app.get('/dashoard', (req, res) => {
    res.sendFile(path.join(__dirname, '../client/doctor', 'dashboard.html'))
})

// Admin Dashboard
app.get('/dashoard', (req, res) => {
    res.sendFile(path.join(__dirname, '../client/admin', 'dashboard.html'))
})

const PORT =  process.env.PORT || 3200

// start server
app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`)
})

I tried to use one API for my form to authenticate the user
register.html:

<div class="container register">
      <div class="form__image register__image">
        <img src="images/register.png" alt="registerImage" />
      </div>
      <div class="form__container">
        <h3>Register</h3>
        <form id="registerForm" method="POST" action="/register">
          <!-- Role Selection -->
          <div>
            <p>Select type of account</p>
            <div id="role-selection" class="selection">
              <span data-role="patient">Patient</span>
              <span data-role="provider">Doctor</span>
              <span data-role="admin">Admin</span>
            </div>
          </div>

          <!-- Form -->
          <div class="form__field">
            <div>
              <input
                type="text"
                id="first_name"
                name="first_name"
                placeholder="First Name"
                required
              />
              <input
                type="text"
                id="last_name"
                name="last_name"
                placeholder="Last Name"
                required
              />
              <input
                type="email"
                id="email"
                name="email"
                placeholder="Email Address"
                required
              />
              <input
                type="password"
                id="password"
                name="password"
                placeholder="Password"
                required
              />
            </div>

            <!-- Dynamic Fields based on Role -->
            <div
              id="patient-fields"
              class="role-specific-fields"
              style="display: none"
            >
              <input
                type="date"
                id="date_of_birth"
                name="date_of_birth"
                placeholder="Date of Birth"
                required
              />
              <div>
                <select id="language" name="language" required>
                  <option value="">Select Language</option>
                  <option value="English">English</option>
                  <option value="Spanish">Spanish</option>
                  <option value="French">French</option>
                </select>
                <select id="gender" name="gender" required>
                  <option value="">Select Gender</option>
                  <option value="Male">Male</option>
                  <option value="Female">Female</option>
                  <option value="Other">Other</option>
                </select>
              </div>
            </div>

            <div
              id="provider-fields"
              class="role-specific-fields"
              style="display: none"
            >
              <input
                type="text"
                id="specialty"
                name="specialty"
                placeholder="Specialty"
                required
              />
              <input
                type="text"
                id="phone_number"
                name="phone_number"
                placeholder="Phone Number"
                required
              />
            </div>
          </div>

          <p>Already have an account ? <a href="login.html">Login</a></p>

          <button type="submit">Register</button>
        </form>
      </div>
      <div id="message" style="display: none"></div>
    </div>

register.js:

// Role Selecetion
document.querySelectorAll('#role-selection span').forEach((span) => {
  span.addEventListener('click', function() {
    const selectedRole = this.getAttribute('data-role');

    document.querySelectorAll('#role-selection span').forEach(s => s.classList.remove('selected'));

    this.classList.add('selected');

    const patientFields = document.getElementById('patient-fields');
    const providerFields = document.getElementById('provider-fields');

    patientFields.style.display = 'none';
    providerFields.style.display = 'none';

    // Reset required fields
    const allRequiredFields = document.querySelectorAll('input[required], select[required]');
    allRequiredFields.forEach(field => field.removeAttribute('required'));

    if (selectedRole === 'patient') {
      patientFields.style.display = 'flex';
      patientFields.querySelectorAll('input, select').forEach(field => field.setAttribute('required', true));
    } else if (selectedRole === 'provider') {
      providerFields.style.display = 'flex';
      providerFields.querySelectorAll('input').forEach(field => field.setAttribute('required', true));
    }

    document.getElementById('role-selection').setAttribute('data-selected-role', selectedRole);
  });
});


// Handle Register
document.getElementById('registerForm').addEventListener('submit', async (e) => {
  e.preventDefault();

  const role = document.getElementById('role-selection').getAttribute('data-selected-role');
  const first_name = document.getElementById('first_name').value;
  const last_name = document.getElementById('last_name').value;
  const email = document.getElementById('email').value;
  const password = document.getElementById('password').value;
  let date_of_birth = document.getElementById('date_of_birth') ? document.getElementById('date_of_birth').value : '';
  let language = document.getElementById('language') ? document.getElementById('language').value : '';
  let gender = document.getElementById('gender') ? document.getElementById('gender').value : '';
  let specialty = document.getElementById('specialty') ? document.getElementById('specialty').value : '';

  if (!role) {
    return alert('Please select a role.');
  }

  if (!first_name || !last_name || !email || !password) {
    return alert('Please fill in all required fields.');
  }

  if (role === 'patient' && (!date_of_birth || !language || !gender)) {
    return alert('Please fill in all patient-specific fields.');
  }

  if (role === 'provider' && !specialty) {
    return alert('Please provide your specialty.');
  }

  const response = await fetch('http://localhost:3200/telemedicine/api/patients/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ first_name, last_name, email, password, role, date_of_birth, language, gender, specialty }),
  });

  const data = await response.json();

  if (response.ok) {
    alert('Registration successful!');
    window.location.href = '/login'; 
  } else {
    alert(data.message);  
  }
});


The user should be authenticated based on their role, then they should be redirected to their respective routes. However When I try to login or register, this is what I am getting

Failed to load resource: the server responded with a status of 400 (Bad Request)
register.js:67 
        
        
       POST http://localhost:3200/telemedicine/api/patients/register net::ERR_INTERNET_DISCONNECTED

Script Editor Mac OS Catalina not working?

The code,

// Create a simple dialog box
var app = Application.currentApplication();
app.includeStandardAdditions = true;

// Show a dialog box
var userResponse = app.displayDialog("Welcome to MyApp! Click OK to continue.", {
    buttons: ["OK"],
    defaultButton: "OK"
});

// Run your shell script if OK is clicked
if (userResponse.buttonReturned === "OK") {
    try {
        app.doShellScript("~/Desktop/MyApp.app/Contents/MacOS/MyApp");
        app.displayDialog("MyApp executed successfully!", {
            buttons: ["OK"],
            defaultButton: "OK"
        });
    } catch (err) {
        app.displayDialog("An error occurred: " + err.message, {
            buttons: ["OK"],
            defaultButton: "OK"
        });
    }
}

Script Editor returns with Error -1,752, can you fix my code? Using JS, you can give a AppleScript response. File extension is .app

A dialog box was what I was expecting, but returned with error 1752, I checked everything, nothing changed. This has gone on for 17 years [2007]

Sequelize with typescript defining associations

For the past three days, I’ve been trying to integrate Sequelize M:N (many-to-many) associations with TypeScript.

The issue arises when I follow the official Sequelize documentation, which suggests defining associations alongside the model definitions. This works initially, but when I attempt to implement the association through a join (proxy) table, I encounter the following error: .belongsTo called with something that's not a subclass of Sequelize.Model. I suspect this is due to a circular dependency. If this isn’t the correct approach, why does it appear in the official docs? (Rhetorical question.)

Moving on, I decided to add an associate method to each individual model and call it after initializing all models. However, this led to some awkward workarounds, such as needing to write (ImportConfig as any).associate = for every model. Now, I’m facing a new challenge: dynamically importing models from a directory since the model files have a .ts extension.

Does anyone know a better way to organize this? I’d prefer not to manually add static imports to the initialization script every time I add a new model.

How do I properly play a video using Javascript?

When the play button is clicked the video is supposed to play. Why is the play button not working?

let vid = document.getElementById("myVideo");

function playvid() {
    vid.play();
}
 <div class="myvideo">
            
            <iframe width="420" height="315" id="myVideo"
src="https://www.youtube.com/embed/mvUkiILTqI?controls=0">
</iframe>
        <button onclick="playvid()" class="button" type="button">PLAY</button>
    </div>

NVDA is skipping table cells when they contain input or select tags

When I activate the “+” button which adds a new row to the table, NVDA then no longer focuses on each cell individually and skips over them. If you let it read out one of the cells it does focus on, it instead reads them all at once.

JSfiddle to demonstrate the issue: https://jsfiddle.net/0nc29jr6/1/

const rowStr = '<tr><td><input class="inp1" name="inp1"/></td><td><select class="sel1" name="sel1"></select></td><td><input class="inp2" name="inp2"/></td><td><select class="sel2" name="sel2"></select></td><td style="display:flex"><div><input value="+" type="button" class="inp3" name="inp3"/></div><div><input value="-" type="button" class="inp4" name="inp4"/></div></td></tr>'

$(document).ready(function() {
  addRow();
})

function addRow() {
  let row = $(rowStr);
 
  row.find(".sel1").append("<option>opt1</option><option>opt2</option>");
  row.find(".sel2").append("<option>opt3</option><option>opt4</option>");
  row.find(".inp3").on("click", addRow);
  row.find(".inp4").on("click", function() {
    remRow(row);
  })
  
  $("#tbody1").append(row);
}

This only seems to be an issue when the table specifically contains input elements like these. Using Tab seems to navigate properly but using the arrow keys does not.

dynamically import es module provided as a blob with es-mdoule-shims and angulars native federation

Problem

I am developing a plugin based architecture in angularjs.
To load a plugin in runtime I first send a request to the backend to download and store the plugins source code. This way I already have the source code available when loading the plugin in the future.

However when trying to import this source code in the frontend I have the following problem:
Because I am using openapis typescript-angular generator I dont have an explicit url to use inside await import(<url>) but rather an autogenerated service that returns an Observable<Blob>. Of course I could use the plugins url to import the plugin directly from its remote but this way I have to fetch it every time I want to import it (eg on startups).

What I tried

  1. Creating a blob url using URL.createObjectUrl(<blob>) and import it, but I am using angulars native federation which internally uses es-module-shims and it throws the error TypeError: Failed to construct 'URL': Invalid URL
  2. Same problem with data urls:
    const reader = new FileReader();
    reader.onload = async function () {
        const blobAsDataUrl: string = reader.result as string;
        const module = await import(blobAsDataUrl);
    };

    reader.readAsDataURL(<blob>);
  1. creating a script tag with type=module-shim and using innerHTML to inject the plugins source code does work, but then I dont have access to the plugins exports and because every plugin exports a function called initialize I cannot use global scope.

hello , i am Timotyh

I am timothy from USA.
I help anyone.
Can any Help me.

You Help me,
can you help me,
this issue is real,You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page.

Your questions should be reasonably scoped. If you can imagine an entire book that answers your question, you’re asking too much.

If your motivation for asking the question is “I would like to participate in a discussion about ______”, then you should not be asking here. However, if your motivation is “I would like others to explain ______ to me”, then you are probably OK.