Change gradient Values on click / Pressed

The link will show you what I’m trying to achieve

(this is not a real outcome. this video is a concept of my goal)

https://www.youtube.com/watch?v=U_MggL4-AMc

I could really do with a helping hand on this lol

(I need to be able to do this for MULTIPULE different gradients individually)

I’ve tried using Vars with colours and using a Event listener which worked somewhat in codepen with solid colours not gradients but didn’t work on my actual site. (this didn’t previously work for me.

I have now tried using background images to somewhat success. I’m now trying to figure out how I can go back and fourth with the theme colours as well as set the scale for the background retrieved by the script. (however I’d prefer the original method of changing gradient values on click)

here’s a link to the CodePen

<!DOCTYPE html>
<html>
<head>
<style> 
#Background {
  width: 1920px;
  height: 1080px;
  background-image: url("https://previews.dropbox.com/p/thumb/ACUv6h-QQ6PskOhByDXYwHCGjtk1ar3JN5ufhLEEwKxFAJvxxqUyCHMT-DMbK318IVJ_Zn2ustYtg-CcpEPp3egLeHMJoH_teEMKWVjtmw3VSeDvSJpwcqCk89QsDdKjbL4Q9cuPviRrw--RPRXN-uIDTcQYQfkyiQyQT0VMVN5FOwsblLq222dzHRW-YL9huPTGqgmWYNVOc36wpcNva2sVah0UVRLxjeSiGEbF4RPZijO2tp0kYovzRsuybNjkvHbxK4SgO_WGPjebe2Uh9OzoLmygGI-zItBzoqLk9dzLe0Bo6jMQr7v_8fDX3VnJpHNAOMZstzdmXlhQ_INGmlqaaCoTM175t6pYfVxUy_s2qxRotclVumgogKWY2RwUyqk/p.png");
}

  .Embers-Theme-Card {
    --perspective: 1400px;
    --rotateX: 0;
    --rotateY: 0;
    --angle: 6.5deg;
  
    position: relative;
    display: grid;
    place-content: center;
    text-align: center;
    box-shadow: rgba(0, 0, 0, 0.25) -20px 20px 20px 0px;
    padding: 2rem;
    aspect-ratio: 1 / 2;
    background-image: url("http://localhost:10060/images/Embers.png");
    background-size: cover;
    transform: perspective(var(--perspective)) rotateX(var(--rotateX))
      rotateY(var(--rotateY));
    transition: transform 350ms ease;

    width: 180px;
    height: 75px;
    border-radius: 20px;
    left:800px;
    Top: 100px;
  }
  
  .Embers-Theme-Card > :where(h1, p) {
    background: rgba(221, 221, 221, 0.432);
    margin: 0;
    padding: 0.5rem;
  }
  
  .mouse-position-tracker {
    position: absolute;
    inset: 0;
  }
  
  .mouse-position-tracker > div {
    position: absolute;
    width: calc(100% / 3);
    height: calc(100% / 3);
    z-index: 2;
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(1):hover) {
    --rotateX: var(--angle);
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(2):hover) {
    --rotateX: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(3):hover) {
    --rotateX: var(--angle);
    --rotateY: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(4):hover) {
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(6):hover) {
    --rotateY: var(--angle);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(7):hover) {
    --rotateX: calc(var(--angle) * -1);
    --rotateY: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(8):hover) {
    --rotateX: calc(var(--angle) * -1);
  }
  
  .Embers-Theme-Card:has(.mouse-position-tracker > div:nth-child(9):hover) {
    --rotateX: calc(var(--angle) * -1);
    --rotateY: var(--angle);
  }
  
  /* 1st, 4th, 7th */
  .mouse-position-tracker > div:nth-of-type(3n - 2) {
    left: 0;
  }
  /* 2nd, 5th, 8th */
  .mouse-position-tracker > div:nth-of-type(3n - 1) {
    left: calc(100% / 3);
  }
  /* 3rd, 6th, 9th */
  .mouse-position-tracker > div:nth-of-type(3n) {
    right: 0;
  }
  
  /* 1-3 */
  .mouse-position-tracker > div:nth-child(n + 1):nth-child(-n + 3) {
    top: 0;
  }
  
  /* 4-6 */
  .mouse-position-tracker > div:nth-child(n + 4):nth-child(-n + 6) {
    top: calc(100% / 3);
  }
  
  /* 7-9 */
  .mouse-position-tracker > div:nth-child(n + 7):nth-child(-n + 9) {
    bottom: 0;
  }
  
  /* general styling */
  :root {
    --shadow: 0px 1px 2.2px rgba(0, 0, 0, 0.02),
      0px 2.5px 5.3px rgba(0, 0, 0, 0.028), 0px 4.6px 10px rgba(0, 0, 0, 0.035),
      0px 8.3px 17.9px rgba(0, 0, 0, 0.042), 0px 15.5px 33.4px rgba(0, 0, 0, 0.05),
      0px 37px 80px rgba(0, 0, 0, 0.07);
  }

  .Embers-Theme-Card
  {
    cursor:pointer;
  }
</style>
</head>
<body>


<div id="Background">
        <div class="Embers-Theme-Card"<button onclick="myFunction()"></button>
  <h1>Embers</h1>


  <div class="mouse-position-tracker">
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
  </div>
</div>
</div>


<script>
function myFunction() {
   document.getElementById("Background").style.backgroundImage = "url(https://previews.dropbox.com/p/thumb/ACX0qlkI5_4X1wx38BE5OYUXzWxSZf1IDvUqHhiRXEWE8XbQf6t-OTWScbY8iUOJi1Zw-v0B89055hqh7J87eIpVkC3gfh4ceH5AATuzh95VVChO9wD1TDCYsgQN9Qc6XDWT2p9x3_BG8zhGu6tuaCxreeS_NJDzAa-W3VU38f7L0Ik2lrn-1KI19pu8caW2DkBL1aY7-QePYnjLvaYmGvCrk4ZUYu27ITHJMQYtJd_VsEwCyp3-CLABikGcO0gtaeo1GrhtAjKjC6QRxnmCz3A-uCbb-aF9aJyxkOs3Mues2Pi8H8PNhZ3sZ7pQqbqhChdgg4BvXJPUfeK5RZhWa6jxsXVgYnbTaqEjLWWO7ONvOw/p.png)";
}

</script>

</body>
</html>

How can I connect a like counter to my firebase database

I have a post view counter (Blogger) which is connected to a Firebase database and is working fine. But I would like to add the like counter to the same database and structure for each post id.

Postviews js

<script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("My-Project-URL/pages/id/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); }); </script> 

Show the views value

<i class='fa fa-eye'/> <a expr:name='data:post.id'/><span id='postviews'/> Views

Like counter js

<script>
// store the main Firebase URL
var firebaseURL = 'My-Project-URL/pages/id/';

// update the likeCounts shown in a <span> beside each blogpost
var postDivs = document.querySelectorAll('.post');

for (var i = 0; i < postDivs.length; i++) {

    var postID = postDivs[i].id;

    var numLikes = getLikeCount(postID);

}

// this function grabs the likeCount for a particular post from the Firebase
function getLikeCount(postID) {
 
    console.log('running getLikeCount for post ID:', postID);
    
    var thisPostRef = new Firebase(firebaseURL + postID + '/like-count/');
    
    thisPostRef.once('value', function(snapshot) {
        
        console.log( postID + ' value:', snapshot.val() );
        
        if ( snapshot.val() ) {
            
            console.log( postID + ' contains:', snapshot.val() );

            document.querySelector('#' + postID + ' .like-count').innerHTML = snapshot.val() + ' likes';
            
        } else {
            
            console.log( postID + '- no data in Firebase' );
            
            return 0;
        
        }
    
    });
    
}

function likePost(id) {

    console.log('running likePost() for post ID:', id);
    
    var postRef = new Firebase(firebaseURL + id);
    
    // get current number of likes here, so we can increment if any exist
    postRef.child('like-count').once('value', function(snapshot){
        
        console.log( 'snapshot.val():', snapshot.val() );
        
        var currentLikes = snapshot.val() ? snapshot.val() : 0;
        
        console.log( 'currentLikes:', currentLikes );
    
        postRef.update({
            
            'postID': id,
            'like-count': currentLikes + 1
            
            }, function(error) {
                
              if (error) {
                  
                console.log('Data could not be saved:' + error);
              
              } else {
              
                console.log('Data saved successfully');
              
              }
            
            });
            
        getLikeCount(id);
    
    });
    
}
</script>

Show the likes value:

<a expr:name='data:post.id'/> <button onclick='likePost()'> <i class='fa fa-thumbs-up' style='font-size:36px'/></button> <span id='likes'/>

I tried to get the post id but always have to put it manually on the onlick=’likePost()’ function to get something stored in the database.

I don’t know how to integrate the like counter code to the viewpost code (which is working) and have same database structure.

Three JS loop through materials

I want to search for the material called COIN and assign a new texture to it. I know it’s material number 0, but what I want is to search through the materials and if it finds a name match, assign the texture.

object.traverse( function( node ) {
  if (node.isMesh) {
    if ( node.material[0].name == 'COIN' ) {
      node.material = textura
    } 
  }
})
// Works perfect

Looking something like:

if ( node.material[].name == 'COIN' )
// Error

How can I loop through the object’s textures to find the one I’m interested in without knowing the material index?

Just in case it matters, the object format is FBX.

Thanks!!!

FileDownload Open in a new tab

I implemented TelerikUpload in my project. Upload is working fine.
My following code is downloading the file to download folder then I have to click it to open the folder. But I want the file to open in a new tab or in a popup window without the download.
I tried all options, Any option I try it is always downloading to download folder.
Is it because my Blazor application is a single page app?

    //JRazor file
<a href="" @onclick="() => AttachmentOpen(item)" @onclick:preventDefault target="_blank">fileName</a>

function openFile(filename, content, mimeType) {
    var blob = new Blob([content], { type: mimeType });
    var url = window.URL.createObjectURL(blob);
    var anchorElement = document.createElement('a');
    document.body.appendChild(anchorElement);    
    anchorElement.setAttribute("type", "hidden");
    anchorElement.href = url;
    anchorElement.target = "_blank";
    anchorElement.click();

    anchorElement.remove();
    window.URL.revokeObjectURL(url);
}
//Razor.cs file
private async Task AttachmentOpen(Attachment attachment)
{
    var extension = Path.GetExtension(attachment.fileName);
    var mimeType = MimeTypeHelper.GetMimeType(extension);
    byte[] DownloadFileBytes = ReadFile(attachment.Path);
    await JSRuntime.InvokeVoidAsync("openFile", attachment.fileName, FileBytes, mimeType);
}

Convert objects into array

A = [{"name":"John","age":30,"city":"New York"},{"name":"Jimmy","age":40,"city":"Toronto"}]

B = [["John", 30, "New York"], ["Jimmy", 40, "Toronto"]]

How to convert A into B in JavaScript?

Thanks in advance for your help!

Use ajax to call php, to call python, and get the result

I have built a website with a fairly complex structure and lots of javascript and php functions. I avoided jquery to make it lighter.

I now want to add a python function that should return a value to it. Most people recommend Flask for this, but all the examples I have found seem to require re-arranging the index page etc, which I don’t want to do (but please correct me if I am misunderstanding that).

So, the simple solution I thought about is to use ajax to call a php script, which in turn executes a python file. The problem, is that ajax isn’t waiting for the python script to complete and return the result.

I am mostly self-taught, so maybe what I did is all wrong, and any suggestion for a simple fix is much appreciated. Again, I’d like to avoid jquery and any major re-arrangement of pages etc.

Here is my code.

The ajax function that I use for lots of things on the site:

 var ajaxResponseText = "";//a global variable that I use to get back the results of PHP functions
function ajaxRequestReturn(phpRequest, vars, isAsync=false, setHeader=false, jsonParsed=true){
  ajaxResponseText = "";
  var req = new XMLHttpRequest();
  req.open("POST", phpRequest, isAsync);//not asynchronous
  if(setHeader){
    req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  }
  req.onProgress = function(){
    console.log("READYSTATE: ", req.readyState );
  }
  req.onload = function(){
    if(this.status==200){
      console.log("READYSTATE: ", this.readyState);
      console.log("responseText: ", this.responseText);
      if(jsonParsed){
        ajaxResponseText = JSON.parse(this.responseText);
      }else{
        ajaxResponseText = this.responseText;//php functions will echo a json array
      }
      // console.log(ajaxResponseText);
    }else if(this.status==404){
      ajaxResponseText = "Not found";
    }
  }
  req.onerror = function(){
    throw new Error("Bad request.");//this will stop the script and report the error
  }
  req.send(vars);
}

An event handler on the page calls:

ajaxRequestReturn("myPhpPythonCaller.php", vars="", isAsync=false, setHeader=false, jsonParsed=false)

myPhpPythonCaller.php simply has:

echo exec("pathToMyPythonEnv .venv/bin/python3 pathToMyPythonScript.py");

And the python script would produce and then print the result, say

from library import functionx

res = functionx()

print(res)

This set-up works for simple functions (e.g. print(“hello”) from MyPythonScript.py sends “hello” to ajaxResponseText, as expected ). However, if I call a function that takes time (I want to run an LLM, which would take dozens of seconds to produce an output), ajax doesn’t wait for the result, gets to status==200 and console.logs an empty ajaxResponseText.

What is the simplest, lightest way to do what I am trying to do?

Thank you so much for any tips!

How to check both mouse click down while dragging mouse over an element?

I am working on a basic sketching application using React JS. The intended functionality is that when a user clicks the mouse while hovering over an element, the element should change color.

One approach I considered involves using a variable (e.g., shouldDraw). This variable would be set to true on onMouseDown and set back to false on onMouseUp.

When shouldDraw is true, any element the mouse hovers over should change to the new color.

Is there a more idiomatic way to implement this in React JS?

How to change Radar Chart size? Chart JS

I’m trying to make a Radar Chart using react and ChatJs. It works just fine on bigger screens, but on mobile phone the chart is too small. How could I remove the blank spaces(Example on image) and make the chart bigger(As example the line red)?
Code:

// RadarChart.js
import React from 'react';
import { Radar } from 'react-chartjs-2';
import {
    Chart,
    RadialLinearScale,
    PointElement,
    LineElement,
    Filler,
    Tooltip,
    Legend,
} from 'chart.js';



Chart.register(
    RadialLinearScale,
    PointElement,
    Legend,
    Filler,
    LineElement,
    Tooltip,
);
Chart.defaults.font.size = '16';
Chart.defaults.color = 'black';

const RadarChart = () => {
    const data = {
        labels: ['Running', 'Swimming', 'Cycling', 'Reading'],
        datasets: [
            {
                data: [80, 30, 100, 65],
                borderWidth: 1,
            },
        ],
    };

    // Chart options

    return (
        <Radar
            data={data}
            options={{
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function (tooltipItems) {
                                return 'Result: ' + tooltipItems.raw + '%';
                            },
                        },
                    },
                    legend: {
                        display: false,
                    },
                    title: {
                        text: 'Title Here',
                        display: true,
                        font: { size: 24 },
                    },
                },

                responsive: true,
            }}
            className='rounded-md bg-zinc-300'
        />
    );
};

export default RadarChart;

How I want to make the chart looks like

Content Security Policy Blocked JS file from live reload

Essentially i have tried loading my site multiple times and cannot get the JS to work.

tester.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple HTML Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
        }
        header, footer {
            background-color: #f8f8f8;
            padding: 10px;
            text-align: center;
        }
        nav {
            margin-bottom: 20px;
        }
        nav a {
            margin: 0 10px;
            text-decoration: none;
            color: #333;
        }
        main {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<h1>Choose a country</h1><br>
<button function="onClick()">Grab my location</button>   
<script type="text/javascript" src="tester.js"></script>
</body>
</html>

the js file.


    function onClick(){
        if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(successCallback, errorCallBack)
        } else {
            alert("Geolocation is not supported by this browser")
        }
    }

    function    successCallback(){
        console.log(position)
        console.log(position.coords.latitude)
        console.log(position.coords.longitude)

        alert("Latitude is "+ position.coords.latitude +" and "+ position.coords.longitude )

        function errorCallBack() {
            switch(error.code) {
                case error.PERMISSION_DENIED:
                alert("Geolocation is not supported by this browser")
                break;
                case error.POSITION_UNAVAILABLE:
                alert("Geolocation is not supported by this browser")
                break;
                case error.TIMEOUT:
                alert("Geolocation is not supported by this browser")
                break;
                case error.UNKNOWN_ERROR:
                alert("Geolocation is not supported by this browser")
                break;
            }
        }
    }

It should be loading the button and asking for the location through the alert but it is not working. Nothing is showing up in the console either.

And then here is the output with the inspect showing me CSP has blocked my JS.

enter image description here

Trying to mock all the functions of a JavaScript class with Jest

I am trying to mock a JavaScript service class (AppInsightsService) that I pass in to a tool class (OrderHistoryTool) to use. I don’t want to return any data from the mock – I just want to ignore all calls to the service functions, and also allow me to pass in the mock when I create my tool that uses that service.

I have tried various and sundry examples that I have seen when searching online, but they are not working for me. I’m sure I’m doing something wrong, but I’m not sure what it is.

Here is a nutshell of the service class that I want to mock:

@Injectable()
export class AppInsightsService {
  constructor(private readonly config: ConfigService) {
...
  }

  async postEvent(appInsightsEventDTO: AppInsightsEventDTO) {
...
  }
...

Here is the tool class that uses the service:

export class OrderHistoryTool extends DynamicStructuredTool {
  constructor(
    ...
    appInsightsService: AppInsightsService,
  ) {
    super({
...
      }),
      func: async (payload: OrderHistoryInput): Promise<string> => {
        appInsightsService.postEvent(
          {
            name: 'OrderHistoryRequested',
            properties: {
              conversationId: conversationId,
              athleteId: athleteId,
            },
          });
...

Here is my test:

const appInsightsServiceMock = jest.mock('../../app-insights/app-insights.service', jest.fn());
import { AppInsightsService } from '../../app-insights/app-insights.service';

enableFetchMocks();

// NOTE: TRIED USING THIS TOO BUT SAME ERROR
// jest.mock('../../app-insights/app-insights.service', () => {
//   return {
//     AppInsightsService: jest.fn().mockImplementation(() => {
//       return jest.fn().mockImplementation(() => {
//         return undefined;
//       });
//     }),
//   };
// });

describe('orderHistory - unit tests', () => {

  it('verify correct output', async () => {

    // NOTE: TRIED USING THIS TOO BUT SAME ERROR
    // const appInsightsServiceMock = jest.fn();

    const orderHistoryTool = new OrderHistoryTool(
      ...
      appInsightsServiceMock as unknown as AppInsightsService,
    );

    const result = await orderHistoryTool.invoke(
      {
        orderNumber: '123456',
      },
    );

I am getting an error when I try to run the test. It is failing when it tries to execute the postEvent() function from the service:

    [tool/error] [1:tool:order_history] [37ms] Tool run errored with error: "appInsightsService.postEvent is not a function
    TypeError: appInsightsService.postEvent is not a functionn    at OrderHistoryTool.func (orderHistory.ts:63:28)n    at OrderHistoryTool._call 

How do I create a mock of the class that will mock all the functions, and allow the user to call those functions as if they are real?

Dynamically creating a reusable, editable, and savable clipping path with bezierCurveTo() for image masking in canvas

I want to dynamically create, with mouse, savable, reusable and editable bezier curve paths comprising moveable points and handles just like the pen tool allows in Photoshop. I would use these for masking parts of an image for composite layering. I’m looking for a lightweight vanilla javascript solution that I can work with, expand, and learn from.

Because of my current very little knowledge of HTML5 canvas applications, I could only programmatically supply clipping path values via bezierCurveTo() for masking an image through an irregular shape, but I am looking for a solution that allows me to dynamically draw, edit, reuse, and save clipping paths for image mask creation just like the pen tool in Photoshop provides. Here is the programmatical version I tried so far in this fiddle:

Note: Using img.onload for example only.

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');

// Create an image element
var img = document.createElement('IMG');

// When the image is loaded, draw it
img.onload = function () {

// Save the state, so we can undo the clipping
ctx.save();

var xoff = 10; //  pixel x-offset of handle (when moved dynamically)
var yoff = 10; //  pixel y-offset of handle (when moved dynamically)
    
// This is the irregular shape
ctx.beginPath();
ctx.moveTo(29 + xoff, 55 + yoff);
ctx.bezierCurveTo(18 + xoff, 37 + yoff, 39 + xoff, 16 + yoff, 48 + xoff, 28 + yoff);
ctx.bezierCurveTo(82 + xoff, 75 + yoff, 162 + xoff, 5 + yoff, 155 + xoff, 18 + yoff);
ctx.bezierCurveTo(128 + xoff, 73 + yoff, 154 + xoff, 123 + yoff, 167 + xoff, 131 + yoff);
ctx.bezierCurveTo(186 + xoff, 143 + yoff, 111 + xoff, 145 + yoff, 96 + xoff, 148 + yoff);
ctx.bezierCurveTo(81 + xoff, 151 + yoff, 24 + xoff, 154 + yoff, 34 + xoff, 135 + yoff);
  
ctx.closePath();

// Clip to the current path
ctx.clip();
    
ctx.drawImage(img, 0, 0);
    
// Undo the clipping
ctx.restore();
}

// Specify the src to load the image
img.src = "http://i.imgur.com/gwlPu.jpg";

In attempting to solve my problem, I analyzed pertinent code made freely available in this post, but I can’t quite grasp how to conjugate only what is strictly needed for implementing the dynamic aspect of drawing clipping paths with bezierCurveTo().

Lastly, I want to implement the clipping path functionality into this freely available javascript-canvas-image-mask application. I would add a pen tool option right over the paint brush tool option that is already implemented in that code. Therefore, the javascript-canvas-image-mask application will be the UI/UX template used to provide both pen and paint brush tools for image masking.

So any working samples, hints or suggestions you want to offer me should be applicable to the javascript-canvas-image-mask application mentioned in the above link. Lean and simple is best – I’m not interested in adopting existing frameworks because they usually provide many more functionality than I actually need.

Thank you for your guidance, can’t wait to get my hands more dirty on this one.

ReactNative not rendering spinner and rendering other unwanted loading component

I’m trying to do loading spinner using ActivityIndicator with ReactNative. I’ve mocked rest api to see if spinner works. The problem is, despite that I am using ActivityIndicator, I see component which I have not created, while isLoading is true.

Component I see instead has text ‘Loading…’ in top left corner.

loading component

Function which mocks endpoint with loading time:

async fetchFishDetails(fishId: number): Promise<ApiResponse<any>> {
        let fish: Fish | undefined
        let user: any | undefined

        fish = this.user1.fishes.find(fish => fish.id === fishId)
        user = this.user1
        if (fish === undefined) {
            fish = this.user2.fishes.find(fish => fish.id === fishId);
            user = this.user2
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        
        return {
            status: 200,
            body: {fishDetails: fish, user: user}
        }
    }

Function that handle response from function above:

export const getFishDetails = async (fishId: number): Promise<ServiceResponse<any>> => {
    console.debug('getFishDetails(), fishId=', fishId);

    try {
        const response = await fishRestApi.fetchFishDetails(fishId);
        
        if (response.status === 200) {
            return new ServiceResponse(Type.SUCCESS, response.body);
        } else {
            console.error('Error occurred fetching fish from backend')
            return new ServiceResponse(Type.FAIL, undefined);
        }
    } catch (error) {
        console.error('Error occurred getting fish, err=', error);
        return new ServiceResponse(Type.FAIL, undefined);
    }
};

Fetching data in component

    useEffect(() => {
        setIsLoading(true)
        console.log('start loading')
        getFishDetails(fishId)
            .then(response => {
                if (response.type === Type.SUCCESS) {
                    const {fishDetails, user} = response.body;
                    setFishDetails(fishDetails);
                    setUser(user);
                    setProfilePictureUri(user.picture ? {uri: user.picture} : require('../assets/user-default.png'));
                } else {
                    console.log('Failed to get fish details');
                }
            })
            .catch(err => {
                console.error('Error fetching fish details:', err);
            })
            .finally(() => {
                setIsLoading(false);
                console.log('loading ended')
            })

    }, [fishId]);

View that is returned

return (
        <ScrollView style={styles.container}>
            {isLoading ? (<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <ActivityIndicator size="large" animating={true}/>
            </View>) : <View style={styles.content}> ....  </View>

Would be grateful for an explanation about this ‘Loading…’ component and for all other advices.

I’ve tried to search google and documentation about the component and couldn’t find anything.

Nightwatch test don’t fail when NoSuchElementError is thrown

I inherited an automation test suite in Nightwatch/Cucumber and encountered an interesting issue. When a step fails due to an element not being found or an assertion error, the scenario continues running and eventually marks as ‘passed’.

I tried adding abortOnAssertionFailure: true and abortOnElementLocateError: true to my config file, but it didn’t make any change to the test run. Ideally, the scenario should abort as soon as anything fails, and the scenario should be marked as ‘failed’. A day of research didn’t give me an answer. I’d appreciate any pointers.

Using ES2021 for Public Angular Libraries instead of Angular Package Format?

I’ve been using the Angular Package Format for publishing public Angular libraries like this one.

I’m considering switching the build to just output ES2021 modules with Typescript Types instead of using the Angular Package Format, and I’m wondering whether there are any versions of Angular 2+ that would not be compatible with this?

I was thinking of using a tsconfig.json like this:

{
  "compilerOptions": {
    "target": "es2021",
    "module": "es2020",
    "lib": ["es2021", "DOM", "DOM.Iterable"],
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "inlineSources": true,
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noImplicitThis": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "forceConsistentCasingInFileNames": true,
    "noImplicitOverride": true,
    "types": ["mocha"]
  },
  "include": ["src/**/*.ts"],
  "exclude": []
}

So the "src/**/*.ts" files would be compiled into the build directory. The src/index.ts would be used to export the public API that same way public-api.ts does in the Angular Packge Format.

And within package.json the resources built would be exposed like this:

"main": "build/index.bundle.js",
"module": "build/index.js",
"type": "module",
"types": "build/index.d.ts",

Are the any Angular 2+ versions that would be incompatible with this approach?

code in script tag of html within a flask app throwing small annoying errors

Home.html file:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" type="text/css" href="{{url_for("static",filename="css/css.css")}}">
</head>
<body>
<h1>Welcome to recipe book</h1>
<p>{{length}}</p>
<script>
const amount = "{{length}}";
let list = {{images , tojson}};
const base_URL = "{{ url_for('static',filename='images') }}"; 
const altText = {0:"Breakfast",1:"Lunch",2:"Dinner",3:"Snacks"};
for(let count=0;count<amount;count++){
    let current_image = document.createElement('img');
    let Cur_URL = base_URL + "/" + list[count];
    console.log(Cur_URL);
    current_image.setAttribute("src",Cur_URL);
    current_image.setAttribute('alt',altText[count]);
    current_image.setAttribute('height','200');
    current_image.setAttribute('width','auto');
    document.body.appendChild(current_image);
}   
</script>
</body>

</html>

main.py Flask python file:

#,redirect,url_for,send_from_directory,
from flask import Flask,render_template
import os
app = Flask(__name__)
@app.route("/")
def home():
    parent  = r"C:UserskhaitDesktopWebsiteRecipe_Bookstaticimages"
    everything = os.listdir(parent)
    images = []
    for i in everything:
        if os.path.isfile(os.path.join(parent,i)):
            images.append(os.path.join(parent,i))
    length = len(images)
    return render_template("Home.html",images=images,length=length)

if __name__ == "__main__":
    app.run(debug=True)`

i was just tryna use the length variable in my html. and it throws these errors in relation to this line: “const amount = {{length}};” and this line “console.log(amount);”:

Error 1:
Property assignment expected.javascript
Error 2:
Declaration or statement expected.javascript

I am aware many similar questions have been asked on this and I asked a similar one about the length variable. But that was a numerical flask variable and this is a list flask variable. I looked through them and couldn’t find an answer to my problem. I’m also interested to know what would the proper syntax be for boolean,char and string variables. I assume dict variables would have the same logic as the list variables. Right?
Any help would be greatly appreciated.