Autodesk.Viewing.ModelBuilder changeGeometry Freezes the Model Selection

I am using Autodesk.Viewing.ModelBuilder to add a clickable model in the Autodesk Viewer. While attempting to modify the shape of the added model, I used the changeGeometry method. Although the shape was successfully updated, I encountered an issue where the highlight indicating the selected state of the model does not disappear after clicking on it.

Code Example

 if (hit) {
                    let geom = new THREE.BufferGeometry().fromGeometry(
                        new THREE.BoxGeometry(10, 10, 60)
                    );
                    const material = new THREE.MeshBasicMaterial({
                        color: 0xff0000,   
                        transparent: true,
                        opacity: 0.5
                    });                        
                    const pillarMesh = new THREE.Mesh(geom, material);
                    pillarMesh.matrix = new THREE.Matrix4().compose(
                        new THREE.Vector3(hit.point.x, hit.point.y, hit.point.z),
                        new THREE.Quaternion(0, 0, 0, 1),
                        new THREE.Vector3(1, 1, 1)
                    );
                    
                    //model add
                    await viewer3D.loadExtension('Autodesk.Viewing.SceneBuilder');
                    const ext = viewer3D.getExtension('Autodesk.Viewing.SceneBuilder');
                    const modelBuilder = await ext.addNewModel({
                        conserveMemory: false, 
                        modelNameOverride: 'My Model Name' 
                    });
                    modelBuilder.addMesh(pillarMesh);

                    let newGeom = new THREE.BufferGeometry().fromGeometry(
                        new THREE.CylinderGeometry(5, 5, 60, 50)
                    );
                    console.log("changeGeometry", modelBuilder.changeGeometry(pillarMesh.geometry, newGeom));
}

Problem Description
Once the geometry is changed, the highlight persists, even after attempting to deselect the model.

What I Have Tried
Attempted to clear the selection using these methods:

viewer.clearSelection();
viewer.select([]);
viewer.toggleSelect(dbid, ModelBuilder.model);

None of these methods resolved the issue. The highlight remains.

Used changeFragmentGeometry instead:
I replaced changeGeometry with changeFragmentGeometry to modify the geometry. However, the same issue persists, where the highlight does not disappear.

Expected Outcome
I want to modify the geometry of the model dynamically and ensure that the selection state behaves correctly. The highlight should disappear when the selection is cleared or toggled off.

How can I correctly render an OWL component using t-component in an Odoo view template? Am I missing something in the setup or registration?

I am trying to render an OWL component in Odoo using t-component within my view template. However, the component is not loading, and nothing appears on the page.

Here’s what I’ve done:

1.My OWL Component:

/** @odoo-module **/

import { Component } from "@odoo/owl";

export class ProductImageGallery extends Component {
    setup() {
        console.log("ProductImageGallery component is working");
    }
}
ProductImageGallery.template = "multi_image_master.ProductImageGalleryTemplate";

2.My Component Template:

<template id="ProductImageGalleryTemplate" name="Product Image Gallery">
    <div>
        <h3>Product Image Gallery</h3>
        <p>Gallery of images for this product will appear here.</p>
    </div>
</template>

views/xml file

This is supposed to render the component using t-component:

<template id="ProductPageTemplate" name="Product Page">
    <t t-call="website.layout">
        <div id="product-page-content" class="container">
            <t t-component="multi_image_master.ProductImageGallery"/>
            <p>Hello Bharathi</p>
        </div>
    </t>
</template>

Controller:
The page is loaded via this controller.

from odoo import http
from odoo.http import request

class ControllerProductPage(http.Controller):
    @http.route('/shop', type='http', auth='public', website=True, csrf=False)
    def renderProductPage(self, **kwargs):
        return request.render('multi_image_master.ProductPageTemplate', {})

manifest file

   {
    "name": "Product Multi-Image Manager",
    "version": "0.1",
    "category": "Product",
    "depends": ["website"],
    "data": [
        "views/product_template.xml"
    ],
    "assets": {
        "web.assets_backend": [
            "multi_image_master/static/src/js/product_image_gallery.js",
            "multi_image_master/static/src/xml/product_image_gallery.xml"
        ]
    },
    "installable": True,
    "application": True,
    "license": "LGPL-3"
}

Issue:
When I load the /shop route, the page renders the static content but does not render the component (t-component=”multi_image_master.ProductImageGallery”). Also, the console.log() in the setup method of the component does not execute, indicating that the component is not being loaded.

Any guidance would be appreciated.

Page.locator() is the recommended way to select and interact with elements. Why does it offer less functionalities than Page.$()?

From Page interactions | Puppeteer:

Locators is the recommended way to select an element and interact with it. Locators encapsulate the information on how to select an element and they allow Puppeteer to automatically wait for the element to be present in the DOM and to be in the right state for the action. You always instantiate a locator using the page.locator() or frame.locator() function. If the locator API doesn’t offer a functionality you need, you can still use lower level APIs such as page.waitForSelector() or ElementHandle.

This table sums up my understanding on the difference between locator() and $():

Page method Returned class Wait for element to present in the DOM? Need await? Input methods
locator() Locator Yes (retry until success or timeout) No Only have click, hover, scroll,
$() ElementHandle No Yes Various

I have two questions:

  • If locator() waits for element to present in the DOM, then isn’t that it has to have await? Similarly, if $() doesn’t wait, then isn’t that it doesn’t need await?
  • Why does $(), a method that doesn’t wait for elements to present in DOM, have more input methods than the one waits for them?

CSP issue while trying to preview the image in vb.net

When I try to select the image and preview it. It shows below error in developer tool in the browser.

Refused to load the image ‘data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADhAOEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT…KKKKAPJv2q/Dkvi/8AZp+Kej20Pn3l14a1AQRDrJKsDtGv/fSrX830N9X9TVfA3i7/AII3/BzxJr19qOna/wCKtChupHlOn2txbvBBubO2PdDuVR6MzUAfkR4btJvE2oQabD/r7u4S2T+P55Jdq1/Sx4X0caD4X0jTP+fCzhtv++EVf/Za+VvgR/wTL+EHwG8UWfiOH+2PE+t2dwtzZy65dr5MEg+6yQxIisV/6absH5uK+waACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//2Q==’ because it violates the following Content Security Policy directive: “img-src ‘self'”.

I have added below META tag on the page, and it works on my local pc but it is not working on server.

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:; style-src 'self' 'unsafe-inline';" />

Below is the java script code where I preview the image on my page.

function previewImage(fileUpload, imgPreviewId) {
    var file = fileUpload.files[0];
    if (file) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var imgPreview = document.getElementById(imgPreviewId);
            imgPreview.src = e.target.result;
            imgPreview.style.display = 'block';
        }
        reader.readAsDataURL(file);
    }
    else {
        var imgPreview = document.getElementById(imgPreviewId);
        imgPreview.src = '';
        imgPreview.style.display = 'none';
    }
}

Below is the VB code

<tr>
    <td>
        <div style="display: flex; gap: 10px; margin-top: 10px">
            <asp:Label ID="frontimg" runat="server" Text="Front Image"></asp:Label>
            <asp:FileUpload runat="server" ID="Frtimg" accept=".jpg,.png,.jpeg" onchange="previewImage(this, 'imgFrontPreview')"/>
            <asp:HyperLink runat="server" ID="frontimgView" Text="View" Target="_blank"></asp:HyperLink>
        </div>
    </td>
    <td>
        <div>
            <img id="imgFrontPreview" style="display: none; width: 200px; height: 150px;  margin-top: 10px;" />
        </div>
    </td>
    <td>
    </td>
</tr>

How to apply styles with DOM in ReactJS and server-side framework?

I am new at reactjs and i want to manipulate styles directly with DOM or inline-styles. I am using useLayoutEffect to make this run as early as possible.



import { useLayoutEffect } from 'react'


const App = () => {
  useLayoutEffect(() => {
    document.querySelector('.my-element').style.background = 'red'
  }, [])

  return <div className="my-element">Hello World!</div>
}

export default App

And the effect is runs like regular styles. But, am I doing the right thing? Or is there a better method for applying style directly with DOM?

And let’s say I want to use it on server-side or static-side thing, I always has a slight FOUC (unstyled state) before the real styles is applied, like in NextJS for example.

Wanted to learn how to apply styles with DOM, in server-side, in SSG, and what the best way to do it.

Multiple file uploads resulting in each disabled button becoming enabled

On a page I have multiple file uploads and each has its own Upload button.

When i call the type=”submit” button each file load goes off to its own controller and its file is loaded. This works nicely and the same code can be used for all file uploads $("form").submit(function (eventObj)

What i am struggling with is this: I don’t want the user to be able to press the Upload button if they have not selected a file, so i have disabled the button until a file is pressed, the disabling bit works fine. What i need help with is how when the file is selected do i call something that changes the disabled button to enabled (when user selects a file) and works for multiple file uploads using the same bit of code that can be used for all file uploads.
Is there a way to get the enable button to work a bit like this line: $("form").submit(function (eventObj) { which handles all file uploads?
I want to try to avoid having different bits of code for each file upload and keeping names like id=”filename” the same for every file upload. I can get it working for a single file upload but not multiple.

Hopefully my question makes sense, I am newish to Javascript.

Thank you in advance.

<h1>Upload Files</h1>

<form enctype="multipart/form-data" asp-action="UploadFile" asp-controller="Ls" method="post">
    <dl>
        <dd>
            <input type="file" name="file" id="filename">             
            
        </dd>
    </dl>
    <input class="btn btn-primary" id="uploadButton" type="submit" value="Upload" disabled/>
</form>


<form enctype="multipart/form-data" asp-action="UploadFile" asp-controller="Cv" method="post">
    <dl>
        <dd>
            <input name="file" type="file" id="filename">            
        </dd>
    </dl>
    <input class="btn btn-primary" id="uploadButton" type="submit" value="Upload" disabled/>
</form>
   //there are more of these upload forms



@section Scripts {
    <script>    
        filename.onchange = function(eventObj)  {
                //this works but only for the first file upload not the other ones.
                if($(this).val())
                {
                    $("#uploadButton").prop("disabled", false);
                }
                else
                {
                    $("#uploadButton").prop("disabled", true);
                }
        };

        $("form").submit(function (eventObj) {                        
           //some stuff
            var formData = new FormData(eventObj.currentTarget);                  
            
            $.ajax({
                url : eventObj.currentTarget.action,
                type: "POST",
                data : formData,
                processData: false,
                contentType: false,
                cache: false,
                enctype: 'multipart/form-data',   
               
                success:function(data, textStatus, jqXHR){                    
                    console.log("in success");                   
                },
                error: function(jqXHR, textStatus, errorThrown){                      
                }
            });            
            return false;            
        }); 
    </script>
}

Flickering/being removed when using sortablejs with dcraw

I try to list files selected using multiple file input using the code below (also available at jsbin). When trying to move li items to sort and nest them, they start flickering and sometimes are dropped from the list and completely removed from DOM. Can it be solved while keep using dcraw and SortableJS? It seems to work

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Bootstrap-Flask Demo Application</title>

    <style>
        .handle {
            cursor: -webkit-grabbing;
            cursor: move;
        }
    </style>
</head>

<body>
    <input class="form-control" id="files" multiple="" name="files" required="" type="file">
    <div id="files-selected" class="mb-3">
        <ul class="list-group very-first-parent nested-sortable h-200">

        </ul>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/dcraw"></script>
    <script src="https://sortablejs.github.io/Sortable/Sortable.js"></script>
    <script>
        var filesField;
        var filesSelected;
        document.addEventListener('DOMContentLoaded', function () {
            filesField = document.getElementById("files");
            filesSelected = document.getElementById("files-selected");

            filesField.addEventListener('change', function (e) {
                var files = e.target.files;

                var reader = [];
                var filenames = Array.from(files).map(file => file.name);

                filesSelected.querySelector('.very-first-parent').innerHTML = '';
                filenames.forEach((filename, index) => {
                    // alert('file selected');
                    var file = files[index];
                    var li = document.createElement('li');
                    li.className = 'list-group-item';
                    li.innerHTML = `
                    <div class="d-flex align-items-center">
                        <i class="handle bi-arrows-move"></i>
                        <button type="button" class="btn btn-danger me-3 ms-3" onclick="dismiss(this)">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <span class="file-name">${filename}</span>
                        <!--spinner--><div class="spinner spinner-border ms-auto" role="status"><span class="visually-hidden">Loading...</span></div><!--/spinner-->
                    </div>
                    <ul class="list-group nested-sortable"></ul>
                    `;
                    showPreview(file, li);
                    filesSelected.querySelector('.very-first-parent').appendChild(li);
                });

                makeNestedSortable();
            });
        });
        function isImage(file) {
            const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
            return imageTypes.includes(file.type);
        }

        function isRawImage(file) {
            const rawImageExtensions = ['.nef', '.cr2', '.tiff'];
            return rawImageExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
        }

        function isVideo(file) {
            const videoTypes = ['video/mp4', 'video/quicktime'];
            return videoTypes.includes(file.type);
        }

        function replaceSpinner(string_old, string_new) {
            return string_old.replace(/<!--spinner-->.*<!--/spinner-->/gi, string_new)
        }

        function showPreview(file, li) {
            if (isImage(file)) {
                const reader = new FileReader();
                reader.onload = function (e) {
                    li.innerHTML = replaceSpinner(li.innerHTML, `<img class="preview ms-auto" src="${e.target.result}" height="70" style="max-height: 70px;">`);
                };
                reader.readAsDataURL(file);
            } else if (isRawImage(file)) {
                // You can use a library like raw.js to decode raw images and show a preview
                const reader = new FileReader();
                reader.onload = (function (o) {
                    return function (e) {
                        // Get the image file as a buffer
                        var buf = new Uint8Array(e.currentTarget.result);

                        // Get the RAW metadata
                        var metadata = dcraw(buf, { verbose: true, identify: true }).split('n').filter(String);

                        // Extract the thumbnail
                        var thumbnail = dcraw(buf, { extractThumbnail: true });

                        // Create thumbnail
                        var blob = new Blob([thumbnail], { type: "image/jpeg" });
                        var urlCreator = window.URL || window.webkitURL;
                        var imageUrl = urlCreator.createObjectURL(blob);
                        li.innerHTML = replaceSpinner(li.innerHTML, `<img class="preview ms-auto" src="${imageUrl}" height="70" style="max-height: 70px;">`);
                    };
                })(file);
                reader.readAsArrayBuffer(file);
            } else if (isVideo(file)) {
                li.innerHTML = replaceSpinner(li.innerHTML, `<video src="${URL.createObjectURL(file)}" class="ms-auto" controls height="70" style="max-height: 70px;"></video>`);
            } else {
                li.innerHTML = replaceSpinner(li.innerHTML, `<span class="preview ms-auto">Preview not available</span>`);
            }
        }

        function dismiss(target) {
            var li = target.closest('li');
            var fileToDelete = li.querySelector('span.file-name').textContent;

            var dt = new DataTransfer();
            Array.from(filesField.files).forEach((file, i) => {
                if (file.name !== fileToDelete)
                    dt.items.add(file)

                filesField.files = dt.files // this will trigger a change event
            });

            li.remove();
        }

        function makeNestedSortable() {
            nestedSortables = [].slice.call(document.querySelectorAll('.nested-sortable'));
            console.log(nestedSortables.length);

            for (var i = 0; i < nestedSortables.length; i++) {
                new Sortable(nestedSortables[i], {
                    group: 'nested',
                    animation: 150,
                    fallbackOnBody: true,
                    // invertSwap: true,
                    swapThreshold: 0.5
                });
            }

        }
    </script>
</body>

</html>

How can I display an interactive JavaScript object on the page? [duplicate]

I consume a rest service that returns a fairly large javascript object. I want to display this object on the screen not in the console. I would like the displayed object to be interactive (have arrows to expand and collapse sub-objects) just like I can in the console.

console view

Is there any way for display chrome’s console output directly on the page? If not, can I use some library to display the javascript object the same way chrome’s console does? I don’t want to just print everything because the object is large and unreadable if you do that.

How To Solve CSP Blocking Problem in Javascript

btnLogin.Attributes.Add(“onclick”, ” javascript:return ABC(‘” & Convert.ToString(Session(“No”)) & “‘);”) This line is Call My ABC Function But When i Add CSP in My Code its NOt Working Can Someone Please Help Me

I try addEventListener And Also more thing

How to render an OWL component using t-component in Odoo view templates?

I am trying to render an OWL component in Odoo using t-component within my view template. However, the component is not loading, and nothing appears on the page.

Here’s what I’ve done:

1.My OWL Component:

/** @odoo-module **/

import { Component } from "@odoo/owl";

export class ProductImageGallery extends Component {
    setup() {
        console.log("ProductImageGallery component is working");
    }
}
ProductImageGallery.template = "multi_image_master.ProductImageGalleryTemplate";

2.My Component Template:

<template id="ProductImageGalleryTemplate" name="Product Image Gallery">
    <div>
        <h3>Product Image Gallery</h3>
        <p>Gallery of images for this product will appear here.</p>
    </div>
</template>

views/xml file

This is supposed to render the component using t-component:

<template id="ProductPageTemplate" name="Product Page">
    <t t-call="website.layout">
        <div id="product-page-content" class="container">
            <t t-component="multi_image_master.ProductImageGallery"/>
            <p>Hello Bharathi</p>
        </div>
    </t>
</template>

Controller:
The page is loaded via this controller.

from odoo import http
from odoo.http import request

class ControllerProductPage(http.Controller):
    @http.route('/shop', type='http', auth='public', website=True, csrf=False)
    def renderProductPage(self, **kwargs):
        return request.render('multi_image_master.ProductPageTemplate', {})

manifest file

   {
    "name": "Product Multi-Image Manager",
    "version": "0.1",
    "category": "Product",
    "depends": ["website"],
    "data": [
        "views/product_template.xml"
    ],
    "assets": {
        "web.assets_backend": [
            "multi_image_master/static/src/js/product_image_gallery.js",
            "multi_image_master/static/src/xml/product_image_gallery.xml"
        ]
    },
    "installable": True,
    "application": True,
    "license": "LGPL-3"
}

Issue:
When I load the /shop route, the page renders the static content but does not render the component (t-component=”multi_image_master.ProductImageGallery”). Also, the console.log() in the setup method of the component does not execute, indicating that the component is not being loaded.

Question:
How can I correctly render an OWL component using t-component in an Odoo view template? Am I missing something in the setup or registration? Any guidance would be appreciated.

cookies _clsk & _clck are not set as SameSite=None;Secure. Clarity implementation using GTM

I have implemented microsoft clarity using Google Tag Manager and currently I am not able to set the cookies as SameSite=None;Secure. I do not have any option in the clarity and google tag manager consoles.

How can I implement the cookies with SameSite=None and Secure?

I could set the cookies dynamically in my js but this might affect the clarity’s analysis and tracking. I’d prefer if I could set it in console or by some other way that doesn’t involve manually manipulating the cookie.

How to modify the code for the display of the lenticular effect under the Canvas feature in the Html

I am Derby. I am new in this community. I would need the help to modify the code for the display of the lenticular effect under the Canvas feature in the Html as the result of the demonstration on the website Lenti (https://danielgamage.github.io/lenti/). The source code is from the old project entitled “Lenti” (https://github.com/danielgamage/lenti?tab=readme-ov-file). I tried to combine the index.js into the html under one simple file to display lenticular effect in the html Canvas, but I cannot perform the same result as the demonstration on the website Lenti (https://danielgamage.github.io/lenti/). Attached is the source code. I wish the source code and files of the link from one old project would help you solve the problem and provide the solutions based on your specialty. Thank you.

<!DOCTYPE html>
<html>
<head>
<script>
/* global window */
class Lenti {
  constructor (options) {
    // Config
    this.container = options.container
    this.accelerometerEvents = (options.accelerometerEvents !== undefined)
      ? options.accelerometerEvents
      : true
    this.mouseEvents = (options.mouseEvents !== undefined)
      ? options.mouseEvents
      : true
    this.stripWidth = options.stripWidth || 16
    this.height = options.height || 50
    this.width = options.width || 50
    this.tiltMax = options.tiltMax || 45
    this.tiltMin = options.tiltMin || -45

    this.init = this.init.bind(this)
    this.sampleImages = this.sampleImages.bind(this)
    this.getImage = this.getImage.bind(this)
    this.handleSizing = this.handleSizing.bind(this)
    this.getBoxPosition = this.getBoxPosition.bind(this)
    this.checkVisibility = this.checkVisibility.bind(this)
    this.bindEvents = this.bindEvents.bind(this)
    this.destroy = this.destroy.bind(this)
    this.redraw = this.redraw.bind(this)
    this.handleMouse = this.handleMouse.bind(this)
    this.handleOrientation = this.handleOrientation.bind(this)
    this.remap = this.remap.bind(this)
  }

  // Initialize
  init () {
    this.images = [...this.container.querySelectorAll(`img`)]
    this.imageCount = this.images.length
    this.imageDataArray = [...Array(this.imageCount).keys()] // empty array w/ same length as this.images
    this.container.innerHTML += `<canvas />`
    this.canvas = this.container.querySelector(`canvas`)
    this.ctx = this.canvas.getContext(`2d`)
    this.tempCanvas = document.createElement(`canvas`)
    this.tempCtx = this.tempCanvas.getContext(`2d`)

    this.handleSizing()
    this.bindEvents()
    this.getBoxPosition()
    this.checkVisibility()
  }

  // Sample image
  sampleImages () {
    this.images.map((imageEl, imageIndex) => {
      if (this.imageDataArray[0]) {
        this.getImage(imageEl, imageIndex)
      } else {
        imageEl.addEventListener(`load`, function () {
          this.getImage(imageEl, imageIndex)
        }.bind(this))
        return imageEl
      }
    })
  }
  getImage (image, imageIndex) {
    this.tempCtx.drawImage(image, 0, 0, image.naturalWidth, image.naturalHeight, 0, 0, this.canvasWidth, this.canvasHeight)
    const currImageData = this.tempCtx.getImageData(0, 0, this.canvasWidth, this.canvasHeight)
    this.imageDataArray[imageIndex] = new Uint32Array(currImageData.data.buffer)
  }

  // Handle window resize
  handleSizing () {
    // use offsetWidth bc clientWidth = 0 when resizing
    // multiply by device pixel ratio to convert css pixels → device pixels
    this.canvasWidth = Math.floor(this.canvas.offsetWidth * window.devicePixelRatio)
    this.canvasHeight = Math.floor(this.canvasWidth * (this.height / this.width))
    this.canvas.width = this.canvasWidth
    this.canvas.height = this.canvasHeight
    this.tempCanvas.width = this.canvasWidth
    this.tempCanvas.height = this.canvasHeight
    // Resample images
    // careful on the fire rate here.
    this.sampleImages()
    this.imageData = this.tempCtx.getImageData(0, 0, this.canvasWidth, this.canvasHeight)
    this.getBoxPosition()
  }

  getBoxPosition () {
    const boxyRect = this.canvas.getBoundingClientRect()
    this.box = {
      top: boxyRect.top + window.pageYOffset
    }
  }
  // Check if canvas is in view
  checkVisibility () {
    const vTop = window.pageYOffset
    const vHeight = window.innerHeight
    if (vTop + vHeight < this.box.top ||
      this.box.top + this.canvasHeight < vTop) {
      // viewport doesn't include canvas
      this.visible = false
    } else {
      // viewport includes canvas
      this.visible = true
    }
  }

  // Event Binding
  bindEvents () {
    if (this.mouseEvents) {
      this.canvas.addEventListener(`mousemove`, this.handleMouse)
    }
    if (this.accelerometerEvents) {
      window.addEventListener(`deviceorientation`, this.handleOrientation)
    }
    window.addEventListener(`scroll`, this.checkVisibility)
    window.addEventListener(`resize`, this.handleSizing)
  }

  // Event Unbinding
  destroy () {
    this.canvas.removeEventListener(`mousemove`, this.handleMouse)
    window.removeEventListener(`deviceorientation`, this.handleOrientation)
    window.removeEventListener(`scroll`, this.checkVisibility)
    window.removeEventListener(`resize`, this.handleSizing)
  }

  // Redraw canvas
  redraw (balance) {
    // make sure data is loaded before redrawing
    if (this.imageDataArray[0]) {
      let data = this.imageData.data
      let data32 = new Uint32Array(data.buffer)

      const dataArray = this.imageDataArray
      const canvasWidth = this.canvasWidth
      const canvasHeight = this.canvasHeight
      const stripWidth = this.stripWidth
      const imageCount = this.imageCount

      const addOn = (balance * (imageCount - 1))

      for (let x = 0; x < canvasWidth; x++) {
        const set = (x % stripWidth / stripWidth) + addOn
        const setClamped = Math.floor(set)

        for (let y = 0; y < canvasHeight; y++) {
          const pixel = x + (canvasWidth * y)
          data32[pixel] = dataArray[setClamped][pixel]
        }
      }

      this.ctx.putImageData(this.imageData, 0, 0, 0, 0, this.canvasWidth, this.canvasHeight)
    }
  }

  // Handle mouse events
  handleMouse (e) {
    const balance = this.remap(e.offsetX / this.canvasWidth, 0, 1, 1, 0)
    this.redraw(balance)
  }

  // Handle device accelerometer events
  handleOrientation (e) {
    if (this.visible) {
      const clamped = Math.min(Math.max(e.gamma, this.tiltMin), this.tiltMax)
      const balance = this.remap(clamped, this.tiltMin, this.tiltMax, 1, 0)
      this.redraw(balance)
    }
  }

  // Map values from one range to another
  remap (value, inLow, inHigh, outLow, outHigh) {
    return outLow + ((value - inLow) * (outHigh - outLow) / (inHigh - inLow))
  }
}

export default Lenti

</script>
</head>

<body>
global.window = global

document.body.innerHTML = `
  <div data-lenticular-list="true" data-strip-width="8" data-tilt-min="-35" data-tilt-max="35">
    <img src="./images/1.png" crossorigin="anonymous" alt="" width="1024" height="1024" />
    <img src="./images/2.png" crossorigin="anonymous" alt="" width="1024" height="1024" />
    <img src="./images/3.png" crossorigin="anonymous" alt="" width="1024" height="1024" />
    <img src="./images/4.png" crossorigin="anonymous" alt="" width="1024" height="1024" />
  </div>
`

const el = document.querySelector('[data-lenticular-list]')

const testInstance = new Lenti({
  container: el,
  tiltMax: el.getAttribute('data-tilt-max'),
  tiltMin: el.getAttribute('data-tilt-min')
})

describe("Lenti", () => {
  it('instantiates properly', () => {
    expect(testInstance).toBeInstanceOf(Lenti)
  })
  it('initializes without error', () => {

    testInstance.init()
  })
})
describe("remap", () => {
  it('maps values from one range to another', () => {
    expect(testInstance.remap(5,    0, 10,   0, 100)).toEqual(50)
    expect(testInstance.remap(9,    0, 100,  0, 2)).toEqual(0.18)
    expect(testInstance.remap(7.5,  5, 10,   0, 2)).toEqual(1)
  });
})

</body>
</html>

Chained https requests using promises seem to be out of order

I’m trying to figure out how Promises work with multiple HTTPS requests in Javascript, but I have a problem where the results seem out of order with the request sequence. I’m using an ASP.NET Controller API implementation for a simple calculator, and Javascript to access the API. I seem to have a synchronization issue, but I can’t for the life of me work out why.

The CalculatorController:

using Microsoft.AspNetCore.Mvc;

namespace Wolflight.Calculator.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class CalculatorController : Controller
    {
        private const string TotalName = "Total";


        private decimal RetrieveTotal()
        {
            return ToDecimal(HttpContext.Session.GetString(TotalName));
        }

        private void StoreTotal(decimal value)
        {
            HttpContext.Session.SetString(TotalName, FromDecimal(value));
        }

        private static string FromDecimal(decimal value)
        {
            return value.ToString();
        }

        private static decimal ToDecimal(string? value)
        {
            if (value != null)
            {
                return Decimal.Parse(value);
            }
            else
            {
                return 0M;
            }

        }

        [HttpGet()]
        [Route("/api/Calculator/Total")]
        public decimal? GetTotal()
        {
            return RetrieveTotal();
        }

        [HttpPut()]
        [Route("/api/Calculator/Add")]
        public void AddValue(decimal value)
        {
            StoreTotal(RetrieveTotal() + value);
        }

        [HttpPut()]
        [Route("/api/Calculator/Subtract")]
        public void SubtractValue(decimal value)
        {
            StoreTotal(RetrieveTotal() - value);
        }

        [HttpPut()]
        [Route("/api/Calculator/Multiply")]
        public void MultiplyValue(decimal value)
        {
            StoreTotal(RetrieveTotal() * value);
        }

        [HttpPut()]
        [Route("/api/Calculator/Divide")]
        public void DivideValue(decimal value)
        {
            StoreTotal(RetrieveTotal() / value);
        }


    }
}

The site.js:

const uriBase = "/api/Calculator/";
const uriTotal = uriBase + "Total";
const uriAdd = uriBase + "Add";

let GetTotalValuePromise = function () {
    return new Promise(function (myResolve, myReject) {
        let total = fetch(uriTotal)
            .then(response => response.text())
            .catch(error => myReject('Unable to get total.', error));

        myResolve(total);
    })
};

let PutAddValuePromise = function (addValue) {
    return new Promise(function (myResolve, myReject) {
        fetch(uriAdd + '?value=' + addValue, { method: 'PUT' })
            .catch(error => myReject('Unable to add value.', error));

        myResolve();
    }
    )
};

function DisplayTotal(total) {
    const tBody = document.getElementById('totalDisplay');
    tBody.innerHTML = total;
}

function GetTotal() {
    UpdateDisplay();
}

function AddValue() {
    let value = document.getElementById('addValue').value;

    PutAddValuePromise(value)
        .then(function () {
            UpdateDisplay();
        });
}

function UpdateDisplay() {
    GetTotalValuePromise()
        .then(
            function (total) { DisplayTotal(total); },
            function (message, error) { console.error(message, error); }
        )
}

When I call AddValue() from a form button, the result is that sometimes the /Total call returns the value before the /Add occurs, and sometimes it returns the result after.

e.g.

  • Total = 0
  • Call AddValue, with element addValue as 5.

Network Requests:

  • /Add?value=5 (no response)
  • /Total – Response: 0.

OR

Network Requests:

  • /Add?value=5 (no response)
  • /Total – Response: 5.

Am I missing something in how Promises work, or is the problem on the server side?

If I call GetTotal manually after the AddValue, it always returns the correct value.

Return any possible palindrome [closed]

You are given a string S made of lowercase letters (‘a’-‘z’ and question marks (‘?’). You must replace each question mark in S with any lowercase letter. You are also given an integer K. After replacing the question marks, you may replace at most K characters in S with any lowercase letter.

Write a function that, given a string S of length N and an integer K, returns any palindrome that can be obtained by performing the operations described above. If it is not possible to obtain a palindrome from S, the function should return the string “NO”.

A palindrome is a string that reads the same both forwards and backwards. Some examples of palindromes are: “kayak”, “abba”,”zaz”.

Examples:

  1. Given S= “?ab??a” and K = 0, the function should return “aabbaa”.
  2. Given S = “guz?za” and K = 1, the function should return “NO”.
  3. Given S=”?gad?bcc?dg?” and K=2, the function may return “agadccccdaga”. It may also return “fgddcbbcddgf”, among other possible answers. The function is supposed to return only one of the possible answers.

Assume that:
N is an integer within the range [1 ..1,000];
K is an integer within the range [0 .. N];
String S is made only of lowercase English letters (‘a’-‘z’) and/or ‘?’ characteers.

In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

Sorry I have not made any attempt.