Type return value based on parameter with unknown type

Say I have two types:

type User = {
  name: string;
  age: number;
  roles: string[];
}

type Post = {
  title: string;
  author: string;
}

I have a generic class that can retrieve properties from these types:

class Resource<T = {}> {
  public declare resource: T;

  constructor(resource: T){
    this.resource = resource;
  }

  get(key: keyof T): any {
    return this.resource[key];
  }
}

Now if I extend this class for the user:

class UserResource extends Resource<User> {}

const user = new UserResource({
  name: 'Bob Smith',
  age: 40,
  roles: ['Author', 'Admin']
});

What I’d like to do is type the return value of the get function based on the parameter provided.

const roles = user.get('roles'); // string[]
const name = user.get('age'); // number

I’ve seen answers using conditional types, but it wouldn’t be realistically possible here to construct a conditional type for all of the properties of each type. Is this possible?

Test createRoot().render() using jest

I have a custom theme I am adding as in the code below:

//main.tsx
import App from "./app/lib/App";
import { ThemeProvider } from "./core";
import { MyThemeProvider} from "./MyThemeProvider";
import { themeRegistries} from "./ThemeProviders/themeRegistries";

const domNode = document.getElementById("root");
createRoot(domNode).render(
  <ThemeProvider themeName={"CompanyDefaultTheme"}>
    <MyThemeProvider
      applicationName="My Custom Application Name"
      scopeName="My application scope"
      themeName="MyCustomTheme"
      themeRegistries={[themeRegistries]}
    >
       <App />
    </MyThemeProvider>
  </ThemeProvider>
);

My plan to test it is to load the component and find the component with the My Custom Application Name and verify it exists in the DOM.

//main.spec.tsx
/// <reference types="jest" />
import React from "react";
import { screen } from "@testing-library/react";

jest.mock("react-dom", () => {
  jest.fn();
});

describe("Application root", () => {
  it("should render without crashing", async () => {
    const div = document.createElement("div");
    div.id = "root";
    document.body.appendChild(div);

    require("./main");
    const component = await screen.findByText("My Custom Application Name");
    expect(component).toBeInTheDocument();
  });
});

My test fails with the below error:

  ● Test suite failed to run
                                                                                                                                                                                                                                                                                                              
    TypeError: Cannot read properties of undefined (reading '__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED')

      2 | import React from "react";
    > 3 | import { screen } from "@testing-library/react";
        | ^
      4 |
      5 | jest.mock("react-dom", () => {
      6 |   jest.fn();

      at ../../node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1125:32
      at Object.<anonymous> (../../node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-test-utils.development.js:1740:5)
      at Object.<anonymous> (../../node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/test-utils.js:6:20)
      at Object.<anonymous> (../../node_modules/.pnpm/@[email protected][email protected][email protected]/node_modules/@testing-library/react/dist/act-compat.js:10:41)
      at Object.<anonymous> (../../node_modules/.pnpm/@[email protected][email protected][email protected]/node_modules/@testing-library/react/dist/index.js:7:18)
      at Object.<anonymous> (src/main.spec.tsx:4:1)

I am not really experienced with testing libraries like jest. How can I confirm MyThemeProvider was loaded?

Attempted to finish an input event but the input event receiver has already been disposed and setTimeOut()

$('.status').on('change', function(){
    if (glWatchIdGeo === 0) {
        glWatchIdGeo = navigator.geolocation.watchPosition(setWatchingPosition, errorWatchingPosition, { timeout: 4000, enableHighAccuracy: true });
    };
    setTimeout(navigator.geolocation.getCurrentPosition(setStat, setStat, { timeout: 15000, enableHighAccuracy: true, maximumAge: 0 }),5000);
    });
}

seems not the best way – cause error. “Attempted to finish an input event but the input event receiver has already been disposed”. Is there another way to make timeout for letting geowatch gather some data?

I try this construction, because I don’t want to set constant geowatch, but cold call of getCurrentPosition sometimes returns the wrong coordinates with big displacement.

overlapping divs and problem with html on smaller screen devices

So iam working on a website but the problem is that there is a overlap objects over other objects when entering a mobile phone mode
Some elements apears on others and also the screen starts in the buttom not the top
Images :

enter image description here

as You see there is the sentence: Join with us which does apear above others and also the content starts from buttom and not top

<body>
    <div class="container">
        <!-- FORM SECTION -->
        <div class="row">
            <!-- SIGN UP -->
            <div class="col align-items-center flex-col sign-up">
                <div class="form-wrapper align-items-center sign-up">
                    <div class="form sign-up">
                        <form id="registrationForm">
                            <!-- Your form elements remain unchanged -->
                        </form>
                    </div>
                </div>
            </div>
            <!-- END SIGN UP -->
            <!-- SIGN IN -->
            <div class="col align-items-center flex-col sign-in">
                <div class="form-wrapper align-items-center sign-in">
                    <div class="form sign-in">
                        <!-- Your sign-in form elements remain unchanged -->
                    </div>
                </div>
                <div class="form-wrapper">
                    <!-- Additional content if needed -->
                </div>
            </div>
        </div>

        <div class="row content-row">
            <div class="col align-items-center flex-col">
                <div class="text sign-in">
                    <div class="eyes-container">
                        <div class="eye" id="left-eye">
                            <div class="pupil"></div>
                        </div>
                        <div class="eye" id="right-eye">
                            <div class="pupil"></div>
                        </div>
                    </div>
                </div>
                <div class="img sign-in">
                </div>
            </div>
            <div class="col align-items-center flex-col">
                <div class="img sign-up">
                </div>
                <div class="text sign-up">
                    <h2>
                        Join with us
                    </h2>
                </div>
            </div>
            <!-- END SIGN UP CONTENT -->
        </div>
        <!-- END CONTENT SECTION -->
    </div>
    <script src="/src/js/signup.js"></script>
</body>

here is the Body of my html
my css file is 450 lines so i will leave it
so anyone can help?

I tried some solutions from the Internet which did not work

Given a string change every second letter to an uppercase ‘Z’. Assume there are no space. let str1 = “javascript”;

// Given a string change the every second letter to an uppercase ‘Z’. Assume there are no space.
let string be javascript
// Example output:
// jZvZsZrZpZ OR each letter on a new line

// *********** HERE IS MY CODE **********************

> let newarr = str1.split(''); 
> let newword = "Z";
> for(i = 1; i < newarr.lenth; i += 2){
> newarr[i] = newword; newword.join('');}
> 
> console.log(newword);

// *************** Here is my other code I tried ****************

> let newarr = str1.split(''); 
> for(i = 1; i < newarr.lenth; i+=2){
> newarr.replace('newarr[i]' , 'z'); newarr.join('');}
> 
> console.log(newarr);

Which code closer to correct ? And where Did I go wrong for both codes??

Simplybook book(). Instance not defined error

I’m relatively new to programming and I have to create a booking system for the company I work at using Simplybook.me

This is the code I’ve tried

jQuery(document).ready(function () {
    

    
    
    
    var loginClient = new JSONRpcClient({
        'url': 'https://user-api.simplybook.me' + '/login', //Connects to the API
        'onerror': function (error) {
            instance.error(error);
            }
    });
    
    client = null,
    
    
    $company = "COMPANY";
    $user = "USER"; //Fill in this data. Name of the account: email
    $pass = "PASS"; //Fill in this data. Password
    
    var token = loginClient.getUserToken($company, $user, $pass);
    this.client = new JSONRpcClient({
        'url': 'https://user-api.simplybook.me' + '/admin/',
        'headers': {
            'X-Company-Login': $company,
            'X-User-Token': token
        },
        'onerror': function (error) {
            instance.error(error);
        }
    });
    
    // Booking trial (Danger)
    
    $additionalFieldsActivated = this.client.isPluginActivated('event_field');
    //console.log($additionalFieldsActivated); // FALSE
    
    //$additionalFields = this.client.getAdditionalFields();
    $additionalFields = {};
    
    //console.log($additionalFields);
    
    
    
    //console.log($additional);
    
    var eventId = 170;
    var unitId = 35; // Luis Solana unit (provider) code
    var date = "2023-12-12";
    var time = "11:11:11";
    var clientData = {
        'id': 293,
        'name': "Luis" + " " + "Solana",
        'email': "EMAIL",
        'phone': "+34XXXXXXXXX",
    };
    //$clientData = 293;
    
    console.log(clientData);
    
    $booking = new Object();
    $booking = this.client.book(eventId, unitId, date, time, clientData, $additionalFields);
    console.log($booking);
    // Logs
    
    $servicesList = this.client.getCategoriesList();
    $clientList = this.client.getClientList();
    $unitList = this.client.getUnitList();
    $eventList = this.client.getEventList();
    //console.log($clientList);
    
    
    
    
    
    
});

However, an error pops.

Uncaught ReferenceError: instance is not defined
    onerror file:///C:/Users/lsolana/Desktop/DATA TASAP/Software/TASAP_Bookings_a1/js/query.js:29
    success file:///C:/Users/lsolana/Desktop/DATA TASAP/Software/TASAP_Bookings_a1/js/json-rpc-client.js:100
    jQuery 6
    method file:///C:/Users/lsolana/Desktop/DATA TASAP/Software/TASAP_Bookings_a1/js/json-rpc-client.js:88
    <anonymous> file:///C:/Users/lsolana/Desktop/DATA TASAP/Software/TASAP_Bookings_a1/js/query.js:62
    jQuery 8

I’ve tried console.log()-ing $booking, and it says it doesn’t find the client details, but I believe it is because of the preceding code.

Thanks!

Sequelize how to select all Tours that belongs to a Category?

I have four tables, a category has many region, a region has many location, a location has many tour, like a stair, I want to select all tours that belong to one category, I tried this solution but it always return all the tour, seems like the “where” is placed in the wrong place because it checks for the condition of Region, not the Tour, and return all the tour.

 Tour.findAndCountAll({
        include: {
            model: Location,
            include: {
                model: Region,
                include: {
                    model: Category,
                    where: {
                        id: req.params.category
                    }
                }
            }
        }, 

Thanks in advance :”D

I tried to directly include Category in Tour but Sequelize doesn’t support that

How to write dynamic expressions in javascript [closed]

I want to write a dynamic condition in javascript

like this

let condition = (string.length>10)?(variable1+variable2<=variable3):true

if(condition) { }

if(condition(variable1,variable2,variable3) {}

how to pass variable1,variable2,variable3 to condition ?
variable1 ia a constant , variable2 is array value while traveling array, variable3 is string length

Thank you

chrome exension background script keeps removing listener

I’ve a chrome extension with a content + background + popup scripts.

On the first line of my background script i do:

chrome.runtime.onMessage.addListener(handleAction);

in absolutely nowhere in the code i call removeListener or something similar. however, at some random moments, when the popupscript tries to call chrome.runtime.sendMessage I get an error that there are no listeners

I can catch the exception and reload the extension than everything goes fine, BUT THIS IS NOT SOLUTION IS A HORRIBLE WORKAROUND

the question is, what can cause an chrome extension to remove a background script as listener for these events? how can i prevent or force the listener to be re-inserted?

I’m using webpack to minify and mingle the code, is it possible that it is doing something? what would be another option to obfuscate the extension code?

thanks

Issue with Displaying “X” on First Click in Tic-Tac-Toe Game

Description:

I’m working on a tic-tac-toe game, and I’m encountering an issue where the “X” sign is not displaying on the first click on any box. After the first click, it works correctly.

Problem Details:

  1. Issue 1: “X” not displaying on the first click

    • When I click on a box in the game, the “X” sign doesn’t appear on the first click. However, subsequent clicks work as expected.

If you find any further problems in my code then please suggest me as I am a beginner

Code Snippets:

Here is the relevant code for my tic-tac-toe game:

HTML file:

replit

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>

<div class="boxes" onclick = "tosswinner(this);turner();"></div>
<div class = "head">TOSS</div>

<div id = "para">HEADS OR TAILS ? </div>

<br/>

<div>

<button class = "toss" onclick = "Heads()">HEADS</button>        

<button class = "toss"onclick = "Tail()">TAIL</button>

</div>

 </div>

CHOOSED

<div class = "head">TOSSING</div>

<div id="tossing1" class="load">

</div>

display:flex;

justify-content:center;

height:100vh;

width:100vw;

align-content:center;

flex-direction:column;

}

#mainbox{

width: 240px;

height: 240px;

display:flex;

position:absolute;

right:60px;

flex-flow:row wrap;

background-color: yellow;

}

.boxes{

height:75px;

width:75px;

background:red;

margin:2px;

color:white;

font-size:25px;

}

#pop,#tosser,#toss1{

height:200px;

width:280px;

background:skyblue;

position:absolute;

top:0%;

left:12.5%;

visibility:hidden;

transform:translate(0px,0px)

scale(0.01);

transition:transform 0.4s,top 0.4s;

display:flex;

flex-flow:column wrap;

border-radius:20px;

justify-content:space-between;

align-items:center;

}

#pop.popup,#tosser.tosseropen,#toss1.open1{

visibility:visible;

display:flex;

top:0%;

transform:translate(0px,100px)

scale(1);

}

.head{

width:280px;

height:50px;

background:darkblue;

color:white;

font-size:30px;

display:flex;

justify-content:center;

align-items:center;

font-weight:bolder;

border-top-left-radius:20px;

border-top-right-radius:20px;

}

#para{

display:flex;

justify-content:center;

align-items:center;

font-size:30px;

color:white;

font-weight:bold;

}

.toss{

height:50px;

width:100px;

margin:0px 20px 30px 18px;

background:royalblue;

color:white;

font-size:25px;

border:none;

border-radius:10px;

font-weight:bold;

}

#tossing{

color:white;

font-size:27px;

font-weight:bolder;

margin-bottom:60px;

}

.text{

color:white;

font-size:18px;

font-weight:bolder;

margin-bottom:38px;

}

.text1{

color:white;

font-size:25px;

font-weight:bolder;

margin-bottom:65px;

}

.load{

height:50px;

width:50px;

border:5px black solid;

border-top:5px royalblue solid;

border-radius:50%;

position:fixed;

top:80px;

animation:SpinAnimate 1s linear 0s infinite normal;

}

@keyframes SpinAnimate{

from{

transform:rotate(0deg);

}

to{

transform:rotate(360deg);

}

let arr = Array.from(boxes)

console.log(arr);

let pop = document.getElementById(“pop”)

let tossing = document.getElementById(“tossing”)

let tosser = document.getElementById(“tosser”)

let toss1 = document.getElementById(“toss1”)

let tossing1 = document.getElementById(“tossing1”)

setTimeout(() => {

pop.classList.add(“popup”)

},3000)

let botTurn = “”

let choosedToss = “”;

let count = 0;

async function turner(){

let selected = arr[Math.floor(Math.random()*arr.length)];

setTimeout(() => {

if (selected.innerHTML == “”){

setTimeout(() => {

  selected.innerHTML='O'

},50)

}else{

return turner()

}

},50)

count++;

}

function tosswinner() {

let box = this

if (box.innerHTML === ""){

box.innerHTML = “X”;

}

boxes.forEach(box => {

box.addEventListener(‘click’, function() {

tosswinner.call(this);

});

count++;

})

}

async function FinalFunc() {

let Hulk = new Promise((resolve,reject) => {

setTimeout(() => {

toss1.classList.remove("open1")

  resolve(1)

},2000);

});

const result = await Hulk;

console.log(result);

}

async function R() {

let THOR = new Promise((resolve,reject) => {

setTimeout(() => {

  if(choosedToss == botTurn){

tossing1.innerHTML="you won , first turn is yours";

  }else{

    tossing1.innerHTML="you have losted , you will play next to the winner ";

  }

tossing1.classList.add("text1")

  resolve("Thor");

},1500);

});

const result = await THOR;

console.log(result);

}

async function botTurns(){

let TOSS = [“Heads”,”Tail”];

botTurn = TOSS[Math.floor(Math.random()*TOSS.length)];

tossing1.innerHTML=<h1>${botTurn}</h1>

tossing1.classList.add(“text”)

}

async function Messi() {

let cap = new Promise((resolve,reject) => {

setTimeout(() => {

tossing1.classList.remove(“load”)

  botTurns()

  resolve(botTurn);

},3000);

});

const result = await cap;

console.log(result);

}

async function Message() {

let stark = new Promise((resolve,reject) => {

setTimeout(() => {

tossing.classList.remove(“load”)

  tossing.innerHTML=`you choosed ${choosedToss} !`

  resolve(`you choosed ${choosedToss}`);

},1000);

});

const result = await stark;

console.log(result);

}

async function popdown() {

let tony = new Promise((resolve,reject) => {

setTimeout(() => {

tosser.classList.remove(“tosseropen”)

  resolve("rate");

},2000);

});

const result = await tony;

console.log(result);

}

async function Heads(){

choosedToss = “Heads”

pop.classList.remove(“popup”);

tosser.classList.add(“tosseropen”)

await Message();

await popdown();

toss1.classList.add(“open1”)

await Messi();

await R();

await FinalFunc()

}

async function Tail(){

choosedToss = “Tail”

pop.classList.remove(“popup”);

tosser.classList.add(“tosseropen”)

await Message();

await popdown();

toss1.classList.add(“open1”)

await Messi();

await R();

await FinalFunc();

}

Regards

Thank you if you only tried to solve my problem

What I’ve Tried:

I’ve reviewed the code for the turner and tosswinner functions, as suggested by an expert on the OpenAI platform.I’ve ensured that I’m correctly invoking the tosswinner function on box clicks.

Additional Information:

I’m using HTML, CSS, and JavaScript to build this game.I suspect there might be a conflict in event handling or a timing issue, but I’m unable to pinpoint the exact problem.

Request for Help:

I would appreciate any guidance or suggestions on how to fix the issues described above. If you can identify the problem in my code or offer a different approach to solve these issues, it would be greatly appreciated.

Thank you for your help!

zoom and pan not working in fabricjs for touch devices

I implemented the drawing feature on canvas using fabric js in angular. all things works perfect for me. but Now I have to add canvas zoom and pan options using fabric js. for that I refer this fabricjs example.

Zoom and Pan option working on Mouse Event there is no issue. but when I’m using Touch Devices it not works.

see below code what I tried.

import {
  AfterViewInit,
  Component,
  ElementRef,
  VERSION,
  ViewChild,
} from '@angular/core';
import { fabric } from 'fabric';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
  version = VERSION.full;

  @ViewChild('mainHtmlCanvas') mainHtmlCanvas!: ElementRef;

  mainCanvas!: fabric.Canvas;
  isDragging: boolean = false;
  selection: boolean = true;
  lastPosX!: number;
  lastPosY!: number;
  isDrawingMode: boolean = false;

  ngAfterViewInit() {
    this.mainCanvas = new fabric.Canvas(this.mainHtmlCanvas.nativeElement, {
      hoverCursor: 'pointer',
      selection: this.selection,
      selectionBorderColor: 'blue',
      width: 800,
      height: 500,
      allowTouchScrolling: true,
      isDrawingMode: this.isDrawingMode,
      backgroundColor: '#eee',
    });

    const rect = new fabric.Rect({
      left: 100,
      top: 100,
      fill: 'red',
      width: 50,
      height: 100,
    });
    this.mainCanvas.add(rect);
    // this.mainCanvas.centerObject(rect);

    const circle = new fabric.Circle({
      left: 80,
      top: 50,
      fill: 'pink',
      radius: 50,
    });
    this.mainCanvas.add(circle);
    this.mainCanvas.centerObject(circle);

    const sequre = new fabric.Rect({
      left: 300,
      top: 350,
      fill: 'blue',
      width: 100,
      height: 100,
    });
    this.mainCanvas.add(sequre);

    const textbox = new fabric.Textbox('ABC Text', {
      left: 300,
      top: 100,
      width: 150,
      fontSize: 25,
      textAlign: 'center',
    });
    this.mainCanvas.add(textbox);

    this.mainCanvas.on('touch:gesture', (e) => {
      console.log('touch:gesture', e);
    });

    this.mainCanvas.on('touch:drag', (e) => {
      console.log('touch:drag', e);
    });

    this.mainCanvas.on('mouse:wheel', (opt) => {
      var delta = opt.e.deltaY;
      var zoom = this.mainCanvas.getZoom();
      zoom *= 0.999 ** delta;
      if (zoom > 20) zoom = 20;
      if (zoom < 0.01) zoom = 0.01;
      this.mainCanvas.zoomToPoint({ x: opt.e.offsetX, y: opt.e.offsetY }, zoom);
      opt.e.preventDefault();
      opt.e.stopPropagation();
      var vpt = this.mainCanvas.viewportTransform ?? [];
      if (zoom < 400 / 1000) {
        vpt[4] = 200 - (1000 * zoom) / 2;
        vpt[5] = 200 - (1000 * zoom) / 2;
      } else {
        if (vpt[4] >= 0) {
          vpt[4] = 0;
        } else if (vpt[4] < this.mainCanvas.getWidth() - 1000 * zoom) {
          vpt[4] = this.mainCanvas.getWidth() - 1000 * zoom;
        }
        if (vpt[5] >= 0) {
          vpt[5] = 0;
        } else if (vpt[5] < this.mainCanvas.getHeight() - 1000 * zoom) {
          vpt[5] = this.mainCanvas.getHeight() - 1000 * zoom;
        }
      }
    });

    this.mainCanvas.on('mouse:down', (opt) => {
      var evt = opt.e;
      if (evt.altKey === true) {
        this.isDragging = true;
        this.selection = false;
        this.lastPosX = evt.clientX;
        this.lastPosY = evt.clientY;
      }
    });
    this.mainCanvas.on('mouse:move', (opt) => {
      if (this.isDragging) {
        var e = opt.e;
        var vpt = this.mainCanvas.viewportTransform ?? [];
        vpt[4] += e.clientX - this.lastPosX;
        vpt[5] += e.clientY - this.lastPosY;
        this.mainCanvas.requestRenderAll();
        this.lastPosX = e.clientX;
        this.lastPosY = e.clientY;
      }
    });
    this.mainCanvas.on('mouse:up', (opt) => {
      // on mouse up we want to recalculate new interaction
      // for all objects, so we call setViewportTransform
      this.mainCanvas.setViewportTransform(
        this.mainCanvas.viewportTransform ?? []
      );
      this.isDragging = false;
      this.selection = true;
    });
  }
}

<p>Start editing to see some magic happen :)</p>
<p>
  angular <b>v{{ version }}</b>
</p>

<div style="border: 1px solid">
  <canvas #mainHtmlCanvas></canvas>
</div>

“fabric”: “5.3.0”,
“@types/fabric”: “^5.3.4”,
“typescript”: “4.8.2”,
“angular”: “14.2.0”

You can test my Code on stackblitz

How to render the api call only when there is some change

#In below code : I have used useEffect hook. In that I am calling apiData()(it has array of objects coming from api).
From API we are getting id, name, parent name, isActive. isActive is mapped with toggle which changes. I need to update the changes and retrive it. so I have used products. But because of this the whole data is called again and again. Is there any other way of solving this issue. #

const [products, setProducts] = useState([]);
const transformData = (data) => {
    return data.map((item) => ({
      id: item.structureId,
      name: item.name,
      parent: item.parentName,
      isActive: item.isActive,
    }));
  };
 useEffect(() => {
    apiData()
      .then((data) => {
        const transformedData = transformData(data);
        setProducts(transformedData);
      })
      .catch((error) => console.error("Error in fetching data:", error));
  }, [products, transformData]);

Pass a text value from one website to another website using cypress

I want to pass a value from one website to admin dashboard using cypress. But the issue I am facing is that, whenever I try to use any method like to use a variable, localstorage, cookies, the next command cy.visit(‘second website’) clears everything I store and returns null value.

How can I do this in cypress?

I tried using localstorage, cookies , cypress.env() and variables