Why is my Chess.js board in React not shown?

I am trying to build a simple chess website in IntelliJ by using React in Vite. I have just begun the project and for now I just want a web page, where a chess board with all the figuers in the starting position are shown.

This is my App.jsx

function App() {

    return <Chessboard position={"start"} />;
}
export default App;

This is my main.jsx

import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <App />
  </StrictMode>,
)

This is my index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="src/main.jsx" ></script>

  </body>
</html>




This is my vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
export default defineConfig({
  plugins: [react()],
})

This is my App.css

#root {
  max-width: 1280px;
  margin: 0 auto;
  padding: 2rem;
  text-align: center;
}

.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
  transition: filter 300ms;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
  filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@media (prefers-reduced-motion: no-preference) {
  a:nth-of-type(2) .logo {
    animation: logo-spin infinite 20s linear;
  }
}

.card {
  padding: 2em;
}

.read-the-docs {
  color: #888;
}

With these I just get an empty page in Google Chrome or Edge but without any error or warning in the console. The board does not appear.

Odoo 18 (js): How to extend the native payment_paypal module to activate the PayLater feature?

I am trying to figure out how to extend the js class of the native module payment_paypal, so that the PayLater option, that i have activated in PayPal get activated.

In the native js code in /addons/payment_paypal/…/payment_form.js:


import paymentForm from '@payment/js/payment_form';

paymentForm.include({
//...
//...
    async _prepareInlineForm(providerId, providerCode, paymentOptionId, paymentMethodCode, flow) {
        if (providerCode !== 'paypal') {
            this._super(...arguments);
            return;
        }

        this._hideInputs();
        this._setPaymentFlow('direct');
        document.getElementById('o_paypal_button').classList.remove('d-none');
        document.getElementById('o_paypal_loading').classList.remove('d-none');
        // Check if instantiation of the component is needed.
        this.paypalData ??= {}; // Store the component of each instantiated payment method.
        const currentPayPalData = this.paypalData[paymentOptionId]
        if (this.selectedOptionId && this.selectedOptionId !== paymentOptionId) {
            this.paypalData[this.selectedOptionId]['paypalButton'].hide()
        }
        if (currentPayPalData && this.selectedOptionId !== paymentOptionId) {
            const paypalSDKURL = this.paypalData[paymentOptionId]['sdkURL']
            const paypalButton = this.paypalData[paymentOptionId]['paypalButton']
            await loadJS(paypalSDKURL);
            paypalButton.show();
        }
        else if (!currentPayPalData) {
            this.paypalData[paymentOptionId] = {}
            const radio = document.querySelector('input[name="o_payment_radio"]:checked');
            if (radio) {
                this.inlineFormValues = JSON.parse(radio.dataset['paypalInlineFormValues']);
                this.paypalColor = radio.dataset['paypalColor']
            }

            // https://developer.paypal.com/sdk/js/configuration/#link-queryparameters
            const { client_id, currency_code } = this.inlineFormValues
            const paypalSDKURL = `https://www.paypal.com/sdk/js?client-id=${
                client_id}&components=buttons&currency=${currency_code}&intent=capture`
            await loadJS(paypalSDKURL);
            const paypalButton = paypal.Buttons({ // https://developer.paypal.com/sdk/js/reference
                fundingSource: paypal.FUNDING.PAYPAL,
                style: { // https://developer.paypal.com/sdk/js/reference/#link-style
                    color: this.paypalColor,
                    label: 'paypal',
                    disableMaxWidth: true,
                    borderRadius: 6,
                },
                createOrder: this._paypalOnClick.bind(this),
                onApprove: this._paypalOnApprove.bind(this),
                onCancel: this._paypalOnCancel.bind(this),
                onError: this._paypalOnError.bind(this),
            });
            this.paypalData[paymentOptionId]['sdkURL'] = paypalSDKURL;
            this.paypalData[paymentOptionId]['paypalButton'] = paypalButton;
            paypalButton.render('#o_paypal_button');
        }
        document.getElementById('o_paypal_loading').classList.add('d-none');
        this.selectedOptionId = paymentOptionId;
    },

In my custom module payment_paypal_custom, if i try to extend this js class using paymentForm.include to override the function _prepareInlineForm in order to add parameters in the sdkURL, the native function of the payment_paypal module will be loaded anyway, so that paypal sdk will be loaded twice. And i can not override complettely this function without calling _super(), because _super() enables the loading of the other payment methods too (Stripe…)!

Any idea how to extend it the right way ?

why is head and tail pointing to null after popping last element in my linkedlist class’s pop method in JS

i’m learning DSA for js through udemy. i resorted to asking this question here and not heading towards chatgpt because im still old frashioned in learning and not convinced that AI helps in learning but just makes us lazy. Hence i’m here, you see i’m learning LinkedLists now and im working those examples in udemy editor. And i have stumbled in pop method as i’m failing in their tests repeatedly. my code is like this

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;

  }
}
class LinkedList {
  constructor(value) {
    const newNode = new Node(value);
    this.head = newNode;
    this.tail = this.head;
    this.length = 1;
  }
  printList() {
    let temp = this.head;
    while (temp !== null) {
      console.log(temp.value);
      temp = temp.next;

    }
  }
  getHead() {
    if (this.head === null) {
      console.log("Head: null");
    } else {
      console.log("Head: " + this.head.value);
    }
  }
  getTail() {
    if (this.tail === null) {
      console.log("Tail: null");
    } else {
      console.log("Tail: " + this.tail.value);
    }
  }
  getLength() {
    console.log("Length: " + this.length);
  }
  makeEmpty() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
  push(value) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;

      this.tail = newNode;
    }
    this.length++;
    return this;
  }
  pop() {
    let temp = this.head;
    if (!this.head) {
      return undefined;
    }
    let pre = temp;
    while (temp.next) {
      pre = temp;
      temp = temp.next;

    }
    this.tail = pre;
    this.tail.next = null;
    temp.next = null;
    this.length--;
    return temp;
  }
}


let myLinkedList = new LinkedList(1);

myLinkedList.push(2);
// (2) Items in LL - Returns 2 Node

if (myLinkedList.length !== 0) {
  console.log(myLinkedList.pop().value);
} else {
  console.log("null");
}

// (1) Item in LL - Returns 1 Node
if (myLinkedList.length !== 0) {
  console.log(myLinkedList.pop().value);
} else {
  console.log("null");
}

// (0) Items in LL - Returns null
if (myLinkedList.length !== 0) {
  console.log(myLinkedList.pop().value);
} else {
  console.log("null");
}
/*
    EXPECTED OUTPUT:
    ----------------
    2
    1
    null
*/

the failed test message is like this:
here is the error message:
 https://ibb.co/wZDKBMrM

How fast does the entire site load? [closed]

Our projects are based on WordPress. We founded a group of projects called USS GROUP which unites three platforms, my colleagues and I also achieved significant progress in modernizing both the external style of the projects and completely changing the standard engine code for the sites: uastend.com, usiic.co, uss.eu.com.

Now our platforms have an original style, added an internal currency UASTCOIN for monetizing content for authors, which is important the coin is changeable and its value reacts to activity on the sites, created a plugin that allows you to subscribe and track a specific author by email subscription. We still have a lot of work and ideas ahead.It is very important for us to understand how quickly our sites load and how useful they are for the audience, what else needs to be improved?

Issue with dependencies in react native

I am having an issue installing a react-native project.
I can’t add some options in console because script is running in expo.dev (remote server)

npm error While resolving: @react-navigation/[email protected]
npm error Found: [email protected]
npm error node_modules/react-native
npm error   react-native@"0.79.3" from the root project
npm error   peer react-native@"*" from @expo/[email protected]
npm error   node_modules/@expo/metro-runtime
npm error     peerOptional @expo/metro-runtime@"*" from [email protected]
npm error     node_modules/expo
npm error       expo@"53.0.10" from the root project
npm error       27 more (expo-application, expo-asset, expo-blur, expo-constants, ...)
npm error     @expo/metro-runtime@"5.0.4" from [email protected]
npm error     node_modules/expo-router
npm error       expo-router@"~5.0.7" from the root project
npm error   35 more (@expo/vector-icons, ...)
npm error
npm error Could not resolve dependency:
npm error peer react-native@"0.79.2" from @react-navigation/[email protected]
npm error node_modules/@react-navigation/drawer
npm error   @react-navigation/drawer@"*" from the root project
npm error   peerOptional @react-navigation/drawer@"^7.3.9" from [email protected]
npm error   node_modules/expo-router
npm error     expo-router@"~5.0.7" from the root project
npm error
npm error Conflicting peer dependency: [email protected]
npm error node_modules/react-native
npm error   peer react-native@"0.79.2" from @react-navigation/[email protected]
npm error   node_modules/@react-navigation/drawer
npm error     @react-navigation/drawer@"*" from the root project
npm error     peerOptional @react-navigation/drawer@"^7.3.9" from [email protected]
npm error     node_modules/expo-router
npm error       expo-router@"~5.0.7" from the root project
npm error

The details does not expand to full size when dynamically generated

I am making a menu, and as suggested by members here. As can be seen in the first code snippet the menu does not resize to its full size. But all the elements are correctly filled with elements. attributes and text content. I am trying to make it fully javascript generated.

   class GLMenuTemplate
   {
      #style_id    = "webgl_menu_template_style";
      #template_id = "webgl_menu_template";
      #webgl_css   = `
        div.webgl_menu /*element.class*/
        {
           position:absolute;z-index:10;border:1px solid black;
        }
        div.webgl_menu  summary /*element.class elements*/
        {
           background-color: #eee;
           width:            1.3em;
           height:           1.3em;
           border:           solid black thin;
           border-radius:    .3em;
           padding:          0;
           margin:           0;
           align-content:    center;
           text-align:       center;
           cursor:           pointer;
        }
        div.webgl_menu  summary::marker  {  content: "+"; } /*element.class elements*/
        div.webgl_menu  summary:hover { background-color:#ddd; }
        div.webgl_menu  details[open] summary::marker { content: "x"; }`;

      constructor ()
      {
         this.#styleInit();
         this.#templateInit();
      }
      get template () {return document.getElementById(this.#template_id);}
      #styleInit()
      {
         if (document.getElementById (this.#style_id)) return;
         let style = document.createElement("style");
         style.setAttribute ("id", this.#style_id);
         style.innerText = this.#webgl_css;
         document.body.appendChild(style);
      }
      #templateInit()
      {
         if (document.getElementById (this.#template_id)) return;
         let div = this.#createDiv();
         let tr  = this.#createTr();
         let template = this.#createTemplate (this.#template_id, [div, tr]);
         document.body.appendChild(template);
      }
      #createElement(elementName, children)
      {
         let element = document.createElement (elementName);
         if (children) 
            for (let child of children)
               element.appendChild (child);
         return element;
      }
      #createTemplate(id, contents)
      {
         let template = document.createElement("template");
         template.setAttribute ("id", id);
         document.body.appendChild(template);
         if (contents)
            for (let content of contents)
               template.content.appendChild(content);
         return template;
      }
      #createDiv()
      {
         //template for menu item <tr><td><label><input>
         let summary = document.createElement ("summary");
         let table   = document.createElement ("table");
         //table.appendChild(tr);
         let details = this.#createElement ("details", [summary, table]);
         let div     = this.#createElement ("div", [details]);
         div.setAttribute ("class", "webgl_menu");
         return div;
      }
      #createTr ()
      {
         let label = this.#createElement ("label");
         let td    = this.#createElement ("td",    [label] );
         let tr    = this.#createElement ("tr",    [td]);
         return tr;
      }

   }
   class GLMenu
   {
      #x = 0xffff; #y = 0xffff;
      #rowt    = null;
      #items   = null;
      #tpl     = null;
      constructor (x, y, relativeElement)
      {
         let menuTemplate =  new GLMenuTemplate();
         this.#template = menuTemplate.template;
         [this.#x, this.#y] = [window.scrollX + x, window.scrollY + y];
         if (relativeElement)
         {
            let r = relativeElement.getBoundingClientRect();
            this.#x += r.left;
            this.#y += r.top;
         }

         let divt = {div: this.#template.content.querySelector("div")};
         let dive = {div: document.importNode(divt.div, true)};
         [dive.div.style.top, dive.div.style.left] = [this.#y, this.#x];
         document.body.appendChild(dive.div);

         this.#rowt  = {tr: this.#template.content.querySelector("tr")};
         this.#items = dive.div.querySelector ("table");

      }
      
      set #template(value) { this.#tpl = value; }
      get #template()      { return this.#tpl; }

      attachEventListeners(element, listeners)
      {
         if (!listeners) return;
         if (typeof listeners  === "function")
         {
            element.addEventListener ("click", listeners);
            return;
         }
         if (Array.isArray(listeners))
         {
            for (let listener of listeners)
               element.addEventListener (listener.name, listener.callback);
            return;
         }
         element.addEventListener (listeners.name, listeners.callback);
      }
      addCheckbox (text, events)
      {
         let input = document.createElement ("input");
         input.setAttribute ("type", "checkbox");
         input.textContent = text;
         this.attachEventListeners (input, events);

         let rowe  = {tr: document.importNode(this.#rowt.tr, true)};
         let label = rowe.tr.querySelector("label");
         label.appendChild (input);
         rowe.tr.appendChild (label);
         this.#items.appendChild (rowe.tr);
         return input;
      }
   }

   document.addEventListener('DOMContentLoaded',
         (event) =>
         {
            let canvas = document.getElementById("cone1 heart geometry 2");
            // Menu 1
            let menu1 = new GLMenu(10, 10, canvas);
            menu1.addCheckbox ("write to console",    [{name:"click", callback: (e) => 
               {
                  console.log (e.target.textContent  + ": checked:" + e.target.checked); 
               }}]   );
            menu1.addCheckbox ("don't write to console",    (e) => 
               {
                  console.log (e.target.textContent  + ": don't, checked:" + e.target.checked); 
               }   );
            //Menu 2
            let menu2 = new GLMenu(100, 100, canvas);
            menu2.addCheckbox ("write to console 2",    {name:"click", callback: (e) => 
               {
                  console.log (e.target.textContent  + ": 2 checked:" + e.target.checked); 
               }}   );
            menu2.addCheckbox ("don't write to console 2",    (e) => 
               {
                  console.log (e.target.textContent  + ": don't 2, checked:" + e.target.checked); 
               }   );

         }
      );

Here is an earlier version of above program, which works correctly. First difference, the <template is statically included in html code, also there is a preinitialized <tr> in the table. Also the <tr> in dynamic variant above is added outside table, so the table will be empty when imported from template.

     document.addEventListener('DOMContentLoaded',
        (event) =>
        {
           let template = document.getElementById("webgl_menu_template");
           let divt = {div: template.content.querySelector("div")};
           let dive = {div: document.importNode(divt.div, true)};
           [dive.div.style.top, dive.div.style.left] = [10, 10];
           document.body.appendChild(dive.div);
        }
     );
div.webgl_menu /*element.class*/
              {
                 position:absolute;z-index:10;border:1px solid black;
              }
              div.webgl_menu  summary /*element.class elements*/
              {
                 background-color: #eee;
                 width:            1.3em;
                 height:           1.3em;
                 border:           solid black thin;
                 border-radius:    .3em;
                 padding:          0;
                 margin:           0;
                 align-content:    center;
                 text-align:       center;
                 cursor:           pointer;
              }
              div.webgl_menu  summary::marker  {  content: "+"; } /*element.class elements*/
              div.webgl_menu  summary:hover { background-color:#ddd; }
              div.webgl_menu  details[open] summary::marker { content: "x"; }
   <template id="webgl_menu_template">
      <div class="webgl_menu">
        <details>
           <summary ></summary>
           <table>
              <tr> <td><label><input type="checkbox">Show line</input></label></td> </tr>
           </table>
        </details>
      </div>
   </template>

My Google Apps Script Works Perfectly with Only Two Exceptions

My name is Robert, and I am middle school math teacher who is attempting to use a Google Apps Script to create Google Forms quizzes and tests from Google Sheets data starting with the following school year.

function createQuizFromSheet() {
  // Get the active spreadsheet and sheet
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  const quizTitle = sheet.getName();
  // Get all the data from the sheet, skipping the header row
  const data = sheet.getDataRange().getValues().slice(1);

  // Create a new Google Form
  const form = FormApp.create(quizTitle);
  form.setIsQuiz(true); // Turn the form into a quiz

  // Loop through each row of data (each question)
  data.forEach(row => {
    // Extract question details from the row
    const questionTitle = row[0];
    const choices = row.slice(1, 5); // Choices A-D
    const correctAnswerLetter = row[5];
    const points = row[6];

     // Convert the letter to index for correct choice
    let correctAnswerIndex = 0;
    if (correctAnswerLetter === "B") correctAnswerIndex = 1;
    if (correctAnswerLetter === "C") correctAnswerIndex = 2;
    if (correctAnswerLetter === "D") correctAnswerIndex = 3;


    // Add multiple choice question to the form
    const item = form.addMultipleChoiceItem()
      .setTitle(questionTitle);

     // Create choices, mark the correct one and set points
    const choiceItems = [];
    for(let i = 0; i< choices.length; i++){
      if (choices[i]){ //only create if the choice is not blank
        choiceItems.push(item.createChoice(choices[i], i === correctAnswerIndex));
      }
    }
    item.setChoices(choiceItems);
    item.setPoints(points);
  });


  // Get and log the form's published URL
  const formUrl = form.getPublishedUrl();
  Logger.log('Form URL: ' + formUrl);

  // Optional: Display form URL in the spreadsheet
  // sheet.getRange(1, 8).setValue('Form URL'); // Set header
  // sheet.getRange(2, 8).setValue(formUrl); // Output URL
}

I want you to know my Google Apps Script Works Perfectly with two exceptions. (Exception 1): The script doesn’t publish the url of the new Google Forms assessment. Therefore, I can only access the form from my Google Drive. (Exception 2): If you click the attached Google Form, you will see the script tried to add another question after Problem 14 referred to as “Question” with an “Option 1” choice. If the script is reading Columns I through L, I am wondering whether or not there is a way to program the script to ignore that data. Any assistance you can provide will be greatly appreciated. I provided you with the attached links to my Google Forms assessment; my Google Sheets data and the Apps Script for your reference.Google Forms AssessmentGoogle Sheets DataGoogle Apps Script

Robert

Frida Interceptor not triggering on JNI method registered via RegisterNatives (libnative-lib.so)

I’m analyzing an Android application that uses native methods via a shared library libnative-lib.so. Here’s the relevant Java code:



static {

    System.loadLibrary("native-lib");

}



public final native byte[] f(Context context, String m5);

public final native String m(Context context, int p02, int p12);

After decompiling libnative-lib.so using Ghidra, I found only one exported symbol: JNI_OnLoad(). No symbols for f() or m() were present, which made me suspect that the native methods are registered dynamically via RegisterNatives.

Here’s a snippet of the JNI_OnLoad implementation in Ghidra:



undefined4 JNI_OnLoad(long *param_1) {

  ...

  iVar2 = (**(code **)(*local_40 + 0x6b8))(local_40, lVar3, &DAT_001cc108, 5);

  ...

}

I copied a Frida script to hook RegisterNatives and extract the names and addresses of the registered native methods:



let addrRegisterNatives = null;

Process.enumerateModules().forEach(function (m) { 

    Module.enumerateSymbolsSync(m.name).forEach(function (s) { 

        if (s.name.includes("RegisterNatives") && (!s.name.includes("CheckJNI"))) { 

            console.log(m.name, s.name);

            addrRegisterNatives = s.address;

        } 

    });

});



setTimeout(() => {

    Interceptor.attach(addrRegisterNatives, {

        onEnter: function (args) {

            var nMethods = parseInt(args[3]);

            console.log("n[+] env->RegisterNatives()");

            console.log("tNumber of methods:", nMethods);



            var class_name = Java.vm.tryGetEnv().getClassName(args[1]);

            console.log("tClass name:", class_name);



            var methods_ptr = ptr(args[2]);

            for (var i = 0; i < nMethods; i++) {

                var base = methods_ptr.add(i * Process.pointerSize * 3);

                var methodName = Memory.readCString(Memory.readPointer(base));

                var sig = Memory.readCString(Memory.readPointer(base.add(Process.pointerSize)));

                var fnPtr = Memory.readPointer(base.add(Process.pointerSize * 2));

                console.log(`ttMethod: ${methodName}, Signature: ${sig}, Address: ${fnPtr}`);

            }

        }

    });

}, 2000);

This successfully logs the method names f() and m(), their signatures, and function pointers.

The problem is now that I have the function pointer for m(), I tried hooking it using the following script:



setTimeout(() => {

    Java.perform(function () {

        const NATIVE_OFFSET = 0x14610c; // offset from base

        const libName = "libnative-lib.so";

        const libBase = Module.findBaseAddress(libName);

        if (libBase) {

            const nativeFuncPtr = libBase.add(NATIVE_OFFSET);

            Interceptor.attach(nativeFuncPtr, {

                onEnter: function (args) {

                    console.log("[+] Native m() called!");

                    console.log(`arg1 (this): ${args[0]}`);

                    console.log(`arg2 (context): ${args[1]}`);

                },

                onLeave: function (retval) {

                    console.log(`[+] Native m() returned: ${retval}`);

                }

            });

        } else {

            console.error(`[-] Could not find ${libName}`);

        }

    });

}, 5000);

But no output at all is printed — not even the initial log statement. I’m sure the method is being called at runtime.

Attempting to draw in a word document with a Microsoft Word addin using vscode

I’m a total newbie taking my first steps in developing a Word Addin using vscode and javascript. I’ve used this example that I’m trying to expand on:
https://github.com/OfficeDev/Office-Add-in-samples/tree/main/Samples/word-get-started-with-dev-kit

My requirement is that want the plugin to automatically draw lines in certain areas of an existing document, so I’m simply trying to learn how to draw in Word through an Addin. I’ve modified the taskpane.js file as follows in order to try:

Office.onReady((info) => {
  if (info.host === Office.HostType.Word) {
    document.getElementById("sideload-msg").style.display = "none";
    document.getElementById("app-body").style.display = "flex";
    document.getElementById("run").onclick = run;
  }
});

export async function run() {
  return Word.run(async (context) => {
    // Insert a paragraph at the end of the document.
    const paragraph = context.document.body.insertParagraph("Hello Wonderful World", Word.InsertLocation.end);

    // Change the paragraph color to blue.
    paragraph.font.color = "blue";

// Start new part

    // Insert a drawing canvas
    const canvas = context.document.body.insertParagraph("").insertDrawingCanvas(0, 0, 200, 100);

    // Insert a shape into the canvas
    const shape = canvas.insertShape("rectangle", 10, 10, 150, 70);

    // Change the shape's fill color
    shape.fill.color = "red";
    
// End new part

    await context.sync();
  });
}

I know this wouldn’t draw a line, but right now I just want it to draw something. I have a feeling I’m missing something important, so drawing does not work at all. When I run the Addin, and press the ‘Run’ button in the Taskpanel, I get an error:

Uncaught runtime errors:

ERROR

context.document.body.insertParagraph(…).insertDrawingCanvas is not a function

I don’t understand why it won’t let me add a Canvas so I can start drawing stuff. As always, I’ve googled a lot, but there are no real answers to be found, at least not by me. Can anybody help?

Drag event provides strange values at the end of dragging

Granted, I probably use the drag event in a way that is not intended. But I want to make a window scrollable by just “dragging” a non-draggable element. So my drag function looks like this:

<body id="body">
  <img alt="..." id="panorama" src="...">
</body>
<script>
  const
    $container = document.getElementById('body'),
    $panorama = document.getElementById('panorama')
  ;

  const drag = function(e){
    if(clientX === e.clientX)
        return;

    clientX = e.clientX;
    console.warn('dragging', e.clientX, e.offsetX, e.x)        

    const dx = e.clientX - pos.x;
    window.scroll({ left: pos.left - dx });
  };

  $container.addEventListener('drag', drag);
  $panorama.addEventListener('dragend', dragend);
  $panorama.addEventListener('mousedown', dragstart);

It works, but after I release the mouse, the window jumps somewhere completely different. The last values in the console.warn output are always the same, no matter how far I drag. They change however, when I change the window size…


I tried to use mousemove instead of drag but then I don’t get any events while clicking down, holding and moving the mouse.

Sharing the same function/code with imports between frontend and backend causing errors

I would like to validate a form on the frontend client-side and then re-validate it using the exact same function code in the backend API after submission.

The validate function works fine in both front and backend, but I get errors when I start using imports in the file that contains the function code.

I have removed the main code for brevity because this is more to do with the architecture of how the code can be shared.

Backend: validate.js

export function validateForm() {
        
  // Runs some validation checks on a form

}

Frontend: signup.vue

<template>
<form @submit.prevent="submitForm">
<!-- Form fields here --->
</form>
</template>

<script setup>
import {validateForm} from "../api/validation.js";

async function submitForm() {
  const ValidationResult = validateForm(Form); // This works fine
}
</script>

What I did next was this one line which causes errors throughout the app:

Backend: validate.js

import * as Lookup from './lookup.js';
    
export function validateForm() {
        
  // Runs some validation checks on a form
  // Doesn't use anything from Lookup

}

export function differentFunction() {
        
  // Uses a function from Lookup

}

I understand, but don’t know why, that the frontend doesn’t like it (even though I am only importing the validateForm() function which doesn’t use anything from the Lookup import).

Unfortunately I don’t know what this issue is known as in order to search for solutions. The immediate solution would be to move the validateForm() into its own separate file but I want to understand WHY that is necessary and if theres any other way to around this.

I am using Webpack 5 as a bundler.

i have changed gradles many times but I could not solve this problem

Task :expo-gradle-plugin:expo-autolinking-settings-plugin:compileKotlin FAILED

[Incubating] Problems report is available at: file:///home/farshad/Desktop/New%20Folder/test/android/build/reports/problems/problems-report.html

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:expo-gradle-plugin:expo-autolinking-settings-plugin:compileKotlin’.

Could not resolve all files for configuration ‘:expo-gradle-plugin:expo-autolinking-settings-plugin:compileClasspath’.
Could not find com.android.tools.build:gradle:8.5.0.
Searched in the following locations:
https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/8.5.0/gradle-8.5.0.pom
https://repo.maven.apache.org/maven2/com/android/tools/build/gradle/8.5.0/gradle-8.5.0.pom
Required by:
project :expo-gradle-plugin:expo-autolinking-settings-plugin

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.
Get more help at https://help.gradle.org.

Deprecated Gradle features were used in this build, making it incompatible with Gradle 9.0.

You can use ‘–warning-mode all’ to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

For more on this, please refer to https://docs.gradle.org/8.13/userguide/command_line_interface.html#sec:command_line_warnings in the Gradle documentation.

BUILD FAILED in 2s
11 actionable tasks: 3 executed, 8 up-to-date

how to solve this problem I need to convert to Apk file.

Toggle Boolean on ‘flick’

Have a next task

Create a function that always returns True/true for every item in a given list.
However, if an element is the word ‘flick’, switch to always returning the opposite boolean value.

Examples

[‘codewars’, ‘flick’, ‘code’, ‘wars’] ➞ [True, False, False, False]

[‘flick’, ‘chocolate’, ‘adventure’, ‘sunshine’] ➞ [False, False, False, False]

[‘bicycle’, ‘jarmony’, ‘flick’, ‘sheep’, ‘flick’] ➞ [True, True, False, False, True]

[“flick”, “flick”, “flick”, “flick”, “flick”]), [false, true, false, true, false]

How I understand problem statment.

If an element in the array is ‘flick’, it toggles a switch. ‘flick’ may turn the switch to false, and the elements after it will follow this state. If the next ‘flick’ is encountered, it toggles the switch again to true, and the following elements will follow that state, and so on.

Here is how I solved this task.

function flickSwitch(arr) {
    let flag = true
    let array = [];
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].toLowerCase() == 'flick') {
            flag = false;
            array.push(flag);
        } else {
            array.push(flag);
        }
    }
    return array;
}

console.log(flickSwitch(["codewars", "flick", "code", "wars"]));

And most of the tests passed successfully.

But if there are two ‘flick’ elements next to each other in the array, like [“codewars”, “flick”, “flick”, “wars”], my solution breaks.

How can I solve this problem? Please help me!

Why is my “ not displaying anything when using JavaScript in a separate file?

I’m trying to display the current time inside a paragraph element using JavaScript. My HTML and JavaScript are in separate files.

Here’s my HTML snippet:

<p id="time"></p>

And in my JavaScript file, I have:

const showTime = document.querySelector("p#time");

const intervalId = setInterval(() => {
  if (!showTime) {
    clearInterval(intervalId);
    return;
  }
  showTime.innerText = new Date().toLocaleTimeString();
}, 1000);

But nothing is showing up in the paragraph. There are no errors in the browser console.

What could be the reason p#time is not displaying anything?