I need my bot to run a function that adds a guilds info to a database, but I’ve been unable to find a way to run code when the bot joins a new server.
Category: javascript
Category Added in a WPeMatico Campaign
make split-file-stream synchronous [duplicate]
I am a newbie in javascript so I’m still having many issues that I still don’t get it. I’m using this module ‘split-file-stream’ https://www.npmjs.com/package/split-file-stream and this code particularly:
var splitFileStream = require("split-file-stream");
let maxFileSize = 1024; // 1024 bytes per file
let outputPath = __dirname + "/outputFiles"; // file path partition's prefix
var customSplit = splitFileStream.getSplitWithGenFilePath((n) => `${outputPath}-${(n + 1)}`)
customSplit(readStream, maxFileSize, (error, filePaths) => {
/* If an error occured, filePaths will still contain all files that were written */
if (error) throw error; // Alternatively you could just log the error instead of throwing: if (error) console.error(error)
console.log("This is an array of my new files:", filePaths);
});
if I’m correct, I understand that fs.createReadStream is asynchronous. But what I need is that the file splitting makes it synchronous way. This is because after creating the parts, I’m going to use the splitting parts for some other stuff. But I cannot do that because when I want access to the files, these ones don’t exist yet. The question is whether a way to make this code synchronous.
PD: I’ve using Promises (async/await) but I don’t know if I am using them wrong because doesn’t wait.
Snake Game- Snake rotation and segment adding. (Im a beginner) [closed]
(Snake game)Snake rotation. New to coding, how do I make the snake segments follow and rotate when it has more than 3 parts to it? Thanks!
Mon PC cree des fichiers de type application dans tous mes dossiers
Cloudflare Workers: Inject code if cookie is available
I am trying to inject some code with Cloudflare Workers if cookie is available for example “ok=no” cookie is available.
addEventListener("fetch", (event) => { event.respondWith( handleRequest(event.request).catch( (err) => new Response(err.stack, { status: 500 }) ) ); }); class ElementHandler { element(element) { element.append(`<style>.test {display:none}</style>`, { html: true }); } } async function handleRequest(request) { const url = new URL(request.url) const res = await fetch(request) if (cookies.includes("returning=true")) { return new HTMLRewriter().on("head", new ElementHandler()).transform(res) } else { return fetch(request) } }
Unfortunately it doesn’t work… the code is not added to the head if I cookie is available.
Please tell me the right code.
Keeping indexes while sorting an array of floats in js
I have this particular array of floats
segm3 = [0.0, 2.5, 3.62, 0.0, 2.5, 3.62, 0.0]
I desire to sort it while keeping the original indexes. This is my code:
var indices = Array.from(Array(segm3.length).keys())
.sort(function(a,b) { if (segm3[a] > segm3[b]) return 1;
else if (segm3[a]<segm3[b]) return -1 ;else return 0;})
The thing is when I try to console.log the indexes I get this
[
0, 3, 6, 1,
4, 2, 5
]
The first 5 elements are correct but the last two are wrong and seem swapped incorrectly, why is that ? How do I fix it ? I tried all variations found in stackoverflow but I always get the same result.
how to greate a multiaple sheets (google sheet)?
i wana duplicate a sheet with protected ranges and i use this code, but i need to copy this sheet multiaple times by range.
function copy(){
const sh = SpreadsheetApp.getActiveSpreadsheet();
const ss = sh.getSheetByName("Support Sheet");
const prot = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE)
let nSheet = ss.copyTo(sh).setName("Year Data");
let p;
for (let i in prot){
p = nSheet.getRange(prot[i].getRange().getA1Notation()).protect();
p.removeEditors(p.getEditors());
if (p.canDomainEdit()) {
p.setDomainEdit(false);
}
}
}
React has detected a change in the order of Hooks?
I keep getting this error saying “ERROR Warning: React has detected a change in the order of Hooks called by MainMenuScreen. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks”. Really confused don’t know why am getting this error if someone can please explain or show an example it would greatly be appreciated. Many thanks for considering my request.
function MainMenuScreen({ navigation, route, props }) {
const globalContext = useContext(Context)
const { setIsLoggedIn, appSettings, domain, userObj, setUserObj, setToken, address, setAddress } = globalContext;
const [selecedTab, setSelectedTab] = React.useState(tabs[0]);
return (
<View style={styles.container}>
<LinearGradient colors={['gold', '#FF7F50', '#FF7F50']} style={StyleSheet.absoluteFill}>
<FlatList
data={tabs}
horizontal
showsHorizontalScrollIndicator={false}
style={{ flexGrow: 0 }}
keyExtractor={(item, index) => `${item}-${index}`}
renderItem={({ item: tab }) => {
return (
<TouchableOpacity onPress={() => setSelectedTab(tab)}>
<View style={[styles.pill,
{
backgroundColor: selecedTab === tab ? 'gold' : 'transparent',
},
]}>
<Text style={[styles.pillText, { color: selecedTab === tab ? 'white' : 'black' }]}>{tab}</Text>
</View>
</TouchableOpacity>
)
}}
/>
<FlatList
data={popularFood}
keyExtractor={item => item.key}
renderItem={({ item }) => {
return (
<View style={{ flexDirection: 'row' }}>
<Image source={{ uri: item.image }} style={{ width: 100, height: 100, margin: 10 }} />
<View>
<Text style={{ fontSize: 20, fontWeight: 'bold' }}>{item.type}</Text>
<View>
<AntDesign name="star" size={20} color="gold" style={{ marginRight: 10 }} />
<Text style={{ fontSize: 20, fontWeight: 'bold' }}>{item.rating}</Text>
</View>
</View>
</View>
)
}}
/>
<Text style={styles.title}>Address</Text>
<Text style={styles.title}>{address}</Text>
</LinearGradient>
</View>
);
};
Error:
ERROR Warning: React has detected a change in the order of Hooks called by MainMenuScreen. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
How do i remove a single element from my shopping cart? Using only JavaScript
I was able to code a function to clear the whole cart, but i’m really struggling to find a way to remove an item by itself. Also i’m not able to change the quantity of a product in the cart itself. I would love some guidance in this matter as this is my first JavaScript project, any comment is welcome! Thank you!
[1]: https://i.stack.imgur.com/5GOzE.jpg
Trading crypto on Binance with Node.js/JavaScript?
It’s possible to trade crypto on Binance using Node.js? I want to create a trading bot, is there any library and example on how to connect to Binance using JavaScript?
Prevent data from duplicating in Javascript
I am working on a weather app and I have one thing that need to be polished, and I am unsure of where to place a solution. Everything is working great, except when a new city is selected, it displays the 5 day forecast for the new city right next the the old 5 day forecast. It creates a long line that keeps stacking up side by side, 5 days at a time. I have tried many things, and am at a loss. Can someone point me in the right direction as far as placement is concerned? Thanks!
let citiesArr = [];
// let cityStorage = localStorage.setItem("searchHistory", JSON.stringify(citiesArr));
function handleWeather() {
let city = document.querySelector('input').value;
if (!city) return;
let url = `http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`;
fetch(url).then(data => data.json()).then(data => {
let { lat, lon } = data[0];
let url2 = `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=imperial&appid=${apiKey}`;
fetch(url2).then(data => data.json()).then(data => {
console.log(data);
let icon = `http://openweathermap.org/img/w/${data.current.weather[0].icon}.png`
let main = data.current.weather[0].main;
let description = data.current.weather[0].description;
let temp = Math.round(data.current.temp);
let humidity = data.current.humidity;
let windSpeed = Math.round(data.current.wind_speed);
let uvi = data.current.uvi;
let name = city;
document.getElementById('icon').setAttribute('src',icon);
document.getElementById("cityDescription").innerHTML = description;
document.getElementById("cityTemp").innerHTML = temp + "°";
document.getElementById("cityHumididty").innerHTML = humidity + "%";
document.getElementById("cityWindSpeed").innerHTML = windSpeed + " mph";
document.getElementById("cityUVI").innerHTML = uvi;
document.getElementById("cityName").innerHTML = name;
document.getElementById("currentDate").innerHTML = moment().format("MMM Do YYYY");
$("#cityUVI").each(function() {
if (uvi < 3) {
$(this).addClass("favorable");
}
else if(uvi >= 3 && uvi <= 8) {
$(this).addClass("moderate");
}
else {
$(this).addClass("severe")
}
});
for (let i = 0; i < 5; i++) {
let date = moment().add(i+1,"days").format("MM/DD/YYYY");
let icon2 = data.daily[i].weather[0].icon;
let temp = data.daily[i].temp.day;
let wind = data.daily[i].wind_speed;
let humidity = data.daily[i].humidity;
// if (citiesArr[i] == name) {
// return;
// }
document.getElementById('forecast').innerHTML +=
`<div class="forecastCard">
<h5>${date}</h5>
<img src="http://openweathermap.org/img/w/${icon2}.png">
<h6>Temp: ${Math.round(temp) + "°"}</h6>
<h6>Wind: ${Math.round(wind) + " mph"}</h6>
<h6>Humidity: ${humidity + "%"}</h6>
</div>`
}
for (let i = 0; i < citiesArr.length; i++) {
if(citiesArr[i] == city){
return;
}
}
citiesArr.unshift(city);
handleCities();
pastSearhces();
localStorage.setItem("searchHistory", JSON.stringify(citiesArr));
});
document.querySelector(".hide").style.display = "block";
});
}
$("#city-input").keypress(function (event) {
if (event.key === "Enter") {
$("#search-button").click();
}
});
function handleCities () {
$("#searchHistory").empty();
for (let i = 0; i < citiesArr.length; i++) {
let cityBtn = $('<button>');
cityBtn.addClass("city btn btn-primary");
cityBtn.attr("city-input", citiesArr[i]);
cityBtn.text(citiesArr[i]);
$("#searchHistory").append(cityBtn);
}
}
function pastSearhces() {
$(".btn-primary").on("click", function () {
let pastCity = $(this).attr("city-input");
$("#city-input").prop("value", pastCity);
handleWeather();
});
}
function displayCities() {
let storedCities = JSON.parse(localStorage.getItem("searchHistory"));
if (storedCities !== null) {
citiesArr = storedCities;
}
handleCities(citiesArr);
}
pastSearhces();
displayCities();
React – How to select all checkboxes based on one without using the map function
I created a simple form in React that displays the submitted data in the console. I created three checkboxes, the first one to mark the two below, and the other two regarding data processing. Is there a way to change the state of two checkboxes by clicking only the “Accept All” checkbox?
I found solutions that worked on checkboxes mapped from array, while my checkboxes are simply written in the code. I can’t understand how I can target each of the two checkboxes that I need to make change in based on “Accept all” checkbox
Here is the snippet of code, I am using styled components.
import { useState } from 'react';
const Contact = () => {
const [isChecked, setIsChecked] = useState(false);
const handleOnChange = () => {
setIsChecked(!isChecked);
};
return (
<Processing>
<Label>
<Checkbox type='checkbox' />
<CheckboxText>Accept all</CheckboxText>
</Label>
<Label>
<Checkbox type='checkbox' defaultChecked={false} required />
<CheckboxText>I agree to the processing my data</CheckboxText>
</Label>
<Label>
<Checkbox type='checkbox' defaultChecked={false} required />
<CheckboxText>RODO processing my data by company</CheckboxText>
</Label>
</Processing>
);
};
export default Contact;
Synchronized countdown timer across different users [closed]
Hi I would like to implement countdown timers in my project. However, I would like the countdown to be synchronized across all users. For example, if the countdown at user A is 03:05, the countdown at user B should be the same 03:05. I have been able to create a countdown timer but am not able to synchronize across all users. I would like to have an interval of 5 minutes, once the 5 minutes expires, the timer will restart at 5 min, 4:49, 4:48 etc to zero. But this should be the same across all users or devices.
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 1,
display = document.querySelector('#demo');
startTimer(fiveMinutes, display);
};
</script>
How to get webpage in the same state after reloading in jquery and html?
I have a webpage which is in some state currently, that is, some divs are shown and some are hidden. I am using cookies to post data to Python CGI scripts. So now, when I click a button, I want it to send data to the python cgi file, and so, I want the button reload the page, so that, due to reloading the cookie can be updated and thus, the updated cookie can be sent to the python-cgi file. (Also, I am using iframe to display the python-cgi file inside my html webpage).
Now, the methods such as location.load() doesn’t work as it reloads the webpage into the initial state where all my divs were hidden but I want it to be in the same state as before reloading where some divs were shown and some were hidden.
How can I achieve that? Please help me with that! Thanks!
Mongoose Sequence not inserting autoincrement NodeJS
Trying to make a field auto-increment I use Mongoose Sequence but it never auto-increments as Mongoose always throws me the following error:
Error: Product validation failed: idProduct: Cast to Number failed for
value “undefined” (type string) at path “idProduct”
at ValidationError.inspect (C:UsersPoshDesktopapi2node_modulesmongooseliberrorvalidation.js:48:26)
at formatValue (node:internal/util/inspect:763:19)
at inspect (node:internal/util/inspect:340:10)
at formatWithOptionsInternal (node:internal/util/inspect:2006:40)
at formatWithOptions (node:internal/util/inspect:1888:10)
at console.value (node:internal/console/constructor:323:14)
at console.log (node:internal/console/constructor:359:61)
at newProduct (C:UsersPoshDesktopapi2controllersproducts.js:87:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5) { errors: {
idProduct: CastError: Cast to Number failed for value “undefined” (type string) at path “idProduct”
This is my model and how it configures Mongoose Sequence:
const { Schema, model } = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const mongoose = require('mongoose');
const AutoIncrement = require('mongoose-sequence')(mongoose);
const ProductSchema = Schema (
{
barCode: {
type: String,
maxlength:64,
unique: true,
required: [true, 'El Código de Producto es obligatorio']
},
idProduct: {
type: Number,
unique: true
}
}
);
ProductSchema.plugin(AutoIncrement, {inc_field: 'idProduct'});
ProductSchema.plugin(mongoosePaginate);
module.exports = model('Product', ProductSchema);
I really don’t understand what is happening since I only copied and pasted the Mongoose Sequence configuration as it is in other models where it works perfectly.