How to Implement Real-time Decryption and Playback of Encrypted Video Streams in Front-end Development? [closed]

We have bytes encrypted video files stored on the server, and we want to achieve “real-time” decryption of the byte stream on the web browser side for online playback.

PS: Implementation on the client-side is not an issue; the client can intercept the player’s requests, decrypt the returned byte stream, and then pipe it to the player. However, tackling this issue on the web side presents a challenge.

Leaflet Layers Not Displaying Immediately After Addition in Vue.js

I am encountering an issue with Leaflet in a Vue.js application, where layers are not displaying immediately after being added to the map. The problem occurs specifically when removing a layer and then attempting to add it again; the layer is present in the featureGroup, but it does not appear on the map until a subsequent zoom event occurs.

    <a-tree checkable :auto-expand-parent=true :tree-data="treeData" :default-checked-keys="defaultCheckedKeys"
        :defaultExpandAll=true :show-icon=true @check="onCheck">
        <template slot="title" slot-scope="item">
            <img :src="item.img" v-if="item.img" style="width: 27px; height: 27px;" />
            {{ item.title }}
        </template>
    </a-tree>
onCheck(checkedKeys, info) {
    const { dataRef } = info.node._props;
    const { layer, children } = dataRef;

    if (info.checked) {
        if (children) {
            children.forEach(item => {
                if (!this.parent.featureGroup.hasLayer(item.layer)) {
                    this.parent.featureGroup.addLayer(item.layer);
                }
            });
        } else if (!this.parent.featureGroup.hasLayer(layer)) {
            this.parent.featureGroup.addLayer(layer);
        }
    } else {
        if (children) {
            children.forEach(item => {
                this.parent.featureGroup.removeLayer(item.layer);
            });
        } else {
            this.parent.featureGroup.removeLayer(layer);
        }
    }
}
  1. Has anyone else experienced a similar issue with Leaflet layers not displaying immediately after addition in a Vue.js application?
  2. Are there any known solutions or workarounds for this problem?
  3. Are there specific Leaflet or Vue.js configurations that may impact the rendering of layers in such scenarios?
    Any insights or guidance would be greatly appreciated. Thank you!

A small strange behavior of map with parseInt in JavaScript [duplicate]

I want to convert a string array to int array using map and parseInt function, but I find a interesting thing is ['2023', '12', '0'].map(parseInt) returns [2023, NaN, 0].

I have to rewrite to [‘2023′, ’12’, ‘0’].map(elem=> parseInt(elem)).

From the docs of parseInt, this function accepts one or two arguments. Maybe it’s the root case.

Update: I found it’s duplicated with Strange behavior for Map, parseInt and map + parseInt – strange results.

See more detailed explanation there.

.map calls parseInt() with three parameters – the value, the array index, and the array itself.

The index parameter gets treated as the radix:

parseInt('2023', 0, ['2023', '12', '0']); // OK - gives 2023, 0 radix here is become 10 because '2023', see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#description
parseInt('12', 1, ['2023', '12', '0']); // FAIL - gives NaN, 1 isn't a legal radix
parseInt('0', 2, ['2023', '12', '0']); // OK - gives 0 in base 2 

Tips to overcome pre-selection tests for junior positions? [closed]

community, I wanted to ask you something.

I’ve been applying to some LinkedIn job postings, and for the ones that respond, they typically send me the usual online test with 30 questions in 30 minutes. Honestly, I find it challenging to excel in these types of assessments where there’s so little time to think per question.

The worst part is that the questions aren’t exclusively related to the technology I’m applying for; they involve mathematical or logical problems reminiscent of math/logic Olympiads that inherently have different interpretations before arriving at the correct answer.

What I’m looking for is if you can help me find or recommend a way to practice for these tests.

It truly feels disheartening to fail even before seeing the technical test.

no response coming back from python httpserver to javasacript request

No response (status, responseText) is coming back from python httpserver “example” to javasacript request. javasacript request seems to be okay, but it is not getting from HTTP server “example”.
Any advice would be much appreciated.


XML HTTP Request in Javascript


    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
           x = this.responseText
        }
    xhr.open('GET', 'http://127.0.0.1:8080/example', true);
    xhr.send();

HTTP Server “example” in Python


from http.server import BaseHTTPRequestHandler, HTTPServer

hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
     def do_GET(self):
        self.send_response(200)
        #self.send_response(status.code, status.message)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
        self.wfile.write(bytes("<p>GET: %s</p>" % self.path, "utf-8"))
        self.wfile.write(bytes("<body>", "utf-8"))
        self.wfile.write(bytes("<p>This is do_GET of HTTP server.</p>", "utf-8"))
        self.wfile.write(bytes("</body></html>", "utf-8"))
        self.wfile.close()
        #self.wfile.write(bytes("Hello, world!", "utf-8"))

     def do_POST(self):
        # read the content-length header
        content_length = int(self.headers.get("Content-Length"))
        # read that many bytes from the body of the request
        body = self.rfile.read(content_length)
        self.send_response(200)
        self.end_headers()

        self.wfile.write(body)
    
if __name__ == "__main__":        
    webServer = HTTPServer((hostName, serverPort), MyServer)
    print("Server started http://%s:%s" % (hostName, serverPort))

Modal Onclick Visibility Not Working As Intended

My modal below isn’t working but I’m not experienced enough to figure why. I’m trying to hide my modal using visibility: hidden, then changing to visibility: visible onclick.

HTML

    <div class="modalSignin"></div>

     <div class="authBtns" onclick="modalLogin()">
          <a href="#" id="loginBtn">Login</a>
          <a href="#" id="regBtn">Register</a>
     </div>

CSS:

    .modalSignin {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: black;
        min-width: 40%;
        min-height: 400px;
        visibility: hidden;
    }

JAVASCRIPT:

   function modalLogin() {
        var modal = document.getElementsByClassName("modalSignin");
         modal.style.visibility = "visible";
    };

Please see above code snippets.

javascript consoling didn’t return expected result

I am trying to learn graph datastructure and found this weird behaviour by consoling the current data, my main code is as follows

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) this.adjacencyList[vertex] = [];
  }

  addEdge(v1, v2) {
    this.adjacencyList[v1].push(v2);
    this.adjacencyList[v2].push(v1);
  }

  removeEdge(v1, v2) {
    this.adjacencyList[v1] = this.adjacencyList[v1].filter((el) => el !== v2);
    this.adjacencyList[v2] = this.adjacencyList[v2].filter((el) => el !== v1);
  }
}

and my console logs were

let graph = new Graph();
graph.addVertex("tokyo");
graph.addVertex("dallas");
graph.addVertex("aspen");

graph.addEdge("tokyo", "dallas");
graph.addEdge("dallas", "aspen");

console.log(graph.adjacencyList);

graph.removeEdge("dallas", "tokyo");

console.log(graph.adjacencyList);

what I normally expected was the first console.log before removing should contain the edges and the after would contain the edges after removed, that is what I also see in the object

{tokyo: Array(1), dallas: Array(2), aspen: Array(1)}

{Tokyo: Array(0), dallas: Array(1), aspen: Array(1)}

but when I open up the object I don’t see the expected values in object 1

aspen: ['dallas']
dallas: ['aspen']
Tokyo: []

This is exactly the same for the second object in console.log

Instant abortion functionality for an arbitrary function that takes time to execute? [duplicate]

I’m experiencing difficulty creating an “abortion function” for a looping function that takes significant time to execute, in JavaScript. My goal is to be able to have some stimulus (or one of a few different stimuli) immediately terminate the looping function and run some shutdown sequence instead. While I could obviously accomplish this by having conditional break/return statements all throughout the looping function that constantly check the abort condition(s), surely there must be a cleaner, easier-to-maintain way to accomplish this (async maybe)?

Below is some skeleton code to clarify the situation:

// Func() runs until some stimulus occurs, such as
// a key being pressed or a condition being met,
// after which it immediately stops in its tracks
// and Abort() runs instead

function Func() {
    while (true) {
        // Does a bunch of complicated stuff.
        // Probably calls other functions,
        // maybe has some Time.sleep() calls in there.
    }
}

function Abort() {
    // Shuts down whatever procedure was being performed
    // in Func() and terminates
}

I’m sure that the solution to this is simpler than I think, but I appreciate any input nevertheless!

Updating a specific data in Mysql databasese using Flask api and SQLAlchemy from NextJs

So I have created an API in flask with a PUT method in order for me to update a specific data. In my nextjs client side I have created an update handler that is responsible for handling this event in a form. But I keep getting an error.
“Uncaught (in promise)
AxiosError {message: ‘Request failed with status code 404’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request: XMLHttpRequest, …}
code
:
“ERR_BAD_REQUEST”
config
:
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
:
“Request failed with status code 404”
name
:
“AxiosError”
request
:
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
:
{data: ‘<style data-n…p”:true,”scriptLoader”:[]}x3C/script>’, status: 404, statusText: ‘Not Found’, headers: AxiosHeaders, config: {…}, …}
stack
:
“AxiosError: Request failed with status code 404n at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)n at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:125:66)”
[[Prototype]]
:
Error”

Flask API:

@app.route("/api/specific_todo/<int:id>", methods=['PUT'])
def update_specific_todo_data(id):
    data = request.get_json()
    todo_to_update = Todo.query.get(id)

    new_todo_item = data.get('todo_item')

    todo_to_update.todo_item = new_todo_item
    db.session.commit()
    return jsonify(todo_to_update)
    # if request.method == "POST":
    #     # Get the new todo item from the request body
    #     new_todo_item = request.json.get('todo_item')

    #     # Update the todo item
    #     todo_to_update.todo_item = new_todo_item
    #     db.session.commit()

    #     # Convert the updated todo to a dictionary
    #     updated_todo = {'id': todo_to_update.id, 'todo_item': todo_to_update.todo_item, 'status': todo_to_update.status}
    #     return jsonify(updated_todo)
    # else:
    #     return jsonify({'error': 'Todo not found'}), 404

Nextjs

 // Handle update/edit handler
  function handleUpdate(e: FormEvent) {
    try {
      e.preventDefault();
      // Send the id and the new item value to the server
      axios
        .put(`/api/specific_todo/${itemToEditId}`, {
          todo_item: newTodoItem,
        })
        .then((response) => {
          console.log(response.data);
        });
      // Handle success or any additional actions after the update

      setNewTodoItem("");
    } catch (error) {
      //displaying an error message to the user
      console.error("Update failed:", error);
    }
  }

What am I doing wrong?

How I get data from JSON file? [closed]

In Javascript, I have a file resulting from using Axios.get command from a loop, but I can’t get the data inside it.
I can see the file at console.log(Authors), this is it:

Authors:
[]
0:
  config: {transitional: {...}, adapter:Array(2), transformRequest: Array(1),timeout: 0,
  data: Array(2)
    0: {Author_name:"Mark", Author_lastName: "Twain", title:"Tom Sawyer"}
    1: {Author_name:"Mark", Author_lastName: "Twain", title:"Huckleberry Finn"}
    [[Prototype]]: Array(0)
  headers: AxiosHeaders {access-control-headers: "*", access-control-allow-methods: "*",
  request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials
  status: 200
  statusText: "OK"
  [[Prototype]]: Object
1:
  config: {transitional: {...}, adapter:Array(2), transformRequest: Array(1),timeout: 0,
  data: Array(2)
    0: {Author_name:"Edgar Allan", Author_lastName: "Poe", title:"The Black Cat"}
    [[Prototype]]: Array(0)
  headers: AxiosHeaders {access-control-headers: "*", access-control-allow-methods: "*",
  request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials
  status: 200
  statusText: "OK"
  [[Prototype]]: Object

I tried to get the variables inside “data” but couldn’t. I can’t understand how the array is composed. Almost every attempt to capture the data results “undefined”
Authors[data] –> “data” is not defined no-undef
or
Authors[0] –> undefined

I tried to get something like this:
books = [{Author_name:”Mark”, Author_lastName: “Twain”, title:”Tom Sawyer”}, {Author_name:”Mark”, Author_lastName: “Twain”, title:”Huckleberry Finn”}, {Author_name:”Edgar Allan”, Author_lastName: “Poe”, title:”The Black Cat”}]

What’s the simplest way to assign unique sliders to each clicked element in this case?

I currently have a table with a javascript function where when a table cell is clicked, the entire row will be removed and the clicked cell will be copied to the leftmost position with a slider opening up on the right. However, I only have a universal slider for all clicked elements but I want to make each table cell’s slider unique. What’s the best approach for that in this case?

document.addEventListener("DOMContentLoaded", function () {
  var table = document.getElementById("TrendGames");
  table.addEventListener("click", function (event) {
    var clickedCell = event.target.closest("td");
    if (clickedCell) {
      handleCellClick(clickedCell);
    }
  });
});

function handleCellClick(clickedCell) {
  const row = clickedCell.parentElement;
  const cells = row.children;
  const display = cells[cells.length - 1].style.display ? "" : "none";

  // Hide/Show all cells
  for (var i = 0; i < cells.length; i++) {
    cells[i].style.display = display;
  }
  if (display) {
    // First click (third, fifth, ...)
    // Copy(!) the clicked cell in the leftmost position
    const newCell = clickedCell.cloneNode(true);
    newCell.style.display = "";
    newCell.colSpan = cells.length;
    row.insertBefore(newCell, row.firstChild);
    // Open the slider and display information
    openSlider(newCell);
  } else {
    // Remove the cell that was inserted on previous click
    clickedCell.remove();
    closeSlider(clickedCell);
  }
}
<table id="TrendGames">
  <tbody>
    <tr>
      <td id="cell1">
        Cell 1
        <img class="GameCover" src=".png" alt="cell1" />
      </td>
      <td id="cell2">
        Cell 2
        <img class="GameCover" src=".png" alt="cell2" />
      </td>
      <td id="cell31">
        Cell 3
        <img class="GameCover" src=".png" alt="cell3" />
      </td>
      <td id="cell4">
        Cell 4
        <img class="GameCover" src=".png" alt="cell4" />
      </td>
    </tr>
  </tbody>
</table>

Firebase Firestore – get error response with offline persistence

I was wondering if there was a way to get an error response from a firestore write while using offline persistence the same as if it were online. Basically, if I submit a write and the doc name has a special character that is not allowed, when online, this will throw an error. However, when offline, you don’t know if there is an error until you go back online and firebase attempts to write the data to the online database.

Is there a way to get Firestore to throw an error even if using offline persistence (so that the user can be alerted that they need to change the name etc.)?

Thank you all!

communication between iframe using postMessage

I’m trying to remove buttons from a screen that I access with an iframe so that my parent software doesn’t make changes through the buttons. To do this, I am using postMessage communication to inform a variable in the ifram’s child application, but in this application the change to the variable that I send is not happening.

The code is javascript, so there is no debugging, so I am using consoleLogs to see what is coming to the console. And I haven’t found the update yet.

FOR SENDING:

const sendBooleanToIframe = () => {
    const iframe = frameRef.current
    if (iframe) {
      setTimeout(() => {
        iframe.contentWindow?.postMessage({ yourBooleanVariable: true }, '*')
      }, 3000)
    }
}
useEffect(() => {
    const iframeLoadHandler = () => {
      sendBooleanToIframe()
    }
    const iframe = frameRef.current
    if (iframe) {
      iframe.addEventListener('load', iframeLoadHandler)
    }
    return () => {
      if (iframe) {
        iframe.removeEventListener('load', iframeLoadHandler)
      }
    }
}, [])

FOR RECEIVED:

setTimeout(() => {
 useEffect(() => {
  const handleMessage = (event) => {
    console.log('start handleMessage diagnostics')
   if (event.data.yourBooleanVariable) {
    console.log('Menssage iframe:', event.data.yourBooleanVariable)
    headerInfo = false
   }
  };
  window.addEventListener('message', handleMessage)
  return () => {
   window.removeEventListener('message', handleMessage)
  }
 }, [])
} , 3000)

Display file (image) on another file with nextjs

I want to upload a file on a page and then display it in another page
Here’s my post.jsx (where I want to upload the file):

import Layout from '../components/layout';
import Link from 'next/link';
import { useRouter } from 'next/router';
import { useState } from 'react';
import { getCookie } from 'cookies-next'

export default function postPage({ username }) {
  const router = useRouter();
  const { msg } = router.query;
  const [showError, setShowError] = useState(msg !== undefined);
  const [selectedFile, setSelectedFile] = useState(null);


  const handleFileChange = async (e) => {
    const file = e.target.files[0];
    setSelectedFile(file);
  };

  const handleDismissError = () => {
    setShowError(false);
  };

  return (
    <Layout pageTitle="Se connecter">
      <div className="navbar-signup">
        <div className="left">
          <Link href="/" className="accueil">
            Accueil
          </Link>
          <br />
        </div>
        <div className="right">
          <Link href="/signup" className="connexion">
            S'inscrire
          </Link>
          <br />
        </div>
      </div>
      <div className='informations'>
        <img src="https://media.discordapp.net/attachments/972878173488447568/1184484661565599825/stickers-muraux-logo-nike.jpg?ex=658c244d&is=6579af4d&hm=e6230816ac8a2b23526abdf6b724d6f0f070f47cc533251ff2f03e04fc564acd&=&format=webp"></img>
      </div>
      <div className="box">
        <br></br>
        {showError && (
        <div className="error-box">
          <p className="error-message">{msg}</p>
          <button onClick={handleDismissError}>Ok</button>
        </div>
      )}
        <p className="signuptitle">Poste Ta Note !</p>
        <form action="/api/post" method="POST">
          <p>Matière :</p>
          <input
            minLength="1"
            name="subject"
            id="subject"
            type="text"
            placeholder="Mathématiques, Anglais etc.."
            required
          ></input>
          <br />
          <p>Moyenne De La Matière :</p>
          <input
            minLength="1"
            name="subjectaverage"
            id="subjectaverage"
            type="number"
            placeholder="10, 15, 17 etc..."
            required
          ></input>
          <br />
          <p>Temps De Révision :</p>
          <input
            minLength="1"
            name="revisiontime"
            id="revisiontime"
            type="text"
            placeholder="aucune, 2h, 15min etc.."
            required
          ></input>
          <br />
          <p>Photo De Ta Feuille :</p>
          <input type="file" name='picture' onChange={handleFileChange}/>
          {selectedFile && (
          <img src={URL.createObjectURL(selectedFile)}></img>
      )}
          <input type="hidden" name="username" value={username}></input>
          <br />
          <br></br>
          <input type="submit" value="Poster" />
        </form>
      </div>
    </Layout>
  );
}

export async function getServerSideProps(context) {
  const req = context.req
  const res = context.res
  let username = getCookie('username', { req, res });
  if (!username) {
      return {
          redirect: {
              permanent: false,
              destination: "/"
          }
      }
  }
  return {
    props: { username },
  }
}

here’s the backend:

import clientPromise from "../../lib/mongodb";

export default async function handler(req, res) {
  if (req.method === "POST") {
    const username = req.body['username'];
    const subject = req.body['subject'];
    const subjectAverage = req.body['subjectaverage'];
    const revisionTime = req.body['revisiontime'];
    const picture = req.body['picture']

    const client = await clientPromise;
    const db = client.db("Notes");

      const noteObject = {
        username,
        subject,
        subjectAverage,
        revisionTime,
        picture,
      };


      await db.collection("Notes").insertOne(noteObject);

      res.redirect("/");
  } else {
    res.redirect("/");
  }
}

So, I don’t really know how can I upload a file and then display it in another page by storing the file in the database, I’ve been trying for hours and didn’t find any solution, can someone help please.

Can’t stop promise chain javascript

I have a stream of text that I send to a function to turn into speech. I send the text sentence by sentence for better latency. The issue im running into is handling interruptions. Right now, I send each sentence to a function containing a promise. So I end up with a chain of awaits that pile on fairly quickly, so when I try to interrupt the function, althought it properly breaks out, the await chain continues to run. Here is a snippet of the code (send_voice returns a promise)

const stream = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: conversation_history,
      stream: true,
    });

    let sentence = ""; 

    for await (const chunk of stream) {
      
      const content = chunk.choices[0]?.delta?.content || "";
      sentence += content; 

      if (interruptionState.value){
        console.log("breaking");
        break; //break correctly called but send_voice chain continues
      }
      
      if (sentence.endsWith('.') || sentence.endsWith('!') || sentence.endsWith('?')) {
        
        console.log("FINAL: ", sentence);
        
        conversation_history.push({ "role": "system", "content": sentence });
        
        await send_voice(sentence, ws, elleven_key, voice_id,interruptionState); 
        sentence = ""; 
      }
    }

I know that I can’t stop the await chain, but is there any way around this? I essentially need to call send_voice sequentially and be able to stop it quickly on interruption. I’ve been stuck on this for a while so any help would be much appreciated!

I’ve been stuck on this for a while so any help would be much appreciated!