THREE.JS : display image on objects issue

I am currently creating a webpage in three.js and I struggle to display an image on an object. What I want to do is to display an image on a Mesh with PlaneGeometry.

I first tried to load my image as a texture to replace the material of my mesh but it failed it doesn’t display anything (even the object disappeared).

To create and display my object I used these lines of code (scene is my scene and onglets is the group in which I gathered several objects (onglet1, onglet2, …)):

    couleur = new THREE.MeshBasicMaterial( {color: 0x031f3c , side: THREE.DoubleSide } );
    plan = new THREE.PlaneGeometry( 0.75 , 0.4 );
    var onglets = new THREE.Group();

    onglet1 = new THREE.Mesh( plan , couleur );
    onglet1.position.set( 0, 0, r );
    onglets.add(onglet1);
    scene.add(onglets);

To load my image I modified my code like this:

    couleur = new THREE.MeshBasicMaterial( {color: 0x031f3c , side: THREE.DoubleSide } );
    plan = new THREE.PlaneGeometry( 0.75 , 0.4 );
    var onglets = new THREE.Group();

    var map = new THREE.TextureLoader().load( "../media/groupe.jpg" );
    var material = new THREE.SpriteMaterial( { map: map, color: 0x000000 } );

    onglet1 = new THREE.Mesh( plan , material );
    onglet1.position.set( 0, 0, r );
    onglets.add(onglet1);
    scene.add(onglets);

If you see what I did wrong or have any advice to improve my code in general I would be happy to hear it.
Thanks in advance for the help guys!

ReactJS onClick event not work in Google Chrome for option tag

In ReactJS, onClick event does not work in Google Chrome browser but works fine in Firefox. When I add onClick event with arrow function in option tag inside select it’s not work in any situation in Google Chrome.

<select>
   {data.map( (item) => {                            
     return(
       <>
         <option onClick={()=>alert('Test')} value={item.name} key={item.id}>{item.name}</option>
       </>
      )
   })}
</select>

I actually need to call an ES6 arrow function with some parameter inside option tag

<select>
{data.map( (item) => {
  return(
     <>
      <option onClick={()=>LoadNew(item.id)} value={item.name} key={item.id}>{item.name}</option>
     </>
    )
  })}
</select>

This is working fine in Firefox but doesn’t work in the Google Chrome browser. Any idea how can I solve this problem?

How do I automatically add a slug to my url in nodejs

I’m having templating issues.

I’m working on an online store and I’m using my json file, which has all the details about a product, to generate cards for each product.
Because I have a lot of products, creating a page for each product is out of the question so I also have a template page to show more details on a product.
What I want is that whenever I click on a product card, it takes me to the template product page then replaces the dummy data with the data for the product. I also want to make the url for the template page /product/product-slug but when i use this method, I’m unable to change the dummy data.

I eventually found a way to change the dummy data but the only way I could do it was by using the query id to find the data so the url looks like /product?id=productId instead and I really don’t know how to work around it. I can’t leave it like this because as I said before, I have a lot of products.

Here’s my js code

const fs = require('fs')
const url = require('url')
const express = require('express');
const app = express();

app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');

const replaceTemplate = (temp, product) =>{
    let output = temp.replace(/{%NAME%}/g, product.name);
    output = output.replace(/{%ID%}/g, product.id);
    output = output.replace(/{%FIRST%}/g, product.image.primary);
    output = output.replace(/{%SECOND%}/g, product.image.secondary);
    output = output.replace(/{%SLUG%}/g, product.slug);
    output = output.replace(/{%PRICE%}/g, product.price);
    output = output.replace(/{%M1NAME%}/g, product.materials.material1.name);
    // output = output.replace(/{%M2NAME%}/g, product.materials.material2.name);
    output = output.replace(/{%M1IMG%}/g, product.materials.material1.img);
    // output = output.replace(/{%M2IMG%}/g, product.materials.material2.img);

    return output;
}

const earrings = fs.readFileSync(`${__dirname}/views/earrings.html`,'utf-8');
const product = fs.readFileSync(`${__dirname}/templates/product.html`,'utf-8');

const tempCard = fs.readFileSync(`${__dirname}/templates/stud-cards.html`,'utf-8');

const data = fs.readFileSync(`${__dirname}/dev-data/earrings/studs.json`,'utf-8');
const dataObj = JSON.parse(data);

app.get('/product', (req, res) => {
    const { query, pathname } = url.parse(req.url, true)
    // // // const prod = url.parse(req.url, `http://${req.headers.host}`)
    // // // const prod = dataObj[]
    // // // const output = replaceTemplate(product, prod);
    // // console.log(req.params.slug)
    // // res.end(product);
    // res.render('product', {pro: req.params.slug});

    res.writeHead(200, {'Content-type': 'text/html'});
    const prod = dataObj[query.id];
    const output = replaceTemplate(product, prod);

    console.log(prod);
    res.end(output);
}); 

app.listen(7664);

console.log('Now the server is running in url: http://127.0.0.1:7664');
 

And this is what my json file looks like

[
{
        "id": 0,
        "name":"Amethyst Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/0_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Amethyst Flat Sphere Studs/2_BirthstoneSphereStud_AmethystSphereStuds_February_YG_Hero_Stacked_1.jpg"
        },
        "slug":"amethyst-flat-sphere-studs",
        "price":"180.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Amethyst",
                "img": "../img/products/color/Amethyst.png"
            } 
        }
    },
    {
        "id": 1,
        "name":"Aquamarine Flat Sphere Studs",
        "image":{
            "primary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/0_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero.jpg",
            "secondary": "../img/products/earrings/studs/Aquamarine Flat Sphere Studs/1_BirthstoneSphereStud_AquamarineSphereStuds_March_YG_Hero_Stacked_1.jpg"
        },
        "slug":"aquamarine-flat-sphere-studs",
        "price":"200.00",
        "materials":{
            "material1":{
                "name": "14k Yellow Gold, Aquamarine",
                "img": "../img/products/color/Aquamarine.png"
            }
        }
    }
]

please tell me about any improvements you think I should make to my questions. don’t vote me down please

Form Action redirect with javascript json data

Use of fetch is very common but it not going to redirect it just send data and receive data.

How to use it like normal HTML form submit but instead of using name i can send data like fetch and but open new link as form action does. Open New Page.

<!-- Here is example of using alpine and using fetch to send data it return whole page but i can't do anything with it -->
<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
<div x-data="{order:''}">
  <form @submit.prevent="fetch('/user/payment', {method: 'POST', headers:{'Content-Type': 'application/json'},body: JSON.stringify(order)})">
    <div class="mt-6">
      <button><span>Proceed to RazorPay<br>₹ 747</span>
      </button>
    </div>
  </form>
</div>

<Br>
<Br>
<!-- I like something Like this so action page but here i like to send array of data -->
  <form method="POST" action= '/user/payment'>
  <input type="text" name="order"/>
    <div class="mt-6">
      <button><span>Proceed to RazorPay<br>₹ 747</span>
      </button>
    </div>
  </form>

How to make a simple counter work when the tag is inactive

I have a simple timer to record the time:

let div = document.querySelector('div')
let interval = window.setInterval(function(){
div.textContent =parseFloat(div.textContent)+1
},1)
<div>0</div>

I found that when I switch to another tab, the setInterval will not working.

Are there some simple solution to solve this problem?

I do do some research like, people suggest to use window.requestAnimationFrame, but it doesn’t work as well.

Are there some simple solution or built-in function to solve this (I just want to make a simple timer)?

Thanks for any responds!

Modified Object.assign in typescript

I am trying to create a “assign default” function in typescript, where it loops through the keys of the source, and if that value by the same key is nullish in the target, it will use the value from the source instead. Here’s my attempt:

const assignDefault = <T, U>(target: T, source: U): T & U => {
  Object.keys(source).forEach(key => {
    // typecasted as Object.keys returns string[]
    const prop = target[key as keyof T]
    if (typeof prop === 'undefined' || typeof prop === 'null') {
      // Error: Type 'U[keyof U]' is not assignable to type 'T[keyof T]'.
      target[key as keyof T] = source[key as keyof U] 
    }
  })
  return target // Error: Type 'T' is not assignable to type 'T & U'.
}

I borrowed the generics from how Object.assign is typed in typescript: ObjectConstructor.assign<T, U>(target: T, source: U): T & U; But I couldn’t find a way to get around these errors.

React “Uncaught TypeError: ontoggle is not a function” exception when a function from parent is passed in

I’ve been trying a tutorial video in YouTube named React JS Crash Course 2021 and i have created a TaskCheckbox component for a Task component. TaskCheckbox component has a function “ontoggle” and an id:number passed in as constructor parameters. It is only supposed to call the function in App.js and console.log the id for now.

The hierarchy is as following: App => Tasks => Task => TaskCheckbox

Even though i am pretty sure i passed the right functions to its child for each component i am unable to locate the reason of the exception: “Uncaught TypeError: ontoggle is not a function”

App.js snippet:

const taskSelectHandler = (e, id) => {
    console.log(id)
    //setTasks(tasks.map(task => task.id === id ? task.selected = e.target.checked : ""))
  }
return (
    <div className='main'>
      <div className = "container">
        <Header className="header-title" title="TASK TRACKER" />
        <section className='tasks-outer-container'>
          {tasks.length > 0 ? 
            <Tasks tasks={tasks} ondelete={deleteTask} ontoggle={taskSelectHandler}/>
          :
          <p className="info-text">Go set some tasks!  </p>  
          }
        </section>
      </div>
    </div>
  )
}

Tasks.js snippet:

const Tasks = ({tasks, ondelete, ontoggle}) =>{
    return (
        <div className='tasks-container'>
            {
                tasks.map((task) => (
                <Task key={task.id} task={task} ondelete={ondelete} ontoggle={ontoggle}/>)
                )
            }
        </div>
    )
}

Tasks.propTypes = {
    tasks: PropTypes.array,
    ondelete: PropTypes.func.isRequired,
    ontoggle: PropTypes.func.isRequired,
}

export default Tasks

Task.js snippet:

const Tasks = ({tasks, ondelete, ontoggle}) =>{
    return (
        <div className='tasks-container'>
            {
                tasks.map((task) => (
                <Task key={task.id} task={task} ondelete={ondelete} ontoggle={ontoggle}/>)
                )
            }
        </div>
    )
}

Tasks.propTypes = {
    tasks: PropTypes.array,
    ondelete: PropTypes.func.isRequired,
    ontoggle: PropTypes.func.isRequired,
}

export default Tasks

TaskCheckbox snippet:

const TaskCheckbox = (ontoggle, id) => {
    return (
        <div className="task-checkbox-container">
            <input className="task-checkbox" onClick={(e) => ontoggle(e, id) } type="checkbox"></input>
        </div>
    )   
}

TaskCheckbox.propTypes = {
    ontoggle: PropTypes.func.isRequired,
    id : PropTypes.number.isRequired,
}

export default TaskCheckbox

This part was around 59:00 in the video if that helps.

How to put Json Tiled into HTML5 Canvas

How do i take json tiled map editor files and render the images (my map) into a HTML 5 Canvas. it shows an array for the individual images the map used but im not sure how to render that to a Canvas to make the map appear on my game.

Please Help

Nodemailer : Can’t create new access token for user

const nodeMailer = require("nodemailer");

const sendEmail = async (options) => {
  const transporter = nodeMailer.createTransport({
    host: process.env.SMTP_HOST,
    port: process.env.SMTP_PORT,
    secure: true,
    service: process.env.SMTP_SERVICE,
    auth: {
      type: 'OAuth2',
      user: process.env.SMTP_MAIL,
      pass: process.env.SMTP_PASSWORD,
    },
  });

  const mailOptions = {
    from: process.env.SMPT_MAIL,
    to: options.email,
    subject: options.subject,
    text: options.message,
  };

  await transporter.sendMail(mailOptions,function(err,info){
      if(err){
          console.log(err)
      } else {
          console.log('success')
      }
  });
};

module.exports = sendEmail;

when i process this it says “Can’t create new access token for user” can anyone help reg this?
in env files host is “smtp.gmail.com” and port no is 465 , smtp_service is gmail.

i have read some docs regarding gmail api where you require client Id,access token, refresh token but was confused if naming convection is correctly defined or not or if gmail api naming convection is different?

Extending VSCode Markdown syntax highlighting to match nested Javascript code

I am trying to extend VSCode’s Markdown syntax highlighter in order to highlight some nested Javascript wrapped in a custom syntax. For example, the following Markdown file

# Example

@@$ var value = 10;

The result is @@{value}.

would be converted to

# Example

The result is 10.

I would like the following to be highlighted as Javascript in VSCode, as if they were wrapped in a fenced code block:

  • The contents of a line starting with @@$.

  • The contents wrapped between @@{ and }.

I tried modifying markdown.tmLanguage.json to add these:

"fenced_code_block_majsdown2": {
    "begin": "(^|\G)(@@$)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\G)(\r\n|\r|\n)\s*$",
    "patterns": [{ "include": "source.js" }]
},
"fenced_code_block_majsdown": {
    "begin": "(^|\G)(@@{)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\G)(})\s*$",
    "patterns": [{ "include": "source.js" }]
},

The code gets highlighted properly, but it seems that the "end" bit is ignored and I don’t understand why — starting from either a @@$ or @@{, the entire document is highlighted as Javascript. I’ve tried several combinations of regexes, and tried removing the initial part ((^|\G)), but I couldn’t figure out why the highlighter is so greedy.

How can I achieve my desired goal?

how to connect phantom wallet and send transactions?

hello everyone if someone can write code even on codepen and send it to me where you connected the phantom wallet and you can send the transaction by just pressing a button and you will have a connection to the wallet and then the transaction.

of course if you do everything I will write to you and drop up to $ 50 on the card)

please help very much needed

Word font family variations

An introduction. My teacher from university is kind of weird. She wants all essays handwritten by students and this is is a bit exaggerated given the fact the we live in computers era. I created a font family that resembles my handwriting and saved is as .ttf and installed it on windows and use it in word. It doesn’t seem convincing, so I was wondering: If I create 100 ttf each with slight variations of a letter, is there a way in word, when you type a letter, to chose randomly from those 100 ttf files to make the writing seem more organic, because I’m not a callighraphist, I can’t write a letter twice exactly the same way, so a slight variation would make it more convincing.

If it is not possible I have a way using HTML + JS:

document.getElementById("randomize").disabled=true;
function setupFonts(){

   var handwritten = document.getElementsByTagName("handwritten")[0];
   var raw_text = handwritten.innerHTML; //no tags in handwritten tag body
   var taggedText = "";
   var fontTag = "</font><font>";
   for(var i = 0; i < raw_text.length;i++){
      if((/[a-zA-Z]/).test(raw_text.charAt(i))){
         taggedText = taggedText.concat("<font>", raw_text.charAt(i), "</font>");
      }
      else{
         taggedText = taggedText.concat(raw_text.charAt(i));
      }
   }
   handwritten.innerHTML = taggedText;
   document.getElementById("randomize").disabled=false;
}
function randomizeFonts(){
   var fontNames = ['Arial', 'Verdana', 'Consolas']; //here will be listed the variations
   var fontsArray = document.getElementsByTagName("font");
   for(var i = 0; i < fontsArray.length;i++){
      fontsArray[i].setAttribute("face", fontNames[Math.floor(Math.random()*fontNames.length)]);
   }
}
<html>
<body>
<!-- Just 1 handwritten tag allowen on a page -->
<handwritten>
This is a sentence handwritten.
</handwritten>
<br>
<button id="setup" onclick="setupFonts()">Setup Fonts</button>
<button id="randomize" onclick="randomizeFonts()">Randomize Fonts</button>
</body>

<html>

It works, however if this is possible in word it would be better.

Ramda – reduce parentheses nesting on composition

I have array like this:

const arr = [
  ['1 1 1', '', '2 2 2'], 
  ['', '3 3 3', '4 4 4']
]

and my goal is to convert i to this array:

[
  [ [1,1,1], [2,2,2] ],
  [ [3,3,3], [4,4,4] ]
]

I am trying to do that in functional way using function composition. I am also using Ramda.

I have this code

const filterEmpty = filter(o(not, isEmpty));

const getFinalArr = map(
  compose( map(map(parseInt)), map(split(' ')), filterEmpty )
)

console.log(getFinalArr(arr))

It works just fine, but it’s not quite readable. I am wondering if is there way to write it with less map nesting. Something like that would be great:

const getFinalArr = map(
  compose( parseInt, map, map, split(' '), map, filterEmpty )
)

From my point of view it is much more readable. But of course it did not work.

Or if you can suggest another way how to easily deal with arrays nested like this. I am curious.

How to process updated object property values with Javascript and React?

I am looking to use Node and React for displaying dynamic table data where one property, `cost’ will be updated via a WebSocket listener and perform some functions, i.e. find highest/lowest, or addition, etc., to all costs within a list of pools (also think of a table with updating live stock values and columns for calculated values):

┌─────────┬─────────┬──────────────────────────────────┐
│ (index) │  name   │              pools               │
├─────────┼─────────┼──────────────────────────────────┤
│    0    │ 'pizza' │      [ [Object], [Object] ]      │ sum(cost), etc.
│    1    │ 'apple' │ [ [Object], [Object], [Object] ] │ sum(cost), etc.
└─────────┴─────────┴──────────────────────────────────┘

// singular pool object
// {Walmart, apple, 1.Wallmart.apple, 1.00}
class Pool {
    constructor(exchangeName, symbols, id, cost) {
        this.exchangeName = exchangeName;
        this.symbols = symbols;
        this.id = id;
        this.cost = cost;
    }
}

// takes in an array of pools
class Pools {
    constructor(poolName, pools) {
        var costCounter = 0;        // add up all costs in pools
        var exchangeList = '';
        for (var poolObj of pools) {
            //costCounter += poolObj.cost        // this works on object initialization but not cost updated property      
            exchangeList += poolObj.exchangeName + " ";
        }

        this.poolName = poolName;
        this.pools = pools;
        //this.costCounter = _costCounter;
        this.exchangeList = exchangeList;
    }

    // perform math functions
    get costCounter() {
        for (var poolObj of pools) {
            _costCounter += poolObj.cost;
        }
        return _costCounter;
    }

}

var arrPools = [];  // array of a symbol's pools

arrPools.push(new Pool("1.exch", "1.symbols", "1.someID", 1.00)),
arrPools.push(new Pool("2.exch", "2.symbols", "2.someID", 2.00)),
arrPools.push(new Pool("3.exch", "3.symbols", "3.someID", 3.00))

var thisPoolResults = new Pools("First Pool", arrPools);

//console.log(arrPools);
console.log(thisPoolResults);

After the initial data is defined, I will want subscribe to a cost event that will update each individual Pool.cost in the collection.

The output table will contain rows of individual pools properties and a calculated total cost, by costCounter.

I am having a difficult time creating a getter to automatically recalculate costs when a cost is updated.

As I am planning to use React (I assume there are similar features to Angular for data updates), what is a recommended way of achieving this?