3Js Raycasting + OrbitControls + Camera Rotation on a Globe

I would like for the user to be able to hover over the little spheres inside the countries to receive information.

Using a raycaster seems to be the first step here, but it does not trigger upon mouse move. Also, it is not pointing where the mouse is. I believe this has something to do with the camera being rotated.

This is less important because I think I can figure it out, but it’s a bug in the code snippet below so I’m mentioning it:

I also would like for my globe to be rotating constantly, unless the user is controlling it with OrbitControls. Right now, when I try to use OrbitControls (dragging the mouse), the globe just zooms in and out- why is that? Does this have to do with the camera being updated constantly in d3.timer()?

I think this is the part of the code that’s most important.

d3.timer( function ( t ) {
        theta += 0.1;

        camera.position.x = 100 * Math.sin( THREE.MathUtils.degToRad( theta ) );
        camera.position.y = 100 * Math.sin( THREE.MathUtils.degToRad( theta ) );
        //camera.position.z = 100 * Math.cos( THREE.MathUtils.degToRad( theta ) );
        camera.lookAt( scene.position );
        camera.updateMatrixWorld();

        controls.update();
        raycaster.setFromCamera( pointer, camera );
        const intersects = raycaster.intersectObjects( earthPivot.children, false );

        if ( intersects.length > 0 ) {

                if ( INTERSECTED != intersects[ 0 ].object ) {

                    console.log(intersects[0].object.name)
                    INTERSECTED = intersects[ 0 ].object;

                }

            } else {

                INTERSECTED = null;

            }

            renderer.render( scene, camera );
    } );

Please take a look at this snippet.

<div id='container'> </div>
<script src="https://d3js.org/d3.v6.js"></script>
<script src="https://unpkg.com/topojson-client@3"></script>
<script src="https://unpkg.com/d3-array@1"></script>
<script src="https://unpkg.com/d3-collection@1"></script>
<script src="https://unpkg.com/d3-dispatch@1"></script>
<script src="https://unpkg.com/d3-request@1"></script>
<script src="https://unpkg.com/d3-timer@1"></script>
<script type='module'>
import * as THREE from "https://unpkg.com/[email protected]/build/three.module.js";
import { OrbitControls } from "https://unpkg.com/[email protected]/examples/jsm/controls/OrbitControls.js";

var width = 650;
var height = 650;
var radius = 168,
    scene = new THREE.Scene(),
    camera = new THREE.PerspectiveCamera( 100, width / height, 1, 1000 ),
    renderer = new THREE.WebGLRenderer( { alpha: true } ),
    container = document.getElementById( 'container' ),
    controls,
    raycaster;

const pointer = new THREE.Vector2();
let INTERSECTED;
raycaster = new THREE.Raycaster();
container.addEventListener( 'mousemove', pointerMove );
let theta = 0;

scene.background = new THREE.Color( "rgb(20,20,20)" );

camera.position.set( 0, 0, 300 );
camera.lookAt( 0, 0, 0 );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( width, height );
container.appendChild( renderer.domElement );

let earthPivot = new THREE.Group();

d3.json( "https://raw.githubusercontent.com/alessiogmonti/alessiogmonti.github.io/master/Pages/Index/dataFranceModified.json", function ( error, topology ) {

    if ( error ) throw error;
  
  /// NO NEED TO LOOK AT ////////////////////////////////////////////
    var countries = [];
    var cones = [];
    for ( var i = 0; i < topology.objects.countries.geometries.length; i ++ ) {

        var rgb = [];
        var newcolor;
        for ( var j = 0; j < 3; j ++ ) {
            rgb.push( Math.floor( Math.random() * 255 ) );
            newcolor = 'rgb(' + rgb.join( ',' ) + ')';
        }

        var mesh = wireframe( topojson.mesh( topology, topology.objects.countries.geometries[ i ] ), new THREE.LineBasicMaterial( { color: newcolor, linewidth: 5 } ) );
        countries.push( mesh );
        scene.add( mesh );

        mesh.geometry.computeBoundingBox();
        var center = new THREE.Vector3();
        mesh.geometry.boundingBox.getCenter( center );

        mesh.add( earthPivot );
        let height = 1;
        const geometry = new THREE.SphereGeometry( height, 50, 36 );
        const material = new THREE.MeshBasicMaterial( { color: newcolor } );
        const cone = new THREE.Mesh( geometry, material );
        cone.position.copy( center );
        cone.position.setLength( radius + height );
        cone.name = topology.objects.countries.geometries[ i ].properties[ 'name' ];
        cones.push( cone );
        earthPivot.add( cone );

  /// NO NEED TO LOOK AT //////////////////////////////////////////////////////////////
    }


    controls = new OrbitControls( camera, renderer.domElement );

    const helper = new THREE.CameraHelper( camera );
    scene.add( helper );

    const axesHelper = new THREE.AxesHelper( 50 );
    scene.add( axesHelper );

    d3.timer( function ( t ) {
        theta += 0.1;

        camera.position.x = 100 * Math.sin( THREE.MathUtils.degToRad( theta ) );
        camera.position.y = 100 * Math.sin( THREE.MathUtils.degToRad( theta ) );
        //camera.position.z = 100 * Math.cos( THREE.MathUtils.degToRad( theta ) );
        camera.lookAt( scene.position );
        camera.updateMatrixWorld();

        controls.update();

    // this code was to look at the interaction between pointer and camera
        // const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
        // const geometry = new THREE.BufferGeometry().setFromPoints( [pointer,camera.position] );
        // const line = new THREE.Line( geometry, material );
        // scene.add(line)

        raycaster.setFromCamera( pointer, camera );
        const intersects = raycaster.intersectObjects( earthPivot.children, false );

        if ( intersects.length > 0 ) {

                if ( INTERSECTED != intersects[ 0 ].object ) {

                    console.log(intersects[0].object.name)
                    INTERSECTED = intersects[ 0 ].object;

                }

            } else {

                INTERSECTED = null;

            }

            renderer.render( scene, camera );
    } );
} );

// Converts a point [longitude, latitude] in degrees to a THREE.Vector3.
function vertex( point ) {

    var lambda = point[ 0 ] * Math.PI / 180,
        phi = point[ 1 ] * Math.PI / 180,
        cosPhi = Math.cos( phi );
    return new THREE.Vector3(
        radius * cosPhi * Math.cos( lambda ),
        radius * cosPhi * Math.sin( lambda ),
        radius * Math.sin( phi )
    );

}

function pointerMove( event ){

    pointer.x = ( event.clientX / width ) * 2 - 1;
    pointer.y = - ( event.clientY / height ) * 2 + 1;

}

// Converts a GeoJSON MultiLineString in spherical coordinates to a THREE.LineSegments.
function wireframe( multilinestring, material ) {

    var geometry = new THREE.BufferGeometry();
    var pointsArray = new Array();
    multilinestring.coordinates.forEach( function ( line ) {

        d3.pairs( line.map( vertex ), function ( a, b ) {

            pointsArray.push( a, b );

        } );

    } );
    geometry.setFromPoints( pointsArray );
    return new THREE.LineSegments( geometry, material );

}
</script>

Multiple File Upload VueJS

I am new to VueJS and I was trying to upload multiple pictures. The form looks like this. I am using Vue from CDN on a blade file. The problem is when I click delete, it is not the one clicked which is removed, but the last one. I have noticed that the one clicked is actually removed from the data, but the form doesn’t update like that. Any help is appreciated. My code looks like this:

Vue.createApp({
    data() {
        return {
            images: []
        }
    },
    methods: {
        addField(images){
            images.push({});
        },
        removeField(index, images){
            images.splice(index, 1);
        }
    }
}).mount('#picture')

<input id="picture" type="file"
 class="form-control-file{{ $errors->has('picture') ? ' is-invalid' : '' }}"
 name="picture[]" accept="image/*" required>
                                    
 @if ($errors->has('picture'))
 <span class="invalid-feedback" role="alert">
     <strong>{{ $errors->first('picture') }}</strong>
 </span>
 @endif

Typeahead not working in my laravel blade page

I want to search a client by his name from DB.
I have the following controller function(note: I saved them with “nume” instead of “name”)

namespace AppHttpControllers;
use AppModelsPlati;
use AppModelsClients;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
use Datatables;
use IlluminateHttpRedirectResponse;
use SymfonyComponentHttpFoundationResponse;

public function autocomplete(Request $request)
        {
            $data = Clients::select("nume")
                ->where("nume","LIKE","%{$request->get('query')}%")
                ->get();
   
        return response()->json($data);

}

This function outputs this:enter image description here

This is each’s client’s name.

In my blade page I have the following:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <title></title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" ></script>
 <style>
    .container{
    padding: 10%;
    text-align: center;
   } 
 </style>
</head>
<body>
 
<div class="container mt-3">
    <h1 class="mb-3">Laravel 8 Autocomplete Search using Bootstrap Typeahead JS - LaraTutorials</h1>   
    <input id="search" class="typeahead form-control" type="text">
</div>
 
<script type="text/javascript">
    var path = "{{ url('autocomplete') }}";
    $('#search').typeahead({
        return $.get(route, {
                    query: query
                }, function ($data) {
                    return process($data);
                });
        }
    });
</script>
   
</body>
</html>

But when I type it doesn’t show me anything.
Does anyone know why?

Variable is initialized again after the input value changes in angular

I have a shared component with some input values and one declared variable. The input values of the component change in between and whenever the input value changes, showItems is declared again and it’s value is false.
I tried to use behavior subject, but it doesn’t solve my problem. Is there any better workaround for this one?

Code:

export class Component{
    @Input() input1: boolean;
    @Input() input2: string[];

    showItems: boolean;

    constructor() {}

    toggleItems() {
        this.showItems= !this.showItems;
    }
}

Jquery – add class to the specific child element

Hello Stackoverflow friends… I am trying to solve a problem…

I have 4 link blocks which are having the class “faq-tab_link” and they have a child element of the image having the class of “careers-faq-icon” and the image have a combo class of “is__hide”

what I am trying to achieve is when I click on any of the link block the image element which is having the combo class of is__hide should be removed to that particular link block only..so that the image will appear on the clicked link block.. and which clicked on the second link the image should appear on the second link and all other images of other links should be hidden…

can anybody help me with that please?

input type=”number” addClass on increase removeClass on decrease

In an online game, students are asked “How many 12-year-olds already have (…)” and have to choose how many of 25 people’s icons (4%) they color in. This is actually kind of a range input, but I thought it could be done easily with an input type=”number” too.

I’ve already got it working to some extent. Arrow up or mouse up adds the necessary class, but the remove class doesn’t work yet. When I enter a number, the people’s icon with that number gets the class, but all icons with a lower id should also get the class.

You can find the live example here. The code I’m using:

HTML:

<svg id="manneke1" class="manneke" (…) /></svg>
(…)
<svg id="manneke25" class="manneke" /></svg>
<input type="number" id="inputMannekes" class="form-control text-center" name="inputMannekes" value="0" min="0" max="25"/>

CSS:

.manneke {
  fill:none;
  stroke:#004f75;
  stroke-linecap:round;
  stroke-linejoin:round;
  stroke-width:11.49px;
}

.gevuld {
  fill:#f5c1bc;
  stroke: #e66557;
}

Javascript:

$("#inputMannekes").change(function () {
    if (this.getAttribute('value') === this.value) {
        $(this).data('lastvalue', this.value);
        console.log(this.value);
    } else {
        if (this.value > $(this).data('lastvalue')) {
            $("#manneke"+$(this).val()).addClass("gevuld");
        } else {
            $("#manneke"+$(this).val()).removeClass("gevuld");
        }
    }
}).change();

What is the shorthand syntax for callback functions generating a new interface instance?

Given the following TypeScript example to construct a new object with default values

interface MyInterface {
  foo: boolean;
};

const generateMyInterfaceWithDefaults: () => MyInterface = () => { foo: false };

The syntax seems to be invalid because the function needs to have a nested return statement like so

const generateMyInterfaceWithDefaults = () => { return { foo: false }; }; // returns function that returns a new interface of MyInterface

I’m wondering if my first approach can be fixed because primitve objects seem to work fine

const generateFalsy = () => false; // returns boolean

So do I have to use the return statement for non primitive types or is it possible to have something like ( … pseudo code … )

const generateMyInterfaceWithDefaults = () => MyInterface.of({ foo: false }); // fixes the first approach

Issue with axios call, When trying to fetch api with name as parameter in Vuejs?

HelloWorld.vue

<template>
  <div>
    <div v-for="name in names" :key="name.PipelineID">
      <div>status: {{ name.OverallStatus }}</div>
    </div>
    <div v-for="item in items" :key="item.SourceDatabaseName">
      {{ item.DBIcon }}
    </div>
  </div>
</template>

<script>
import { tabsandcontent } from "./tabsandcontent";
import { tabs } from "./tabs";
export default {
  name: "HelloWorld",
  components: {},
  data() {
    return {
      names: [],
      items: [],
    };
  },
  mounted() {
    tabsandcontent().then((r) => {
      this.names = r.data;
    });

    tabs().then((r) => {
      this.items = r.data;
    });
  },
};
</script>

tabsandcontent.js

import axios from "axios";

export const tabsandcontent = (name) =>
  axios.get(
    "http://35.162.202.237:3000/pip?s_name=" + name **(api call edited for safety purpose, exact api call in codesandbox)**
  );

code:-
https://codesandbox.io/s/angry-euler-xt2wqh?file=/src/components/tabsandcontent.js

in tabsandcontent.js file, i have api call where i need to pass the name as query params at the end of the api url.
Then only i can able to call the api and get the response.

I tried writting above code logic, But it gives me like undefined when i pass name as params at the url end.

How to call api, that which has name as the query params?

In developer tools inside network tab. i am getting as

http://35.162.202.237:3000/pip?s_name=**undefined**

What is causing this TypeError

Uncaught TypeError: Failed to resolve module specifier “events”. Relative references must start with either “/”, “./”, or “../”. index.html:1

what is causing this error?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script defer type="module"src="./index.js"></script>
</head>
<body>

    <form class="add">
        <Label for="Fornavn">Fornavn:</Label>
        <input type="Text" name="Fornavn" required>
        <Label for="Etternavn">Etternavn:</Label>
        <input type="Text" name="Etternavn" required>
        <Label for="Forkort">Partiforkortelse:</Label>
        <input type="Text" name="Forkort" required>

        <button>Legg til politiker</button>

    </form>
    
</body>
</html>

First time writing on here so im sorry if its not clear enough, if you need more information ill do my best to give you it.

Chatbot in Dialogflow

I am trying to implement a chatbot in dialogflow CX, and I have never done it before.
I want to customise the buttons that appear in the chat and a couple more things as the background.
I already know that I have to use javascript files and the code for that is here. The thing is… how do implement that in the dialogflow CX? Thank you

SlashCommands not showing up

I just finished my bot and wanted to invite it to another server to test it out.

However, when I typed / no commands showed up.

When I invited the bot I enabled application.commands so I can use the slashcommands but it still did not work. My bot also has a global slashcommand handler so it should normally work right?

I don’t know if the handler code is needed but I’ll still add it here in case you do need it:

const { Perms } = require('../Validation/Permissions');
const { Client } = require('discord.js');

/**
 * @param {Client} client
 */

module.exports = async (client, PG, Ascii) => {
    const Table = new Ascii("Command Loaded");

    CommandsArray = [];

    (await PG(`${process.cwd()}/Commands/*/*.js`)).map(async (file) => {
        const command = require(file);

        if(!command.name)
        return Table.addRow(file.split("/")[7], "⛔ FAILED", "Missing a name.")

        if(command.type !== "USER" && !command.description)
        return Table.addRow(command.name, "⛔ FAILED", "Missing a description.")

        if(command.permission){
            if(Perms.includes(command.permission))
            command.defaultPermission = false;
            else
            return Table.addRow(command.name, "⛔ FAILED", "Permission is invalid.")
        }

        client.commands.set(command.name, command);
        CommandsArray.push(command);

        await Table.addRow(command.name, "✅ SUCCESSFUL");
    });

    

    console.log(Table.toString());

    // PERMISSIONS CHECK //

    client.on("ready", async () =>{
        client.guilds.cache.forEach((g) => {
            g.commands.set(CommandsArray).then(async (command) =>{
                const Roles = (commandName) => {
                    const cmdPerms = CommandsArray.find((c) => c.name === commandName).permission;
                if(!cmdPerms) return null;
    
                return g.roles.cache.filter((r) => r.permissions.has(cmdPerms) && !r.managed).first(10);
                }
    
                const fullPermissions = command.reduce((accumulator, r) =>{ 
                    const roles = Roles(r.name);
                    if(!roles) return accumulator;
    
                    const permissions = roles.reduce((a, r) =>{
                        return [...a, {id: r.id, type: "ROLE", permission:true}]
                    }, []);
    
                    return [...accumulator, {id: r.id, permissions}]
                }, []);
    
                await g.commands.permissions.set({ fullPermissions });
    
            });
        })
        });
}

Problems making a button disabled/change color depending on the input. Any advice?

I’ve been tying to work on this code, but can’t find the mistakes (and I’m guessing there are many of them) I’m making.
So far I tried it using querySelector and getElementById and I’ve been rewriting the functions quite a few times, but no luck so far. Any advice?
Thanks in advance.

const btnNext = document.querySelector(".btn-next");
const logIn = document.querySelector(".btn-login");
const inputMail = document.querySelector(".input-mail");
const inputPassword = document.querySelector(".input-password");

function btnLogIn() {
    if (inputMail.value.length && inputPassword.value.length == 0) {
        btnNext.disabled == true;
    } else {
        btnNext.disabled == false;
    }
}
function changeColor() {
    if (document.getElementById("input-mail") !== "") {
        document.getElementById("btn-next").style.background = "gray";
    } else {
        document.getElementById("btn-next").style.background = "blue";  
    }
}
body{
    margin: auto;
    width:50%;
    padding: 0;
    background-color: #eeeeee;
}
form{
    display: flex;
    flex-direction: column;
}
.btn-next{
    margin-top: .5rem;
    background-color: #949aa6;
    color: white;
    border: none;
    border-radius: 2px;
    padding: 18px 119px 18px 119px; 
    font-size: .8rem;
    font-weight: 600;
}
input{
    width: 16.5rem;
    height: 2rem;
    box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
    }
<body>
     <form>
        <p>Email</p>
        <input type="email" placeholder="Email" class="input-mail" id="input-mail">
        <p>Password</p>
        <input type="password" placeholder="Password" class="input-password" id="input-password"><br>
    </form>    
        <button class="btn-next" id="btn-next">NEXT</button> 
</body>

ID match with differen fields using if condtion in JS?

I Have two objects booking and History. I have to check booking userId matches with History userId or History CustomerID

If booking userId matches with any of these two fields(History userId or History CustomerID) we should return “ID matched” in the console.

If booking userId does not match with any of these two fields(History userId or History CustomerID). we should return “ID not matched with booking”.

Below is my code .its working as expected but is this a better approach? or i can do this in some other way

Please suggest

var booking = {"userId":"1233","CustomerID":null,"username":"av"};
var History = {"userId":"123","CustomerID":null,"username":"av"};

var a = booking.userId != History.userId;
var b = booking.userId == History.CustomerID;
var c = booking.userId == History.userId;
var d = booking.userId != History.CustomerID;
console.log(a)
console.log(b)
console.log(c)
console.log(d)

if( a && !b || c && !d)
{
console.log("ID not mathced with booking ")
}else{
console.log("ID mathced")
}

Uncaught ReferenceError: removeFiled is not defined

I am getting Function Reference undefined error while i add new Dynamic Fields. Note that I have split my bladed files into different parts or sections. but the function is defined in the same file. So basically i have a different- different part of files to make code easier to read. but the problem is when i write a function in a different file and mention that function name in the different file where all files part being included in one file. after that, i am getting errors many times like this `foo is not defined. in other words, all part of the files is included in one file. let’s check my code.

it is a script file in blade: script.blade.php

 <script> 
   var count_custom_field =0;
   $(document).on('click', '.new-row-weekly', function () {
    count_custom_field++;
    $(' <div class="clearfix field_'+count_custom_field+'" >&nbsp;</div>  ' +
        ' <div class="row field_'+count_custom_field+'">  <div class="col-md-4">  ' +
        ' <label class="text-label"> Repeat Day </label> {{ Form::select("repet_days[]",
         $days,null,array("class" => "form-control")) }} </div>  '+
        '  <div class="col-md-4">  ' +
        '  <label class="text-label"> Repeat Return Halt Duration(Minutes) </label>{!! Form::text("repet_times[]", null,
        array("class" => "form-control  repet_times" , "placeholder"=>"Ex. 120" ) ) !!} 
    </div>'+
        '  <div class="btn btn-danger"  onClick="removeCustFiled(213123)"  style="margin: 30px 0 0 0; height: 40px; padding-bottom: 18px;" > <i class="fa fa-close"></i> </div> </div> '+
        '</div>' ).appendTo('#weekly').hide().fadeIn(280);
   }

    function removeCustFiled( ref ) { console.log(ref);
       /* $('.'+ref+'').remove();
        if( Number( count_custom_field ) > 0)
        {
            count_custom_field--;
        }*/
    }
  </script>

UI blade file.
enter image description here

enter image description here

Please tell me what is reason i am getting this error.

Creating custom React hook to store File(s) (push/ purge), doesn’t render component where it is used

I’ve a create-react-app project with custom hook like this:

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const useStagedUploads = () => {
    const [items, setItems] = useState<CustomFileWithPath[]>([]);
    const setUploadItems = (files: CustomFileWithPath[]) => setItems(files);

    return [items, setUploadItems] as const;
};

export default useStagedUploads;

I use it to push files to when browsed (using react-dropzone). Now in one of my other component, I use it like below *:

const [ items, setUploadItems ] = useStagedUploads();

    useEffect(() => {
        if (items) {
            onDrop(items);
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            items.map((i) =>
                // eslint-disable-next-line @typescript-eslint/no-unsafe-return
                setUploadItems(
                    items.filter(
                        (items: CustomFileWithPath) => items.path !== i.path
                    )
                )
            );
        }
    }, [items]);

Now when upload is made like so (react-dropzone):

const { getInputProps, open, acceptedFiles } = useDropzone({
        noClick: true,
        noKeyboard: true,
    });

    useEffect(() => {
        if (acceptedFiles) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            acceptedFiles.map((el) => stageUpload(el));
        }
    }, [acceptedFiles]);

… The former component (*) doesn’t re-render (tried console, debugger, etc.) ie I don’t receive items its empty “[]” array. Also doesn’t react useEffect body.

Gave a try using simple primitive type it does re-render. Is it so that files couldn’t be stored in react custom hooks or prevents re-render/ any serialization problem?

Thanks.