How to synchronize a python dictionary across a flask app and a background thread

Here is my problem. I have a Flask application which does some predictions on some datasets. The users can upload multiple datasets to the server and operate on any of the dataset.

Here, I need to clean the user data directory which is

static/files/userdata_<ip_of_client>/

I am trying to remove the entire directory if user does not connect for 30 seconds.
FYI, the client side javascript sends a POST request using fetch every 10 seconds, so if it misses 3 window the files will be cleared. Thats the idea.

The POST request triggers an API having code like this

@app.route("/api/ping", methods=["POST"])
def ping():
  try:
     client_ip = request.remote_addr
     with data_lock:
       folder_access_times[client_ip] = datetime.datetime.now()


Here data_lock is a globally declared Lock() from threading module

In another thread I am checking if any client did not connect for 30 sec like this

with data_lock:
    curtime = datetime.datetime.now()
    for key,val in folder_access_times.items():
        diff = (curtime-val).seconds
        if diff > 30:
            shutil.rmtree(...)

The problem is that the lock is not working properly. noticing very strange beheavior like

Even if I am using Lock here and the ping API successfully modifies the dictionary, but I am noticing and the background thread sees the old data even long after the API updated it.

The data is very inconsistent as current date also reverts back to previous in next iteration of background process ( I am using while loop in the background process) which is not intended in case of Lock.

Don’t understand what am I missing.
Any help will be appreciated.

HTML File picker not working in Firefox addon

I am trying to attach a image from my local machine to Firefox addon and show it in popup.html. But the addon’s popup closes immediately after the input element’s onChange event is triggered.

Iam using manifest V3. It is working fine in chrome.
Using Vite and React.

async function pickImage() {

    let input = document.createElement('input');
    input.type = 'file';
    input.accept = "image/*"
    input.multiple = true;
    input.addEventListener('input', filePickerListener)
    input.click()
    
    function filePickerListener() {
      const fileList = this.files;
      console.log('IMAGES PICKED FROM EXTENSION')
      setImages([...images, ...fileList]);
    }
}

Main purpose of this task is assigning an identification number to computers running our software [closed]

Main purpose of this task is assigning an identification number to computers running our software.
We need a method to create fingerprint for computer identification.
Following approaches are available, but some disadvantages:
• Using MAC address of network adapters. in modern OS, sometimes OS generates a random MAC address regularly. This is for security & privacy concerns. So MAC is not static anymore.
• Şerial number of mainboard: This method have 2 issues:

  • Some heuristic anti-virus applications may consider WWII queries if application contains WMI queries inside. Please avoid using WMI queries.
  • Modern mainboard producers hide serial numbers (ako OEM mainboards may have this issue)
    Please search methods of computer identifications as well as fingerprint generation. Think flexible and be open minded for other possible solutions.

add and delete quizquestion and quiz answers

`I can add quiz questions and answers as a list form and delete them like a todo list. But after I added todos, the todos overwrite themselves and are no longer visible and no longer available in the dictionary.

my javascript code:


let dictionary = JSON.parse(localStorage.getItem("dictionary")) || {};
let ran_key;
let obj_keys;

function addQuizQuestion() {
    dictionary[questionforQuiz.value] = answer.value;
    questionforQuiz.value = '';
    answer.value = '';

    localStorage.setItem("dictionary", JSON.stringify(dictionary));
    render();
}


function render() {
    Quizlist.innerHTML = ''; 
    for (let key in dictionary) {
        Quizlist.innerHTML += `
            <li>${key} - ${dictionary[key]}
            <button onclick="deleteQuiz('${key}')">x</button>
            </li>`;
    }
}

function deleteQuiz(key) {
    if (confirm("Möchten sie wirklich diese Frage inkl. Antwort löschen?") == true) {
        delete dictionary[key];
    }
    render();
}

function nextQuizQuestion() {
    obj_keys = Object.keys(dictionary);
    ran_key = obj_keys[Math.floor(Math.random() * obj_keys.length)];
    question.innerHTML = `${ran_key}`;
}

function compare() {
    if (Textfield.value == `${dictionary[ran_key]}`) {
        text.innerHTML = "Richtig!";
    } else {
        text.innerHTML = "Falsch!";
    }
    Textfield.value = '';
    nextQuizQuestion();
}

my html code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
    <script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
    <link rel="stylesheet" href="Quizapperstellen.css">
    <script src="Quizapperstellen.js"></script>
    <title>Quiz erstellen</title>
</head>

<body onload="render()">

    <h1>Quizfragen erstellen</h1>

    <br>
    <br>



    <form onsubmit="addQuizQuestion();return false;">
        <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
            <input class="mdl-textfield__input" type="text" id="questionforQuiz">
            <label class="mdl-textfield__label" for="sample3">Quizfrage eingeben...</label>
        </div>

        <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
            <input class="mdl-textfield__input" type="text" id="answer">
            <label class="mdl-textfield__label" for="sample3">Quizantwort eingeben...</label>
        </div>

        <button id="Hinzufügen" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
            Hinzufügen
        </button>

    </form>

    <ul id="Quizlist">

    </ul>

</body>

</html>

and my css code:

body {
    background-color: lightblue;
    overflow: hidden;
}

.mdl-textfield {
    width: 100%;
}

#Hinzufügen {
    width: 100%;
}

I can add quiz questions and answers as a list form and delete them like a todo list. But after I added todos, the todos overwrite themselves and are no longer visible and no longer available in the dictionary.

I googled for 3 hours with no results

I would be grateful for any answer.

How to delete and modify specific Google ad using Google Apps script

Now I’m trying to make script to delete and duplicate targeted ads which I give below as Ad ID.

Before deleting the ads, copy it and duplicate it to under the same ads group which was belonging to.

For example, here’s targeted Ad information.

targetAccountId:’123-456-7890′
campaignId:’1234567890′
adGroupId:’0987654321′
adId:’8901234567′

I want to delete adId:’8901234567′ and duplicate it to under adGroupId.
Also, I will use MCC account.

Type of ad is “responsive video ads”
*here’s a reference; Support for Responsive Video Ads in Scripts

I wrote script as below.
However, everytime I got an error
Error: No more values at main (Code:23:8)

although ad adGroupId and adId is existing and active.

function main() {
  var targetAccountId = '123-456-7890'; // Account ID
  var campaignId = '1234567890'; // Campaign ID to be added
  var adGroupId = '0987654321'; // Ad group ID
  var adId = '8901234567'; // Ad ID

  // Select and iterate over accounts within the MCC.
  var accountIterator = AdsManagerApp.accounts()
    .withIds([targetAccountId])
    .get();

  while (accountIterator.hasNext()) {
    var account = accountIterator.next();
    AdsManagerApp.select(account); // Selecting the child account.

    // Log for clarity.
    Logger.log('Processing account: ' + account.getCustomerId());

    // Attempt to find and process the specific campaign, ad group, and ad.
    var campaign = AdsApp.campaigns()
      .withIds([campaignId])
      .get()
      .next();

    var adGroup = campaign.adGroups()
      .withIds([adGroupId])
      .get()
      .next();

    var adIterator = adGroup.ads()
      .withIds([adId])
      .get();

    if (adIterator.hasNext()) {
      var adToDuplicate = adIterator.next();
      // Ensure it's a responsive video ad before proceeding.
      if (adToDuplicate.getType() === 'VIDEO_AD') { // This type check might need to be adjusted.
        // Duplicate ad logic goes here. As an example:
        var newAdOperation = adGroup.newVideoAd().responsiveVideoAdBuilder()
          // Builder methods to replicate the ad's properties.
          // Note: Actual methods will vary based on the ad's specifics.
          .build();

        if (newAdOperation.isSuccessful()) {
          // Remove the original ad after successful duplication.
          adToDuplicate.remove();
          Logger.log('Ad duplicated and original ad removed for account ' + account.getCustomerId());
        } else {
          Logger.log('Failed to create duplicate ad for account ' + account.getCustomerId());
        }
      } else {
        Logger.log('The specified ad is not a responsive video ad for account ' + account.getCustomerId());
      }
    } else {
      Logger.log('Ad not found in account ' + account.getCustomerId());
    }
  }
}


Uncaught TypeError: this.submitData is not a function

I have defined a async function in methods and when trying to call the same function in mounted.. it is giving the error – Uncaught TypeError: this.submitData is not a function.
Please help me out how to call async function in mounted() in vue js. Below is my code –

<script>
import axios from 'axios';
    export default{
        props:{
            categories: {
                default: []
            },
        },
        data(){
            return {
                formData:{
                    category: [],
                    price: '',
                },
            }
        },
        methods: {
            async submitData(){
                try{
                    const response = await axios.post('/api/category', this.formData)
                    console.log(response);
                }
                catch(error){
                    console.log(error)
                }
            },
        },
        mounted() {
            this.submitData()
                .then((res)=>{
                    console.log(res);
                })
                .catch((err)=>{
                    console.log(err);
                });
        }
    }
</script>

How to transfer value from chrome.storage when changed in popup.js to content.js

I want to transfer value from popup.js to content.js.

Overall, it works. But I can’t do “live” change, because content.js loads old value of chrome.storage.

popup.js

button.addEventListener('click', () => {
    chrome.storage.sync.set({ 
      text: form.textContent, // form.textContent = "1"
    });
});

chrome.storage.sync.get(["text"]).then((result) => {
      pageText.textContent = result.text; // result.text = "2"
    });

content.js

function getInterval() { //test
    chrome.storage.sync.get(["text"]).then((result) => {
      pageText.textContent = result.text; //result.text = "1"
    });
}

Initially result.text (storage) is “1”, saved from previous time;
I change value in popup to “2”.
If I try to read it via sync.get in popup.js I get it as “2”
But when I try to read it from content.js its “1”

But if I refresh tab, result.text = 2 in content.js.

Can you help me fix this?

How to Dynamically Add OpenGraph URL in Next.js?

I’m working on a Next.js project and I’m trying to implement dynamic OpenGraph meta tags. Specifically, I want to set the og:url dynamically based on the current page URL. However, I’m not sure how to achieve this within the Next.js framework.

export async function generateMetadata({ params, searchParams }, parent) {

   const metadata = await getRequest(
    `get-page-seo`
  );


  if (!metadata) {
    return null;
  }

  const previousImages = (await parent).openGraph?.images || [];

  let metatitle = metadata.meta_title;
  let metadescription = metadata.meta_description
     let metaogImage = metadata.og_image && metadata.seo.og_image;
  let metaKeyword = metadata.meta_key

  return {
    title: metatitle,
    description: metadescription,
    keywords: metaKeyword,
    openGraph: {
      images: [`${metaogImage}`, ...previousImages],
      type: "website",
    url : "" // This should be dynamic value will be same as browser url
          },
    twitter: {
      card: "summary_large_image",
      title: twitterTitle,
      description: twitterDescription,
      images: [`${twitterImage}`, ...previousImages],
    },
  };
}

Error occurred: ElementClickInterceptedError: element click intercepted:

I’m trying to make a program where if I give it a web page and any word it will click that for example I can give it a Github profile and give the word “Follow” then it will press that follow button, and start following that Github profile.

How can I do this in Selenium? I’m currently getting this error: Error occurred: ElementClickInterceptedError: element click intercepted:

Code:

import { Builder, By, until } from "selenium-webdriver";

async function clickElementWithText(url, targetText) {
  const driver = await new Builder().forBrowser("chrome").build();

  try {
    await driver.get(url);

    const element = await driver.wait(
      until.elementLocated(
        By.xpath(`//body//text()[contains(., '${targetText}')]/parent::*`)
      ),
      10000
    );

    await element.click();
    console.log(`Clicked on element containing "${targetText}"`);
  } catch (error) {
    console.error("Error occurred:", error);
  }
}

const url = "https://github.com/shs96c";
const targetText = "Follow";
clickElementWithText(url, targetText);

A problem with leaflet map with fastapi + js

I want to draw markers and borders of selected region. And Sometimes when I change it, it works good, but sometimes markers moves to new region and there are still old borders (bad image). How can I solve it? I think problem is in updateMAP function

<html lang="en">

<body>
  <label for="citySelect">Выбор региона:</label>
  <select id="regionSelect" name="region">
    {% for region in regions %}
    <option value="{{ region }}">{{ region }}</option>
    {% endfor %}
  </select>

  <div id="map"></div>

  <script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/leaflet.heat/dist/leaflet-heat.js"></script>
  <script>
    var map;
    var data = {{ data|tojson }};
    var markers = []
    var heatLayer;
    var geojsonLayer;

    function updateMap() {
      var selectedRegion = document.getElementById("regionSelect").value;
      clearMarkers();
      var filteredData = data.filter(function(item) {
        return item["ФИАС Регион"] === selectedRegion;
      });
      var heatmapData = filteredData.map(function(item) {
        return [item['Координаты: широта'], item['Координаты: долгота'], item['Страховая сумма Кумуляция']];
      });
      addMarkers(filteredData);
      if (heatLayer) {
        map.removeLayer(heatLayer);
      }

      heatLayer = L.heatLayer(heatmapData, { radius: 25 }).addTo(map);

      fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${selectedRegion}&polygon_geojson=1`)
        .then(response => response.json())
        .then(data => {
          if (data.length > 0 && data[0].geojson) {
            if (geojsonLayer) {
              map.removeLayer(geojsonLayer);
            }
            geojsonLayer = L.geoJSON(data[0].geojson).addTo(map);
          }
        })
        .catch(error => console.error('Error fetching region data:', error));
    }

    function initMap() {
      map = L.map('map').setView([0, 0], 2);
      L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);
    }

    function clearMarkers() {
      for (var i = 0; i < markers.length; i++) {
        map.removeLayer(markers[i]);
      }
      markers = [];
    }

    function addMarkers(data) {
      for (var i = 0; i < data.length; i++) {
        var marker = L.marker([data[i]['Координаты: широта'], data[i]['Координаты: долгота']]).addTo(map);
        markers.push(marker);
      }
    }

    document.getElementById("regionSelect").addEventListener("change", updateMap);
    </script>
  <script>initMap();</script>
</body>
</html>

my html code is above. also there is part of python code of fastapi connection, but i think it doesn’t matter now

How to fix active thumbs and only move them on the last track using swiper.js

I want to make the active thumbs fixed as in the link below, and only make the thumbs move on the last track. I want to use swiper.js instead of slick slider. How should I do it?

slick slider

<script>
var swiper1 = new Swiper(".mySwiper1", {
                  spaceBetween: 10,
                  slidesPerView: 4,
                  freeMode: true,
                  watchSlidesProgress: true,
                });

                var swiper2 = new Swiper(".mySwiper2", {
                  spaceBetween: 10,
                  navigation: {
                    nextEl: ".swiper-button-next",
                    prevEl: ".swiper-button-prev",
                  },
                  thumbs: {
                    swiper: swiper1,
                  },
                });

</script>

Array element becomes undefined after asynchronous function call in JavaScript

Problem Description:
I’m encountering an issue where a specific element of my file array becomes undefined after using an asynchronous function to check the size of image files. Although all asynchronous processes complete successfully, attempting to access the array element results in undefined.
console.log(2${copyFile[i]}); return “2undefined”

Relevant Code:

 this.addFiles = async function (files)
    {
        let falseFiles = [];
        const copyFile = files;
        var dataGrid = self.dataGrid;
        for (let i = 0; i < copyFile.length; i++) {
            console.log(`1${copyFile[i]}`);
            const checkImageLimitFlag = await this.checkImageLimit(copyFile[i]);
            console.log(`2${copyFile[i]}`);
        }
    }

this.checkImageLimit = async function (file){
       let isValid = true;
        try {
            const maxWidth =1000;
            const maxHeight =1000;
            const { width, height } = await this.loadImage(file);
            // if(validExtension.includes(extension)){ 
                if(width > maxWidth || height > maxHeight)
                    isValid = false;
            // }
        } catch (error) {
        }
        return isValid
}

this.loadImage = function(file) {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
      
          reader.onload = function (e) {
            const img = new Image();
      
            img.onload = function () {
              resolve({ width: img.width, height: img.height });
            };
      
            img.onerror = reject;
            img.src = e.target.result;
          };
      
          reader.onerror = reject;
          reader.readAsDataURL(file);
        });
      }

Attempted Solutions:

I’ve reviewed the code to ensure the array is not modified within the asynchronous function.
Used console.log to check the state of the array before and after the asynchronous calls.
Tested to see if the same problem occurs in different browsers and environments.

Questions:

Why does an array element become undefined after a call to an asynchronous function using the await keyword?
Are there any possible approaches to solve this issue?