“jinja2.exceptions.TemplateNotFound” error when attempting to access JavaScript file

I’m trying to pass an array into a javascript file (taskTableDip.js) to later create a table in a HTML file (supportDash.html), however for some reason Flask keeps throwing jinja2.exceptions.TemplateNotFound: {{ url_for('js', filename='taskTableDip.js') }}.
Weirdly I noticed that this line seems to differ from the one that appears in the code, I’m unsure whether this has something to do with jinja, and if I’ve named the file wrong.

WebManager_main.py

from flask import Flask, render_template, url_for
#this is the library responsible for the hosting of the Web app
from werkzeug.middleware.proxy_fix import ProxyFix
import DataBaseHandler_Main as DBHM


app = Flask(__name__)
app.config["SECRET_KEY"] = "thisistotallysecret"
app.wsgi_app = ProxyFix(app.wsgi_app)

@app.route("/")
def login():
  return render_template("login.html")
  #this is the login site where the user will initiall be diurected to

@app.route("/supportdash")
def supportDash():
  tasks = DBHM.fetch("1.0", None)
  return render_template("supportDash.html", tableData = tasks)



#if __name__ == "WebManager_main":
#  app.run(port=8080, debug = True)

templates/base.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/main.css') }}" />
    {% block head %}{% endblock %}
  </head>
  <body>
    {% block main %}{% endblock %}
  </body>
</html>
<!--   this is th basic template for the different html files   -->

templates/supportDash.html

{% extends "base.html" %}

<!--{% include "{{ url_for('js', filename='taskTableDip.js') }}" %}-->
<!-- This is to fix the issue with passing values to the js file -->

{% block head %}
<title>Siteswift - Support Team DashBoard</title>
<!--script type = "text/javascript" src = ""></script-->
<script type="text/javascript" src="{{ url_for('static', filename='js/taskTableDip.js') }}"></script>
<script type="text/javascript">
    var taskData = dataReturn({{tableData|tojson}})
 </script>
{% endblock %}

{% block main %}
 <table>
   <h1>Support Team Portal</h1>
  <tr>
    <th>Task</th>
    <th>User</th>
    <th>Priority</th>
    <th>Deadline</th>
    <th colspan = 3>Actions</th>
  </tr>
   <tbody id="taskTable"></tbody>
 </table>
{% endblock %}

static/js/taskTableDip.js

var tableData = {}

function dataReturn(vars) {
  return vars
}
function createTable() {
  var table =
  for (var i in tableData){
    var row = `<tr>
      <td>${tablData[i][0]}.Task</td>
      <td>${tablData[i][1]}.User</td>
      <td>${tablData[i][3]}.Priority</td>
      <td>${tablData[i][4]}.Deadline</td>
      <td><a href="{{ url_for('templates',filename='editTask.html')}}">Edit</a>.Actions</td>
      <td>.Actions</td>
      <td>.Actions</td>
    </tr>`
    
  }
}

The file structure:

enter image description here

I’ve tried moving the file out of the static folder. In addition to shutting down and re-running the code, as well as deleting the packager files to reinstall Flask, in the hopes it will update the file it’s running if it’s stuck on an old one. (I was sort of pulling at loose ends as I didn’t know why the error code looked different)

I’d greatly appreciate any help whatsoever!

Can someone explain why this happen?

const chessBoard = document.querySelector("#board");
let aSwitch = true; // define a switch to create black & white square
let increment = 1; // will be use to determine the row of the board

for (let i = 0; i < 64; i++) {
  let square = document.createElement("div");
  square.classList.add("square");

  if (aSwitch === true) {
    square.classList.add("white");
    aSwitch = false;
   } else {
        square.classList.add("black");
    aSwitch = true;
  }

  if (i === 7 * increment) {
    increment++;
   aSwitch = !aSwitch;
  } // ensure that the next row will follow a checkered pattern
  chessBoard.append(square);
}

output:

chessboard with the equation 8 * increment - 1

however if i change the sequence to i === 8 * increment, the output is:

chessboard with the equation 8 * increment

Please help me understand this phenomenon since i am very dummb and confused, thanks alot!

I did try using the internet, and best i came up with was that the square was in a 0-index sequence, but when i try using the equation 7 * increment, the output was also wrong:

chessboard with equation 7 * increment

Override NestJs module configuration

I’m trying to build API which will be calling different external services under the hood. API will look like GET /order/{serviceName}/{itemId}. Amount of services is arbitrary.

So I created orders module which looks like:

@Module({
  imports: [HttpModule.register({
    baseURL: 'https://someUrl/api/abcd',
  })],
  controllers: [OrdersController],
  providers: [OrdersService, AService]
})
export class OrdersModule { }

and also I’ve created an AModule which will receive HttpModule from OrdersModule. It looks like that:

@Module({
  imports: [
    HttpModule,
  ],
  providers: [AService],
  exports: [AService],
})
export class AModule { }

The problem is that I define settings for HttpModule at OrdersModule (baseUrl) and it looks like I can’t do this at the level of AModule. That means that I’m not able to add new module for some external service (ServiceB) to that structure, because I’ll need to set different baseUrl for that service.

How can I overcome that problem? What should I do differently?
Thanks in advance!

#2006 – mysql server has gone away XAMPP

I’m using XAMPP, MySQL on Window 11 and I have connected to DB with Sequelize with the code below:

const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('hoidanit', 'root', null, {
  host: 'localhost',
  dialect: 'mysql' 
});

let connectDB = async () => {
    try {
        await sequelize.authenticate();
        console.log('Connection has been established successfully.');
      } catch (error) {
        console.error('Unable to connect to the database:', error);
      }
}

module.exports = connectDB;

And the console print out:

Backend Nodejs is running on the port : 8090
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.

But when I try visiting localhost/phpmyadmin from XAMPP Control Panel, MySQL in XAMPP is crashed and the error appear in localhost/phpmyadmin as shown below:
enter image description here
enter image description here

my.ini file in MySQL:

# Example MySQL config file for small systems.
#
# This is for a system with little memory (<= 64M) where MySQL is only used
# from time to time and it's important that the mysqld daemon
# doesn't use much resources.
#
# You can copy this file to
# C:/xampp/mysql/bin/my.cnf to set global options,
# mysql-data-dir/my.cnf to set server-specific options (in this
# installation this directory is C:/xampp/mysql/data) or
# ~/.my.cnf to set user-specific options.
#
# In this file, you can use all long options that a program supports.
# If you want to know which options a program supports, run the program
# with the "--help" option.

# The following options will be passed to all MySQL clients
[client]
# password       = your_password 
port=3306
socket="C:/xampp/mysql/mysql.sock"


# Here follows entries for some specific programs 

# The MySQL server
default-character-set=utf8mb4
[mysqld]
port=3306
socket="C:/xampp/mysql/mysql.sock"
basedir="C:/xampp/mysql"
tmpdir="C:/xampp/tmp"
datadir="C:/xampp/mysql/data"
pid_file="mysql.pid"
# enable-named-pipe
key_buffer=16M
max_allowed_packet=128M
sort_buffer_size=512K
net_buffer_length=8K
read_buffer_size=256K
read_rnd_buffer_size=512K
myisam_sort_buffer_size=8M
log_error="mysql_error.log"

# Change here for bind listening
# bind-address="127.0.0.1" 
# bind-address = ::1          # for ipv6

# Where do all the plugins live
plugin_dir="C:/xampp/mysql/lib/plugin/"

# Don't listen on a TCP/IP port at all. This can be a security enhancement,
# if all processes that need to connect to mysqld run on the same host.
# All interaction with mysqld must be made via Unix sockets or named pipes.
# Note that using this option without enabling named pipes on Windows
# (via the "enable-named-pipe" option) will render mysqld useless!
# 
# commented in by lampp security
#skip-networking
#skip-federated

# Replication Master Server (default)
# binary logging is required for replication
# log-bin deactivated by default since XAMPP 1.4.11
#log-bin=mysql-bin

# required unique id between 1 and 2^32 - 1
# defaults to 1 if master-host is not set
# but will not function as a master if omitted
server-id   =1

# Replication Slave (comment out master section to use this)
#
# To configure this host as a replication slave, you can choose between
# two methods :
#
# 1) Use the CHANGE MASTER TO command (fully described in our manual) -
#    the syntax is:
#
#    CHANGE MASTER TO MASTER_HOST=<host>, MASTER_PORT=<port>,
#    MASTER_USER=<user>, MASTER_PASSWORD=<password> ;
#
#    where you replace <host>, <user>, <password> by quoted strings and
#    <port> by the master's port number (3306 by default).
#
#    Example:
#
#    CHANGE MASTER TO MASTER_HOST='125.564.12.1', MASTER_PORT=3306,
#    MASTER_USER='joe', MASTER_PASSWORD='secret';
#
# OR
#
# 2) Set the variables below. However, in case you choose this method, then
#    start replication for the first time (even unsuccessfully, for example
#    if you mistyped the password in master-password and the slave fails to
#    connect), the slave will create a master.info file, and any later
#    change in this file to the variables' values below will be ignored and
#    overridden by the content of the master.info file, unless you shutdown
#    the slave server, delete master.info and restart the slaver server.
#    For that reason, you may want to leave the lines below untouched
#    (commented) and instead use CHANGE MASTER TO (see above)
#
# required unique id between 2 and 2^32 - 1
# (and different from the master)
# defaults to 2 if master-host is set
# but will not function as a slave if omitted
#server-id       = 2
#
# The replication master for this slave - required
#master-host     =   <hostname>
#
# The username the slave will use for authentication when connecting
# to the master - required
#master-user     =   <username>
#
# The password the slave will authenticate with when connecting to
# the master - required
#master-password =   <password>
#
# The port the master is listening on.
# optional - defaults to 3306
#master-port     =  <port>
#
# binary logging - not required for slaves, but recommended
#log-bin=mysql-bin


# Point the following paths to different dedicated disks
#tmpdir = "C:/xampp/tmp"
#log-update = /path-to-dedicated-directory/hostname

# Uncomment the following if you are using BDB tables
#bdb_cache_size = 4M
#bdb_max_lock = 10000

# Comment the following if you are using InnoDB tables
#skip-innodb
innodb_data_home_dir="C:/xampp/mysql/data"
innodb_data_file_path=ibdata1:10M:autoextend
innodb_log_group_home_dir="C:/xampp/mysql/data"
#innodb_log_arch_dir = "C:/xampp/mysql/data"
## You can set .._buffer_pool_size up to 50 - 80 %
## of RAM but beware of setting memory usage too high
innodb_buffer_pool_size=16M
## Set .._log_file_size to 25 % of buffer pool size
innodb_log_file_size=128M
innodb_log_buffer_size=8M
innodb_flush_log_at_trx_commit=1
innodb_lock_wait_timeout=50

## UTF 8 Settings
#init-connect='SET NAMES utf8'
#collation_server=utf8_unicode_ci
#character_set_server=utf8
#skip-character-set-client-handshake
#character_sets-dir="C:/xampp/mysql/share/charsets"
sql_mode=NO_ZERO_IN_DATE,NO_ZERO_DATE,NO_ENGINE_SUBSTITUTION
log_bin_trust_function_creators=1

character-set-server=utf8mb4
collation-server=utf8mb4_general_ci
[mysqldump]
max_allowed_packet=128M

[mysql]
# Remove the next comment character if you are not familiar with SQL
#safe-updates

[isamchk]
key_buffer=20M
sort_buffer_size=20M
read_buffer=2M
write_buffer=2M

[myisamchk]
key_buffer=20M
sort_buffer_size=20M
read_buffer=2M
write_buffer=2M

[mysqlhotcopy]

Could someone please help me know what’s wrong and how to fix it?
Thank you very much!

I tried to change the two max_allowed_packet parameters from 1M to 128M, innodb_log_file_size to 128M (in xampp/mysql/bin/my.ini) and upload_max_filesize=8M (in xampp/php/php.ini).

Title placement with ‘amCharts5’

I’d like to have an amCharts5 chart with a vertical legend at its right side, like this:

enter image description here

and with a title at the top or the bottom. I can get the chart and the legend as on the picture but I’m unable to get the title.

I have a code like this:

// Create wrapper container
var container = root.container.children.push(
  am5.Container.new(root, {
    width: am5.p100,
    height: am5.p100,
    layout: root.horizontalLayout
  })
);
// Create venn series
var chart = container.children.push(
  am5venn.Venn.new(root, {
    categoryField: "name",
    valueField: "count",
    intersectionsField: "sets",
    paddingTop: 40,
    paddingBottom: 40,
    paddingLeft: 40,
    paddingRight: 40
  })
);
// Set data
chart.data.setAll(x.data);
// Add legend
var legend = container.children.push(
  am5.Legend.new(root, {
    layout: root.verticalLayout,
    centerX: am5.p100,
    x: am5.p100,
    centerY: am5.p50,
    y: am5.p50
  })
);
legend.data.setAll(chart.dataItems);

Now, how to set the title?

input type file not showing all the selected files

I am having one event creation page which has multiple file upload option. here they select the all images at a time or they can load the files one by one like that.

Now the problem is, when I open file select dialog another time, the previously selected files got removed from the file input.

How to resolve this?

Thank you

Html.erb

<div class="uploads">
  <span id="media" class="row gallery attachment_gallery">
  </span>
  <div class="file_upload">
    <label for="event_file" ><%= image_tag('upload.png', class: "upload_img figure-img img-fluid") %></label>
      <%= f.file_field :media, multiple: true, id: "event_file", hidden: true %>
  </div>
</div>

Js script

<script type="text/javascript">
$(document).ready(function() {
    $("#event_file").on("change", function(e) {
      var files = e.target.files,
        filesLength = files.length;
      for (var i = 0; i < filesLength; i++) {
        var f = files[i]
        var fileReader = new FileReader();
        fileReader.onload = (function(e) {
          var file = e.target;
          $("<span class="pip">" +
            "<img class="imageThumb" src="" + e.target.result + "" title="" + file.name + ""/>" +
            "<br/><span class="remove">X</span>" +
            "</span>").appendTo(".attachment_gallery");
          $(".remove").click(function(){
            $(this).parent(".pip").remove();
          });
        });
        fileReader.readAsDataURL(f);
      }
    });
});
</script>

enter image description here

Duplicated files when mixing CommonJS and ES6 modules with webpack

I am building an extension for Azure DevOps using Javascript and webpack 5 to bundle all files. After having started with the require() syntax, I tried to move to the ESM import way as recommended by the webpack documentation. There are two dependencies that cause problems, however:

  • One dependency I have is the azure-devops-extension-sdk package. Note that it comes bundled with two flavors, one for require and one for ESM. Its package.json contains:
    "exports": {
      "types": "./SDK.d.ts",
      "import": "./esm/SDK.min.js",
      "require": "./SDK.min.js"
    },
    
  • Another dependency is the azure-devops-extension-api package, which is published only with the require syntax.

The azure-devops-extension-api package has itself a dependency to azure-devops-extension-sdk. Its published CommonClient.js file contains:

define(["require", "exports", "azure-devops-extension-sdk"], function (require, exports, azure_devops_extension_sdk_1) {
    "use strict";
    ...
}

In my own code, I now try to import both dependencies via

import * as adoSDK from 'azure-devops-extension-sdk';
import * as adoAPI from 'azure-devops-extension-api';

Unfortunately, webpack bundles both versions of the azure-devops-extension-sdk files, i.e. ./esm/SDK.min.js due to my import, and ./SDK.min.js due to the dependency in CommonClient.js. I.e. both SDK files are included in the webpack output, and also used during runtime.
The SDK has global side effects and checks that it is loaded only once:

if (global._AzureDevOpsSDKVersion) {
    console.error("The AzureDevOps SDK is already loaded. Only one version of this module can be loaded in a given document.");
}
global._AzureDevOpsSDKVersion = sdkVersion;

This check is triggered because both files are included.

I think it is clear to me why both versions of the SDK are bundled by webpack: The “import” version because I use import, and the “require” version because the API-package does not use import.

Of course I can simply stick to using require in my own code to include both dependencies, and then everything works:

require(['azure-devops-extension-sdk', 'azure-devops-extension-api'], 
    function (adoSDK, adoAPI) {
        // ...
    }
);

However, besides this, is there any way I can use import and tell webpack about the problem? E.g. tell webpack to ignore the ./esm/SDK.min.js file for my import and instead use ./SDK.min.js always? I already tried webpack rules as outlined in this post, but this did not work.

I’m creating a list of objects from a files in a directory. How do i nest “subpage” objects?

Creating a list of “page” objects from a file system. which looks like


pages/

  • Home.jsx
  • Blog.jsx
  • Post.Blog.jsx
  • Posts.Blog.jsx
  • private/
    — Admin.jsx
    — Dashboard.jsx
    — admin/
    — Main.Admin.jsx
    — author/
    — Post.Admin.jsx
    — editor/
    — Editor.Admin.jsx
  1. For Filenames with single name before the extension, I want to return objects that look like:
{name:"Home", isPrivate:false, permission:"guest"} 
  1. for Dot separated names outside of the private directory, I want to look like:
{name:"Blog", isPrivate:false permission:"guest", subpages:[{name:"Post", isPrivate:false, permission:"guest"},{name:"Posts", isPrivate:false, permission:"guest"},...]}
  1. For Files inside of the Private will have the “isPrivate” key/val pair set to true, the “permission” key/val set to the subdirectory it lives in. for example:
{name:Admin, isPrivate:true permission:"private", subpages:[{name:"Post",isPrivate:true, permission:"author"},{name:"Main", isPrivate:true, permission:"admin"},...]}

I’ve tried for loops inside of the conditional to add subpages to the current page object being created but that caused issues when I tried to use recursion at that level to access the files in the private directory or its subfolders, so i broke it back down to this and am trying to build up from here.

 const __filename = fileURLToPath(import.meta.url)
    const __dirname = path.dirname(__filename)
    const directoryPath = join(__dirname,'../../../../ui/src/pages')
    const files = []
    const createList = (dir)=>{
        const fileMatrix = fs.readdirSync(dir)
        fileMatrix.map(file=>{
            const filePath = join(dir,file)
            const stats = fs.statSync(filePath) 
            const isDir = stats.isDirectory()
            const isPrivate = filePath.includes('private')
            const permission = isPrivate ? path.dirname(filePath).split('/').pop():"guest"
            const fileParts = path.basename(filePath,'.jsx').split('.')
            const fileName = fileParts[0]
            const parent = fileParts[1]
            if (!isDir){
                file = {
                    name:fileName,
                    isPrivate,
                    permission
                }
                console.log(file)
            }
            else if(isDir){
                createList(filePath)
            }
        })
    }
       
      createList(directoryPath);

Click Button From Specific id

I was hoping someone could help me with some javascript that would click on this button:

<div tabindex="0" role="button" id="id_72229384732282" class="collapsed focus-visible" data-tutorial-selector-id="filterButton" aria-label="Filter rows">

I can’t use the id_7222…. because this is dynamic and changes after a page refresh. Is there a way to click this button based on the id=”filterButton”?

Thanks!

I’ve tried all sorts of methods but I know my syntax or the class reference is wrong. Here are the general ones I’ve tried:

document.getElementsByClassName('filterButton').click();
document.getElementById("filterButton");

AlpineJS not initializing in dynamically loaded content

I am creating a custom searchable select widget in my django application.

When returning the template normally all is well, however Alpine is not initializing when I render this field dynamically inside a modal. I use HTMX to make the ajax request; Django responds with a template and the template gets inserted into the DOM/modal.

Things I’ve tried

  1. Adding my Alpine.data‘s data directly into the x-data. This works but there is quite a lot a would like to avoid it if possible
  2. Hacky ways to try initialize Alpine but does not work (maybe I’ve missed something)
  3. Hooking into HTMX beforeSwap event to try load the JS before the template (no dice)

If anyone knows how to remedy this it would be greatly appreciated

Template

<div x-data="autocomplete" x-init="init('{{ widget.value }}')" class="relative">
# template stuff...
</div>

Script

document.addEventListener('alpine:init', () => {
  Alpine.data('autocomplete', () => ({
    open: false,
    selectedValue: '',

    init(value) {
      if (!['None'].includes(value)) {
        this.selectedValue = value;
      }
    },

    # functions used inside the template...

  }));
});

I want sum of income states but it concat togheteher

this is my react app screenshot. and this is my context project in AppContext,jsx file. this file handel all variables and methods in my app so I don’t send you other components source code because you dont need it. I want when I click at add button the cart add with income state. you can see I did it successfully and two carts with 5$ and 7$ state created in income state. but the main challenge is the Income area. in this area that have green background and green fonts I want when I click in add btn it shows the sum of my Incoms. for example in this screenshot it should 12$ because sum of 5 and 7 is 12. now this is source code of AppContext.jsx. please help me.
screen shot of my project
the code :
AppContext.jsx

import { createContext, useEffect, useState } from "react";
// Create a context to share data across components
export const AppContext = createContext();

export default function AppContextProvider({ children }) {
   // State variables for income and expense tracking
  const [cost, setCost] = useState(0);
  const [income, setIncome] = useState(0);
  const [outcome, setOutcome] = useState(0);
  const [total, setTotal] = useState(0);
  // State variables for transaction details
  const [describe, setDescribe] = useState("");
  const [date, setDate] = useState("");
  const [type, setType] = useState("Income");
    // Array to store individual transactions
  const [cart, setCart] = useState([]);
  // Arrays to track total income and outcome for potential calculations
  const [totalIncome , setTotalIncome] = useState([0]);
  const [totalOitcome , setTotalOitcome] = useState([0]);
  // Function to handle adding a new transaction to the cart
  const addBtnHandel = () => {
    setCart((prev) => {
      return [
        ...prev,
        {
          id: Date.now(), // Generate a unique ID for the transaction
          cost: cost,
          describe: describe,
          type: type,
          date: date,
        },
      ];
    });
  // Calculate the new total income array
  const newTotalIncome = [...totalIncome, cost];
  // Calculate the sum of the total income array
  const totalIncomeSum = newTotalIncome.reduce((sum, item) => sum + item, 0);
  // Update both states with the new values
  setTotalIncome(newTotalIncome);
  setIncome(totalIncomeSum);
  // Clear input fields for the next transaction
    setCost(0);
    setDescribe("");
    setDate("");
    setType("Income");
  };
  // Provide the context values to child components
  return (
    <AppContext.Provider
      value={{
        cost,
        outcome,
        total,
        setCost,
        setDescribe,
        describe,
        type,
        setType,
        cart,
        setCart,
        income,
        setIncome,
        outcome,
        setOutcome,
        total,
        setTotal,
        date,
        setDate,
        addBtnHandel,
      }}
    >
      {children}
    </AppContext.Provider>
  );
}

Income is displayed in the green area as 057 instead of 12 when I input 5 and 7.

Cannot Send ID Product Using Json (ASP NET CORE 6)

I’m doing invoice product and using cascading dropdowns. Here the view

image.

When user click on plus button there will be a new product row here example

example.

I using cascading dropdowns to select all the colors of that product. The problems is the size select box doesn’t work, as you can see in the pictures its blank. Here my code using javascripts and ajax in the view

@model Invoice
@{
    ViewData["Title"] = "Invoice";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";

    IEnumerable<ProductItem> lstProduct = ViewBag.ListProduct as IEnumerable<ProductItem>;
}

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $(function () {
        $(".datepicker").datepicker();
    });
</script>

<h2>@ViewData["Title"]</h2>

<div class="card">
    <div class="card-body">
        @using (Html.BeginForm())
        {
            <div class="form-group row pb-2">
                <div class=" col-md-6">
                    <label class="col-form-label font-weight-bold" asp-for="SupplierId">Nhà cung cấp</label>
                    <select  asp-for="SupplierId" class="form-control" asp-items="@ViewBag.Supplier"></select>
                </div>
                <div class="col-md-6">
                    <label class="col-form-label font-weight-bold">Ngày nhập</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text"><i class="fa fa-calendar"></i></span>
                        </div>
                        <input type="datetime-local" asp-for="CreateDate" class="form-control" />
                    </div>
                </div>
                <div class="clearfix"></div>
            </div>
            @*Phần chi tiết nhập hàng *@
            <table class="tblInvoiceDetail table  table-hover">
                @* tạo 1 tr với nd nhập hàng của 1 sp *@
                <tr class="trAppend table-borderless">
                    <td>
                        <select class="ddlProductItemsId productList" id="productList" asp-items="ViewBag.Product">
                        </select>
                        
                    </td>
                    <td>
                        <select name="" class="ddlColors colorId" id="colorId"></select>
                    </td>
                    <td>
                        <select name=""  id="sizeId">
                        </select>
                    </td>

                    <td>
                        <input name="" class="txtPrice" value="0" />
                    </td>
                    <td>
                        <input name="" class="txtQuanity" value="0"/>
                    </td>
                    <td>
                        <input type="button" class="btnDelete btn btn-danger" style="width: 2em; height:2em;" value="-" />
                    </td>
                   
                </tr>
        
                <tr class="trFirstChild" data-id="-1">
                    <td class="col-form-label font-weight-bold">Product</td>
                    <td class="col-form-label font-weight-bold">Color</td>
                    <td class="col-form-label font-weight-bold">Size</td>
                    <td class="col-form-label font-weight-bold">Price</td>
                    <td class="col-form-label font-weight-bold">Quantity</td>
                    <td></td>
                </tr>
               
            </table>
   
           
            <div class="form-group row">
                <div class="col-md-offset-2 col-sm-6">
                    <input type="button" value="+" class="btn btn-sm btn-success font-weight-bold mr-2" style="width: 3em; height:2em;" id="btnAdd" />
                    <input type="submit" value="Submit" class="btn btn-sm btn-primary font-weight-bold " id="btnNhapHang" />
                </div>
            </div>
        }
      
    </div>
</div>
<style>
    .trAppend {
        display: none;
    }
</style>

@section Scripts
{
    <script>

        $(document).on('change', '.ddlProductItemsId', function () {
            GetProductByColor($(this));
          
        });
       

        function GetProductByColor(selectedProductDropdown) {
            var productId = $(selectedProductDropdown).val(); 
            var colorDropdown = $(selectedProductDropdown).closest('tr').find('select[id="colorId"]'); 

            $.ajax({
                url: '@Url.Action("GetProductByColor", "Invoice")',
                type: 'GET',
                data: { id: productId },
                success: function (data) {
                    $(colorDropdown).empty(); 
                    $.each(data["$values"], function (index, item) {
                        
                        
                        $(colorDropdown).append('<option value="' + item.productItemsId + '">' + item.color.colorName + '</option>');
                    });
                }
            });
        }

        $(document).on('change', '.ddlColors', function () {
            GetProductBySize($(this));
        });
        function GetProductBySize(selectedSizeDropdown) {
            var productItemsId = $(selectedSizeDropdown).val();
            var sizeDropdown = $(selectedSizeDropdown).closest('tr').find('select[id="sizeId"]');

            $.ajax({
                url: '@Url.Action("GetProductBySize", "Invoice")',
                type: 'GET',
                data: { id: productItemsId },
                success: function (data) {
                    $(sizeDropdown).empty(); 
                    $.each(data["$values"], function (index, item) {
                       
                        $(sizeDropdown).append('<option value="' + item.productVarId + '">' + item.sizeId + '</option>');
                    });
                }
            });
        }
    </script>
<script>
        $('#btnAdd').click(function () {
            var id_last = $(".tblInvoiceDetail").find("tr:last-child").attr("data-id");
            i = parseInt(id_last) + 1;     

            var tdcontent = $(".trAppend").html();
            var trcontent = "<tr class="trAppended" data-id="" + i + "">" + tdcontent + "<tr>";
            $(".tblInvoiceDetail").append(trcontent);
            loadIDCard();
            var newProductDropdown1 = $(".tblInvoiceDetail").find("tr:last-child").find("#colorId");
            var newProductDropdown = $(".tblInvoiceDetail").find("tr:last-child").find(".ddlProductItemsId");
            GetProductByColor(newProductDropdown);
            GetProductBySize(newProductDropdown1);
         
        });

        $("body").delegate(".btnDelete", "click", function () {
            $(this).closest(".trAppended").remove();
            UpdateID();
        });

        $("#btnConfirm").click(function () {
            if (reviewPrice() == false) {
                return false;
            }

            if (reviewQuanity() == false) {
                return false;
            }

            var totalPrice = 0;
            var totalQuanity = 0;

            $(".tblInvoiceDetail .trAppended").each(function () {


                var Price = parseFloat($(this).find(".txtPrice").val()) || 0;
                var Quanity = parseInt($(this).find(".txtQuanity").val()) || 0;


                totalPrice += Price;
                totalQuanity += Quanity;
            });

            if (totalPrice <= 0 && totalQuanity <= 0) {
                alert("Error input !");
                return false;
            }
        });

        function loadIDCard() {
            $(".trAppended").each(function () {
                var id = $(this).attr("data-id");

               
                var nameIdProduct = "[" + id + "].ProductItemsId";
                var namePriceImport = "[" + id + "].Price";
                var nameQuanityImport = "[" + id + "].Quanity";

              
                $(this).find(".ddlProductItemsId").attr("name", nameIdProduct);
                $(this).find(".txtPrice").attr("name", namePriceImport);
                $(this).find(".txtQuanity").attr("name", nameQuanityImport);
            })
        };

        function UpdateID() {
            var id_last = $(".tblInvoiceDetail").find("trFirstChild").attr("data-id");
            i = parseInt(id_last) + 1;

            $(".trAppended").each(function () {
                var id = i = $(this).attr("data-id");

                var nameSize = "[" + id + "].SizeId";
                var nameIdProduct = "[" + id + "].ProductItemsId";
                var namePriceImport = "[" + id + "].Price";
                var nameQuanityImport = "[" + id + "].Quanity";

                $(this).find(".ddlSize").attr("name", nameSize);
                $(this).find(".ddlProductItemsId").attr("name", nameIdProduct);
                $(this).find(".txtPrice").attr("name", namePriceImport);
                $(this).find(".txtQuanity").attr("name", nameQuanityImport);
            });
        }

        function reviewPrice() {
            var bl = true;

            $(".txtPrice").each(function () {
                var value = $(this).val();
                if (isNaN(value) == true) {
                    alert("Invalid Price!");
                    bl = false;
                    return bl;
                }
            });

            return bl;
        }

  
</script>
}

I color dropdown work correctly when I click on the button plus. Its show the list color of product but not the size and when I choose a different color, the Size column works. I want like when I click on plus button both method work correctly.I figure it out that when I click on the plus button there is no ID is passed to the GetProductBySize method

inspect the website .

But when I change the color it does

change the color.

Does anyone know where is the problem? I really appreciate any instructions. Thank for your reading

calculator app in svelte producing wrong result with certain numbers

i am watching a crash course in svelte that creates a calculator app, also a beginner in javascript, when i do 1.1 x 3 it produces the result pic below but when i do 1.1 x 4 it show the correct result 4.4, anybody can figure out why?

<script lang="ts">
  const numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."];
  const operations = ["/", "x", "-", "+", "="];

  let selectedOperation = "";
  let display = "";
  let firstNumber = "";
  let secondNumber = "";
  let isDisplayingResults = false;

  // the selected operation in the calculator
  const handleOperationClick = (operation: string) => {
    // prevent selecting operation if firstNumber is empty
    if (!firstNumber) return;
    // if "=" is clicked check if secondNumber is empty then no action, else
    if (operation === "=") {
      if (!secondNumber) return;
      // check if numbers has decimal point
      const hasDecimalfirst = /./.test(firstNumber);
      const hasDecimalsecond = /./.test(secondNumber);

      let firstNum;
      let secondNum;

      // parse first number as integer if no decimal point else parse as float
      if (!hasDecimalfirst) {
        firstNum = parseInt(firstNumber);
      } else {
        firstNum = parseFloat(firstNumber);
      }

      // parse second number as integer if no decimal point else parse as float
      if (!hasDecimalsecond) {
        secondNum = parseInt(secondNumber);
      } else {
        secondNum = parseFloat(secondNumber);
      }

      let results = "";

      // select operation based on selected operation
      switch (selectedOperation) {
        case "/":
          results = (firstNum / secondNum).toFixed(2);
          break;
        case "x":
          if (!hasDecimalfirst || !hasDecimalsecond) {
            results = (firstNum * secondNum).toString();
          } else {
            results = (firstNum * secondNum).toFixed(2);
          }
          break;
        case "+":
          if (!hasDecimalfirst || !hasDecimalsecond) {
            results = (firstNum + secondNum).toString();
          } else {
            results = (firstNum + secondNum).toFixed(2);
          }
          break;
        case "-":
          if (!hasDecimalfirst || !hasDecimalsecond) {
            results = (firstNum - secondNum).toString();
          } else {
            results = (firstNum - secondNum).toFixed(2);
          }
          break;
      }
      display = results;
      isDisplayingResults = true;
    }
    selectedOperation = operation;
  };

  const handleClear = () => {
    firstNumber = "";
    secondNumber = "";
    selectedOperation = "";
    display = "";
    isDisplayingResults = false;
  };
  // the handler when selecting numbers in the calculator
  const handleNumberClick = (number: string) => {
    // clear all values after displaying the result when selecting a number
    if (isDisplayingResults) {
      handleClear();
    }
    // if display is empty and selected number is 0 then no action
    // does not allow the initial number 0 assuming not float
    if (!display && number === "0") return;
    // if selected number is . and display already has . then no action
    // does not allow more than one .
    if (number === "." && display.includes(".")) return;

    // no selected operation yet
    if (!selectedOperation) {
      // if display is empty and selected number is . assign to firstNumber then display
      if (!display && number === ".") {
        firstNumber = "0.";
        return (display = firstNumber);
      }
      // if display is not empty append to current display and assign to firstNumber
      firstNumber = `${firstNumber}${number}`;
      return (display = firstNumber);
    } else {
      // already have a selected operation
      // if display is empty and selected number is . assign to secondNumber then display
      if (!display && number === ".") {
        secondNumber = "0.";
        return (display = secondNumber);
      }
      // if display is not empty append to current display and assign to secondNumber
      secondNumber = `${secondNumber}${number}`;
      return (display = secondNumber);
    }
  };
</script>

<main>
  <div class="calculator">
    <div class="results">{display}</div>
    <div class="digits">
      <div class="numbers">
        <button class="btn btn-xlg" on:click={handleClear}>C</button>
        {#each numbers as number (number)}
          <button
            class={`btn ${number === "0" ? "btn-lg" : null}`}
            on:click={() => handleNumberClick(number)}
          >
            {number}
          </button>
        {/each}
      </div>
      <div class="operations">
        {#each operations as operation (operation)}
          <button
            class={`btn ${operation === selectedOperation ? "btn-silver" : "btn-orange"}`}
            on:click={() => handleOperationClick(operation)}
          >
            {operation}
          </button>
        {/each}
      </div>
    </div>
  </div>
</main>

enter image description here

Typed Arrays byte offset

Even though the byte offset is 12, and the underlying buffer size is of 12 bytes, how are we able to set the starting of int8Array beyond the underlying buffersize?

let buffer = new ArrayBuffer(12);
const intArray = new Int32Array(buffer);
console.log(intArray.buffer);
const int8Array = new Int8Array(buffer, 12);
int8Array[0] = 200;
console.log(intArray.buffer);

How is const int8Array = new Int8Array(buffer, 12) possible?

I was expecting a

RangeError: RangeError: Start offset 12 is outside the bounds of the buffer