Nested select menu in angular

How do we create or is it possible to create a nested select menu like the example select screenshot menu below but using my mat-select below , if user select an item from REPM mat select it will show on the right side the Master Broker Company menu. Thanks.

#example select

enter image description here

#html code

<div style="margin-top: 8px;margin-left:8px;">  
                                <mat-form-field appearance="fill" class="transaction-control-filter">
                                    <mat-label class="transaction-detail-header-label">REPM</mat-label>
                                    <mat-select #rempselect multiple (openedChange)="changeREMPFilter($event)">
                                        <div  class="select-all-property-transaction-list">
                                            <mat-checkbox color="primary" [(ngModel)]="allSelectedREMP" [ngModelOptions]="{standalone: true}"
                                                (change)="toggleAllSelectionREMP()">Select All</mat-checkbox>
                                        </div>
                                        <mat-option (click)="optionClickREMP()" *ngFor="let remp of repmList" [value]="remp.display">
                                            {{remp.display}}
                                        </mat-option>
                                    </mat-select> 
                                </mat-form-field>
                            </div>

                            <div style="margin-top: 8px;margin-left:8px;">  
                                <mat-form-field appearance="fill" class="transaction-control-filter">
                                    <mat-label class="transaction-detail-header-label">Master Broker Company</mat-label>
                                    <mat-select #companyselect multiple (openedChange)="changeCompanyFilter($event)">
                                        <div class="select-all-property-transaction-list">
                                            <mat-checkbox color="primary" [(ngModel)]="allSelectedMasterBrokerCompany" [ngModelOptions]="{standalone: true}"
                                                (change)="toggleAllSelectionCompany()">Select All</mat-checkbox>
                                        </div>
                                        <mat-option (click)="optionClickMasterBroker()" *ngFor="let masterbroker of transactionMasterBrokerCompany" [value]="masterbroker.display">
                                            {{masterbroker.display}}
                                        </mat-option>
                                    </mat-select> 
                                </mat-form-field>
                            </div>

#this is my existing mat select

enter image description here

How to prevent scaling of background image using CSS?

I have a high-resolution image that is the background image of a div. The div keeps scaling it to a lower resolution but I would like to leave it unscaled. I don’t mind that the background image is cropped to show only a portion of the image as long as that portion has the original high-resolution.

How to prevent deleting image in ContentEditable

I created a text editor in ReactJS and I use ContentEditable in my project. so my problem is that when I insert an image into my text editor I will remove it just by clicking on the delete button on the inserted image not by backspace in contentEditable

I also add contentEditable="false" attribute into my image but not work again.

mycode to insert figure section

let cc: any = document.querySelector("#texttoselect");
var newFigure = document.createElement("figure");
var newline = document.createElement("div");
newFigure.setAttribute("contentEditable", "false");
newFigure.className =
  "flex flex-col items-center w-full h-auto text-center";
newFigure.innerHTML = `<div className='relative w-auto self-center max-w-full'><Image contenteditable="false" src='${resolve.data.link}' layout='fill' objectFit='cover' alt={'test'}/></div><figcaption className='w-full p-4 text-gray-g700 bg-gray-g400 justify-center items-center' data-placeholder='عنوانی برای عکس بنویسید'>test</figcaption>`;

newline.className =
  " w-full flex py-4 px-2 whitespace-pre-wrap  text-right item-center";

newline.innerHTML = `<span id="newlinespan"></span>`;
cc.appendChild(newFigure);
cc.appendChild(newline);
const el: any = document.getElementById("newlinespan");

setTimeout(function () {
      el.focus();
    }, 2000);

Auth0 SDK Not Passing code_verifier

I’m currently finishing up a project for a client of mine but am running into one issue preventing launch. I’m trying to set up SSO Login and Account Creation between Thinkific and my Webflow site using Auth0. When I login through my Webflow site and redirect to my Thinkific callback URL, I get an error message saying. Something went wrong when making the token request, error: {"error"=>"invalid_request", "error_description"=>"Parameter 'code_verifier' is required"}.

I tried following this guide to set up the code_verifier, but it was recommended to just use the Single Page App SDK which supposedly handles the sending of the code_verifier. Unfortunately this isn’t working for me at the moment with the below code. Did any of you with Auth0 experience happen to know what might be happening here? Any help would be much appreciated:

<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.2.3/firebase-database.js"></script>
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.13/auth0-spa-js.production.js"></script>
<script src="https://kit.fontawesome.com/1cd721ed46.js" crossorigin="anonymous"></script>

<script>
// Routes reserved for people who are logged in
var privatePages = [
  '/my-courses'
];

// Routes reserved for people who aren't logged in
var publicPages = [
  '/create-account',
  '/log-in'
];

let getStartedButton = document.querySelectorAll('.get-started-button');

// either with async/await
const auth0 = new Auth0Client({
  domain: 'podcatch.auth0.com',
  client_id: '{client id}'
});

console.log(auth0);
</script>
<script>
  let verifier;
  loginLink.addEventListener('click', login);
  
  function login () {    
    auth0.loginWithRedirect({
      redirect_uri: '{callback url}',
      client_id: '{id}',
      cacheLocation: 'localstorage'
    }).then(token => {
    //logged in. you can get the user profile like this:
    auth0.getUser().then(user => {
      console.log(user);
    });
  });
  };
</script>

typescript variable ‘x’ is used before being assigned

I need to push the result object in an array. But typescript is showing an error

TSError: ⨯ Unable to compile TypeScript:
test.ts:15:10 - error TS2454: Variable 'x' is used before being assigned.

15   return x;
            ~
            

This is my code. I don’t know to declare a global variable in typescript

import * as fs from "fs";
import * as path from "path";
import * as csv from "fast-csv";

function search_words(word: string) {
  var x: object[];
  fs.createReadStream(path.resolve(__dirname, ".", "data", "data.csv"))
    .pipe(csv.parse({ headers: true }))
    .on("error", (error) => console.error(error))
    .on("data", (row) => {
      if (row.english_word === word) x.push(row);
    })
    .on("end", (rowCount: number) => console.log(`Parsed ${rowCount} rows`));

  return x;
}

console.log(search_words("Hello"));

This method is I know.any other method is possible

let hi; // global variable
function hello{
hi = "hi mom"
}

Javascript function does not send data into Laravel route

I have created this button:

<button onclick="addToFavourites({{ $product->prd_id }})" class="btn btn-primary">
     <i class="fa fa-heart"></i>
     <span>
        Add to favourites
     </span>
</button>

So as you can see I have added an onlick function named addToFavourites which goes here:

function addToFavourites(productId) {
            $.ajaxSetup({
              headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
              }
            });
            $.ajax({
                url: baseurl + "/add-to-favourites",
                type: "POST",
                data: {
                    prd_id: parseInt(productId)
                },
                dataType: "json",
                success: function (output) {
                    $('#afterAddToFavourites').modal('show');
                }
            });
        }

So this function will call the route with URI of add-to-favourites with POST method:

Route::post("add-to-favourites", "ShopCartsController@addToFavourites")->name('addToFavourites');

And in the CartsController:

public function addToFavourites()
{
    $favPros = new FavouriteProduct();
    $favPros->user_id = auth()->user()->user_id;
    $favPros->prd_id = request()->prd_id;
    $favPros->save();
}

But now the problem is whenever I click on the button, it does not do anything at all!

And at the Console, I see this error:

POST https://sitename.com//add-to-favourites 500 (Internal Server Error)
send @ jquery.js:2
ajax @ jquery.js:2
addToFavourites @ProductName:1187
onclick @ProductName:458

But I don’t what’s going wrong here and how can I fix this…

So if you know, please help me out cause I really need this…

Thanks in advance.

Finding the next Canvas id in Jquery

When looking for the next element id in Jquery the simplest solution is to use closest(element). but it is not working for Canvas and I don’t know why.

$('a.findNext').click(function() {
  debugger;
  var nextSectionWithId = $(this).closest("canvas").nextAll("canvas[id]:first");
  if (nextSectionWithId) {
    var sectionId = nextSectionWithId.attr('id');
    $("#test").text(sectionId)
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="section_1">
  <a href="#" class="findNext">Find</a>
</div>
<div></div>
<canvas id="section_3"></canvas>
<canvas id="section_4"></canvas>

<div id='test'></div>

Demo :
http://jsfiddle.net/jtdgo304/6/

can i import scss file as variable with js ,like import styles from ‘./index.scss’?

i see antd mobile web import less file into ts file ,since react doesnot support less by default,i want to import scss file into my js file as a variable.The code as follows:

tsx file:

import styles from './demo1.less'

<Grid.Item>
        <div className={styles['grid-demo-item-block']}>A</div>
      </Grid.Item>

less file:

    .grid-demo-item-block {
  border: solid 1px #999999;
  background: #f5f5f5;
  text-align: center;
  color: #999999;
  height: 100%;
}

Calculating and positioning absolute DIV’s relative to other elements

I’m displaying a time schedule for a day with events occuring during this day.
Events have starting time and ending time.

It looks like this

time schedule

I made event boxes absolute div’s relative to schedule container. I then TRY to calculate height of box (dependant on event length) and offsetY (transform: translateY()) from top of container in order to place event starting and ending times correctly relative to timeline.

In the first picture there are 2 events, first on starts 9:30 ends 10:30. Second one starts 10:30 ends 13:30

When you look at them they basicly seem correct, but there is a issue with calculating offsetY. Look at this second picture

later events

In 2nd picture there are also 2 events. First starts 15:30 ends 16:30 , second 17:30 to 18:30 but now you can see there is a drift in positioning. Starting times dont match and error gets bigger down the line. Bigger error for 17:30 start than for 15:30.

This is how I calcualte offsetY :

First in Schedule component I set ref’s for Schedule container and one for timeline container which contains span with time text and hr element for line. I get container heights (scrollHeight for schedule container) and widths in this component and send them to MeetingBox component where I calculate this offset

export const Schedule = ({meetings}: ScheduleProps):JSX.Element => {
    const scheduleStart = 7
    const scheduleEnd = 22
    const scheduleLength = scheduleEnd - scheduleStart
    const containerRef = useRef<HTMLDivElement>(null)
    const timelineRef = useRef<HTMLDivElement>(null)
    const [refData, setRefData] = useState<RefElementData>({scheduleContainerHeight: 0, timelineContainerHeigth: 0, timelineContainerWidth: 0})

    useEffect(() => {
        if(timelineRef.current && containerRef.current){
            setRefData({
                scheduleContainerHeight: containerRef.current.scrollHeight,
                timelineContainerHeigth: timelineRef.current.clientHeight,
                timelineContainerWidth: timelineRef.current.clientWidth})
        }
    }, [timelineRef.current, containerRef.current])

    const createScheduleTimes = ():string[] => {
        const scheduleTimes:string[] = []
        for(let i = scheduleStart; i < scheduleEnd+1; i++){
            scheduleTimes.push(`${i}:00`)
            scheduleTimes.push(`${i}:30`)
        }
        return scheduleTimes
    }

    return <div className="sidebar-schedule-container" ref={containerRef}>
        {createScheduleTimes().map((time, index) => {
            return <div key={index} className="sidebar-timeline-container" ref={timelineRef}>
                <span className="sidebar-timeline-time">{time}</span><hr className="sidebar-time-line"/>
            </div>
        })}
        {meetings.map((meeting, index) => {
            return <MeetingBox key={index} refElementData={refData} scheduleStart={scheduleStart} scheduleLength={scheduleLength} meeting={meeting}/>
        })}
        <Spotter refElementData={refData} scheduleStart={scheduleStart} scheduleLength={scheduleLength}/>
    </div>
}

Here is MeetingBox which calculates offsetY.
In a nutshell what I try :

I take scrollHeight of Schedule container div and I map this height to schedule length.

lets say container scrollHeight is 1500 px and schedule starts at 7 and ends 22 like in my example. Then schedule length is 15, this means scrollHeight at 0px equals to 7:00 oclock (0 hours).

9:30 equals to 2.5 (normalized value) units from schedule start (9:30 – 7:00). I then calculate how much that is in percentage by normalized value / schedule length. For example 2.5 / 15.

When I have percentage this is final offsetY calculation :

offsetY: containerHeigth * offsetPercentage - (normalized * modification / 2)

Explanation is that I first tried simply

offsetY: containerHeigth * offsetPercentage

where there were obvious errors, I then modified to remove half of timeline container height because I center align hr element in that.

offsetY: containerHeigth * offsetPercentage - modification / 2

THere were still errors quite obviously and especially with bottom 2 events. I then put in there normalized value because that differs for each of the events and I ened up with

offsetY: containerHeigth * offsetPercentage - (normalized * modification / 2)

This gets me to this point where I am now. It seems quite close, errors on bottom events are much reduced, top events look alright. But I cant seem to figure out what am I missing to make them fit perfect ?

const MeetingBox = ({refElementData, scheduleStart, scheduleLength, meeting}: MeetingBoxProps):JSX.Element => {

    const [boxOffsets, setBoxOffsets] = useState<BoxOffsets>({offsetY: 0, boxHeigth: 0, boxWidth: 0})

    useEffect(() => {
        setBoxOffsets(calculateBoxOffsets(refElementData.timelineContainerHeigth, refElementData.scheduleContainerHeight))
    }, [refElementData])

    const calculateBoxOffsets = (modification: number, containerHeigth: number):BoxOffsets => {
        // calculate Y offset
        const startDate = new Date(meeting.StartTime)
        const startTime = startDate.getHours() + startDate.getMinutes() / 60
        const normalized = startTime - scheduleStart
        const offsetPercentage = normalized / scheduleLength

        console.log(normalized)

        // calculate heigth
        const endDate = new Date(meeting.EndTime)
        const meetingTime = (endDate.getHours() + endDate.getMinutes() / 60)
        const normalizedHeigth = meetingTime - startTime
        const heightPercentage = normalizedHeigth / scheduleLength

        // calculate X offset
        return {offsetY: containerHeigth * offsetPercentage - (normalized * modification / 2), boxHeigth: containerHeigth * heightPercentage - normalizedHeigth * modification / 2, boxWidth: refElementData.timelineContainerWidth}
    }

    return <div className="sidebar-meetingbox-container" style={{transform: `translateY(${boxOffsets.offsetY}px) translateX(47px)`, height:`${boxOffsets.boxHeigth}px`}}>
        <div className="sidebar-meetinbox-edge"></div>
    </div>
}

I cannot access elements included using *csi.min.js* in JavaScript

I want to animate my navbar using JavaScript. I have created separate navbar.html and included it using csi.min.js.
When I try to getElementById my navbar, show and hide button. it returns null and when try it on dev console it works.

navbar.html:

<nav>  
    <div class="site-mobile-menu collapse navbar-collapse show" id="main-navbar">
        navbar content
    </div>
<nav>

index.html:

<div data-include="/src/navbar.html"></div>


<script src="/src/js/navbar.js"></script>

navbar.js:

window.addEventListener("load", function() {
    // debugger;

    var mobNav = document.getElementById("main-navbar");
    var showNavBtn = document.querySelector("#show-nav");
    var hideNavBtn = document.getElementById("hide-nav");
    console.log(mobNav + " " + showNavBtn + " " + hideNavBtn);

    if (!mobNav == null || !showNavBtn == null || !hideNavBtn == null) {
        showNavBtn.onclick = function() {
            console.log("clicked");
            mobNav.classList.add("nav-shown");
        }
    } else {
        console.log("Error Opening Mobile Navbar");
    }
}, false);

how to get all data of price, qty from html in js and multiple it accordingly and add it into html in Django. anyone help me

I have attached the HTML on Photo
Question – how to get all data of price, qty from HTML in js and multiple it accordingly and add it into HTML in Django. anyone help me.

const x = document.getElementById("qty").innerHTML;
const y = document.getElementById("price").innerHTML;
const z = document.getElementById("total");

function calculator(qty, price) {
  let lowercase = price.toLowerCase();
  const remove_price_string = lowercase.replace("only", "");
  console.log(remove_price_string);
  let total = remove_price_string * qty;
  console.log(total);
}

calculator(x, y);

enter image description here

enter image description here

enter image description here

How to edit pipeline transforms

I have this pipeline:

const pipeline = util.promisify(stream.pipeline);

const test = async(socketA, socketB)=>{
    sockstA.on('throttle', () => {
        // how do I introduce throttle transform into the pipeline?
        // I need pipeline(socketA, throttleTransform(), socketB);
    });
    await pipeline(socketA, socketB);
}

The pipeline starts with 2 sockets and, based on a certain event, I want to introduce a throttling transform into the mix but I don’t know how to do that with stream.pipeline. I know it has an abort signal but that closes everything and sends an abort error.

Is there a way to require loopback4 as a node module?

I’ve been working for a long time with Loopback3, but it has reached EOL, so now I’m starting to migrate to LB4, the thing is, I’ve been digging around and haven’t found a specific way to require LB4 as a node module, as it is possible with LB3 (https://loopback.io/doc/en/lb3/Working-with-LoopBack-objects.html). I’m pretty sure I should be importing LB4 from the dist built folder, but I haven’t even found any reference or example on how to use it, if it is even possible.

Button when clicked does not call the callback function, ReactJS

Basically the problem is that when I click on the button nothing happens. If I change the code for the button from this

const Button =({text, callback}) =>(
    <Wrapper type="button" onclick={callback}>
        {text}
    </Wrapper>

);

to this

onst Button =({text, callback}) =>(
    <Wrapper type="button" onclick={callback}>
        {text}
    </Wrapper>

I get this error
Cannot update a component (Login) while rendering a different component (Button). To locate the bad setState() call inside Button,

Here is the code below
/LogIn.js

import React, {useState, useContext, useEffect} from "react";
import {useLocation, useNavigate} from 'react-router-dom'
import API from '../API';
//styles
import { Wrapper } from "./Header/Header.styles";
//Context
import { Content } from "./Header/Header.styles";
import Button from "./Button";
import { Context } from "../context";

const Login = () => {
    const[email, setEmail] = useState('');
    const[password, setPassword] = useState('');
    const[error, setError] = useState(false);

    const[user, setUser] = useContext(Context);
    const navigate = useNavigate();

    
    const handleSumbit = async () => {
        
        setError(false);
        try{
            
            const sessionID = await API.authenticate(
                email,
                password
            );
            console.log(sessionID);
            setUser({sessionID: sessionID.token,  email})
            navigate('/');
        }catch(error){
            setError(true);
        }
    };
    
    const handleInput = e => {
        const name = e.currentTarget.name;
        const value = e.currentTarget.value;
        if (name === 'email') setEmail(value);
        if(name === 'password') setPassword(value);
    };

    return(
        <Wrapper>
            <label>Email</label>
            <input
            type = 'email'
            value = {email}
            name = 'email'
            onChange={handleInput}
            />
            <label>Email</label>
            <input
            type = 'password'
            value = {password}
            name= 'password'
            onChange={handleInput}
            />
            <Button text = 'Login' callback = {handleSumbit} />
        </Wrapper>
    )
}

export default Login;

And here is the code for the Button

import React from "react";

import { Wrapper } from "./Button.styles";

const Button =({text, callback}) =>(
    <Wrapper type="button" onclick={callback}>
        {text}
    </Wrapper>

);

export default Button;