Get Absolute Path of files using .NET Core 8 and JS

How can I get absolute path of a file using .NET Core 8 and Vanilla Javascript?

Issue: I need to send absolute path of a to a service for which I need to use only .NET Core 8 Web app and Vanilla JS to allow user to pick a file in file dialogbox and I need to capture it and send the absolute path to that service.

Attempt: I cannot get the absolute path of files using JS as it’s not possible due to security reasons and I also tried to trigger a ajax call to a action method to show OpenDialogBox and compiling the app to windows application, But this scenario won’t work for hosting and deploying scenarios.

Question: How can I get absolute path of files of user choosing? This can be of any possible way within the tech stack I provided.

Streamlit Javascript integration

I can’t get any js function in streamlit to work, the return value is always 0, no matter how I tried to write it. For instance

anonymous = st_javascript("""
    (() => {
        return 2;
    })()
""")

st.write(f"JavaScript returned: {anonymous}")

What am I doing wrong here? Chatgpt and claude couldn’t help, nor did I see any helpfull posts here.

Can someone provide the correct syntax?

How can I create a new random shape for a Tetris-like game?

I want to have new tetris pieces to appear in the game the longer you play and it doesn’t work, it makes new shapes but the shapes aren’t centered, they aren’t continuous (like the shape might look like 2 shapes because they aren’t touching), and it sometimes adds a shape that’s already part of the shapes array. Each shape has a max squares of 12 and must fit in a 4×4 space
Here’s my code so far:

function randomShape(score) {
  const maxSize = 12; // Max number of squares per shape
  const centerOffset = 1; // Offset to center the shape
  const maxComplexity = Math.min(Math.floor(score / 100), 6); // Max complexity based on score

  let shape;

  do {
    shape = Array.from({ length: 4 }, () => Array(4).fill(0)); // Create an empty 4x4 shape
    const size = Math.max(1, Math.floor(Math.random() * (maxComplexity + 1))); // Shape size varies based on complexity

    let squaresToPlace = Math.min(size, maxSize); // Limit the squares placed to maxSize

    // Fill the shape with random positions of 1s based on size
    while (squaresToPlace > 0) {
      const x = Math.floor(Math.random() * 4);
      const y = Math.floor(Math.random() * 4);

      // Only place a 1 if the spot is empty
      if (shape[y][x] === 0) {
        shape[y][x] = 1;
        squaresToPlace--;
      }
    }
  } while (!shape.flat(5).includes(1)); // Retry if the shape is empty

  // Centering logic
  const centeredShape = Array.from({ length: 4 }, () => Array(4).fill(0));

  // Get the positions of all filled cells
  const filledPositions = [];
  for (let r = 0; r < 4; r++) {
    for (let c = 0; c < 4; c++) {
      if (shape[r][c] === 1) {
        filledPositions.push({ r, c });
      }
    }
  }

  let amount = 0;
  shape.flat(5).forEach((s) => {
    if (s === 1) amount++;
  });
  if (amount === 1) {
    return [
      [0, 0, 0, 0],
      [0, 0, 0, 0],
      [0, 0, 1, 0],
      [0, 0, 0, 0],
    ];
  }

  // Determine how to center the shape
  const minRow = Math.min(...filledPositions.map((p) => p.r));
  const maxRow = Math.max(...filledPositions.map((p) => p.r));
  const minCol = Math.min(...filledPositions.map((p) => p.c));
  const maxCol = Math.max(...filledPositions.map((p) => p.c));

  // Calculate the offsets needed to center the shape
  const height = maxRow - minRow + 1;
  const width = maxCol - minCol + 1;

  // Calculate vertical and horizontal offsets
  const rowOffset = Math.floor((4 - height) / 2); // Center vertically
  const colOffset = Math.floor((4 - width) / 2); // Center horizontally

  // Place the shape in the centered position
  filledPositions.forEach(({ r, c }) => {
    // Ensure we're placing the piece within bounds
    const newRow = r + rowOffset;
    const newCol = c + colOffset;
    if (newRow >= 0 && newRow < 4 && newCol >= 0 && newCol < 4) {
      centeredShape[newRow][newCol] = 1;
    }
  });

  return centeredShape;
}

I tried to add new random shapes that were supposed to look normal and be centered, but they were broken and uncentered and sometimes dupes.

How to get min and max vAxis and vAxis ticks using mm:ss in Google Charts API?

As is typical in my experience, times and durations are causing me trouble with graphs and Javascript. I’m graphing duration in mm:ss on the vAxis and date on the hAxis and trying to expand the min and max of the graph, so that it goes beyond the data points, above and below. For example, I’d like to have a min of 11:00 and a max of 14:00. However, I’m unable to do this. I read on one suggestion (cannot recall the URL and if it was stackoverflow and can’t find right now) that I could convert the mm:ss to just seconds as a whole number, and use that for max and min. When I do that, I get this error: ‘a.getTime is not a function’. I’m guessing that my numbers are not being carried over from my google sheet as a time duration…and maybe just a string. Of course when I use a colon in the max/min, I get an error that it’s not expecting a ‘:’. Thanks for any assistance.

Here’s the code, which has already been assisted by this site once. It works fine if the “viewWindow” portion is removed.

var query = new google.visualization.Query(queryUri + queryString);

// run query
query.send(function (response) {
// determine if error occurred
if (response.isError()) {
  alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
  return;
}

// extract data from response
var data = response.getDataTable();


// need to create dataview to use column as annotation
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
  calc: 'stringify',
  sourceColumn: 2,
  type: 'string',
  role: 'annotation'
}]);

// create options
var options = {
  title: 'L's 2024 Cross Country Run Times',
  width: 900,
  height: 500,
  trendlines: {
    0: {
      color: 'blue'
    }
  },
  vAxis: {
    format: 'mm:ss',
    viewWindow : {min : 660,max : 840}
  }
};

// draw chart
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(view, options);
});
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>

Back Button Appends Source Page to Bottom of Destination Page

I am doing React programming with JavaScript.

I use the history.push function from react-router-dom (v5.2.0) to open a new page. Here is part of the code:

{activeRequests?.map((item, index) => {
  return (
    <tr
      className={styles.tr}
      key={index}
      onClick={() => {
        history.push(`AssetManagement/Default/Edit/${item.assetId}`);
        window.location.reload();
      }}
    >

It opens the new page (which happens to be in Knockout) as expected in the same browser tab.

Something odd happens, however, when I use the Back button to return to the page on which I originally clicked the above link. I see the original page. But then, if I scroll down, I see the page on which I clicked the Back button appended to the bottom.

Call them, let’s say, Page One (where I clicked the link) and Page Two (where I clicked the Back button). Is there anything I can do on Page One to prevent this behavior? (Meaning, of course, I don’t want to see Page Two at the bottom of Page One.) Or do I need to add some sort of unmounting function to Page Two? I would prefer to modify Page One, since I am more familiar with React than Knockout.

Page Loader Stuck When Clicking Browser Back Button in .NET MVC Website

I’m developing a website using .NET MVC, which can be accessed at https://gengecmimarlik.com . The site uses a page loader animation that works as expected during normal navigation through the navbar links. However, I encounter an issue when using the browser’s back button.

Problem:
When I navigate to a different page (e.g., /TumProjeler or /iletisim) and then press the back button on the browser (Chrome or Edge), the loader animation appears but stays stuck, preventing the page from loading properly. The site doesn’t crash or throw any errors, but the loader does not disappear, and the page content doesn’t show up.
If I remove the preloader, the problem disappears, but I need to keep it for design purposes.

Key Details:

  • I’m not using any AJAX calls for page transitions; the navigation is
    straightforward.
  • All routes and navigation links are configured properly.
  • Here is a sample of how the links are set up in the navbar:
<a class="rd-nav-link" asp-controller="Home" asp-action="Index">Ana Sayfa</a>
<a class="rd-nav-link" asp-controller="Home" asp-action="AllProjects">Tüm Projeler</a>
<a class="rd-nav-link" href="@Url.Action("Index", "Home")#ekibimiz">Ekibimiz</a>
<a class="rd-nav-link" asp-controller="Home" asp-action="Contact">İletişim</a>
  • I’m using a preloader that runs when the page loads. However, it
    seems to get stuck when navigating back using the browser’s back
    button.
    What could be causing the page loader to get stuck when the back button is pressed? Are there specific .NET MVC behaviors or browser caching settings that I need to adjust? How can I ensure that the loader doesn’t hang and the content loads properly when users go back to the previous page?

Any advice or suggestions would be greatly appreciated. Thank you!

i coun’t get specefic data from a collection from database. I am using MongoDb, Nodejs, Express j

const burqaCollection = client.db('BubrqaDB').collection('burqas');
app.get('/burqas/:id', async(req,res)=>{
  const id = req.params.id;
  const query = {_id : new ObjectId(id)};
  const result = await burqaCollection.findOne(query);
  console.log(result);
  res.send(result);
});

here is my code..Why i could’t get specefic id related data from here? i face similar problem with my another projects. here i try to console.log(id) , i get my id. but if i try to console.log(result), then i get null

why does js file ignore many statements

this is the html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Oxford Languages Center</title>
    <link rel="stylesheet" href="Quiz.css">
</head>
<body>
    <main class="main">
        <header class="header">
            <a href="#" class="logo"><img src="logo1.png"></a>
            <nav class="navbar">
                <a href="#" class="active">Oxford Languages Center</a>
            </nav>
        </header>
        <div class="container">
            <section class="quiz-section">
                <div class="quiz-box">
                    <h1 id="pl">Placement Test</h1>
                    <div class="quiz-header">
                        <span id="en">English Test</span>
                        <span class="header-score">Score: 0 / 54</span>
                    </div>



                    <h2 class="question-text">Are you ______?</h2>

                    <div class="option-list">
                        <!--<div class="option">
                            <span>AA</span>
                        </div>
                        <div class="option"></div>
                            <span>BB</span>
                        </div>
                        <div class="option">
                        </div>
                            <span>CC</span>
                        </div>
                        <div class="option"></div>
                            <span>DD</span>
                        </div>-->
                    </div>

                    <div class="quiz-footer">
                        <span class="question-total">1 of 54 Questions </span>
                        <button class="next-btn">Next</button>
                    </div>
                </div>

                <div class="result-box">
                    <h2>Test Result!</h2>
                    <div class="percentage-container">
                        <div class="circular-progress">
                            <span class="progress-value">0%</span>
                        </div>

                        <span class="score-text">Your Score 0 out of 54</span>
                    </div>

                    <div class="buttons">
                        <button class="tryAgain-btn">Try Again</button>
                        <button class="goHome-btn">Go To Home</button>
                    </div>
                </div>
            </section>
        <section class="home">
            <div class="home-content">
                <h1>PLACEMENT TEST</h1>
                <p>English</p>
                <button class="start-btn">Start Test</button>
                <br>
                <button class="start-btn" onclick="location.href='aaaaa.html'">Start Listening</button>

            </div>
        </div>
        </section>
    </main>

    <div class="popup-info">
        <h2>Questions</h2>
        <span class="info">Choose the correct answer</span>

        <div class="btn-group">
            <button class="info-btn exit-btn">Exit Test</button>
            <a href="#" class="info-btn continue-btn">Continue</a>
        </div>
    </div>





    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="questions.js"></script>
</body>
</html>

this is questions.js

let questions = [
    {
        numb: 1,
        question: "Are you ______?",
        answer: "British",
        options: [
            "British",
            "Tunisia",
            "Wales",
            "England"
        ]
    },
    {
        numb: 2,
        question: "Where ______ work?",
        answer: "does your brother",
        options: [
            "do your brother",
            "is your brother",
            "your brother",
            "does your brother"
        ]
    },
    {
        numb: 3,
        question: "They ______ a wonderful concert last week.",
        answer: "saw",
        options: [
            "see",
            "have seen",
            "seeing",
            "saw"
        ]
    },
    {
        numb: 4,
        question: "They were ______ work last Saturday.",
        answer: "at",
        options: [
            "at",
            "on",
            "in",
            "by"
        ]
    },
    {
        numb: 5,
        question: "Does she ______ a lot of hobbies?",
        answer: "have",
        options: [
            "Is",
            "got",
            "has",
            "have"
        ]
    },
    {
        numb: 6,
        question: "11h45 is ______.",
        answer: "quarter to twelve",
        options: [
            "quarter past eleven",
            "half past eleven",
            "quarter to twelve",
            "half fast twelve"
        ]
    },
    {
        numb: 7,
        question: "The Piccadilly bus ______ now.",
        answer: "is leaving",
        options: [
            "leaves",
            "are living",
            "leaving",
            "is leaving"
        ]
    },
    {
        numb: 8,
        question: "Where ______ tonight?",
        answer: "are we going",
        options: [
            "are we going",
            "we go",
            "go we",
            "we going"
        ]
    },
    {
        numb: 9,
        question: "Your room is upstairs ______ the left.",
        answer: "on",
        options: [
            "On",
            "in",
            "near",
            "at"
        ]
    },
    {
        numb: 10,
        question: "What ______ rooms!",
        answer: "an empty",
        options: [
            "an empty",
            "a empty",
            "empty",
            "emptiness"
        ]
    },
    {
        numb: 11,
        question: "This is the ______ skyscraper in the world.",
        answer: "biggest",
        options: [
            "big",
            "bigger",
            "most big",
            "biggest"
        ]
    },
    {
        numb: 12,
        question: "She ______ soda.",
        answer: "often drinks",
        options: [
            "often drinks",
            "often drinking",
            "drinks often",
            "is often drink"
        ]
    },
    {
        numb: 13,
        question: "The girl ______ dad is a scientist is very clever.",
        answer: "whose",
        options: [
            "which",
            "whom",
            "who",
            "whose"
        ]
    },
    {
        numb: 14,
        question: "Miss Johnson is my ______ secretary.",
        answer: "father's",
        options: [
            "father",
            "fathers'",
            "father's",
            "fathers"
        ]
    },
    {
        numb: 15,
        question: "You're British, ______?",
        answer: "aren't you",
        options: [
            "are you",
            "aren't you",
            "you are",
            "you aren't"
        ]
    },
    {
        numb: 16,
        question: "My result is ______ than yours.",
        answer: "better",
        options: [
            "good",
            "better",
            "more good",
            "more better"
        ]
    },
    {
        numb: 17,
        question: "I ______ of a number between 1 and 10. What ______ it be?",
        answer: "am thinking.../...would",
        options: [
            "think.../...does",
            "think.../...would",
            "was thinking.../...will",
            "am thinking.../...could"
        ]
    },
    {
        numb: 18,
        question: "You speak English ______ I do.",
        answer: "as well as",
        options: [
            "as well",
            "good as",
            "as good",
            "as well as"
        ]
    },
    {
        numb: 19,
        question: "Catherine wasn't impressed by either of her ______ behavior.",
        answer: "sister's",
        options: [
            "sister's",
            "sisters",
            "sisters'",
            "sister"
        ]
    },
    {
        numb: 20,
        question: "He met neither John ______ his wife.",
        answer: "nor",
        options: [
            "or",
            "also",
            "nor",
            "and"
        ]
    },
    {
        numb: 21,
        question: "I'm looking forward ______ you.",
        answer: "to seeing",
        options: [
            "to see",
            "to seeing",
            "seeing",
            "see"
        ]
    },
    {
        numb: 22,
        question: "I ______ since Tuesday!",
        answer: "haven't slept",
        options: [
            "slept",
            "has slept",
            "haven't slept",
            "sleep"
        ]
    },
    {
        numb: 23,
        question: "'Eventually' means ______.",
        answer: "Finally",
        options: [
            "Firstly",
            "Actually",
            "Likely",
            "Finally"
        ]
    },
    {
        numb: 24,
        question: "______ her last week?",
        answer: "Did you invite",
        options: [
            "You invited",
            "Did you invited",
            "Do you invite",
            "Did you invite"
        ]
    },
    {
        numb: 25,
        question: "The thief ______ by the police 2 days ago.",
        answer: "was caught",
        options: [
            "caught",
            "was caught",
            "catches",
            "is caught"
        ]
    },
    {
        numb: 26,
        question: "If I ______ you, I would tell him the truth.",
        answer: "were",
        options: [
            "am",
            "was",
            "were",
            "'ll be"
        ]
    },
    {
        numb: 27,
        question: "______ they played very well, the English team lost the match.",
        answer: "Although",
        options: [
            "Although",
            "However",
            "Nevertheless",
            "In spite"
        ]
    },
    {
        numb: 28,
        question: "Stamps have cost 30p ______ the beginning of the year.",
        answer: "since",
        options: [
            "while",
            "since",
            "occasionally",
            "at"
        ]
    },
    {
        numb: 29,
        question: "If I had time, I ______ many things.",
        answer: "would do",
        options: [
            "do",
            "would do",
            "did",
            "'ve done"
        ]
    },
    {
        numb: 30,
        question: "Would you mind ______ the door?",
        answer: "closing",
        options: [
            "close",
            "to close",
            "closing",
            "closed"
        ]
    },
    {
        numb: 31,
        question: "You must ______ dive into shallow water.",
        answer: "never",
        options: [
            "never",
            "always",
            "sometimes",
            "constantly"
        ]
    },
    {
        numb: 32,
        question: "I forbid ______ the house dressed like that.",
        answer: "you to leave",
        options: [
            "you from leaving",
            "you leave",
            "you to leave",
            "to you of leaving"
        ]
    },
    {
        numb: 33,
        question: "The worker ignored his boss and ______.",
        answer: "got fired",
        options: [
            "is getting sacked",
            "got fired",
            "is fired",
            "is getting fired"
        ]
    },
    {
        numb: 34,
        question: "I haven't met her ______ 3 years",
        answer: "for",
        options: [
            "since",
            "ago",
            "for",
            "yet"
        ]
    },
    {
        numb: 35,
        question: "I would be very interested in ______ for that job.",
        answer: "applying",
        options: [
            "entering",
            "applying",
            "working",
            "writing"
        ]
    },
    {
        numb: 36,
        question: "______ someone means contacting him on the phone.",
        answer: "Reaching",
        options: [
            "Finally finding",
            "Putting you through",
            "Reaching",
            "I'm just checking"
        ]
    },
    {
        numb: 37,
        question: "______ please tell your children to stop shouting?",
        answer: "Would you",
        options: [
            "May you",
            "Would you",
            "Ought you",
            "Should you"
        ]
    },
    {
        numb: 38,
        question: "By Thursday, I ______ ten meetings.",
        answer: "will have had",
        options: [
            "have had",
            "will have had",
            "was having",
            "have"
        ]
    },
    {
        numb: 39,
        question: "______, not five but rather ten candidates were screened through telephone interviews.",
        answer: "Actually",
        options: [
            "Considerably",
            "Pleasantly",
            "Actually",
            "Leisurely"
        ]
    },
    {
        numb: 40,
        question: "Once you ______ the secret code, you must not reveal it to anyone.",
        answer: "are given",
        options: [
            "are given",
            "have given",
            "gave",
            "give"
        ]
    },
    {
        numb: 41,
        question: "This piece was composed by Stravinsky and consists ______ three movements.",
        answer: "of",
        options: [
            "to",
            "by",
            "in",
            "of"
        ]
    },
    {
        numb: 42,
        question: "______, business-class tickets on this flight are less expensive than economy fares.",
        answer: "Oddly enough",
        options: [
            "In view of that fact",
            "Oddly enough",
            "By virtue of",
            "Owing to"
        ]
    },
    {
        numb: 43,
        question: "I ______ on time if the bus hadn't been late.",
        answer: "'d have been",
        options: [
            "have been",
            "was",
            "would be",
            "'d have been"
        ]
    },
    {
        numb: 44,
        question: "Why didn't you ______ that you were feeling ill?",
        answer: "mention",
        options: [
            "advise",
            "remark",
            "mention",
            "tell"
        ]
    },
    {
        numb: 45,
        question: "Although our opinions on many things ______, we're good friends.",
        answer: "differ",
        options: [
            "disagree",
            "oppose",
            "differ",
            "divide"
        ]
    },
    {
        numb: 46,
        question: "You must try and hurry up because my patience is ______ out.",
        answer: "running",
        options: [
            "running",
            "pacing",
            "racing",
            "turning"
        ]
    },
    {
        numb: 47,
        question: "I alone am responsible ______ the mischief perpetrated last night.",
        answer: "for",
        options: [
            "to",
            "with",
            "of",
            "for"
        ]
    },
    {
        numb: 48,
        question: "This supermarket is trying to ______ young shoppers by offering fashionable clothes.",
        answer: "attract",
        options: [
            "target",
            "encourage",
            "persuade",
            "attract"
        ]
    },
    {
        numb: 49,
        question: "______ means there are no tickets left.",
        answer: "Sold out",
        options: [
            "Sold out",
            "Front row",
            "Free seats",
            "Window shopping"
        ]
    },
    {
        numb: 50,
        question: "Everyone ______ that gentlemen ______ blondes",
        answer: "says.../...prefer",
        options: [
            "say.../...prefers",
            "say.../...prefer",
            "says.../...prefer",
            "says.../...prefers"
        ]
    },
    {
        numb: 51,
        question: "As so few members had turned up at the meeting, it was decided to ______ it until further notice.",
        answer: "postpone",
        options: [
            "delay",
            "postpone",
            "wait",
            "hold"
        ]
    },
    {
        numb: 52,
        question: "I strongly ______ investing in these shares because you will get a very good reward.",
        answer: "recommend",
        options: [
            "recommend",
            "commend",
            "order",
            "respond"
        ]
    },
    {
        numb: 53,
        question: "I have tried and tried again and no matter what I do it still shows 'error', I just can't ______ what's wrong",
        answer: "figure out",
        options: [
            "look out",
            "figure out",
            "check out",
            "bring out"
        ]
    },
    {
        numb: 54,
        question: "The question is whether it is ______ to sell up all your shares at this stage rather than wait",
        answer: "wise",
        options: [
            "wisdom",
            "wisely",
            "wise",
            "wisest"
        ]
    },
    
];

let questionCount = 0;
let questionNumb = 1;
let userScore = 0;

const startBtn = document.querySelector('.start-btn');
const popupInfo = document.querySelector('.popup-info');
const exitBtn = document.querySelector('.exit-btn');
const main = document.querySelector('.main');
const continueBtn = document.querySelector('.continue-btn');
const quizSection = document.querySelector('.quiz-section');
const quizBox = document.querySelector('.quiz-box');
const resultBox = document.querySelector('.result-box');
const tryAgainBtn = document.querySelector('.tryAgain-btn');
const goHomeBtn = document.querySelector('.goHome-btn');
const nextBtn = document.querySelector('.next-btn');
const optionList = document.querySelector('.option-list');

startBtn.onclick = () => {
    popupInfo.classList.add('active');
    main.classList.add('active');
}

exitBtn.onclick = () => {
    popupInfo.classList.remove('active');
    main.classList.remove('active');
}

continueBtn.onclick = () => {
    quizSection.classList.add('active');
    popupInfo.classList.remove('active');
    main.classList.remove('active');
    quizBox.classList.add('active');

    showQuestions(questionCount);
    questionCounter(questionNumb);
    headerScore();
}

tryAgainBtn.onclick = () => {
    quizBox.classList.add('active');
    nextBtn.classList.remove('active');
    resultBox.classList.remove('active');

    questionCount = 0;
    questionNumb = 1;
    userScore = 0;
    showQuestions(questionCount);
    questionCounter(questionNumb);
    headerScore();
}

goHomeBtn.onclick = () => {
    quizSection.classList.remove('active');
    nextBtn.classList.remove('active');
    resultBox.classList.remove('active');

    questionCount = 0;
    questionNumb = 1;
    userScore = 0;
    showQuestions(questionCount);
    questionCounter(questionNumb);
}

nextBtn.onclick = () => {
    if (questionCount < questions.length - 1) {
        questionCount++;
        showQuestions(questionCount);
        questionNumb++;
        questionCounter(questionNumb);
        nextBtn.classList.remove('active');
    } else {
        showResultBox();
        console.log("ok");
    }
}

function showQuestions(index) {
    const questionText = document.querySelector('.question-text');
    questionText.textContent = `${questions[index].numb}. ${questions[index].question}`;

    let optionTag = '';
    questions[index].options.forEach((option, i) => {
        optionTag += `<div class="option" onclick="optionSelected(this)"><span>${option}</span></div>`;
    });
    optionList.innerHTML = optionTag;
}

function optionSelected(answer) {
    const userAnswer = answer.textContent.trim();
    const correctAnswer = questions[questionCount].answer;

    if (userAnswer === correctAnswer) {
        answer.classList.add('correct');
        userScore++;
        headerScore();
        nextBtn.classList.add('active');
    } else {
        answer.classList.add('incorrect');

        // Auto select the correct answer
        [...optionList.children].forEach(option => {
            if (option.textContent.trim() === correctAnswer) {
                option.classList.add('correct');
            }
            option.classList.add('disabled');
        });

        nextBtn.classList.add('active');
    }
}

function questionCounter(index) {
    const questionTotal = document.querySelector('.question-total');
    questionTotal.textContent = `${index} of ${questions.length} Questions`
}

function headerScore() {
    const headerScoreText = document.querySelector('.header-score');
    headerScoreText.textContent = `Score: ${userScore} / ${questions.length}`;
}

function showResultBox() {
    quizBox.classList.remove('active');
    resultBox.classList.add('active');

    const scoreText = document.querySelector('.score-text');
    scoreText.textContent = `Your Score ${userScore} out of ${questions.length}`;

    const circularProgress = document.querySelector('.circular-progress');
    const progressValue = document.querySelector('.progress-value');
    let progressStartValue = -1;
    const progressEndValue = (userScore / questions.length) * 100;
    const speed = 20;

    const progress = setInterval(() => {
        progressStartValue++;
        
        progressValue.textContent = `${progressStartValue}%`;
        circularProgress.style.background = `conic-gradient(#c40094 ${ progressStartValue * 3.6}deg, rgba(255, 255, 255, .1) 0deg)`;
        
        if (progressStartValue >= progressEndValue) {
            clearInterval(progress);
        }
    }, speed);
    const data = new FormData();
    data.append('userScore', userScore);
    
    fetch('update_score.php', {
        method: 'POST',
        body: data
    })
    .then(response => response.text())
    .then(result => {
        console.log(result); // Display the response from the PHP script
    })
    .catch(error => console.error('Error:', error));
}

this is update_score.php :

<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Database connection parameters
$servername = "127.0.0.1"; 
$username = "root"; 
$password = ""; 
$dbname = "englishquizox"; 

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL to create the scores_table
$sql = "CREATE TABLE IF NOT EXISTS scores_table (
    id INT AUTO_INCREMENT PRIMARY KEY,
    tel VARCHAR(15) NOT NULL,
    score INT NOT NULL,
    FOREIGN KEY (tel) REFERENCES login_table(tel) ON DELETE CASCADE
)";
$conn->query($sql); // Create table without checking success here for simplicity

// Check if the user is logged in and the session variable exists
if (isset($_SESSION['tel'])) {
    $tel = $_SESSION['tel'];
    if (isset($_POST['userScore'])) {
        $userScore = intval($_POST['userScore']); // Sanitize the score input
        $sql = "INSERT INTO scores_table (tel, score) VALUES (?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("si", $tel, $userScore); 
        if ($stmt->execute()) {
            echo "Score updated successfully.";
        } else {
            echo "Error updating score: " . $stmt->error;
        }
        $stmt->close();
    } else {
        echo "No score received.";
    }
} else {
    echo "User is not logged in.";
}

$conn->close();
?>

ignore the 56 questions classes, I want to send the score to a php file to insert it into a mysql table and the js file doesn’t seem to work fully like if i put some console.log statements the browser ignores them and deos everything else

WebView Flutter – Changing Date/Time closes application

Currently using webview_flutter package to exhibit a custom html page inside my application. It consists of come input forms that are in hh:mm format.
I have attributed default values to all fields, however when changing the values of any hour field the application closes and I get the following error:


I/mple.dive_calc2(11766): Compiler allocated 4206KB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
D/CompatChangeReporter(11766): Compat change id reported: 170233598; UID 10198; state: ENABLED
D/AndroidRuntime(11766): Shutting down VM
E/AndroidRuntime(11766): FATAL EXCEPTION: main
E/AndroidRuntime(11766): Process: com.example.dive_calc2, PID: 11766
E/AndroidRuntime(11766): java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.EditText.hasFocus()' on a null object reference

I am using the default implementation of webview and the page loads correctly and runs other scripts correctly, however whenever I change the hour or the minutes inside the fields the application closes.

This is the only function that read those fields, I have also tried commenting it but it still closes my application:

// Function to calculate the time difference in hours and minutes between two fields
async function calculateTimeDifference(startInputId, endInputId) {
    const startTime = await document.getElementById(startInputId).value;
    const endTime = await document.getElementById(endInputId).value;

    // Check if the values are available
    if (startTime && endTime) {
        const startDate = new Date(`1970-01-01T${startTime}:00`);
        const endDate = new Date(`1970-01-01T${endTime}:00`);

        // Calculate the total difference in minutes
        const totalMinutes = Math.abs((endDate - startDate) / 60000);

        // Convert total minutes into hours and minutes
        const hours = Math.floor(totalMinutes / 60);
        const minutes = totalMinutes % 60;

        // Display the result in the console (or it can be used to generate a logbook)
        console.log(`Time difference between ${startInputId} and ${endInputId}: ${hours} hours and ${minutes} minutes`);

        // Return the formatted time (can be used in a PDF or logbook)
        return { hours, minutes };
    } else {
        console.log(`One or both fields (${startInputId}, ${endInputId}) are empty.`);
        return null;
    }
}

When the html loads inside the application it gets the 12h(AM/PM) format by default even though the android emulator is set to be 24h.

Currently using macOS.

Some things I have tried:

  1. Removing the function that reads the hh:mm fields.
  2. Hosting the page in the web
  3. Only running the function with onPageFinished:

Script Tag Not Executing Inside Shopify App Embed Block

I’m developing a Shopify App Embed Block to display a list of recommended products. The H1 tag (“Recommended Products”) is successfully displayed on the page, but the product list is not rendered because the JavaScript code inside the <script> tag is not executed. Here’s my code:

<div id="custom-product-list" class="product-list">
  <!-- Products will be injected here by JavaScript -->
  <h1>Recommended Products</h1>
</div>

<script>
  // Mock products array (this can be fetched via AJAX instead)
  export const products = [
    {
      _id: '1',
      title: 'product 1',
      description: 'Lorem ipsum product 1 dummy description.',
      price: 100,
      compare_at_price: 80,
      featured_image: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
      url: 'https://images.pexels.com/photos/985635/pexels-photo-985635.jpeg',
    },
    {
      _id: '2',
      title: 'product 2',
      description: 'Lorem ipsum product 2 dummy description.',
      price: 200,
      featured_image: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
      url: 'https://images.pexels.com/photos/147641/pexels-photo-147641.jpeg',
    }
  ];

  function renderProducts(productList) {
    const productContainer = document.getElementById('custom-product-list');
    productContainer.innerHTML = '';

    productList.forEach((product) => {
      const productItem = `
        <div class="product-item">
          <a href="${product.url}">
            <img src="${product.featured_image}" alt="${product.title}">
          </a>
          <h3><a href="${product.url}">${product.title}</a></h3>
          <p class="price">
            ${product.compare_at_price > product.price
              ? `<span class="sale-price">$${product.price}</span>
                 <span class="original-price">$${product.compare_at_price}</span>`
              : `<span class="regular-price">$${product.price}</span>`}
          </p>
        </div>
      `;
      productContainer.insertAdjacentHTML('beforeend', productItem);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    renderProducts(products);
  });
</script>

{% schema %}
{
  "name": "Custom Product List",
  "target": "section",
  "settings": [
    {
      "type": "number",
      "id": "product_limit",
      "label": "Number of Products",
      "default": 5
    }
  ]
}
{% endschema %}

The H1 tag appears on the page, but the script responsible for rendering the products does not run. This code is inside a Shopify Liquid template file for an App Embed Block.

Why is the JavaScript not executing in this Shopify App Embed Block, and how can I make sure the script is executed to display the product list?

How do I migrate Auth0 rules to actions

I am currently trying to migrate our Auth0 rule to actions. When I take a simple rule that successfully adds a custom role to the token and migrate it to an action the role doesnt show up in the token.

Rule

function (user, context, callback) { if (context.clientName === 'MyClientName') {
  var namespace = 'https://ournamespace.com/';
  var roles = [];

roles.push('testRole');

if (context.accessToken) {  
  context.accessToken[namespace + 'email'] = user.email;
  context.accessToken[namespace + 'scopes'] = roles.join(' ');
}
  
  try {
    user.team_scopes = roles.join(' ');
  } catch (e) {
    console.log(e);
  }
  
  callback(null, user, context);
} else { callback(null, user, context); } }

Result

{
  "name": "My Name",
  "email": "[email protected]",
  "team_scopes": "testRole",
  "iss": "****",
  "sub": "****",
  "aud": "****",
  "iat": ****,
  "exp": ****
}

Action

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://ournamespace.com/';
  let roles = [];
  roles.push('TestRole');
  console.log(`Adding roles to token: ${roles.join(' ')}`);
  api.accessToken.setCustomClaim(`${namespace}team_scopes`, roles.join(' '));
};

Result

{
  "name": "My Name",
  "email": "[email protected]",
  "iss": "****",
  "sub": "****",
  "aud": "****",
  "iat": ****,
  "exp": ****
}

I’ve tried disabling the rule so only the action is there.
The rule and action are named the same.
it almost seems like the action isnt being triggered because when I run it from the Auth0 UI and I seem to get the expected result.

Please help me understand what I’m doing wrong.

Save data submitted from a Form into a Store in Sveltekit

So I’ve got the following component working so far records/new/+page.svelte:

<script>
    import RecordForm from "../../../components/forms/RecordForm.svelte";
    import TrackForm from "../../../components/forms/TrackForm.svelte";
    import { enhance } from '$app/forms';

    export let data;
    export let form;

</script>

<RecordForm mode="new" formData={ {...data, ...form} } />

the above works more as a wrapper, the actual action happens in the RecordForm.svelte component:

<script>
export let mode="new";
export let formData;
</script>

<form method="POST" class="pt-10">
   <!-- a bunch of fields -->
<input
                        name="title"
                        id="title"
                        type="text"
                        value={ formData?.data?.title || "" }
                        class="input input-bordered input-lg w-full max-w-xs"/>

                <label for="title" class="label">
                    {#if formData?.errors?.title}
                        <span class="label-text-alt text-error">{ formData?.errors?.title[0]}</span>
                    {/if}
                </label>

   <div class="flex flex-row pt-10">
                <button type="submit" name="save-and-exit" class="btn btn-primary btn-lg">{ mode == "new" ? "Save and Exit" : "Update and Exit" }</button>
            </div>
</form>

For simplicity, I’ve left out all the fields involved in the form (including only one to showcase the structure of the inputs).
This form has it’s associated action in new/+page.server.js:

export const actions = {
    default: async ({ request, fetch }) => {

        // create API instance
        const recordAPI = new RecordAPI(fetch);

        // retrieve the data from the form
        const data = Object.fromEntries(await request.formData());

        // validate data and create DTO
        const record = recordDTO(data);

        // if errors returned from building the DTO (validation errors) then return the object.
        if (record?.errors && !emptyObject(record.errors)) {
            return {
                "data": record.data,
                "errors": record.errors,
            };
        }

        // save the data
        const response = await recordAPI.post(record);

        if (response.status == 200) {
            throw redirect(302, '/records')
        }

        return {
            data: record,
            "errors": response.errors,
        }

    }
}

So far so good, everything works as expected when the form is submitted.

I want to expand this functionality, and I want to add tracks to a given record. But I want to do this as part of the Record creation process but in a different page/component.

My initial thought is to have 2 buttons on the new Record page. One if the user wants to save the info as it is (without adding the tracks) and another one labeled Tracks that will redirect the user to a page where the tracks for a record can be added.

When the Tracks button is clicked, then we shouldn’t submit the form but save the data into a store, and redirect the user to the Tracks page. Once there the user adds a bunch of tracks and click on Save, at that point the tracks and the record data are merge and send to the backend for processing.

I want to save the record data in a store in case the user wants to go back to the Record page and update some data, so the info is put back in place.

The issue is that I cannot save data into a store from an action in sveltekit, so it has to be done in the client side.

I tried adding the button to the form:

 <div class="flex flex-row pt-10">
                <button type="button" on:click={submitForm} name="add-tracks" class="btn btn-primary btn-lg">{ "-> Tracks" }</button>
            </div>

and retrieve the data from the form in order to save it into the store:

const submitForm = (event) => {
      const data = new FormData(event.currentTarget);
      console.log("FORM DATA", data)
      return
    }

since the data is managed by the formData obj I also tried:

 const submitForm = (event) => {
      event.preventDefault();
      console.log("form data", formData)

      return

but this is not working. Nothing is being printed out.

Any ideas on how to approach this?