hamburger menu lock scroll

hi guys how are u? I’ve spend lot of time trying lock the scroll when the menu is open and i didnt find the solution. is there anybody able to help me? Appreciate!
my code:

 <!-- Navigation bar -->
    <header class="header">
        <!-- Logo -->
        <a href="teste.html" class="logo"><img src="img/ss.png"></a>
        <!-- Hamburger icon -->
        <input class="side-menu" type="checkbox" id="side-menu" />
        <label class="hamb" for="side-menu"><span class="hamb-line"></span></label>
        <!-- Menu -->
        <nav class="nav">
            <ul class="menu" id="menu">
                <li class="nav-link"><a href="teste.html" class="nav-link">Home</a></li>
                <li><a href="about.html">About</a></li>
                <li><a href="servicos.html">Services</a></li>
                <li><a href="contato.html">Contact</a></li>
                <li>
                    <input type="button" name="nome" value="FREE ESTIMATE">
                </li>
            </ul>
        </nav>

Why is the javascript code not working for other elements, and only works for one? [closed]

I don’t know how to explain, but one of the three elements run fine, the other two are just not working for me, I tried changing everything about them, the list name, variable names, etc. These three elements are pretty much the same, but later on I’ll change the content of the array. Can someone let me know what I might be potentially missing here?


< script src = "https://code.jquery.com/jquery-3.4.1.min.js" > < /script> <
script src = "https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.2/TweenMax.min.js" > < /script> <
script src = "https://code.jquery.com/jquery-3.4.1.slim.min.js" > < /script>


var western = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Apple_Pay_logo.svg/2560px-Apple_Pay_logo.svg.png", "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png", "https://e7.pngegg.com/pngimages/426/901/png-clipart-klarna-circle-icon-tech-companies-thumbnail.png"];

let imageTimer, imageIndex = 0;

function updateImage() {
  var image = western[imageIndex];
  $("#western1").attr("src", image);
  console.log(image);
  imageIndex++;
  imageIndex *= (imageIndex < western.length);
  for (var i = 0; i < western.length; i++) {
    // create the image element
    var imageElement = document.createElement('img');
    imageElement.setAttribute('src', western[i]);
  }

  imageTimer = setTimeout(updateImage, 300);
}

onload = () => {
  imageTimer = setTimeout(updateImage, 300);
}


var western2 = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Apple_Pay_logo.svg/2560px-Apple_Pay_logo.svg.png", "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png", "https://e7.pngegg.com/pngimages/426/901/png-clipart-klarna-circle-icon-tech-companies-thumbnail.png"];

let imageTimer2, imageIndex2 = 0;

function updateImage2() {
  var image2 = western2[imageIndex2];
  $("#western2").attr("src", image2);
  console.log(image2);
  imageIndex2++;
  imageIndex2 *= (imageIndex2 < western2.length);
  for (var i = 0; i < western2.length; i++) {
    // create the image element
    var imageElement2 = document.createElement('img');
    imageElement2.setAttribute('src', western2[i]);
  }
  imageTimer2 = setTimeout(updateImage2, 300);
}

onload = () => {
  imageTimer2 = setTimeout(updateImage2, 300);
}


var western3 = ["https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/Apple_Pay_logo.svg/2560px-Apple_Pay_logo.svg.png", "https://cdn1.iconfinder.com/data/icons/logos-brands-in-colors/436/Google_Pay_GPay_Logo-512.png", "https://e7.pngegg.com/pngimages/426/901/png-clipart-klarna-circle-icon-tech-companies-thumbnail.png"];

let imageTimer3, imageIndex3 = 0;

function updateImage3() {
  var image3 = western3[imageIndex3];
  $("#western3").attr("src", image3);
  console.log(image3);
  imageIndex3++;
  imageIndex3 *= (imageIndex3 < western3.length);
  for (var i = 0; i < western3.length; i++) {
    // create the image element
    var imageElement3 = document.createElement('img');
    imageElement3.setAttribute('src', western3[i]);
  }

  imageTimer3 = setTimeout(updateImage3, 300);
}

onload = () => {
  imageTimer3 = setTimeout(updateImage3, 300);
}
max-width: 7vw;
margin: -7%;
margin-top: 0.1px;
z-index: 111111;

/*    height: auto;*/

margin-bottom: 0.1px;
<div>
  <span>
                    <img id="western1" class="img2" src="imgs/r/r1.png" />
                </span>
  <br /><span>
                    <img id="western2" class="img2" src="imgs/r/r2.png" />
                </span>
  <br />
  <span>
                    <img id="western3" class="img2" src="imgs/r/r3.png" />
                </span>
</div>

Multiple Slideshows HTML, CSS, JavaScript

I’m trying to add multiple slideshows to one page but am having some difficulty. I can add two functioning slideshows but when I add a third everything breaks.

var slideIndex = [1, 1, 1, 1];
var slideId = ["slide", "slide2", "slide3", "slide4"]
showSlides(1, 0);
showSlides(1, 1);
showSlides(1, 2);
showSlides(1, 3);

function plusSlides(n, no) {
  showSlides(slideIndex[no] += n, no);
}

function showSlides(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]);
  if (n > x.length) {
    slideIndex[no] = 1
  }
  if (n < 1) {
    slideIndex[no] = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex[no] - 1].style.display = "block";
}

let dots = document.getElementsByClassName("dot");

for (i = 0; i < dots.length; i++) {
  dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex - 1].style.display = "block";
dots[slideIndex - 1].className += " active";
}
.slideshow-container {
  width: 48%;
  position: relative;
  margin: 1%;
  height: auto;
  display: inline-block;
}

html {
  scroll-behavior: smooth;
}

.mySlides {
  display: none
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  padding: 16px;
  margin-top: -22px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
  text-decoration: none;
  background-color: rgba(0, 0, 0, 0.8);
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  color: #e57726;
}

.captiontext {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

.numbertext {
  color: #f2f2f2;
  font-size: 8px;
  padding: 8px 12px;
  position: absolute;
  background top: 0;
  background-color: rgba(0, 0, 0, 0.8);
}

.dot {
  cursor: pointer;
  height: 5px;
  width: 5px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active,
.dot:hover {
  background-color: #717171;
}

.prev,
.next,
.text {
  font-size: 11px
}


}
<p>Welcome to our vibrant showcase of creativity and technical skill in our 3D Modeling and Animation minor! This gallery features a diverse array of student projects, renderings featuring architecture, character design, exhibition design, fantasy and much
  more. Each piece is a testament to our students' dedication and talent, highlighting their journey through the rigorous process of 3D modeling and animation production. Explore these inspiring works and discover how our students bring their unique visions
  to life, using cutting-edge techniques.&#160;&#160;</p>
<hr />
<h2 style="margin-bottom: 2.5%; font-weight: bold; text-align: center;">Student Gallery
</h2>
<div class="slideshow-container">
  <div class="mySlides slide">
    <div class="numbertext">1 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/085a7f94-2a34-47f4-9594-7d87f7421bbd.png" style="width: 100%;" /></div>
  <div class="mySlides">
    <div class="numbertext">2 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/b5c84a45-1b9c-4a12-b76d-a5b30fffa8d0.png" style="width: 100%;" /></div>
  <a class="prev" onclick="plusSlides(-1, 0)" style="text-decoration: none;">❮</a><a class="next" onclick="plusSlides(1, 0)" style="text-decoration: none;">❯</a>
  <div style="text-align: center;"><span class="dot" onclick="currentSlide(1)"></span><span class="dot" onclick="currentSlide(2)"></span>
    <p>Student Name: Alexandro Ayala</p>
  </div>
</div>
<div class="slideshow-container">
  <div class="mySlides slide2">
    <div class="numbertext">1 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/0b7a9a69-a19b-4827-a2a7-037584488937.jpg" style="width: 100%;" /></div>
  <div class="mySlides">
    <div class="numbertext">2 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/de130f4c-1eb1-4707-8137-b07b2ea3f128.jpg" style="width: 100%;" /></div>
  <a class="prev" onclick="plusSlides(-1, 1)" style="text-decoration: none;">❮</a><a class="next" onclick="plusSlides(1, 1)" style="text-decoration: none;">❯</a>
  <div style="text-align: center;"><span class="dot" onclick="currentSlide(1)"></span><span class="dot" onclick="currentSlide(2)"></span>
    <p>Student Name: Deontae Cocroft</p>
  </div>
</div>
<div class="slideshow-container">
  <div class="mySlides slide3">
    <div class="numbertext">1 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/085a7f94-2a34-47f4-9594-7d87f7421bbd.png" style="width: 100%;" /></div>
  <div class="mySlides">
    <div class="numbertext">2 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/b5c84a45-1b9c-4a12-b76d-a5b30fffa8d0.png" style="width: 100%;" /></div>
  <a class="prev" onclick="plusSlides(-1, 2)" style="text-decoration: none;">❮</a><a class="next" onclick="plusSlides(1, 2)" style="text-decoration: none;">❯</a>
  <div style="text-align: center;"><span class="dot" onclick="currentSlide(1)"></span><span class="dot" onclick="currentSlide(2)"></span>
    <p>Student Name: Alexandro Ayala</p>
  </div>
</div>
<div class="slideshow-container">
  <div class="mySlides slide4">
    <div class="numbertext">1 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/085a7f94-2a34-47f4-9594-7d87f7421bbd.png" style="width: 100%;" /></div>
  <div class="mySlides">
    <div class="numbertext">2 / 2</div>
    <img alt="" data-ektron-style="width: 100%;" src="/assets/0/1237/5580/5666/b5c84a45-1b9c-4a12-b76d-a5b30fffa8d0.png" style="width: 100%;" /></div>
  <a class="prev" onclick="plusSlides(-1, 3)" style="text-decoration: none;">❮</a><a class="next" onclick="plusSlides(1, 3)" style="text-decoration: none;">❯</a>
  <div style="text-align: center;"><span class="dot" onclick="currentSlide(1)"></span><span class="dot" onclick="currentSlide(2)"></span>
    <p>Student Name: Alexandro Ayala</p>
  </div>
</div>
<br />

I tried to incorporate fixes from similar answers from users who had this same issue, but now the images don’t appear, and I’m wondering if the issue is somewhere with in the CSS or if I don’t have the correct JS statements.

Trouble updating cookie value after successful API call

I’m encountering an issue with handling access and refresh tokens as cookies. I’m trying to update the accessTokenCookie and refreshTokenCookie values upon a successful API call in the refreshAccessToken() function, however, despite receiving a new access token from the server, the cookie value does not appear to update, resulting in an infinite recursion problem. This, in turn, leads to a DDoS of my website with infinite refresh-token requests. What am I doing wrong?

        const accessTokenCookie = useCookie("access_token")
        const refreshTokenCookie = useCookie("refresh_token")

        async function refreshAccessToken() {
        if (refreshTokenCookie.value) {
            try {
                const response = await useFetch(
                    refreshApi,
                    {
                        refresh: refreshTokenCookie.value,
                    },
                    {
                        headers: {
                            "Content-Type": "application/json",
                        },
                    }
                )

                if (response.status === 401) {
                    accessTokenCookie.value = null
                    refreshTokenCookie.value = null
                } else if (response.ok) {
                    const data = await response.json()
                    accessTokenCookie.value = data.access
                    refreshTokenCookie.value = data.refresh
                    authenticated.value = true

                    await fetchUser()
                }
            } catch (error) {
                console.error("Error refreshing access token:", error)
            }
        } else {
            authenticated.value = false
        }
    }

    async function fetchUser() {
        if (accessTokenCookie.value) {
            try {
                const response = await useFetch(userApi, {
                    headers: {
                        Authorization: `Bearer ${accessTokenCookie.value}`,
                    },
                })
                if (response.status === 401) {
                    refreshAccessToken()
                } else if (response.ok) {
                    const data = await response.json()
                    this.authenticated = true
                    this.user = data
                }
            } catch (error) {
                console.error("Error fetching user:", error)
            }
        } else {
            refreshAccessToken()
        }
    }

Cannot access elements inside of an iframe element

I’ve been facing an issue while trying to access an element inside the document rendered through an Iframe element.

When i access the parent node of the Iframe element you can see the embedded document within the iframe element

Log of the parent:

log of the parent

But when i specifically try to access the iframe element you can see the embedded document becomes empty

Log of the iframe element:

log of the iframe element

I want to access a button that exists within the iframe element and because of this issue i am not able to do so.

How to make radio-group decide the number of input-fields in a group of div’s

I am trying to make a piece of javscript that will decide the number of input-fields (number) in a group of divs, when pressing one of 3 radio buttons. When pressing one of the radio buttons all div’s in the group should have two input fields. When pressing the two other radio buttons there should only be one. I’ve made the following code, but for some reason it only changes the first occurence of the div. The rest of the div’s have no input field. See the attached image.

document.addEventListener('DOMContentLoaded', function () {
  var radioContainers = document.querySelectorAll('.form-step .type-window');
  var numberInputContainers = document.querySelectorAll('.form-step .number-input-container');

  console.log("radioContainers:", radioContainers);


  radioContainers.forEach(function (radioContainer, index) {
    var radioButtons = radioContainer.querySelectorAll('input[name="plan"]');
    var numberInputContainer = numberInputContainers[index];

    radioButtons.forEach(function (radioButton) {
      radioButton.addEventListener('change', function () {
        hideAllNumberInputContainers();

        if (radioButton.id === 'etplan') {
          showNumberInputContainer(numberInputContainer, 'stue-item');
        } else if (radioButton.id === 'toplan') {
          showNumberInputContainer(numberInputContainer, 'stue-item');
          showNumberInputContainer(numberInputContainer, 'sal-item');
        } else if (radioButton.id === 'etagelejlighed') {
          showNumberInputContainer(numberInputContainer, 'lejlighed-item');
        }
      });
    });
  });

  function hideAllNumberInputContainers() {
    numberInputContainers.forEach(function (container) {
      var inputs = container.querySelectorAll('input[type="number"]');
      inputs.forEach(function (input) {
        input.style.display = 'none';
      });
    });
  };

  function showNumberInputContainer(container, selector) {
    var inputs = container.getElementsByClassName(selector);
    Array.from(inputs).forEach(function (input) {
      input.style.display = 'inline-block';
    });
  }
});

enter image description here

How to declare type of destructured function argument *within function call* in JSDoc? [duplicate]

When using Playwright, tests are specified within a function argument of the test function, taking optional fixtures in the nested function’s argument, like so:

// `page` is fixture
test("some test", async ({ page }) => {
    await page.goto("https://google.com");
});

I am using a Page-Object Model pattern, so I’d like to be able to annotate a custom fixture object with its type:

// In TS, this would be as simple as: `pomPage: SomeClass`
test("some test", async ({ pomPage }) => {
    await pomPage.goto();
});

How can I accomplish this with a JSDoc type annotation? There are several SO answers about annotating destructured function arguments, but none of them seem to address the case where the function whose argument should be annotated is itself an argument to another function call.

Note: This question should not receive answers whose basic form reduces to “use TypeScript”—it’s specifically about JSDoc.

Lucky Spin Wheek Get Value On pointer

When the spinner stop i want to get value that is right of the pointer currently not giving me exact value gives random value The below is the code

When I place this as hard code value pointer stop at location and gives accurate value.

The below is actual javascript code.

const wheel = document.getElementById("wheel");
const spinBtn = document.getElementById("spin-btn");
const finalValue = document.getElementById("final-value");

//Object that stores values of minimum and maximum angle for a value
const setRotationValues = [
    //{ minDegree: 0, maxDegree: 30, value: 20 },
    //{ minDegree: 31, maxDegree: 90, value: 10 },
    //{ minDegree: 91, maxDegree: 150, value: 60 },
    //{ minDegree: 151, maxDegree: 210, value: 50 },
    //{ minDegree: 211, maxDegree: 270, value: 40 },
    //{ minDegree: 271, maxDegree: 330, value: 30 },
    //{ minDegree: 331, maxDegree: 360, value: 20 },
];
var size Piece Of Circle = [];
var pie Chart Colors = [];
var showLabels = [];

function Get pin Configuration() {
    $.ajax({
        url: '/Set Individual Points/Spinner Configuration/',
        type: "GET",
        dataType: "json",
        success: function (result) {
            if (result != null) {

                var data = result["result"];
                var colors = ["#8b35bc", "#b163da"];

                sizeOfPieceOfCircle = [];
                pieChartColors = [];
                showLabels = [];

                var totalCount = data.length;
                var partitionOfEach = 360 / totalCount;

                var initialDegree = 0;
                var nextVal = partitionOfEach;

                var piecesValue = 100 / totalCount;

                for (var i = 0; i < totalCount; i++) {

                    setRotationValues.push({ "minDegree": initial Degree, "max Degree": nextVal, 
                    value": data[i] });
                    initial Degree = nextVal + 1;
                    nextVal = nextVal + partition Each;

                    sizeOfPieceOfCircle.push(parseInt(pieces Value));
                    showLabels.push(data[i]);

                    if (i % 2 == 0) {
                        pieChartColors.push(colors[0]);
                    } else {
                        pieChartColors.push(colors[1]);
                    }
                }

               
    });
}

$(document).ready(function () {
    Get pin Configuration();
});

toLocaleString shows ‘0’ at the end when length exceeds

I am using toLocaleString but it keeps on adding after certain length

 let integer = 46738399923867126778;
   
        const integerPart = (integer).toLocaleString('en-IN',{maximumSignificantDigits:21});
        console.log(new Intl.NumberFormat('en-IN').format(integer));

        console.log(integerPart);

output :

  • 4,67,38,39,99,23,86,71,20,000
  • 4,67,38,39,99,23,86,71,20,000

I want it to show the number provided with the formatting specfied and not add zeroes

Convert deep nested array in javascript to CSV

I have a deep nested array that needs to converted into a downloadable CSV. I am trying to build the CSV file by iterating through each array and subarray. Is there a more efficient way of doing this?

This is what the nested array looks like:

[
  id: 123,
  name: "ABC",
    superDepartment: [
      {id: 456,
       name: "PQR",
         keyCompetitor: ["JKL"]
         department: [
           {id: 765,
            name: "XYZ"
              category: [
               {id: 965,
                name: "GHJ"
                  keyCompetitor: ["NMK"],
                  otherCompetitor: ["SDF", "LKJ"]
                  subcategory: [
                   {id: 346, name: "DRJ"},
                   {id: 789, name: "SRE"}              
                  ]
               }
              ]
         ]
    ]
]


Expected output in CSV
| SBU | Super Department | Department | Category | Subcategory | Key Competitor | Core Competitor | Other Competitor |
|-----|------------------|------------|----------|-------------|----------------|-----------------|------------------|
| ABC |                  |            |          |             |                |                 |                  |
|     | PQR              |            |          |             | JKL            |                 |                  |
|     |                  | XYZ        |          |             |                |                 |                  |
|     |                  |            | GHJ      |             | NMK            |                 | SDF, LKJ         |
|     |                  |            |          | DRJ         |                |                 |                  |
|     |                  |            |          | SRE         |                |                 |                  |

This is what I have so far:
let csvData = [];
        downloadData.map(data => {
            if(csvData.length === 0) {
                csvData.push(data.name, "", "", "", csvData.keyCompetitors ? csvData.keyCompetitors[0] : "",
                csvData.coreCompetitors ?  csvData.coreCompetitors.join(): "",
                csvData.otherCompetitors ? csvData.otherCompetitors.join() : "")
            }
        });


Inspecting, Modifying, and Triggering an onclick Function on a Live Website

On this live website, I’m trying to get previous versions of Firmware for a camera lens. The companies’ support generally ignores you, so I was seeing if I could figure out a workaround lol.

AF 135mm F1.8 FE is on version 5 of the firmware. I’m attempting to get version 4 and version 3.

If I inspect it, the button click triggers the following onclick function:

<button type="button" class="bt-full black" onclick="FnFileDownload('964','5');">Download</button>

I’ve tried modifying the DOM through inspector, swapping out to

<button type="button" class="bt-full black" onclick="FnFileDownload('964','4');">Download</button>

But no luck, it still pulls version 5. I was thinking, if I ran something through the console, maybe it would be possible?

https://www.samyanglens.com/en/support/support-download.php?type=3&model=SONY

Sorting strings in an array without using any built in sorting

I am in a JavaScript class and one of my assignments gives me a driver class and txt file full of strings. I have to make a class with three methods that sort the list by amount of vowels, consonants, and word length respectively and it will print out 3 different arrays at the end. I am not allowed to use any built in sorting methods, such as Array.sort. How do I this?

I have tried copying the string array and after that is when I get stumped.

Prisma relation bug, say “missing argument” but I provided argumentId

I’m currently using Prisma in my backend for relation with my database. I have these 2 models :

model User {
    id       String    @id
    login    String
    messages Message[]
}

model Message {
  id          Int        @id @default(autoincrement())
  content     String
  sender      User       @relation(fields: [senderId], references: [id])
  senderId    String
  channel     Channel?   @relation(fields: [channelId], references: [id])
  channelId   Int   
}

When I’m trying to insert a new line, using this code :

let message = await this.prisma.message.create({
    data: { content: data.messageContent, senderId: data.userId, channelId: data.channelId }
})

// data.messageContent is : "salut"
// data.userId is : "117645"
// data.channelId is : 58

// And yes I checked, User "117645" and Channel 58 both exist

Screenshot of the error : enter image description here

I tried to ask chatgpt, he said everything is fine
I tried to add {sender: { connect: { id: data.userId } } } but have an error
I tried to add a name to the @relation

How to Append New Data to Existing SQLite Table in FastAPI without Overwriting Old Data?

I’m working on a FastAPI project with a SQLite database where I have a feature to upload .xlsx files to update taskboards. Each taskboard is stored as a separate table in the SQLite database. My current implementation replaces the old data with the new data upon upload, but I want to modify it so that the new data is appended to the existing data instead.

Here’s the relevant part of my code:

The endpoint:


@app.post("/upload/")
async def upload_file(name: str = Form(...), file: UploadFile = File(...)):
    contents = await file.read()
    workbook = load_workbook(filename=BytesIO(contents))
    sheet = workbook.active
    rows = list(sheet.iter_rows(values_only=True))
    headers = rows[0]

    def convert_to_json_serializable(row):
        json_row = {}
        for key, value in zip(headers, row):
            if isinstance(value, datetime):
                # Convert datetime to ISO string format
                json_row[key] = value.isoformat()
            else:
                json_row[key] = value
        return json_row

    data = [convert_to_json_serializable(row) for row in rows[1:]]  # Convert rows to list of dicts
    return data  # Return the data as a list of dictionaries

The function for uploading:


    def uploadFile(self, name, file_path):
        # Check if the Taskboard exists
        if not self._taskboard_exists(name):
            raise Exception(f"Taskboard '{name}' does not exist.")

        # Load data from the spreadsheet or CSV file
        data = []
        headers = None  # To store column headers
        if isinstance(file_path, str):
            if file_path.endswith(".xlsx"):
                wb = openpyxl.load_workbook(file_path)
                ws = wb.active
                headers = [
                    cell.value for cell in next(ws.iter_rows())
                ]  # Corrected line
                for row in ws.iter_rows(values_only=True):
                    data.append(row)
            elif file_path.endswith(".csv"):
                with open(file_path, "r") as csv_file:
                    csv_reader = csv.reader(csv_file)
                    headers = next(csv_reader)
                    for row in csv_reader:
                        data.append(row)
        elif isinstance(file_path, bytes):  # If file_path is bytes
            # Convert bytes to BytesIO for openpyxl
            inbytes = BytesIO(file_path)
            wb = openpyxl.load_workbook(inbytes)

            ws = wb.active
            headers = [cell.value for cell in next(
                ws.iter_rows())]  # Corrected line
            for row in ws.iter_rows(values_only=True):
                data.append(row)
        else:
            raise Exception(
                "Unsupported file format. Must be filepath as str or file as bytes",
                type(file_path),
            )

        # Ensure that the Taskboard table has columns for all headers
        self._ensure_columns_exist(name, headers)

        # Prevent the headers from being reinserted, this generally causes errors
        data.pop(0)

        # Single quote names to prevent parsing errors when spaces are present in name
        headers = list(map(lambda header: "'" + header + "'", headers))

        # Insert data into the Taskboard table, setting missing columns to None
        with self.global_db:
            cursor = self.global_db.cursor()

            # Check if an 'upload_id' column exists in the table
            cursor.execute("PRAGMA table_info('{}')".format(name))
            columns_info = cursor.fetchall()
            upload_id_exists = any(
                column[1] == "upload_id" for column in columns_info)

            # If 'upload_id' column does not exist, add it with a default value of 0
            if not upload_id_exists:
                cursor.execute(
                    "ALTER TABLE '{}' ADD COLUMN 'upload_id' INTEGER DEFAULT 0".format(
                        name
                    )
                )

                upload_id = 0
            else:
                # Check the last 'upload_id' in the table
                upload_id = cursor.execute(
                    "SELECT MAX(upload_id) FROM '{}'".format(name)
                ).fetchone()[0]
                upload_id = (
                    0 if upload_id is None else (upload_id + 1)
                )  # Check if upload id has no entries.

            # Insert upload_id into headers list
            headers.insert(0, "upload_id")

            for row in data:
                # Add the 'upload_id' as the first column
                values = [upload_id] + [
                    value if value is not None else None for value in row
                ]
                cursor.execute(
                    "INSERT INTO '{}' ({}) VALUES ({})".format(
                        name,
                        ",".join(headers),
                        # Add 1 for 'upload_id'
                        ",".join(["?"] * len(headers)),
                    ),
                    values,
                )

I’m unsure how to modify the SQL queries to achieve this. Can someone guide me on how to adjust the method to append new data to the existing table?

Additional Context (Optional):

Each taskboard is represented as a separate table in the SQLite database.
The frontend is a JavaScript-based web application that sends .xlsx files to the FastAPI backend.
FastAPI handles the file and updates the SQLite database.
Any insights or code examples would be greatly appreciated!

AG-Grid Pivot Table Totals Field

I have a use case where I need to add a Totals field to a pivot table. This Totals field should have the Total for the row group in it. So in this case for 2008 it would be 4 gold and coincidentally for 2012 it would also be 4 gold.

For some reason it seems exceptionally complex to create a “fake” column in a pivot table in AG Grid. If I can make a “fake” column called “Totals” I can map through each row in my renderer and paint the totals on each line, but it is not immediately obvious how to achieve this in the API.

While I was expecting an API function to exist such that I can have a totals field at the very end and it would calculate it based on the pivot value automatically, I am willing to work around that limitation/absent feature. I am advised that this is a common functionality in pivot tables so I am a bit surprised how difficult this requirement is.

Pivot Table