I tried using gray-matter in electron, but there was utils.js:36 Uncaught ReferenceError: Buffer is not defined. Is there a way to use Buffer in electron?
Category: javascript
Category Added in a WPeMatico Campaign
HTML not rendering my basic three.js code
im a bit of a noob when it comes to three.js and html but ive created other js files and they would import into the html page just fine but im confused why my basic box copy pasta code isnt showing up on the page. it works fine when scripting it all in html but not when import the js file in the same folder. could yall help me understand whats going on?
index.js
/*import * as THREE from 'three'
const canvas=document.querySelector('.webgl')
const scene = new THREE.Scene();
const geo = new THREE.BoxGeometry(1,1,1)
const mats = new THREE.MeshBasicMaterial({
color:'red'
})
const boxmesh=new THREE.Mesh(geo,mats)
scene.add(boxmesh)
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,100)
camera.position.set(0,1,2)
scene.add(camera)
const renderer=new THREE.WebGL1Renderer({
canvas:canvas
})
renderer.setSize(window.innerWidth,window.innerHeight)
renderer.setPixelRatio(Math.min(window.devicePixelRatio,2))
renderer.shadowMap.enabled=true
renderer.gammaOutput=true
renderer.render(scene, camera)*/
import * as THREE from 'three';
// init
const camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background= new THREE.Color('black')
const geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
const material = new THREE.MeshNormalMaterial();
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animation );
document.body.appendChild( renderer.domElement );
// animation
function animation( time ) {
mesh.rotation.x = .1;
mesh.rotation.y = .1;
renderer.render( scene, camera );
}
animation()
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="learning html" content="This is learing making websites">
<title>Learing GLTF</title>
<script src="index.js"></script>
</head>
<body>
<canvas class="webgl"></canvas>
?
</body>
</html>
How to continuously run your main code and also listen for new data and include it in your main code without blocking the main Thread?
I’m new to JavaScript and any assistance would be greatly appreciated. A simpler version of the code is shown below. I want to run a while loop that listens for new transactions via sockets and uses them in my while loop.
The issue is that if I don’t leave the call stack, I’ll never be able to add anything from the callback queue to the callstack. I tried using setInterval(()=>/code here,0), but that didn’t help unless I added a 10-20 second time interval. Code in the while loop is CPU intensive. For e.g. if while loop takes 60 seconds to complete, setInterval will add a large number of callbacks in the callback queue which means those sockets messages are there somewhere in the callback queue but I will get them after a long period of time because first, it will run all the callbacks added by setInterval and this continuous.
A Task in the While loop process is CPU intensive, I figured that moving it to the worker thread might help, but I have to pass those transactions to the worker Thread as well, and because of the infinite while loop problem remains the same.
It is clear that I cannot use an infinite while loop. Is there any better approach to handle this?
const io = require("socket.io")(3700, { cors: { origin: "*" } });
const list = [];
class Blockchain {
constructor() {
this.unConfirmedTxs = [];
}
// Listen for new Unconfirmed Txs
startServer() {
io.on("connection", (socket) => {
console.log(`User is connected ${socket.id}`);
socket.emit("message", "Hello from server");
socket.on("sendTx", (data) => {
this.unConfirmedTxs.push(data);
console.log(this.unConfirmedTxs);
});
});
}
async main() {
this.startServer();
// Use UnconfirmedTxs here
while (true) {
console.log(this.unConfirmedTxs);
}
}
}
const blockchain = new Blockchain();
blockchain.main();
Firebase Errors don’t show up on live server but do on localhost
I get the following errors when running my firebase server using local host or deploying it (Firebase serve or firebase deploy commands)
GET
http://localhost:5000/Issue-Tracker/public/Bug-Tracker/CSS/snackBar.css
net::ERR_ABORTED 404 (Not Found) index.html:94 GET
http://localhost:5000/public/Bug-Tracker/JS/firebase.js
net::ERR_ABORTED 404 (Not Found) firebaseNamespaceCore.ts:114 Uncaught
FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created
- call Firebase App.initializeApp() (app/no-app).
at f (firebaseNamespaceCore.ts:114:27)
at Object.i [as auth] (firebaseNamespaceCore.ts:196:31)
at app.js:26:23
However, when I use a live server like here: https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer
I do not get these errors and my program works. I am confused. Why is this so?
Multiform validation on next
folks,
I would really appreciate some help over here. I have a one page containing a multiform using the tag. I’m trying to show an alert of the field is empty on clicking the button Next. I’ve managed to do so, I’m seeing the alert, however, after closing it, the form still proceeds. Here are the snippets from the code:
Form:
<div class="card" id="q3">
<div class="card-body">
<h2 class="card-title">
<div class="card-number">3
<svg height="10" width="11"><path d="M7.586 5L4.293 1.707 5.707.293 10.414 5 5.707 9.707 4.293 8.293z"></path><path d="M8 4v2H0V4z"></path></svg></div>
Question 1 *</h2>
<input class="card-input" type="number" name="age" placeholder="examsple" required />
<div class="btn-block">
<a href="#" class="btn btn-primary">Next</a>
<span class="card-extra-text">This is <strong>required</strong></span>
</div>
</div>
</div>
Script.js
// greeting -> q1 -> q2 = paths
// question with id=q2 defines quiz path
var paths = {
"problem_1": [q3, q6, q7, q_finish],
"problem_2": [q4, q6, q7, q_finish],
"problem_3": [q5, q7, q_finish],
"problem_4": [q_finish]
};
$(document).ready(function() {
var cards = $(".card");
//Selected in card with id=q2 path
var selectedPath;
//Prevents form submit by clicking enter
$(window).keydown(function(event) {
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
$(".form").submit(function(event) {
var activeCard = $(".card_active");
if(activeCard.attr("id") === "q_finish") {
changeProgress(66, 33);
}
});
$(".card a.btn").click(function(event) {
event.preventDefault();
var activeCard = $(".card_active");
if(activeCard.attr("id") === "q1") {
saveUserName(activeCard);
changeProgress(100, 50);
}
var inputs = activeCard.find(':input');
for(var i = 0; i< inputs.length; i++) {
var element = inputs[i];
// validate elements..
// for example for required:
if(element.hasAttribute('required')) {
if($(element).val() === '') {
alert('a field is required');
// or do whatever you want with it..
}
}
}
//Changes active card (selected path or simply next card)
if(selectedPath) {
selectedPath[1] += 1;
var nextCard = paths[selectedPath[0]][selectedPath[1]];
var nextCardIndex = cards.index(nextCard);
showNextCard(cards, activeCard, nextCardIndex, true);
} else {
showNextCard(cards, activeCard, 1, false);
}
});
//Shows/hides button on input
$("input.card-input").on("input", function(event) {
if($(this).val()) {
$(".card_active .btn-block")[0].classList.add("btn-block_shown");
} else {
$(".card_active .btn-block")[0].classList.remove("btn-block_shown");
}
});
});
//Changes value in progress bar
function changeProgress(px, proc) {
var perc = $("#perc_line").css("width");
perc = perc.replace("px", "");
perc = Number(perc) + px;
$("#perc_line").css("width", perc + "px");
perc = $("#perc_num").html();
perc = Number(perc) + proc;
$("#perc_num").html(perc);
// name 50% - 100px
// radio 17% - 34px
// phone 33% - 66px
}
//Changes active card
//parameter q2 defines card with id=q2, type bool
function showNextCard(cards, activeCard, step, q2) {
var cardsLength = cards.length;
var activeIndex = cards.index(activeCard);
if(q2) {
step -= activeIndex;
}
if(activeIndex + step < cardsLength) {
activeCard.removeClass("card_active");
cards.get(activeIndex + step).classList.add("card_active");
}
}
//Saves user name
function saveUserName(activeCard) {
var name = activeCard.find("input").val();
$("#hello_name").html(name);
$("#hello_name_2").html(name);
}
Why returning result using prompt and direct assigning value gives me different result js? [duplicate]
// by direct assigning
let a = 100;
let b = 90;
if(a>b){
console.log(`${a} is greater than ${b}`);
}else{
console.log(`${a} is less than ${b}`);
}
// ans - 100 is greater than 90
writing above check returns me correct ans but after using prompt to take value from user it gives me wrong answer i’m a bit confused
// using prompt
let a = prompt("Enter a number: ");
let b = prompt("Enter a number: ");
if (a > b) {
console.log("a is greater than b");
}
else {
console.log("a is less than b");
}
// for same input on prompt gives me 100 is less than 90
ReactJs and Singleton issue with updating
Firstable, I know its not good practice to share data like this in react App,
But – let say “I have no choice”
Now I have an issue with singleton in ReactJs.
I can see that if i trying to get instance of singleton – constructor works only once.
Inside constructor I have subscription to web socket which updates data inside singleton.
But then Im try to reach the data from different places in app – its not update – shows me version then I took instance. How could I solve it?
export default class Manager {
constructor(){
this.data = null;
socket.on('event', this.parseData)
}
static getInstance(){
if (!this.instance) {
this.instance = new QuotasManager();
}
return this.instance;
}
parseData(data){ ///parsedata}
getData(){ return this.data}
}
forEach objects value equals undefined
I have an object has this structure
{
"0": {
"id": 10250903,
...
},
"1": {
"id": 10810490,
...
},
...
}
I tried to iterate the object to get the values
products?.forEach((product) => {
console.log(product);
});
Result:
Object {
"id": 10250903,
...
}
Object {
"id": 10810490,
...
}
But when I try to access id value, console prints
undefined
undefined
I am stuck I tried everything.
Object.values(products)will not work since product will be undefined until data is received.- Creating a new Array and mapping into it also will not work.
Help. Thanks in Advance
Cannot read properties of undefined (reading ‘comparePositionTo’
I’m making a kick slashCommand in discord.js v13 and i was trying to compared the user roles and the target role but it doesn’t work, I don’t know why is that
here’s my code:
If(interaction.member.highest.comparePositionTo(target.roles.highest.position > 0)) {
const kickErr = new MessageEmbed()
.setDescription(`You cannt kick this member because their role is higher/equal to yours.`)
.setColor(ee.color)
return interaction.reply({ embeds: [kickErr] })
} else if (interaction.guild.me.roles.highest.comparePositionTo(target.roles.highest.position > 0)) {
const kickErr2 = new MessageEmbed()
.setDescription(`I cannot kick this member because their role is higher/equal to mine.`)
.setColor(ee.color)
return interaction.reply({ embeds: [kickErr2] })
}
Jquery grep Vs each for better performance
I have a scenario to create two new arrays(based on certain conditions) from an existing array. I have two different ways to get my result.
-
Use Jquery grep() twice to filter the original array.
var arrErrorRecs = [], arrWarningRecs = []; arrErrorRecs = jQuery.grep(aSelectedRecs,function(oItem){ return oItem.Stat === "Error"; }); arrWarningRecs = jQuery.grep(aSelectedRecs,function(oItem){ return oItem.Stat === "Warning"; }); -
Use Jquery each() once and populate the two new arrays
jQuery.each(aSelectedRecs, function(){ if(this.MinPriceValidation === "Error"){ arrErrorRecs.push(this); }else if(this.MinPriceValidation === "Warning"){ arrWarningRecs.push(this); } });
I have an understanding that in this case Jquery.each would be best as it is looping the array only once. Please advise which is the most effective way for better performance.
Looking pharmacy inventory site
please am looking for a inventory site that’s built with react js or vue js,
is for a pharmacy shop, the features are when a user come to buy a medicne he or she will first go to doctor or nurse describe the medicine he or she want and after that if the nurse check in the uploaded medicine in the site if is avaliable she will print a receipt containing the medicine and the user will take the medicine to casher for payment.
Image Drag top offset position calculation in percent
I’m trying to calculate the top offset of my image draggable within a container of fixed height.
So I can get the value in percent not in pixels and use that value to set the CSS top positioning of image within a container ".container".
Here’s my codes Thanks!
<div class="container">
<img src="" alt="" class="image">
</div>
<script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<style>
.container{
position: relative;
width: 960px;
height: 300px;
overflow: hidden;
}
.image{
top: 0;
width: 100%;
min-height: 100%;
min-width: 100%;
}
</style>
// JS
$(document).ready(function () {
let $container = $('.container');
let $image = $('.image');
let $conWidth = $($container).width();
let $conHeight = $($container).height();
let $imgWidth = $image.width();
let $imgHeight = $image.height();
$image.draggable({
disabled: false,
scroll: false,
axis: 'x, y',
cursor : 'move',
drag: (e, ui)=>{
if(ui.position.top >= 0) ui.position.top = 0;
if(ui.position.top <= $conHeight - $imgHeight)
ui.position.top = $conHeight - $imgHeight;
if(ui.position.left >= 0) ui.position.left = 0;
if(ui.position.left <= $conWidth - $imgWidth)
ui.position.left = $conWidth - $imgWidth;
},
stop: (e, ui)=>{
let $offsetHeight = ui.position.top;
let $offsetWidth = ui.position.left;
let realImageHeight = ($conWidth * $conHeight / $imgWidth) - $imgHeight;
let $top = ($realImageHeight * $offsetHeight / 100 * -1)/100;
console.log($top) // $top value in percent to be used as top positioning CSS
}
});
});
querySelector and getElementById, why doesn’t querySelector work? [closed]
console.log(document.getElementById('#blackjack-hit-button'));
console.log(document.querySelector('#blackjack-hit-button'));
When I execute these two lines, getElementById returns the actual html element, but querySelector returns null. What is the reason behind that?
Thank you so much in advance!
How do you set up workers in a cluster using Node.js without having it in the same file?
I have this code in an index.js that I mostly left unmodified from the official Node.js documentation.
const https = require('https');
const fs = require('fs');
const cluster = require('node:cluster');
const numCPUs = require('node:os').cpus().length;
const process = require('node:process');
const livegame = require('./server-livegame');
const matchmaking = require('./server-matchmaking');
//Start ExpressJS
var express = require('express');
const { match } = require('assert');
var app = express();
app.use(express.json());
if (cluster.isPrimary) {
console.log(`Primary ${process.pid} is running`);
for (let i = 0; i< numCPUs; i++){
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
});
}
else
{
new livegame;
new matchmaking;
}
Here is a simplified code for livegame/matchmaking that produces the error.
const https = require('https');
const fs = require('fs');
const mongoose = require('mongoose');
//Import Models
const LiveMatch = require('./models/livematch');
//Start ExpressJS
var express = require('express');
const { match } = require('assert');
//Interface Security
var options = {
key: fs.readFileSync('key.pem', 'utf8'),
cert: fs.readFileSync('cert.pem', 'utf8')
};
//Server
var httpsServer = https.createServer(options, app);
httpsServer.listen(443);
var app = express();
app.use(express.json());
const chat =
{
puuid: String,
name: String,
roleID: String,
message: String,
}
app.post(':id/chat', (req,res) =>
{
//something here
});
I have livegame and matchmaking as separate .js files alongside the index.js whom I call to launch them programmatically as multiple instances. However, this is the error I get:
node:events:505
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::443
at Server.setupListenHandle [as _listen2] (node:net:1380:16)
at listenInCluster (node:net:1428:12)
at Server.listen (node:net:1516:7)
at C:Users----DocumentsMGsrcserver-matchmaking.js:25:66
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1407:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 443
}
Based on my progress so far, I think the issue is with me creating more “dining space” instead of hiring more “workers”.
How do I properly create instances of a server with proper load balancing using clusters?
Transition effect between two states of svg polygon on hover
function menuHover(navLI, Y) {
const topTriangle = navLI.querySelector(".triangle").querySelector("polygon");
topTriangle.setAttribute("points", "0,0 200,0 100," + Y);
}
function navHoverIn(navLI) {menuHover(navLI, 60);}
function navHoverOut(navLI) {menuHover(navLI, 10);}
<div onmouseenter="navHoverIn(this)" onmouseleave="navHoverOut(this)">
<svg viewBox="0 0 200 60" class="triangle">
<polygon points="0,0 200,0 100,10">
</svg>
</div>
If you hover over the triangle, the coordinate points of the polygon change.
Any ideas what is the most convenient way to create the transition effect between the two states? So it doesn’t just instantly change, but has some kind of ease animation.