how do I executing JS loop returning multiple queries with Dataform

I have the following JS file in my dataform repo:

const values = ["4", "5", "6"];

values.forEach(value => {
  operate("operation" + value,{tags: ["test_operation_tag"]}).queries(
  ctx => `INSERT INTO table (test) VALUES (${value})`
 );
});

It return 3 operations with 3 different names (operation4, operation5, etc…).
As you can see in my code I’m adding a tag but it doesn’t appear as an option for execution. How can I execute the 3 operations returned by this JS script? Do I have to create a dedicated Workflow configurations and select each operations manually?

Dependant dynamically created select(dropdown) fields that run their .change() on page load

I haven’t been in the active programming game for some time so forgive me if the description of my problem is poorly worded.

I have select forms that are generated (using flask) from a database. The database table pre-populates the forms where a value exists, otherwise the code i’m trying to figure out will be used to fill in those blanks by selecting some dependant dropdowns (their values also come from a DB table).

I have ~11 rows of dynamically created ‘s in two columns. one column is dependant on the other. i did manage to get that working using this:

the left column of selects are named: “sel_dstColumn_XXX” where XXX is the row ID in the database.
the right column of selects are named: “sel_dstTable_XXX” and both XXX’s are the same per row. sel_dstColumn_XXX is dependant on sel_dstTable_XXX and works using this .change() below.

  $("select[id^=sel_dstTable]").change(function () {
    table = this.value;
    my_s = this.id.split('_')[2];
    $.get("/get_columns/" + table, function (data, status) {
      var selID = "select[id=sel_dstColumn_" + my_s + "]";
      $(selID).html("");
      data.forEach(function (table) {
        $(selID).append("<option>" + table + "</option>");
      });
    });
  });

i think the code above has the same issues as my code that’s not working but its ok because i’m only working with a single field unlike further down.

the python portion is simple and looks like this for the $.get() url:

@app.route('/get_columns/<value>')
def get_columns(value):
    if value in all_tables:
        return jsonify(all_tables[value])
    return ''

I would like to run this for all the selects with the name sel_dstTable_XXX on page load to pre-populate the dependant selects based on what (if any) values are pulled from the database. I’m trying this below (duplicate code but i dont know how to call the .change() for all the proper forms.. it doesn’t work due to the variable “my_s” not properly passing into the $.get() function. i’m not understand why my_s produces the results below in the console screenshot.

this is what i’m currently working with. it’s mostly duplicate code from my .change() function. i’m not sure how to just call that change function for each select on startup though.

  $(function () {
    $("select[name^=sel_dstTable_]").each(function () {
      table = this.value;
      my_s = this.id.split('_')[2];
      console.log("expected variable my_s: " + my_s);
      $.get("/get_columns/" + table, function (data, status) {
        console.log("actual variable my_s:" + my_s);
# PROBLEM ON THE LINE ABOVE reading my_s, i only get the last row ID (22), instead of 12, 13, 14, 15... etc produced when looping through the .each().
        // var selID = "select[name=sel_dstColumn_" + my_s + "]";
        // $(selID).html("");
        // data.forEach(function (table) {
        //   $(selID).append("<option>" + table + "</option>");
        // });
      });
    });
  });

console output

Thank you so much for any help – i’ve been fighting this all week. I hope this description makes sense.

rendering 2nd layer of nested array in vue 3 within each component

Good day guys

I’d like to seek advise on accessing the 2nd element layer of my nested array to loop through a templated component making it a dynamic card through a year, btw I use laravel vue just incase you need to know

my desired template

----------------------------|
|Component                  |
|---------------------------|
|Title header               |
|---------------------------|
|Event Name  |date |remarks |
-----------------------------

I reffered to this as my guide for the array Nested arrays of objects and v-for

then afterwards i was able to rendered or display the first layer which is the title of my component but the 2nd layer which the data seems to return an empty, but when i try to dump the whole array it returns me the right data

Sample Dump

[
  {
    "event_name": "New Year",
    "month": "01",
    "day": 1,
    "status": "enabled",
    "date": "2024-01-1"
  }
]

here’s my sample codes

Structure of the code/component

title-> first loop to render the 1st element of array (title) using v-for
data->  2nd render the rest of the data loop using v-for inside the first loop

script

<script setup>
import MainContent from '../../Components/MainContent.vue'
import { reactive } from 'vue'

 const props = defineProps({
  title: String,
  january:Array,
  february:Array,
  december:Array,
  department_category:Array
})
const months = [
        {
            name:"January",
            data:props.january
        },
        {
            name:"February",
            data:props.february
            
        }
    ]
</script>

Vue Component

 <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-2 gap-4 mb-4">
                 <!-- Loop through Whole Year -->
                 <div v-for="value in months" :key="value.id"  class="bg-white rounded-md border border-gray-100 p-6 shadow-md shadow-black/5">
                    <div class="flex justify-between mb-4 items-start">
                        <div class="font-medium">{{ value.name}}</div>
                            <div class="dropdown">
                                <button type="button" class="dropdown-toggle text-gray-400 hover:text-gray-600"><i class="ri-more-fill"></i></button>
                                <ul class="dropdown-menu shadow-md shadow-black/5 z-30 hidden py-1.5 rounded-md bg-white border border-gray-100 w-full max-w-[140px]">
                                    <li>
                                        <a href="#" class="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-blue-500 hover:bg-gray-50">Profile</a>
                                    </li>
                                    <li>
                                        <a href="#" class="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-blue-500 hover:bg-gray-50">Settings</a>
                                    </li>
                                    <li>
                                        <a href="#" class="flex items-center text-[13px] py-1.5 px-4 text-gray-600 hover:text-blue-500 hover:bg-gray-50">Logout</a>
                                    </li>
                                </ul>
                            </div>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full min-w-[540px]">
                            <thead>
                                <tr>
                                    <th class="text-[12px] uppercase tracking-wide font-medium text-gray-400 py-2 px-4 bg-gray-50 text-left rounded-tl-md rounded-bl-md">Event Name</th>
                                    <th class="text-[12px] uppercase tracking-wide font-medium text-gray-400 py-2 px-4 bg-gray-50 text-left">Date</th>
                                    <th class="text-[12px] uppercase tracking-wide font-medium text-gray-400 py-2 px-4 bg-gray-50 text-left">Remarks</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="event in [value.data]" :key="event.id">
                                    <td class="py-2 px-4 border-b border-b-gray-50">
                                        <div class="flex items-center">
                                            <img src="https://placehold.co/32x32" alt="" class="w-8 h-8 rounded object-cover block">
                                            <a href="#" class="text-gray-600 text-sm font-medium hover:text-blue-500 ml-2 truncate">{{ event.event_name}}</a>
                                        </div>
                                    </td>
                                    <td class="py-2 px-4 border-b border-b-gray-50">
                                        <span class="text-[13px] font-medium text-gray-400">{{ event.date }}</span>
                                    </td>
                                    <td class="py-2 px-4 border-b border-b-gray-50">
                                        <span class="text-[13px] font-medium text-gray-400">
                                            <button class="ml-2 btn btn-xs btn-accent">Update</button>
                                            <button class="ml-2 btn btn-xs btn-error">Remove</button>
                                        </span>
                                    </td>
                                </tr>



                            </tbody>
                        </table>
                    </div>

My Current Output

----------------------------|
|Component                  |
|---------------------------|
|January                    |
|---------------------------|
|//empty     |//empty       |
-----------------------------



    ----------------------------|
    |Component                  |
    |---------------------------|
    |February                   |
    |---------------------------|
    |//empty     |//empty       |
    -----------------------------

Fail to upload local CSV file with fetch

I’m trying to use fetch to open a .csv file, but i get this message:
Uncaught TypeError TypeError: Failed to fetch
I am using Visual Studio Code and Chrome there.
my code:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Read CSV File</title>
</head>
<body>

<div id="output"></div>

<script>
// Function to fetch the CSV file
function fetchCSV(url) {
    return fetch(url)
        .then(response => response.text())
        .then(csv => processData(csv));
}

// Function to process the CSV data
function processData(csv) {
    var rows = csv.split('n');
    var output = document.getElementById('output');
    output.innerHTML = '';

    for (var i = 0; i < rows.length; i++) {
        var columns = rows[i].split(',');
        if (columns.length >= 3) {
            output.innerHTML += columns[2] + '<br>';
        }
    }
}

// Preload and process the CSV file
fetchCSV('Book1.csv'); // Replace 'example.csv' with the your CSV file
</script>

</body>
</html>

Book1.csv is in the same folder of the file that holds the code.

Kind regards

I tried running in different browsers.
A different .csv file because I thought it was too big, the new file is smaller.

Angular custom file change detection

I am building an Angular app that uses markdown files (.md) to generate my terms of use, privacy policy, etc. pages.

/help
 +- terms-of-use.component.md
 +- terms-of-use.component.html
 +- terms-of-use.component.ts

I have a custom script that converts the .md files to html and it is registered as prestart and prebuild steps:

package.json file excerpt...

"scripts": {
    "ng": "ng",
    "prestart": "node transformMarkdown.js",
    "start": "ng serve --host localhost --port 4200 --disable-host-check --configuration local",
    "prebuild": "node transformMarkdown.js",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
},

And it works great! Whenever I run npm run start or npm run build, my script detects that the .md file has changed and updates the html file. For example:

> npm run start
> [email protected] prestart
> node transformMarkdown.js

Generating... terms-of-use.component.html

> [email protected] start
> ng serve --host localhost --port 4200 --disable-host-check --configuration local

Now I am trying to get Angular to auto-detect the .md file changes and regenerate the html file automatically just it would with a change to any other file. I cannot figure out how to do this.

I believe that at its core, the problem lies in (not just in file change detection), but also that I launched ng serve using node (npm start). Is it possible to get this to work by just using ng serve (and have it detect the .md file changes)?

Any ideas would be appreciated 🙂

React native Expo fails to Loading SIP.js Library in WebView

I am developing a React Native Expo mobile application that integrates SIP functionality using the SIP.js library within a WebView component. The app aims to facilitate VoIP calls using SIP technology, allowing users to initialize a SIP client, register to a SIP server, and initiate SIP calls to communicate with other users.

The error encountered in the React Native Expo app occurs when attempting to load the SIP.js library within a WebView component. Despite verifying network connectivity and ensuring proper WebView configuration, the library fails to load, preventing the initialization of the SIP client. This error disrupts the app’s intended functionality, hindering users from establishing SIP connections and making VoIP calls.

more details to reproduce error git repo below

[https://github.com/martsa/react-native-sip.js

<!DOCTYPE html>
<html lang="en">
<head>
  
<body>
  <h1>SIP Client</h1>
  
  <button id="initializeButton" class="button">Initialize SIP Client</button> <!-- Button to initialize SIP client -->
  <button id="callButton" class="button">Call</button> <!-- Button to initiate SIP call -->
  
  <script src="./node_modules/sip.js/" onload="onSipJsLoad()" onerror="onSipJsError()"></script> <!-- Include SIP.js library with onload and onerror events -->
  <script>
    let sipJsLoaded = false; // Flag to track whether SIP.js library is loaded

    // Function called when SIP.js library is successfully loaded
    const onSipJsLoad = () => {
      console.log('SIP.js library loaded successfully');
      sipJsLoaded = true; // Set flag to true indicating library is loaded
    };

    // Function called when loading SIP.js library fails
    const onSipJsError = () => {
      console.error('Failed to load SIP.js library');
      document.getElementById('errorMessage').innerText = 'Failed to load SIP.js library. Please check your internet connection and try again.'; // Display error message on the page
    };

    // Function to register to SIP server and initialize SIP client
    const registerToServer = () => {
      console.log('Initializing SIP client...');

      // Check if SIP.js library is loaded before proceeding
      if (!sipJsLoaded) {
        console.error('SIP.js library is not loaded. Cannot initialize SIP client.');
        document.getElementById('errorMessage').innerText = 'SIP.js library is not loaded. Cannot initialize SIP client.'; // Display error message on the page
        return;
      }

      // Your code to initialize the SIP client goes here
      // For example:
      const server = {
        uri: 'sip.example.com', // Replace with your SIP server URI
        username: 'username',
        password: 'password',
      };

      // Create SIP User Agent
      const userAgent = new SIP.UA({
        uri: `sip:${server.username}@${server.uri}`,
        transportOptions: {
          server: server.uri,
          wsServers: `wss://${server.uri}:5061`, // Use wss:// for secure WebSocket
        },
        authorizationUser: server.username,
        password: server.password,
      });

      // Start SIP User Agent
      userAgent.start().then(() => {
        console.log('SIP client registered successfully');
      }).catch(error => {
        console.error('Error registering SIP client:', error);
      });
    };

    // Function to initiate SIP call
    const initiateCall = (calleeURI) => {
      console.log('Initiating call to', calleeURI);
      // Your code to initiate SIP call goes here
    };

    // Add event listener to initialize SIP client button
    document.getElementById('initializeButton').addEventListener('click', () => {
      console.log('Button clicked. Initializing SIP client...');
      registerToServer(); // Initialize SIP client
    });

    // Add event listener to call button
    document.getElementById('callButton').addEventListener('click', () => {
      console.log('Call button clicked. Initiating SIP call...');
      initiateCall('sip:[email protected]'); // Replace with the SIP URI of the callee
    });
  </script>
  
  <div id="errorMessage" class="error-message"></div> <!-- Container for displaying error message -->
</body>
</html>

I am expecting to allow sip.js library to load in webview error i am getting here

Implementing token bucket algorithm

I’m currently working on implementing a token bucket algorithm in JavaScript to monitor the number of requests per second. The objective is to allow requests to proceed if there are sufficient tokens available in the bucket, otherwise, the system should enforce rate limiting.
However, upon testing my code, I observed that it consistently outputs ‘false’. Should I incorporate the use of setInterval to ensure its proper functionality?

 class TokenBucket {
        constructor(maxBucketSize, numberOfRequests, windowSizeForRateLimitInMilliseconds) {
            this.maxBucketSize = maxBucketSize;
            this.numberOfRequests = numberOfRequests;
            this.windowSizeForRateLimitInMilliseconds = windowSizeForRateLimitInMilliseconds;
            this.refill();
        }
    
        tryConsume() {
            this.refill();
            if (this.numberOfTokenAvailable > 0) {
                this.numberOfTokenAvailable--;
                return true;
            }
            return false;
        }
    
        refill() {
            if (Date.now() < this.nextRefillTime) {
                return;
            }
            this.lastRefillTime = Date.now();
            this.nextRefillTime = this.lastRefillTime + this.windowSizeForRateLimitInMilliseconds;
            this.numberOfTokenAvailable = Math.min(this.maxBucketSize, this.numberOfTokenAvailable + this.numberOfRequests);
        }
    }
    
    // Example usage:
    const tokenBucket = new TokenBucket(10, 5, 10000); // Max bucket size: 10, 5 requests per 10 seconds
    console.log(tokenBucket.tryConsume()); // Outputs: true (tokens available)
    console.log(tokenBucket.tryConsume()); // Outputs: true (tokens available)
    console.log(tokenBucket.tryConsume()); // Outputs: true (tokens available)
    console.log(tokenBucket.tryConsume()); // Outputs: true (tokens available)
    console.log(tokenBucket.tryConsume()); // Outputs: true (tokens available)
    console.log(tokenBucket.tryConsume()); // Outputs: false (no tokens available)

I’m in charge of create real estate listing but I only have a csv file what could can i use to pull and format specific fields from my csv file

I need specific fields from the csv pulled and formatted as a real estate listing (html or WordPress). I needed someone to create a specific JavaScript or input/export coding to carry out the action.

Read the CSV File: Use JavaScript to read the CSV file. You can achieve this using the FileReader API in modern browsers.

Parse CSV Data: Parse the CSV data into an array or object. You can use libraries like PapaParse to simplify the CSV parsing process.

Extract Specific Fields: Extract the specific fields you need for the real estate listing from the parsed CSV data.

Format the Data: Format the extracted fields into HTML or a format suitable for a WordPress listing.

Display the Listings: Display the formatted listings on your webpage or WordPress site.

How do I enable third party cookies within Electron?

I am trying to use something that requires third party cookies but electron blocking third party cookies won’t allow me to use it.

Is there any work around or possible fix to this issue?

The error I am getting.

Third-party cookie will be blocked. Learn more in the Issues tab.

or is this just skill issue and I have to declare war on electron to get it to work.

**The code I am using: **

const SendRequest = function(API, MESSAGE) {

    const request = new XMLHttpRequest();
    request.open("POST", API);

    request.setRequestHeader('Content-type', 'application/json');

    const params = {
        username: "local bot",
        content: MESSAGE,
        avatar_url: ""
    };

    request.send(JSON.stringify(params));

    console.log("Sent Request");

};

document.getElementById("BodyAPISendRequest").addEventListener("click", function() {

    console.log("Clicked");

    const API_TOKEN = document.getElementById("BodyAPIEntry");
    const API_MESSAGE = document.getElementById("BodyAPIMessageEntry");

    if (API_TOKEN.value.length !== 0) {
        SendRequest(API_TOKEN.value, API_MESSAGE.innerHTML);
        console.log("Starting request");
        console.log(API_TOKEN.value);
        console.log(API_MESSAGE.innerHTML);
    };

});

I am trying to make a GUI that allows you to easily send a message via webhook it was meant to be a easy project until Electron blocked third party cookies.

I was expecting it to just normally work like it does within the browser. But I guess it does not work like that with electron.

How to get rid of datatables reinitialization error?

I am using datatatables to display highcharts. Everything works fine but I am not sure how to get rid of the following error when I click on button two and button one.

  • DataTables warning: table id=example – Cannot reinitialise DataTable.
    For more information about this error, please see
    https://datatables.net/tn/3 DataTables warning: table id=example1 –

  • Cannot reinitialise DataTable. For more information about this error,
    please see https://datatables.net/tn/3

My requirement is by on page load Chart1 should display and hide chart2 and chart3. when I click on chart1 or chart2, it should reinitialize the chart for the user to get animation effect just like chart3. How can I achieve this? Here is my code
https://codepen.io/Shawnny-Tandon/pen/bGJeOev

function initializeChart(chartId, tableId, chartTitle) {
    // Create DataTable
    const table = new DataTable(tableId, {
        searching: false,
        info: true,
        paging: false,
        sort: false
    });

    // Create chart
    const chart = Highcharts.chart(chartId, {
        chart: {
            type: 'pie',
            styledMode: false
        },
        title: {
            text: chartTitle
        },
        colors: ['#1a4480', '#e52207', '#e66f0e', '#ffbe2e', '#fee685', '#538200', '#04c585', '#97d4ea', '#009ec1', '#0076d6', '#adadad', '#8168b3', '#d72d79', '#f2938c' ],
        tooltip: {
            pointFormat: '</b> {point.y:.1f}%'
        },
        series: [
            {
                data: chartData(table)
            }
        ],
        credits: {
            enabled: false
        },
        plotOptions: {
            pie: {
                size: 270,
                innerSize:70,
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true,
                    distance: 30,
                    padding: 1,
                    style: {
                        fontSize: "12px"
                    },
                    format: '{point.y:.1f}%'
                },
                showInLegend: true  // Show legends
            }
        }
    });

    // On each draw, update the data in the chart
    table.on('draw', function () {
        chart.series[0].setData(chartData(table));
    });

    function chartData(table) {
        var data = [];
        table.rows().every(function () {
            var row = this.data();
            data.push({
                name: row[0],  // Assuming the first column is the name
                y: parseFloat(row[1])  // Assuming the second column is the numeric value
            });
        });

        return data;
    }
}

document.addEventListener('DOMContentLoaded', function () {
    // Check if Highcharts is defined before calling the function
    if (typeof Highcharts !== 'undefined') {
        initializeChart('demo-output', '#example1', 'test 2023');
        initializeChart('demo-output2', '#example', 'test 2022');

        var allSeriesData = [];
        var categories = [];

        var table = $("#example2").DataTable({
            searching: false,
            responsive: true,
            lengthChange: false,
            ordering: false,
            info: false,
            paging: false,
            initComplete: function (settings, json) {
                let api = new $.fn.dataTable.Api(settings);

                // get the x-axis caregories from the table headings:
                var headers = api.columns().header().toArray();
                headers.forEach(function (heading, index) {
                    if (index > 0 && index < headers.length) {
                        categories.push($(heading).html());
                    }
                });

                // get the seris data as an array of numbers from the table row data:
                let rows = api.rows().data().toArray();
                rows.forEach(function (row) {
                    group = {
                        name: '',
                        data: []
                    };
                    row.forEach(function (cell, idx) {
                        if (idx == 0) {
                            group.name = cell;
                        } else if (idx < row.length) {
                            group.data.push(parseFloat(cell.replace(/,/g, '')));
                        }
                    });
                    allSeriesData.push(group);
                });
            }
        });

        Highcharts.setOptions({
            lang: {
                thousandsSep: ','
            }
        });

        // Function to initialize trend chart
        function initializeTrendChart() {
            // Your trend chart initialization code here
            // Example:
            var trendChart = Highcharts.chart("chart-A", {
                chart: {
                    type: "column",
                    borderColor: 'lightgray',
                    borderWidth: 1,
                    marginTop: 50
                },
                tooltip: {
                    headerFormat: '{point.key}<br/>',
                    pointFormat: '{series.name}: <b>{point.y:.1f}%</b>'
                },
                legend: {
                    symbolRadius: 0,
                    itemStyle: {
                        color: '#000000',
                        fontSize: '16px'
                    }
                },
                colors: ['#003489', '#ED7D31', '#A5A5A5', '#FFC000', '#5B9BD5'],
                credits: {
                    enabled: false
                },
                title: {
                    text: "test3"
                },
                xAxis: {
                    categories: categories,
                    labels: {
                        style: {
                            fontWeight: '600',
                            fontSize: '16px',
                            color: '#000000'
                        }
                    }
                },
                yAxis: {
                    title: false,
                    tickInterval: 10,
                    max: 60,
                    labels: {
                        formatter: function () {
                            return Highcharts.numberFormat(this.value, 0);
                        },
                        style: {
                            fontWeight: '600',
                            fontSize: '16px',
                            color: '#000000'
                        }
                    }
                },
                series: allSeriesData
            });
        }

        // Button click event listeners
        $('.usa-button').on('click', function () {
            var buttonId = $(this).attr('id');

            // Toggle chart visibility based on button click
            if (buttonId === 'previous') {
                $('#chart2').show();
                $('#chart1').hide();
                $('#chart3').hide();
              initializeChart('demo-output2', '#example', 'test Awards by NAICS Codes, FY 2022');
            } else if (buttonId === 'trend') {
                $('#chart2').hide();
                $('#chart1').hide();
                $('#chart3').show();
                initializeTrendChart(); // Reinitialize trend chart
            } else {
                // Default case, show chart1
                $('#chart2').hide();
                $('#chart1').show();
                $('#chart3').hide();
               initializeChart('demo-output', '#example1', 'test Awards by NAICS Codes, FY 2023');
            }

            // Highlight the active button
            $('.usa-button').removeClass('active');
            $(this).addClass('active');
        });

        // Set default highlight on 2023 button
        $('#current').addClass('active');
    }
});
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

    <link href="https://nightly.datatables.net/css/dataTables.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/dataTables.js"></script>

 <script src="https://code.highcharts.com/highcharts.js"></script>

  </head>
  <body>




<div class="ar-controls grid-row tablet:flex-justify-start">
<div class="tablet:grid-col-auto margin-bottom-205"><button id="current" class="usa-button usa-button--outline" title="Select to see related information below">one</button> <button id="previous" class="usa-button usa-button--outline" title="Select to see related information below">two</button> <button id="trend" class="usa-button usa-button--outline" title="Select to see related information below">three</button></div>
</div>

<div id="chart1">
<div id="demo-output" class="chart-display" style=" margin-bottom: 2em; height: 500px; border: solid 1px lightgray;"></div>

<table id="example1" class="display" style=" width: 100%;"><thead>
<tr>
<th scope="col">2023</th>
<th scope="col">Percent</th>
</tr>

</thead>
<tr>
<td scope="row">ABC</td>
<td>45.9%</td>
</tr>

<tr>
<td scope="row">DEF</td>
<td>22.0%</td>
</tr>

<tr>
<td scope="row">GHI</td>
<td>13.6%</td>
</tr>

</table>
</div>

<div id="chart2" style=" display: none;">
<div id="demo-output2" class="chart-display2" style=" margin-bottom: 2em; height: 680px; border: solid 1px lightgray;"></div>

<table id="example" class="display" style=" width: 100%;"><thead>
<tr>
<th scope="col">2022</th>
<th scope="col">Percent</th>
</tr>

</thead>
<tr>
<td>AAA</td>
<td>51.90%</td>
</tr>

<tr>
<td>BBB</td>
<td>18.60%</td>
</tr>

</table>
</div>

<div id="chart3" style=" display: none;">
<div id="chart-A" style=" width: 100%; height: 500px;"></div>

<table class="row-border stripe no-footer cell-border padding-top-5" id="example2" style=" width: 100%;"><thead>
<tr>
<th>Year</th>
<th>column1</th>
<th>column2</th>
<th>column3</th>

</tr>

</thead>
<tr>
<td scope="row" style=" text-align: left; white-space: nowrap;">FY19</td>
<td style=" text-align: left;">42.7%</td>
<td style=" text-align: left;">17.3%</td>
<td style=" text-align: left;">9.5%</td>

</tr>

<tr>
<td scope="row" style=" text-align: left;">FY20</td>
<td style=" text-align: left;">49.5%</td>
<td style=" text-align: left;">16.3%</td>
<td style=" text-align: left;">3.4%</td>

</tr>


</table>
</div>
</div>

Can’t npm run dev because of JSON.parse issue. No red lines on in VS Code, I’ve checked for errant commas. Not sure what else it could be

**This is what the terminal says when I tried to npm run dev.
**

npm ERR! code EJSONPARSE
npm ERR! path C:UsersuserDocumentsUdemyNext Projectsnext-reviews/package.json
npm ERR! JSON.parse Unexpected string in JSON at position 109 while parsing '{  
npm ERR! JSON.parse     "name": "next-reviews",
npm ERR! JSON.parse     "pri'
npm ERR! JSON.parse Failed to parse JSON data.
npm ERR! JSON.parse Note: package.json must be actual JSON, not just JavaScript.

This is what was in the code.

{
    "name": "next-reviews",
    "private": true,
    "scripts":{
        "dev": "next dev"
    },
    "dependencies": {
        "next": "^14.1.3",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
    }
}

How to Load Dynamic Image into HTML with VUE

This is my first time using VUE and I want to reuse a header component that takes in a backgroundImage string variable. Tried researching it and can’t find any tutorials that helps solve this.

Header.vue – the actual component that the image will appear on

<template>
  <header :style="{ ...headerStyle, backgroundImage: 'url(' + imageUrl + ')' }">
    <h1>Place Holder Text: <br> {{ headings.Index }}</h1>
  </header>
</template>

<script>
export default {
  name: 'ImageHeader',
  props: {
    imageUrl: String
  },
  data() {
    return {
      headings: {
        Index: "Home Page",
        About: "About Page"
      },
      scrolled: false,
    };
  },
  computed: {
    headerStyle() {
      return {
        padding: this.scrolled ? '10px' : '50px 10px',
        color: this.scrolled ? 'black' : 'white',
        textAlign: 'center',
        fontWeight: 'bold',
        position: 'fixed',
        top: 0,
        width: '100%',
        height: this.scrolled ? '100px' : '56rem',
        transition: '0.5s',
        backgroundRepeat: 'no-repeat',
        backgroundPosition: 'center',
        backgroundSize: 'cover',
        margin: 'auto',
        lineHeight: this.scrolled ? '2rem' : '3rem',
        zIndex: 1,
      };
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      this.scrolled = window.scrollY > 50;
    }
  }
};
</script>

App.vue – contains Header component and another component

<template>
  <div>
    <!-- Pass headerImageUrl to the ImageHeader component -->
    <ImageHeader :imageUrl="headerImageUrl"/>
    <SideBar/>
    <!-- Your main content here -->
  </div>
</template>

<script>
import SideBar from './components/SideBar.vue';
import ImageHeader from './components/Header.vue';

export default {
  name: 'App', 
  components: {
    ImageHeader,
    SideBar
  }
}
</script>

index.html – where I want to insert the path to the file

<body>
     <div id="app" image-url="../src/assets/ImageName.png" </div>
</body>

I’ve swapped out some stuff like the image names and content text for security and I’ve only included the relevant div element in the html file. I’m using the default vue directory template if that helps visualise what files and paths I’m working with.

The closest I’ve gotten to this working is declaring the file path with a png/jpeg file on the internet in App.vue but this hardcodes it for every page I want to use the App component on.

How to stop the stream when the timer ends

    <h1 id="div3">{{ pageTitle }}</h1>
    <div class="container">
        <button (click)="startVideo()" id="div4">Show Me</button>
        <div
            class="small-box-container"
            *ngIf="showVideo"
            [@fadeInOut]="fadeInOutState"
        >
            <div class="overlay">
                <div class="text">
                    <h2>Capturing emotion</h2>
                    <h4>Don't move, Stay still !!</h4>
                </div>
                <div class="countdown-container">
                    <mat-progress-spinner
                        [value]="progressValue"
                        color="warn"
                        mode="determinate"
                        diameter="50"
                        class="center-spinner"
                    ></mat-progress-spinner>
                </div>
                <img
                    id="video"
                    [src]="videoUrl"
                    alt="Video Stream"
                    class="small-box"
                />
            </div>
        </div>
    </div>

This is my html page

import { Component, OnInit, OnDestroy, ViewChild } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
import { CancelrequestService } from './cancelrequest.service';
import { ChangeDetectorRef } from '@angular/core';
import {
  trigger,
  state,
  style,
  animate,
  transition,
} from "@angular/animations";
import { Router } from "@angular/router";

@Component({
  selector: "app-home-page",
  templateUrl: "./home-page.component.html",
  styleUrls: ["./home-page.component.css"],
  animations: [
    trigger("fadeInOut", [
      state(
        "in",
        style({
          opacity: 1,
        }),
      ),
      transition(":enter", [style({ opacity: 0 }), animate(300)]),
      transition(":leave", [animate(300, style({ opacity: 0 }))]),
    ]),
  ],
})
export class HomePageComponent implements OnInit, OnDestroy {
  lastPrediction: string[] | null = null;
  lastPredictionValue: string | null = null;
  pageTitle: string = "How are you feeling today?";

  showVideo = false;
  videoUrl = "http://127.0.0.1:5000/video_feed";
  fadeInOutState = "out";
  countdown = 5;
  progressValue = 100; // Initial value for mat-progress-spinner
  progressInterval: any; // Interval reference
  videoComponentActive = false;
  loadingTimeout: any; // Added boolean flag
  httpSubscription: any;

  constructor(
    private router: Router,
    private cdRef: ChangeDetectorRef
  ) {
    
  }
  @ViewChild('video', { static: false }) videoElementRef: any;
  

  ngOnInit() {
    //this.startProgressInterval();
  }

  ngOnDestroy() {
    //this.clearProgressInterval();
  }

  private startProgressInterval() {
    if (!this.progressInterval) {
      const totalTime = 10; // Total time in seconds
      const intervalTime = 100; // Interval time in milliseconds
      const steps = (totalTime * 1000) / intervalTime; // Number of steps

      let currentStep = 0;

      this.progressInterval = setInterval(() => {
        currentStep += 1;
        this.progressValue = 100 - (currentStep / steps) * 100;

        if (currentStep === steps) {
          this.clearProgressInterval();
          this.closeStream();
        }
      }, intervalTime);
    }
  }

  

  private clearProgressInterval() {
    clearInterval(this.progressInterval);
    this.progressInterval = null;
    
  }

  startVideo() {

    // Reset countdown and progress values
    this.countdown = 5;
    this.progressValue = 100;

    //this.clearProgressInterval(); // Clear any existing interval



    this.startProgressInterval();

    this.videoUrl = "http://127.0.0.1:5000/video_feed";
    this.showVideo = true;
    this.fadeInOutState = "in";
    this.videoComponentActive = true; 
    
    
  }

  
  

  closeStream() {
    this.showVideo = false;
    console.log("reached here");
    this.videoUrl = "invalid"
    console.log(this.videoUrl);
    this.clearProgressInterval();
    this.cdRef.detectChanges();
  }

  onHistory() {
    this.router.navigate(["/history"]);
  }

  onLogout() {
    this.router.navigate(["/"]);
  }
}

And this is my component.ts file

I have a backend that uses flask running a facial recognition model to capture emotions, basically when the user clicks the button a pop up is created the facial recognition model gets called and a live video feed is shown and a small timer starts and then after the timer ends the pop up and the video feed close but the api continues to get called and therefore my webcam stays on and everything resets when i refresh the page. How do I stop the api from getting called after the timer ends?

adding a class when the box has a scroll

I need help adding a class to a div when it has an active scroll. This is a list that changes depending on the user – sometimes there are so few things there that the scroll does not appear, but in some situations the scroll does.

I found a script, but it involves adding a class when the user reaches a certain point in the box (setting it to 0 is not what I’m looking for, because the user has to hover over the box first anyway), and I need a script that works regardless of this. Is something like this possible?