Cant access object from scene

I am having trouble accessing a object in my scene. I’ve figured out the reason I wasn’t able to access it was because the Raytracer was loading before the world had finished loading. It works fine for objects added by code, but it doesn’t work when looking for objects imported by GLTFLoader.

I have set up something to trigger an event when all the objects have been loaded. But I am unable to access the variable inside of the check in my update function.

    setRayCaster()
{
    this.rayCaster = new THREE.Raycaster()
    this.foundButton = this.main.scene.children.find(child => child.name === 'Test')
    this.objectsToTest = [this.main.scene.children.find(child => child.name === 'Test')]

    this.resources.on('ready', () =>
    {
        this.UNABLETOACCESSTHIS = this.scene.getObjectByName('Trackpad')
    })
}
update()
{
    this.rayCaster.setFromCamera(this.cursor, this.camera.view)
    this.intersects = this.rayCaster.intersectObject(this.foundButton)
    UNABLETOACCESSTHIS.here
    
    for(const object of this.objectsToTest)
    {
        object.material.color.set('#ff0000')
    }
    for(const intersect of this.intersects)
    {
        intersect.object.material.color.set('#0000ff')
    }
    // console.log(this.intersects)
 }
}

How to directly mutate javascript object containing JSON rather than using array

With a source JSON file below, I wish to read in , and apply the delta from a “`changes.JSON file. There is a more elegant way using direction mutation than reading into an array and writing back out. Curious how to do the direct mutation on the object and merge the changes into the source? The changes.json file has “action” and “payload” keys to direction operations on changes.json

source.json

 {
    "users" : [
      {
        "id" : "1",
        "name" : "Dave Mustaine"
      }
    ]
  }

changes.json

{
    "users": [{
        "action": "add",
        "payload": [{
                "id": "2",
                "name": "James Hetfield"
            }
        ]
    }]

becomes this:

{
    "users" : [
      {
        "id" : "1",
        "name" : "Dave Mustaine"
      },
      {
        "id" : "2",
        "name": "James Hetfield"
    ]
}

In my noob implementation I have all the logic written to parse out the action and payload, but currently writing into an array, but I think that is unnecessary and there is a more elegant way to just directly mutate the object and then stringify it and write out the updated json.

Here is what I have so far:

// Stream in source file
    fs.readFile('./' + inputFile, (err, data) => {
    if (err) throw err;
    let input = JSON.parse(data);
        //console.log(input);
    });

    // Stream in changes file
    fs.readFile('./' + changesFile, 'utf-8', (err, jsonString) => {
    if (err)  {
            console.log(err);
        } else {
            try {
                const data = JSON.parse(jsonString);
            
                const array = [];

                Object.entries(data).map(([key, [{ action,  payload }]]) => {
                    switch (key) {
                        case 'users': {
                            if (action === 'add') {
                                console.log("it's an add");
                                array.push([`${key}`, `${payload}`]);
                            }
                        break;
                        }

                     case 'playlists': {
                        if (action === 'add') {
                            console.log("it's an add");
                            array.push([`${key}`, `${payload}`]);
                        }
                            break;
                        }
                    
                        case 'songs': {
                        if (action === 'add') {
                            console.log("it's an add");
                            array.push([`${key}`, `${payload}`]);
                        }
                        break;
                    }
                 }
                });
                
                console.log(array);

            } catch (err) {
                console.log('Error parsing JSON', err);
            }
        }
    }); 

    // after we have merged changes and source we need to write out
    fs.appendFile('./' + outputFile, JSON.stringify(array, null, 2), err => {
        if (err) {
            console.log(err);
        } else {
            console.log('File sucessfully written');
        }
    });

Cart products quantity not refreshing when clicked multiple times

When I click on a product i want the quantity to go up by 1 the function is working but is not showing in the cart unless I add another product that does not exist in the cart at that moment. Any help?


         const existe = carrito.some(item => item.id === nuevoProducto.id); 

    console.log(existe);

    
    if(existe){

        const producto = carrito.map( item =>{ 
            if (item.id === nuevoProducto.id){
                item.cantidad++;
                return item; 
            }else{
                return item; 
            }
        });
    }else{
        addItemCarrito(nuevoProducto);
    }

How do I force timeouts in Jest to test timeout errors?

We have a function in our React project to fetch a list of stores. If the fetch takes longer than 10 seconds we abort the request and show an error.

const controller = new AbortController();
const getTimeout = setTimeout(() => controller.abort(), 10000);

const fetchStores = storeId => (
    ourFetchStoresFunction(`http://my-api/${storeId}`, {
        headers: { 'x-block': 'local-stores' },
        signal: controller.signal
    })
    .then((results) => {
        clearTimeout(getTimeout);
        return results
    })
    .catch((err) => { throw err; })
);

Here is the basic test for the fetchStores function:

it('fetchStores should return a stores array', () => {
    storesAPI.fetchStores(MOCK_STORES)
    .then((stores) => {
        expect(Array.isArray(stores)).toBe(true);
     })
    .catch();
});

How do I mock this timeout in Jest?

using setTimeout in the .then block while calling that method did not work. Additionally, I would rather NOT have to wait 10 seconds during the test. I looked up jest.useFakeTimers but got nowhere.

Element event listener affects other element

I’m adding divs on user clicks.
If the user clicks an exciting div I want it to change color.
Yet somehow the affected div is always the last appended one. How can I make the pressed div be the one who is affected?

document.addEventListener('click', e =>{
    el=document.createElement('div')
    document.body.appendChild(el)
    el.style.left = e.clientX-25 + 'px'
    el.style.top = e.clientY-25 + 'px'
    el.addEventListener('click', e =>{
      el.style.backgroundColor = 'green'
    })
})
div {
    width:50px;
    height:50px;
    background-color:blue;
    border: 1px solid black;
    position:absolute;
}
<html>
    <body>
        click to make two different squres. then click again on the first squre you created.
    </body>
</html>

try running this code, click to create two squres, then click again on your first squre. Why whould the second one change color?

Text file incorrect tabulation

I’m writing a javascript string in text file. View it in WebStorm and all tabulations are good. But when I`m trying to open it with TextEdit or Word – everything breaks.
Why that happens?
Thank you!

Pop up on swipe?

Is there any way to pop up new window on swipe event, like on click?

Browser’s bockers for some browsers blocking it. So far I tried to trigger click event on swipe, tried to delay pop up, tried to use e.preventDefault(), tried to window.document.write(htmlcontent), so far nothing really helped.

How to make angular identify module

I have an nrwl nx angular project right now I have two libraries one material home and one ui elements. Inside Ui elements I have datatable component which I want to use in my material home. I used the selector and imported the module of UI Elements to material module. In Ui Elements module I have my datatable component inside the export and declaration part. But Angular gives me still this error:

Error: libs/material/src/lib/material-home/material-home.component.html:1:1 - error NG8001: 'moniesta-data-table' is not a known element:
1. If 'moniesta-data-table' is an Angular component, then verify that it is part of this module.
2. If 'moniesta-data-table' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

This is how my html looks:

<moniesta-data-table></moniesta-data-table>

Material Module:

@NgModule({
    imports: [CommonModule, MatButtonModule, UiElementsModule],
  declarations: [
    MaterialHomeComponent,
  ],
})
export class MaterialModule {}

And finally the UiElementsModule

@NgModule({
  imports: [CommonModule, MatButtonModule, MatTableModule],
  declarations: [
    DataTableComponent
  ],
  exports: [
    DataTableComponent
  ]
})
export class UiElementsModule {}

In my general understanding it should work like this, because I have imported UIElementsModule into MaterialModule. So what could be the error?

How can i filter and get values from nouislider

I can filter my products with sizes but now i want the same with price but i don’t know how i can get the value from the range slider(nouislider) and use it to filter my page in the same way i did for sizes? I use a simple script to catch the value that works fine but i want to extend it for the price.

enter image description here

 <div id="price">
                        <p class="mt-2 fw-bold">Price</p>
                        <div class="row d-flex justify-content-center">
                            <div class="col-12  col-sm-8 col-sm-offset-2 mt-2">
                                <!-- Start noUiSlider -->
                                <div id="slider-margin"></div>
                                <div class="d-flex">
                                    <div class="me-5"  id="slider-margin-value-min"></div>
                                    <div id="slider-margin-value-max"></div>
                                </div>


                            </div>
                        </div>

                    </div>
                    <div id="size">
                        <p class="mt-lg-2 fw-bold">Sizes</p>
                        @foreach($sizes as $size)
                            <div>
                                <input class="form-check-input" name="size" type="checkbox" value="{{$size->id}}"
                                       @if(in_array($size->id, explode(',',request()->input('filter.size'))))
                                       checked
                                    @endif
                                >
                                {{$size->size}}
                            </div>
                        @endforeach


                    </div>
$products = QueryBuilder::for(Product::with(['photo','brand','category','size']))
            ->allowedFilters([
              
             
                AllowedFilter::exact('size', 'size_id'),

            ])->paginate(5);

    function getIds(checkboxName) {
    let checkBoxes = document.getElementsByName(checkboxName);
    let ids = Array.prototype.slice.call(checkBoxes)
    .filter(ch => ch.checked==true)
    .map(ch => ch.value);
    return ids;
}

    function filterResults () {
  
  
    let sizeIds = getIds("size");

    let href = '?products';

    

    
    if(sizeIds.length) {
    href += '&filter[size]=' + sizeIds;
        }

    document.location.href=href;
}

    document.getElementById("filter").addEventListener("click", filterResults);


Contact form like a chat with JS

Can you give me a tutorial or information on how to make a contact (multistep) form like a chat?

I thought it could be done as a multistep form using JavaScript. So that each subsequent question is loaded instead of moving to the next step.

Thank you

JAVASCRIPT+DynamicHTML

Would like to add script to my company’s website .

For example, if I work at NY Times, I would like to make sure that I add a script to the Dynamic HTML page. I could edit the page using script in console, but I have cannot pass script to editing.

How can I edit this page, or atleast try to load my script at the end, once DHML solidify into HTML page.

Change dynamic json structure to key,value and children structure

I have a dynamic JSON structure ex:

{
  "video": {
    "width": 1920,
    "height": 1080,
    "video_codec": "H264",
    "CBR": "4337025",
    "frame_rate": {
      "numerator": 25,
      "denominator": 1
    },
    "specified": {
      "numerator": 1,
      "denominator": 1
    },
    "gop": {
      "length": 50,
      "reference_frames": 3,
      "sub_gop": "StaticType"
    },
    "codec_details": {
      "profile": "Main",
      "level": "Level4",
      "entropy_encoding": "CABAC",
      "video_output": "AVC1"
    }
  }
}

I want to transform it to tree node

export class TrackDetailsNode {
  key: string;
  value: string;
  children?: TrackDetailsNode[];
}

I need it in a recursive way.
Tried multiple solution but is taking a long time to parse.

Create blue box area to organize a form

my goal is to create something like this :enter image description here
So an area where I can put a form for authentification or create an account. I already created a form in php which is linked to my database like this

 <form action="connection.php" method="post">
    <div class="form-group">
        <label >Nom</label>
        <input name = nom>
    </div>
    <div class="form-group">
        <label >Prénom</label>
        <input name = prenom>
    </div>
    <div class="form-group">
        <label >Email</label>
        <input name = mail>
    </div>
    <div class="form-group">
        <label >Numéro de telephone</label>
        <input name = tel>
    </div>
    <div class="form-group">
        <label >mot de passe</label>
        <input type=password id="inputPassword" placeholder="Password"">
    </div>
    <button type="submit" class="btn btn-primary" name="add">Creer son compte</button>
function inscription($db,$nom,$prenom,$mail,$tel,$mdp){
    try{
    $request_client = "INSERT INTO client (nom, prenom, mail, tel, mdp) VALUES (:nom, :prename, :email, :phone,:pass);";
    $statement_client = $db->prepare($request_client);
    $statement_client->bindParam(':nom', $nom);
    $statement_client->bindParam(':prename', $prenom);
    $statement_client->bindParam(':email', $mail);
    $statement_client->bindParam(':phone', $tel);
    $statement_client->bindParam(':pass', $mdp);
    $statement_client->execute();
    }
    catch (PDOException $exception)
  {
  error_log('Request error: '.$exception->getMessage());
  return false;
  }
}

Is there something in boostrap or css or even js which can make me creat this blue area ?