After installing react native image picker my working code stoped runing

After installing react native image picker my working code stoped runing and showing many errors of execution errors and compilation errors of some time
task app:compiledebugkotlin failed
then some times
app:ganeratedebugresvalues failed!! and when solving this then many errors come with different names

i simply run the code and my app was working and runing perfectly this all happen after installing react native image picker thus i dont have any solution i need the image pivker bu5 image picker shows errors like this !!

Django messages with javascript fetch() API and redirect

I am doing a request with the fetch() API to a django view, which will set a message with the messages app and redirect the request. I can capture the redirect with response.redirected and the messages-cookie is set, but when i do the redirect with location.replace, the messages get lost.

How do i pass on the messages from the original response?

The django view:

def add(request):

    if request.method != 'POST':
        return HttpResponse("not post")

    pproject = request.POST['pproject']

    print("pproject:", pproject)

    messages.add_message(request, messages.INFO, "Test.")
    return redirect("project_detail")

my urls.py:

    path('project/add/', views_project.add, name='project_add'),

and in my template (javascript):

var csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value;
const headers = new Headers();
headers.append("X-CSRFToken", csrftoken);

const form = new FormData();

form.append("pproject", "{{ project.id }}");

const ops = {
    method: "POST",
    headers: headers,
    body: form,
    credentials: "same-origin"
};

const req = new Request("{% url 'project_add' %}");

fetch(req, ops)
.then((response) => {
    if (response.redirected) {
        console.log("response redirect:", response);

        window.location.replace(response.url);
        return false;

    } else if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    } else {
        return response.json(); // Parse JSON response
    }
})

Issue with Resizing Shapes by Dragging Handles in JavaScript

I’m working on a JavaScript application where I’m implementing functionality to resize shapes by dragging their handles. I’ve encountered an issue with the resizing functionality. Also, when resizing shapes from the top or left handles The position of Shape changed.

const DrawJs = {
    selectedShape: null,
    offsetX: 0,
    offsetY: 0,
    container: null,
    resizing: false,

    init: function (containerId) {
        const container = document.querySelector(containerId);
        this.container = container;
        return container;
    },

    drawRectangle: function (width, height, x, y, color) {
        const shape = document.createElement("div");
        shape.classList.add("resizable-shape");
        shape.style.width = width + "px";
        shape.style.height = height + "px";
        shape.style.left = x + "px";
        shape.style.top = y + "px";
        shape.style.backgroundColor = color;
        this.createHandle("handle-top", shape);
        this.createHandle("handle-bottom", shape);
        this.createHandle("handle-left", shape);
        this.createHandle("handle-right", shape);
        // Add event listeners for drag and drop
        this.draggable(shape);

        this.container.appendChild(shape);
    },
    createHandle: function (handleClass, shape) {
        const handle = document.createElement("div");
        handle.classList.add("resizable-handle", handleClass);

        let isResizing = false;
        let startX, startY, startWidth, startHeight;

        const startResize = (e) => {
            isResizing = true;
            startX = e.clientX;
            startY = e.clientY;
            startWidth = parseInt(document.defaultView.getComputedStyle(shape).width);
            startHeight = parseInt(document.defaultView.getComputedStyle(shape).height);
            document.addEventListener("mousemove", resize);
            document.addEventListener("mouseup", stopResize);
        };

        const resize = (e) => {
            if (isResizing) {
                if (handleClass.includes("right")) {
                    shape.style.width = startWidth + e.clientX - startX + "px";
                } else if (handleClass.includes("bottom")) {
                    shape.style.height = startHeight + e.clientY - startY + "px";
                } else if (handleClass.includes("left")) {
                    const newWidth = startWidth + startX - e.clientX;
                    shape.style.width = newWidth + "px";
                    shape.style.left = startX - newWidth + "px";
                } else if (handleClass.includes("top")) {
                    const newHeight = startHeight + startY - e.clientY;
                    shape.style.height = newHeight + "px";
                    shape.style.top = startY - newHeight + "px";
                }
            }
        };

        const stopResize = () => {
            isResizing = false;
            document.removeEventListener("mousemove", resize);
            document.removeEventListener("mouseup", stopResize);
        };

        handle.addEventListener("mousedown", startResize);
        shape.appendChild(handle);
    },
    draggable: function (element) {
        let isDragging = false;
        let offsetX, offsetY;

        element.addEventListener("mousedown", (e) => {
            if (!this.resizing) {
                isDragging = true;
                const rect = element.getBoundingClientRect();
                offsetX = e.clientX - rect.left;
                offsetY = e.clientY - rect.top;
            }
        });

        document.addEventListener("mousemove", (e) => {
            if (isDragging) {
                const newX = e.clientX - offsetX;
                const newY = e.clientY - offsetY;
                element.style.left = newX + "px";
                element.style.top = newY + "px";
            }
        });

        document.addEventListener("mouseup", () => {
            isDragging = false;
        });
    }
};

const container = DrawJs.init("#container");

window.addEventListener("load", () => {
    DrawJs.drawRectangle(100, 60, 0, 0, "blue");
});
*,
*::after,
*::before {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    height: 100vh;
}


#container {
    width: 100%;
    height: 100%;
}

.resizable-shape {
    position: absolute;
}

.resizable-handle {
    width: 10px;
    height: 10px;
    background-color: #fff;
    position: absolute;
    cursor: pointer;
    border-radius: 50%;
    border: 1px solid #000;
    display: none;
}
.resizable-shape:hover .resizable-handle {
    display: block;
}
.handle-top {
    top: -5px;
    left: 50%;
    cursor: ns-resize;
    transform: translateX(-50%);
}

.handle-bottom {
    bottom: -5px;
    left: 50%;
    cursor: ns-resize;
    transform: translateX(-50%);
}

.handle-left {
    top: 50%;
    left: -5px;
    transform: translateY(-50%);
    cursor: ew-resize;
}

.handle-right {
    top: 50%;
    right: -5px;
    transform: translateY(-50%);
    cursor: ew-resize;
}
<div id="container"></div>

Expectation: I’m seeking guidance on how to properly adjust the position of the shape when resizing from handles to ensure it maintains its position relative to the handle being dragged.

Switching variables in a function based on user input

I am trying to compare two DNA sequences with wobbles and report mismatches. Here !N in if() condition corresponds to the declared array N. I have to manually edit this each time to change it to !R, !Y, or !K etc in the condition.

           const R = ['A','G'];
           const Y = ['C','T'];
           const K = ['G','T'];
           const N = ['A','G','C','T'];
           const wob = ['R','Y','K','M','S','W','N']

        let mismatchPositions = [];
        for (let i = 0; i < referenceLength; i++) {
        
          if ( !N.includes(seq.sequence[i]) && wob.includes(referenceSeq[i]) 
          && referenceSeq[i] !== seq.sequence[i]) {
            const mismatch = `(${i+1} ${referenceSeq[i]} > ${seq.sequence[i]})`;
            mismatchPositions.push(mismatch);
          }
                     
          else if(!wob.includes(referenceSeq[i]) && referenceSeq[i] !== seq.sequence[i]) {
          const mismatch = `(${i+1} ${referenceSeq[i]} > ${seq.sequence[i]})`;
            mismatchPositions.push(mismatch);
            } 

I tried putting all the arrays in one variable with flat() but it loses its functionality because there are same bases in few of the wobbles. Is there any way to individually switch the arrays in if() condition from !N to !R and so. I want it make as a user input variable

vue FormData.entries not provided by submit

I have a little Vue-App with a form and only one <input name"surname"> and <button type="submit">.
Use case: input “myname” and submit.

Init new FormData() with uploaded form doesn’t has entries.

// template.html

<form @submit.prevent="handleFormSubmit">
  <input type="text" name="surname" />
  <button type="submit">Save</button>
</form>
// form.ts
...
import tpl from "./template.html"

export default defineComponent({
  template: tpl,
  ...
  methods: {
    handleFormSubmit(event:SubmitEvent)
    {
      console.log(event.target); // log: <form>...</form>
      console.log(event.target.querySelector('input').value); // log: myname
      const formData = new FormData(event.target);
      console.log([...formData.entries()]) // log: []
    }
  } 
})

Why new FormData(event.target) does not catch the value of my input?

How to reverse the open up animation of content view on click

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Move and Open Orange Rectangles</title>
    <style>
    /* CSS to style the rectangles */
    .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    }

    .rectangle {
    width: 100px;
    height: 50px;
    background-color: orange;
    position: absolute; /* Set position to absolute */
    border-radius: 10px; /* Adjust border radius for rectangle shape */
    transform: rotate(90deg); /* Rotate rectangles by 90 degrees */
    transform-origin: center; /* Set transform origin to the center */
    transition: left 0.5s; /* Add transition for smooth movement */
    cursor: pointer; /* Change cursor to pointer when hovering over rectangles */
    }
    </style>
    </head>
    <body>

    <!-- HTML to create the rectangles -->
    <div class="container" onclick="moveRectangles(event)">
      <div class="rectangle" style="left: 0px;"></div>
      <div class="rectangle" style="left: 0px;"></div>
     <div class="rectangle" style="left: 0px;"></div>
    <div class="rectangle" style="left: 0px;"></div>
    <div class="rectangle" style="left: 0px;"></div>
    <div class="rectangle" style="left: 0px;"></div>
    </div>

    <script>
     function moveRectangles(event) {
     var rectangles = document.querySelectorAll('.rectangle');
     var gap = 5; // Gap between rectangles
     var distance = 100; // Distance to move each rectangle
    
      // Check if the click target is a rectangle
      if (event.target.classList.contains('rectangle')) {
      // Move the rectangles to the left to create a gap
      for (var i = 0; i < rectangles.length; i++) {
        rectangles[i].style.left = (i * -(distance + gap)) + 'px';
      }
      } else {
        // Reset the position of all rectangles to 0
        for (var i = 0; i < rectangles.length; i++) {
        rectangles[i].style.left = '0px';
        }
        }
    
       // Prevent click event from bubbling up to the body
      event.stopPropagation();
    }
     </script>

     </body>
     </html>
    

I tried like making the function such that when someone clicks the blank space other than rectangle then the animation should be reversed but im not getting hold of the function on reversing it cause it just sits without doing anything. Like if i click first on the rectangle then then normally it opens or rises up anything u want to call to the left then it should reverse that action when i click the blank space.

It should be like this :
these are the steps of the whole animation

Google one tap sign in behaves differently in Chrome

I recently implemented Google One Tap sign-in functionality in our website, and it seems to be functioning smoothly overall. However, during testing, I encountered an issue that I hope someone can assist me with.

Observations:

In Chrome Browser:
When I’m not logged into my Google account and visit our site, the Google One Tap sign-in prompt fails to appear.

In Safari and Firefox Browsers:
Contrastingly, when I’m not logged into my Google account and visit our site, the Google One Tap sign-in prompt displays.

Ofcourse, in all 3 browsers if I’m logged in to my Google account and visit our site, the Google one Tap sign-in prompt displays.

Is it typical for Chrome to behave differently compared to Safari and Firefox? Or should I revisit my JavaScript function?

VideoJs, dynamic content creation on working: Cannot read properties of undefined (reading ‘name’)

I am creating HTML Dom element through the Javascript that uses the VideoJs element creation but it does not work.
Same html code works in normal html file, but when creating through js it does not seem to get work.

  let dom: DOMFactoryElement;
dom = {
      tagName: 'div',
      className: ['swiper-slide'],
      children: [
        {
          tagName: 'div',
          className: [
            'swiper-zoom-container',
            darkMode ? 'canon-bg--grey-darkest' : 'canon-bg--grey-lightest',
            image.paddingReq ? 'py-3' : 'py-0',
            image.paddingReq ? 'px-4' : 'px-0',
          ],
          children: [
            {
              tagName: 'div',
              className: ['snap-media', 'position-relative'],
              attributes: { 'data-pure': '' },
              children: [
                {
                  tagName: 'div',
                  className: ['responsive-video__video-element', 'video-autoplay', 'h-100'],
                  children: [
                    {
                      tagName: 'div',
                      className: ['responsive-video__placeholder', 'responsive-video__placeholder--autoplay'],
                      attributes: {
                        'data-account-id': image?.accountId,
                        'data-player-id': image?.playerId,
                        'data-video-id': image?.videoId,
                        'data-poster': image?.stillImageUrl,
                        'data-loop': '',
                      },
                    },
                  ],
                },
                {
                  tagName: 'div',
                  className: [
                    'position-absolute',
                    'snap-media-content',
                    'standard-article__media-hero__media-controls',
                  ],
                  children: [
                    {
                      tagName: 'div',
                      className: 'snap-media__controls-list',
                      attributes: {
                        'data-control-audio': '',
                        'data-control-play': '',
                      },
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    };
const factory: DOMFactory = new DOMFactory(dom);

  return factory.element;

This generate the html of the div as mentioned but nothing works, its just empty div with audio and player id etc given to it
and I received this error:

VIDEOJS: ERROR: TypeError: Cannot read properties of undefined (reading 'name')
    at a.e [as getCustomDimensionValuesFromPlayer]

Form and dynamically generated button JavaScript not working

I am facing a problem with a form on my website. I have a form that works correctly when it exists on the page initially, but when I try to dynamically generate this form via JavaScript, the form does not perform any action when submitted.

When you press the button <button type="submit" class="generate-btn">Generate IA</button> it does not do any action

My form has the following structure:

     segundoDiv.innerHTML = '';
    
           var nuevoElemento = document.createElement('section');
                nuevoElemento.className = 'image-generator';
                nuevoElemento.innerHTML = `
                    <div class="content">
                        <form action="#" class="generate-form">
                            <input class="prompt-input" type="text" placeholder="Describe what you want to see" required>
                            <div class="controls">
                                <button type="submit" class="generate-btn">Generate IA</button>
                            </div>
                        </form>
            </div>
                  <section class="image-gallery">
    <div class="img-card hiddenia"><img src="images/img-1.jpg" alt="image"></div>
  
  </section>`;
    
        // Agregar el nuevo elemento dentro del segundo div
        segundoDiv.appendChild(nuevoElemento);`

This is the script that does not run:

<script>
const generateForm = document.querySelector(".generate-form");
const generateBtn = generateForm.querySelector(".generate-btn");
const imageGallery = document.querySelector(".image-gallery");

const OPENAI_API_KEY = "12345678910"; // Your OpenAI API key here
let isImageGenerating = false;

const updateImageCard = (imgDataArray) => {
  imgDataArray.forEach((imgObject, index) => {
    const imgCard = imageGallery.querySelectorAll(".img-card")[index];
    const imgElement = imgCard.querySelector("img");
    const downloadBtn = imgCard.querySelector(".download-btn");
        imgCard.classList.remove("hidden");

    // Set the image source to the AI-generated image data
    const aiGeneratedImage = `data:image/jpeg;base64,${imgObject.b64_json}`;
    imgElement.src = aiGeneratedImage;
    
    // When the image is loaded, remove the loading class and set download attributes
    imgElement.onload = () => {
      imgCard.classList.remove("loading");
      downloadBtn.setAttribute("href", aiGeneratedImage);
      downloadBtn.setAttribute("download", `${new Date().getTime()}.jpg`);
    }
  });
}

const generateAiImages = async (userPrompt, userImgQuantity) => {
  try {
    // Send a request to the OpenAI API to generate images based on user inputs
    const response = await fetch("https://api.openai.com/v1/images/generations", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${OPENAI_API_KEY}`,
      },
      body: JSON.stringify({
        prompt: userPrompt,
        n: 1,
        size: "1024x1024",
        response_format: "b64_json"
        
      }),
    });

    // Throw an error message if the API response is unsuccessful
    if(!response.ok) throw new Error("Failed to generate AI images. Make sure your API key is valid.");

    const { data } = await response.json(); // Get data from the response
    updateImageCard([...data]);
  } catch (error) {
    alert(error.message);
  } finally {
    generateBtn.removeAttribute("disabled");
    generateBtn.innerText = "Generate";
    isImageGenerating = false;
  }
}

const handleImageGeneration = (e) => {
  e.preventDefault();
  if(isImageGenerating) return;

  // Get user input and image quantity values
  const userPrompt = e.srcElement[0].value;
  const userImgQuantity = 1;
  
  // Disable the generate button, update its text, and set the flag
  generateBtn.setAttribute("disabled", true);
  generateBtn.innerText = "Generating";
  isImageGenerating = true;
  
  // Creating HTML markup for image cards with loading state
  const imgCardMarkup = Array.from({ length: userImgQuantity }, () => 
      `<div class="img-card loading">
        <img src="images/loader.svg" alt="AI generated image">
        <a class="download-btn" href="#">
          <img src="images/download.svg" alt="download icon">
        </a>
      </div>`
  ).join("");

  imageGallery.innerHTML = imgCardMarkup;
  generateAiImages(userPrompt, userImgQuantity);
}

generateForm.addEventListener("submit", handleImageGeneration);</script>

I thank you for your helP

The script is not executeD

I am getting this error related to the array of variants array

I encountered the following error message while updating an array in MongoDB using Mongoose:

Cast to embedded failed for value "{ name: [ 'Regular' ], cals: [ '200' ], price: [ '20' ] }" (type Object) at path "variants" because of "CastError

// Relevant State Initialization
const [variant, setVariant] = useState([]);
const [variantCals, setVariantCals] = useState([]);
const [variantPrice, setVariantPrice] = useState([]);
const [id, setId] = useState(null);

// Handling Save Function
const handleSave = async () => {
    // Constructing variantObjects
    const variantObjects = variant.map((name, index) => ({
        name,
        cals: variantCals[index] || 0,
        price: variantPrice[index] || 0,
    }));

    // Constructing formDataToSend
    const formDataToSend = new FormData();
    formDataToSend.append('protein', formData.protein);
    for (let i in variantObjects) {
        formDataToSend.append(`variants[${i}][name]`, variantObjects[i].name);
        formDataToSend.append(`variants[${i}][cals]`, variantObjects[i].cals);
        formDataToSend.append(`variants[${i}][price]`, variantObjects[i].price);
    }
    
    // Update operation
    await updateProtein(id, formDataToSend);

    // Resetting form data and state
    setFormData({
        price: '',
        calories: '',
        protein: ''
    });
    setVariant([]);
    setVariantCals([]);
    setVariantPrice([]);
    setSelectedImage(null);
};

<div className="form-group">
                                                    <label htmlFor="exampleInputEmail1">Variants</label>
                                                    <TagsInput value={variant} onChange={handleVariantChange} inputProps={variantProps} className='border-none'  />
                                                    <span className="text-danger">{formErrors.variants}</span>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="exampleInputEmail1">Calories</label>
                                                    <TagsInput value={variantCals} onChange={handleVariantCalChange} inputProps={calProps} className='border-none'  />
                                                    <span className="text-danger">{formErrors.variantCals}</span>
                                                </div>
                                                <div className="form-group">
                                                    <label htmlFor="exampleInputEmail1">Price</label>
                                                    <TagsInput value={variantPrice} onChange={handleVariantPriceChange} inputProps={priceProps} className='border-none'  />
                                                    <span className="text-danger">{formErrors.variantPrice}</span>
                                                </div>

I am Using React with react-tagsinput.
I am Attempting to update an array field (variants) in MongoDB via Mongoose.
variant, variantCals, and variantPrice are arrays managed by state in React.

How do I use the data from a get request with axios? [duplicate]

When I try to use variables from outside of the function i get: Uncaught ReferenceError: fetchArray is not defined. But it works without trouble in a fetch get request

getWithAxios() {
        axios.get('https://rickandmortyapi.com/api/character/' + this.randomArray)
          .then(function (response) {

          console.log(response.data);

          this.fetchArray = response.data

        })
      }

Dynamic Pricing using BigCommerce

I’m working with BigCommerce and I have a product banner with dynamic pricing based on user input for width (w) and height (h). However, BigCommerce doesn’t seem to provide any built-in functionality for dynamic pricing based on custom inputs.

Does anyone have suggestions on how I can implement this functionality using the BigCommerce API or perhaps through a plugin or custom development? Any insights or guidance would be greatly appreciated. Thank you!

TypeError: Illegal invocation when calling getBoundingClientRect() on Proxy

A simple code in JavaScript that shows the issue

const obj = document.body;
const proxy = new Proxy(obj, {});
proxy.getBoundingClientRect();     // Uncaught TypeError: Illegal invocation

How to access element’s properties when object is proxified by third-party component (e.g. React’s useRef which is then passed to ant design Table)?

const tableRef = useRef(undefined);
<Table ref={tableRef} />