data = json.loads(request.body.decode(‘utf-8’)) error no se por que :(

Me da este error “data = json.loads(request.body.decode(‘utf-8’))” al querer cargar un json traido de un js con django. Es para un proyecto escolar 🙁
El codigo recibe una foto tomada por el navegador y la guarda y el error aparece al recibir el post por parte del html
Aqui el codigo del view del proyecto.

from django.shortcuts import render
from django.http import JsonResponse
import json
import base64
import os
import logging

from random import randint

logging.basicConfig(level=logging.DEBUG)

def Inicio(request):
    if request.method == 'POST':
        data = json.loads(request.body.decode('utf-8'))
        image_url = data.get('image_url', '')

        # Guarda la imagen físicamente en la carpeta de medios
        guardar_imagen_fisicamente(image_url)

        return JsonResponse({'message': 'Imagen recibida y guardada con éxito.'})
    return render(request, 'plantilla1.html')

def guardar_imagen_fisicamente(image_url):
    # Decodifica la imagen base64
    image_data = image_url.split(",")[1]
    image_binary = base64.b64decode(image_data)

    # Guarda la imagen en la carpeta de medios
    ruta_carpeta = 'capturas'
    ruta_completa = os.path.join('media', ruta_carpeta, generar_nombre_imagen())
    ruta_completa = os.path.join("C:/myproject/myproject/", ruta_completa)

    with open(ruta_completa, 'wb') as f:
        f.write(image_binary)

def generar_nombre_imagen():
    n = randint(0,999999999)
    nombre_imagen = f"imagen_{n}.png"
    return nombre_imagen

Cosas como url y settings estan bien, ya esta revisado pero me da error en cuando quiero obtener la data, y es que me explota
enter image description here

Inexperadamente si me toma la foto, es decir si hace lo que quiero que haga, es raro

aqui el html

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Captura de Imagen</title>
    <!-- Agrega aquí tus enlaces a jQuery o a otras bibliotecas si es necesario -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
</head>
<body>
    <form method="post" action="/Inicio/">
        {% csrf_token %}
        <div>
            <video id="camera-preview" width="640" height="480" autoplay></video>
            <button id="capture-btn">Capturar Imagen</button>
            <div id="image-url-container">URL de la imagen: </div>
        </div>
    </form>

<script>
    //var nombreImagen;  // Variable para almacenar el nombre de la imagen
    var imageURL;  // Variable para almacenar la URL de la imagen capturada

    // Acceder a la cámara y mostrar la vista previa
    navigator.mediaDevices.getUserMedia({ video: true })
        .then(function (stream) {
            var video = document.getElementById('camera-preview');
            video.srcObject = stream;
            video.play();
        })
        .catch(function (err) {
            console.error('Error al acceder a la cámara:', err);
        });

    // Capturar la imagen y almacenar la URL
    var captureBtn = document.getElementById('capture-btn');
    captureBtn.addEventListener('click', function () {
        var video = document.getElementById('camera-preview');
        var canvas = document.createElement('canvas');
        var context = canvas.getContext('2d');
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        imageURL = canvas.toDataURL('image/png');
        document.getElementById('image-url-container').innerText = 'URL de la imagen: ' + imageURL;
        alert('Imagen capturada con éxito.');

        var csrfToken = document.cookie.match(/csrftoken=([^;]+)/)[1];
        // Obtener el token CSRF del formulario
        var csrfToken = document.getElementsByName('csrfmiddlewaretoken')[0].value;
        // Realizar la solicitud POST incluyendo el token CSRF
        fetch('/Inicio/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken,
            },
            body: JSON.stringify({ image_url: imageURL}),
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`La solicitud falló con estado: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            console.log('Respuesta del servidor:', data);
        })
        .catch(error => {
            console.error('Error:', error);
        });
    });

</script>

</body>
</html>

Si se puede arreglar se lo agradecería mucho

Si alguien lo arregla se lo agradecería mucho, por favor y gracias

TS complains about potential null but I did check the value

On line 5 TS complains about the fact that gameInstanceContext.gameInstance might be null. On line 3 it does not complain. Since I checked its value on line 1, I expect TS to understand that the value is not falsy, and I do not understand why it complains on line 5.

    useEffect(() => {
        if (!gameInstanceContext.gameInstance) return

        console.log(gameInstanceContext.gameInstance.players) // TS does not complain
        const ft = () => {
            console.log(gameInstanceContext.gameInstance.players) // TS complains
        }

        ft()
    }, [gameInstanceContext.gameInstance])

gameInstanceContext.gameInstance‘s type is TGameInstance | null | undefined.

Why does TS complain about gameInstanceContext.gameInstance being potentially null or undefined?

Can’t render my items in to my html file with javascript

HI everyone i’am having a issue in javascript I have to files in html and use one javascript for both but i’am getting this issue that it says selectors.cartItems: null

here’s my code:

const renderCart = () => {
        console.log('Rendering cart...');
        console.log('selectors.cartItems:', selectors.cartItems);
        if (selectors.cartItems) {
            console.log('Cart body exists. Rendering cart items.');
            selectors.cartItems.innerHTML = cart.map(({ id, qty }) => {
                //gets products information
                const product = products.find((x) => x.id === id);
                const { title, image, price } = product;
                const amount = price * qty;

                return `
                    <div class="cart-item" data-id="${id}">
                        <img src="${image}" alt="${title}">
                        <div class="cart-item-details">
                            <h3>${title}</h3>
                            <h5>$${price}</h5>
                            <div class="cart-item-amount">
                                <i class="bi bi-dash-lg"></i>
                                <span class="qty">${qty}</span>
                                <i class="bi bi-plus-lg"></i>
                                <span class="cart-item-price">${amount}</span>
                            </div>
                        </div>
                    </div>
                `;
            }).join("");
            console.log('Cart rendered successfully.');
        }
    };

I have try many things but not work.

I want to render this items in to my shoppincart bag to mention I have to different html file one is index.html and other one is cartshop.html and have one javascripte file used in both files.

How to make “ad-hoc” API call to Rails server in the context of default Rails testing framework

How do I make an “ad-hoc” API call to a Rails server in the context of the default Rails testing framework (minitest using Selenium for the end-to-end tests)?

I am working on a Rails app with views that contain client-side JavaScript that make API calls back to the server. The app is designed so that the only API calls should be coming from the web browser. (Is “API calls” the right term for what the JavaScript is doing? Are there separate terms for (a) background data requests from JavaScript running in a web browser and (b) data requests made by external applications such as a mobile app or command line interface? For what I’m working on right now, I’m specifically concerned about (a). I know that at a high level these are the same thing; but, the details of securing the two types of requests differ slightly.)

I would like to write some end-to-end tests that verify that a user can’t access/modify another user’s data by issuing requests to the server that aren’t generated by my application’s JavaScript code.

The main challenge is that issuing such “malicious”/”fake” server requests would require me to have access to both (a) the session cookie and (b) the CSRF token. How do I do that?

  1. Is there a way for the Ruby test code to use Selenium to obtain them from the browser? Or,
  2. Should I use Selenium to instruct the browser to execute the “custom” Javascript I want to make sure my server responds correctly to? Or,
  3. Should I skip the browser for these tests and simply issue a series of HTTP requests directly from the Ruby code? (This seems to be the more straightforward of the two, except for having to manage the session cookie and CSRF tokens “by hand”.)

Or is there a simpler option “4” that I’m overlooking?

.NET Core web page refreshing as expected with meta “Refresh” tag but wish to isolate some javascript to not refresh

I am creating a page using .NET Core that needs to reload every 1-5 seconds and using the meta http=”Refresh” tag as below, which is working no problem:

<meta http-equiv="Refresh" content="1" />

However, I would like to isolate some javscript code (a prompt to ask a user for permission to use their geolocation) as below:

navigator.geolocation.getCurrentPosition(position => {
const {latitude, longitude} = position.coords;
// Show a map centered at latitude / longitude.
});

(sat in the site.js file). Is there any way from isolating this code from the refresh so that the geolocation is only requested once on the page’s initial load?

Thanks very much and hope this is clear!

ChoicesJS how to append programatically options?

How to append options to an existing initialized ChoicesJS instance?

Given the following HTML:

<select id="random-select"></select>

<button onclick="append()">
  Append new data do select
</button>

And the following JS:

// initializes the plugin
function init()
{
    const data = 
    {
        removeItemButton: true,
        duplicateItemsAllowed: false,
        searchEnabled: true,
        searchChoices: true,
    };
    
    const el = document.getElementById('random-select');
  
    new Choices(el, data);
}

function append()
{
    // How to append to existing element already initialized?
    const el = document.getElementById('random-select');
  
    // DOESN'T WORK
    el.setChoices([{ value: 1, label: 'test' }]);
    
     // DOESN'T WORK
    el.choices.setValue([{ value: 1, label: 'test' }]);
}

Both el.setChoices and el.choices.setValue give an error:

setChoices is not a function

Cannot read properties of undefined (reading ‘setValue’)”

Check the JSFiddle.

PlateJS Serializing HTML

I’m trying to make it so that when I click on a button, I can get an html string.
Generally, this rich text editor will be inside the React-Hook-Form and when the form is submitted, it will save the value to html, so it could be saved to the database

Here’s my code:

"use client";

import { plugins } from "@/lib/plugins";
import { CommentsProvider } from "@udecode/plate-comments";
import { Plate, createPlateEditor } from "@udecode/plate-common";
import { serializeHtml } from "@udecode/plate-serializer-html";
import { FC } from "react";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";

import { CommentsPopover } from "@/components/plate-ui/comments-popover";
import { Editor } from "@/components/plate-ui/editor";
import { FixedToolbar } from "@/components/plate-ui/fixed-toolbar";
import { FixedToolbarButtons } from "@/components/plate-ui/fixed-toolbar-buttons";
import { FloatingToolbar } from "@/components/plate-ui/floating-toolbar";
import { FloatingToolbarButtons } from "@/components/plate-ui/floating-toolbar-buttons";
import { MentionCombobox } from "@/components/plate-ui/mention-combobox";

interface PropsType {
  initialValue?: any;
}

const RichTextEditor: FC<PropsType> = ({ initialValue }) => {
  const editor = createPlateEditor({ plugins });

  const html = serializeHtml(editor, {
    nodes: editor.children,
    dndWrapper: (props) => <DndProvider backend={HTML5Backend} {...props} />,
  });
  return (
    <>
      <DndProvider backend={HTML5Backend}>
        <CommentsProvider users={{}} myUserId="1">
          <Plate
            plugins={plugins}
            initialValue={initialValue}
            editor={editor}
            onChange={() => {
              console.log(editor.children);
            }}
          >
            <FixedToolbar>
              <FixedToolbarButtons />
            </FixedToolbar>

            <Editor />

            <FloatingToolbar>
              <FloatingToolbarButtons />
            </FloatingToolbar>
            <MentionCombobox items={[]} />
            <CommentsPopover />
          </Plate>
        </CommentsProvider>
      </DndProvider>
      <button
        onClick={() => {
          console.log(html);
        }}
      >
        Click
      </button>
    </>
  );
};

export default RichTextEditor;

But at the moment I get an empty string for some reason

I think the problem is in creating the html, but I can’t create this variable inside onChange or onClick.

Maybe someone has a ready-made code or knows how to solve the problem. I will be very grateful

javascript code not prompting on my browser

let year= prompt(“in which year were you born “); if (year==1998) alert(‘you are right’) this code does not prompt tried rewriting the code but that did not work. am new to JavaScript’s I need all the help I can get pls

I tried rewriting the code

TamperMonkey script to execute after a table loads

I am working on building a script to parse a table . The table loads after a button is clicked on the page .

I need to query the table once it completely loads , but the tampermonkey script is executing as soon as the page loads .

The table is fetched from backend after the button is clicked so it might take 15-20 minutes to load . Till the button is not clicked the DOM is not modified .

I am using javascript .

react-native-deck-swiper and react-native-image-slider-box IOS Bug

I’m using an image slider component inside of a deck swiper component from the react-native-image-slider-box and react-native-deck-swiper. The images slide smoothly on Android but it is not smooth for iOS. The swiper component is interfering with the slider when I slide on IOS. If I take the slider out of the swiper it slides normally, but I need the slider within the swiper. I cannot fix this issue on my code or the swiper’s source code. I get no error messages either. I even tried to use pointer events, but I still had no luck.

Code Snippet

  return (
    <SafeAreaView style={{ flexGrow: 1, flexShrink: 1, flexBasis: 0, flex: 1, backgroundColor: 'white' }}>


      <View style={{ zIndex: -1, flex: 1, backgroundColor: "purple" }}>

        <Swiper
          ref={swipeRef}
          backgroundColor='#ff00ff00'
          containerStyle={{ background: "transparent" }}
          cards={users}
          cardVerticalMargin={50}
          cardIndex={refreshCardIndex}
          horizontalSwipe={false}
          verticalSwipe={false}
          disableLeftSwipe={true}
          disableRightSwipe={true}
          disableTopSwipe={true}
          disableBottomSwipe={true}
          renderCard={(card) => card ? (
            <>
              <View style={{ height: 530 }}>

                <View style={{ flex: 1, justifyContent: "center", alignItems: "center", marginTop: -30, backgroundColor: 'red' }}>
                  <SliderBox doctColor={"#808080"} inactiveDotColor={"#cccccc"} sliderBoxHeight={450} parentWidth={372}
                    images={["https://static.wikia.nocookie.net/cartoons/images/e/ed/Profile_-_SpongeBob_SquarePants.png/revision/latest?cb=20230305115632", "https://static.wikia.nocookie.net/cartoons/images/4/41/Profile_-_Patrick_Star.png/revision/latest/scale-to-width-down/619?cb=20230111062602"]}
                    ImageComponentStyle={{ borderRadius: 15 }}
                  />


                </View>


              </View>
            </>
          ) : (
            <View style={tailwind("h-3/4 rounded-xl")}>
              <Text>no cards</Text>
            </View>
          )}>
        </Swiper>




      </View>


    </SafeAreaView>
  );

Notable Dependencies

    "react-native": "0.71",
    "react-native-deck-swiper": "^2.0.16",
    "react-native-image-slider-box": "megamaxs1234/react-native-image-slider-box",

Object Iteration: use for of loop to iterate over a children object’s properties [closed]

Here are the instructions for the task with two attempts below it. My email is [email protected]

/*Create a function called birdCan, within it, loop over the bird object’s properties and console log each one, using the for…of loop. Finally call the function as birdCan() to see the output on the console. Remember, you need to console log both the key and the value of each of the bird object’s properties.
*/

const animal = {

canJump: true

};

const bird = Object.create(animal);

bird.canFly = true;

bird.hasFeathers = true;

function birdCan(){

let x = Object.entries([bird]);
console.log(x);

}

birdCan();
//the code should look result in the two key: value pairs below when done correctly. My answer(the wrong answer) is below the correct example code
canFly: true
hasFeathers: true
//My answer below
[ [ ‘canFly’, true ], [ ‘hasFeathers’, true ] ]

/*Create a function called birdCan, within it, loop over the bird object’s properties and console log each one, using the for…of loop. Finally call the function as birdCan() to see the output on the console. Remember, you need to console log both the key and the value of each of the bird object’s properties.
*/

const animal = {

canJump: true

};

const bird = Object.create(animal);

bird.canFly = true;

bird.hasFeathers = true;

function birdCan(){

let x = Object.entries([bird]);
console.log(x);

}

birdCan();
//the code should look result in the two key: value pairs below when done correctly. My answer(the wrong answer) is below the correct example code
canFly: true
hasFeathers: true
//My answer below
[ [ ‘canFly’, true ], [ ‘hasFeathers’, true ] ]

Is it possible to modify properties of multiple objects or class instances all at once with one line of code?

In JavaScript (assuming version is >= ES6), say that I have a class;

class MyClass {
  constructor() {
    this.property = null;
  }
}

… and I create two new instances of the class;

let inst1 = new MyClass(), inst2 = new MyClass();

Now, say I want inst1 and inst2‘s property value to true. This can be easily accomplished with

inst1.property = true;
inst2.property = true;

However, if I end up with many instances, reassigning each and every value, a new line each time, the code can get out of hand;

inst1.property = true;
inst2.property = true;
inst3.property = true;
inst4.property = true;
// ...

Now, I know, this is a very bad example, but you can just imagine a better example in its place. I wanted to know if there was any way to modify multiple instances with only one line of code, through something similar to object destructuring. For example,

[inst1, inst2, inst3, inst4].property = true;

I apologize if this is a bad question, but I just noticed my code getting messy with a scenario similar to this, and wondered if there was a solution to it. Thank you for your help.

timer wont stop running in JavaScript

I am making a quiz in JavaScript and I set a timer for the intro page after the timer the question pops up and the intro page disappears but after I answer the first question the second question shows up momentarily and then it’s gone and restarts the webpage all over again, how do I fix this. the code is provided below

the javascript

let timeLeft = 5; // Set the initial countdown time in seconds
let currentQuestionIndex = 0;
let don = false
function countdown() {
    if(don === false){
    if (timeLeft > 0) {
        timeLeft--;
        document.getElementById("countdown").innerText = timeLeft;

        // Check if the continue button was clicked
        const continueButtonClicked = document.getElementById("nextButton").addEventListener("click", function() {
            // Hide the intro section
            document.getElementById("introSection").style.display = "none";
            // Show the question section
            document.getElementById("questionSection").style.display = "block";
            don = true;
            // Start the countdown
            setInterval(countdown, 1000);
        });
    }
    } if (timeLeft == 0) {
        // Time's up, show the "Next" button or perform other actions
        document.getElementById("introSection").style.display = "none";
        // Show the question section
        document.getElementById("questionSection").style.display = "block";
        don = true;
    }
}
let questions = [];
questions.push({ Question: "What school do we go to?", a: "MTU", b: "ATU", c: "CIT", d: "LIT" });
questions.push({ Question: "What is 2 + 2?", a: "3", b: "4", c: "5", d: "6" });

// Display the first question
displayQuestion();

function displayQuestion() {
    let currentQuestion = questions[currentQuestionIndex];
    document.getElementById("question").innerText = currentQuestion.Question;
    document.getElementById("labelA").innerText = currentQuestion.a;
    document.getElementById("labelB").innerText = currentQuestion.b;
    document.getElementById("labelC").innerText = currentQuestion.c;
    document.getElementById("labelD").innerText = currentQuestion.d;
}
function nextQuestion() {
    don = true;
    // Move to the next question
    currentQuestionIndex++;

    // Check if there are more questions
    if (currentQuestionIndex < 3) {
        // Display the next question
        displayQuestion();
    }
}

// Start the countdown
setInterval(countdown, 1000);

the html

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

</head>
<body>
    <div class="start" id="introSection">
        <h1><u>Welcome to my Quiz</u></h1>
        <p class="start-text">Welcome to my client-side scripting Quiz.
            There will be ten questions you will have to answer, and your 
            results will be shown to you after you have finished the Quiz.
            Best of luck!<br><br>
            You can press "Continue" or wait for the page to load on its own.
        </p> 
        <div id="countdown">5</div>
        <button id="nextButton" onclick="startQuiz()">Continue</button>
    </div>

    <div class="question" id="questionSection" style="display:none;">
        <h2 id="question"></h2>
        <form id="quizForm">
        <label><input type="radio" name="answer" value="a" id="optionA"> <span id="labelA"></span></label><br>
            <label><input type="radio" name="answer" value="b" id="optionB"> <span id="labelB"></span></label><br>
            <label><input type="radio" name="answer" value="c" id="optionC"> <span id="labelC"></span></label><br>
            <label><input type="radio" name="answer" value="d" id="optionD"> <span id="labelD"></span></label><br>
        <button id="nextQuestionButton" onclick="nextQuestion()">Next Question</button>
    </form>
    </div>

    <script src="ScriptingFinal.js"></script>
</body>
</html>

Return source documents using langchain agent javascript

I cant seem to figure out how to pass the source_documents over to the agent, i can see that i get the source documents returned from retrievalChain. But it never passes on from there, has anyone here figured out a way to receive source documents in the executor result?

I already have a issue open on the langchainjs github, but have been unable to find a working solution: https://github.com/langchain-ai/langchainjs/issues/3404

I was suggested to create a custom tool, but i can’t seem to create a custom tool without running into types mismatching.

const vectorStore = await Chroma.fromExistingCollection(
  new OpenAIEmbeddings({
    azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
    azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION,
    azureOpenAIApiDeploymentName:
      process.env.AZURE_OPENAI_API_DEPLOYMENT_EMBEDDING_NAME,
    azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME
  }),
  {
    collectionName: chatbotID,
    url: 'url'
  }
)

const retriever = vectorStore.asRetriever()

const model = new ChatOpenAI({
  temperature: 0,
  azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY,
  azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION,
  azureOpenAIApiDeploymentName:
    process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME,
  azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME,
  streaming: true
})

const retrievalChain = new RetrievalQAChain({
  combineDocumentsChain: loadQAStuffChain(model),
  retriever,
  returnSourceDocuments: true
})

const chatHistory = new ChatMessageHistory(previousMessages)

const memory = new OpenAIAgentTokenBufferMemory({
  llm: model,
  memoryKey: 'chat_history',
  outputKey: 'output',
  inputKey: 'input',
  chatHistory
})


const qaTool = new ChainTool({
  name: `state-of-${company}-qa`,
  description: `State of the ${company} QA - useful for when you need to ask questions about ${company}.`,
  chain: retrievalChain,
  returnDirect: true,
  verbose: true
})


const tools = [qaTool, shippingTool]

const executor = await initializeAgentExecutorWithOptions(tools, model, {
  agentType: 'openai-functions',
  memory,
  returnIntermediateSteps: true,
  agentArgs: {
    prefix:
      'insert prompt here'
  }
})


await executor.call(
  {
    input: input
  },
  {
    callbacks: [
      {
        handleLLMNewToken(token: string) {
          res.write(token)
        }
      }
    ]
  }
)

I am using conditional statements to hide and show items in formIO. How can I get this to work with surveys?

For example Survey

How do I get a text field (API name: textName) to appear using the advanced conditional logic? I presume I will need something like this in the text field advanced conditions;

show = (survey.question = starter) && (survey.value = good)

Any help on how I can write this would be amazing! Thanks

P.S Very much new to coding/formIO!

I have tried using the values assigned to each question and value.