#development
1 messages · Page 154 of 1
same
I'm new in web development. I wanted to create a dashboard for my bot. My bot have like 60+ shards. when user auth I want to show all mutual guilds with bot. Should I use ws to get all guilds from bot to website or should I create a api endpoint?
mutual guilds is not a good idea, its very spammy, api-wise, unless you have all members cached
isnt it literally a case of getting all the guilds the user is in through the oauth scope and then seeing if the bot is in those guilds, whether by querying a database with said IDs or broadcasteval?
then that can be cached
yea use the oauth schope then you can check if the bot is in those servers, and if the user has admin/manage guilds
or however you wanna work that
for communication with my bot and dashboard i used an api setup on the bot side but you could opt in for something more complex like redis message brokers if youre fancy or websockets indeed
depends on your scale
oh yeah i fogot about oauth, since you already have the user's oauth you can just add the guilds scope
is there smth like awaitModalCancel()? when person just closes it without submitting
For Discord? No. No events are sent if the user doesn't submit a modal
can anyone help me with puppeteer here?
client side:```js
console.log('- [client] launching browser...')
const browser = await puppeteer.launch({
headless: 'new'
})
console.log('- [client] launching browser page...')
const page = await browser.newPage()
console.log('- [client] requesting to localhost:8080...')
await page.goto('http://localhost:8080', {
waitUntil: 'domcontentloaded'
})
console.log('- [client] running tests...')
const a = await page.evaluate(async () => {
return window.a.toString()
})
index.html: ```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<script type="module">
window.a = 69
</script>
</body>
</html>
page.evaluate doesn't work because it says that window.a is undefined, despite me using waitUntil: 'domcontentloaded'
nope
how do you even make puppeteer wait until all scripts are executed
deum, thats sux
with hopes and prayers
hm
@radiant kraken have you tried looking into the waitForFunction?
or any of the other wait methods
something there might be able to help you
what happens if you do waitForNetworkIdle or put networkidle0 in the waitUntil
presumably that will wait until all javascript has executed at least according to stack overflow
Error handling request
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_protocol.py", line 433, in _handle_request
resp = await request_handler(request)
File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_app.py", line 504, in _handle
resp = await handler(request)
File "/home/container/.local/lib/python3.10/site-packages/topgg/webhook.py", line 163, in _handler
(BotVoteData if type_ is WebhookType.BOT else GuildVoteData)(**data),
File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 366, in __init__
super().__init__(**parse_vote_dict(kwargs))
File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 46, in parse_vote_dict
query_dict = {k: v for k, v in [pair.split("=") for pair in query.split("&")]}
File "/home/container/.local/lib/python3.10/site-packages/topgg/types.py", line 46, in <dictcomp>
query_dict = {k: v for k, v in [pair.split("=") for pair in query.split("&")]}
ValueError: not enough values to unpack (expected 2, got 1)```
what does this error mean and why am i getting it?
and py Error handling request Traceback (most recent call last): File "/home/container/.local/lib/python3.10/site-packages/aiohttp/web_protocol.py", line 332, in data_received messages, upgraded, tail = self._request_parser.feed_data(data) File "aiohttp/_http_parser.pyx", line 551, in aiohttp._http_parser.HttpParser.feed_data aiohttp.http_exceptions.BadStatusLine: 400, message="Bad status line 'Invalid method encountered'"
it means ur doing (a, b) = someArray
but someArray only has 1 value
show where ur creating topgg client
if that giant string is your secret or any type of token I'd suggest not putting it in this channel like that.
if u did put, reset it ASAP
dblclient = topgg.DBLClient("token").set_data(CLIENT)
autoposter: topgg.AutoPoster = (
dblclient.autopost()
.on_success(on_autopost_success)
.on_error(on_autopost_error)
.stats(stats)
)```
there are selfbots here to grab tokens
but anyways this is where i set up the client
DBLClient takes 2 args
i ate the token it was delicious
hey guys sorry for these dumb questions all the time, but would working with vh and vw be a good practice for a responsive website?
i mean, by doing this the site changes, scales up or down relative to the viewport of the user.
i see thankss!
damn i am samrt
nice
How do you link app commands like this? ❤️
</NAME:COMMAND_ID> right?
yes
I didn’t know that was fast way get command id
There's another way to get the id?
ahh ty ty, I just grabbed it from Intergrations, but you're way is much easier 😄
my idiot brain took me to intergrations before trying anything else 🤣
Oh
You can probably fetch it in the code or read it when receiving interactions
You can fetch it from the API. You can get the commands endpoint to dynamically fetch all command names and IDs.
That's the best way instead of hard-coding it
Guys, has finally been verified my bot
GGs
-nobadge
So it is no longer possible to get it? Sorry my ignorance
Yea
This is one of those og badges you'll never get
Like early supporter or something like that
How can I do this now that my bot is verified?
You can't add it, it will appear by itself some time after your bot is verified
oh ok
what platform is that? last time i saw a platform that did that, the results were so wrong you had people with slow ass code with a higher score than actual fast codes lmao
It’s leetcode
I could make the function even faster
By returning if the initial condition wasn’t met before the loop.
is there a way to see other people's solutions and their performance results?
then check if their performance results make sense, for example a solution using for loops will always be faster than a solution using array methods like .forEach or.map
because i remember one website where their results were completely non-sensical
yeah I did. I was surprised i created this code and didn’t believe it so I did my research by looking at other solutions written in js. I used for loops and others usually forEach, while etc.
i dont remember what was the name of the other website
but i remember they had like rankings for problems, and the top rank solution was slow af
lmao
Also what i did was creating an arrow function to check whether a condition was met, others usually didn’t create a seperate function but copy pasted the checks each time
Ahahahhaha
leetcode is pretty fun and cool to learn. So far i think I know a lot about the dom and nodejs so i thought let’s do some challenge problems
like, their benchmarking system was really bad and pretty much random, every time you ran the function you would get completely different results
so the guy got top rank by luck
Oowhh no leetcode is pretty known for accurate results. It’s also linked to lots of companies who provide tests, reviews and challenges
thats what im interested in, how accurate their results are
because js is not easy to benchmark
there is a lot of variance
Lets do a quick research 🙂 I think they have a field on their website talking about the benchmarks
One sec I’ll try to find it
yeah pretty much same shit
- check top ranked solutions
- copy paste them and run them
- watch the result being slower than what you initially did
- yet somehow they got top rank
this was back in 2020 tho
idk over the years it got way more popular due to people talking about it etc
they might have fixed it but I’ll take the runtime with a grain of salt..
as long as my code passes the test cases I’m good ig
the thing is, its almost impossible to accurately benchmark js
especially online like that
i would rather trust a loop with 1 million iterations and run my function in there
Leetcode is known to be inaccurate tho
because what these companies do, is they put your code in a file, and call node thatfile, and measure the time to complete that
which includes the whole nodejs spin up time, which is wildly variant
Best u can do is benchmark it yourself with console.time() or create a big-O notation if your function isn’t too complicated
also who knows how many machines they have to run thousands of things per day, which introduces even more variance
But if you benchmark it yourself you’ll need other function to compare to, ran in the exact same environment
an accurate comparison has to be always done in the same machine in the same configuration
yeah
so basically, online benchmarking competitions are a lottery, you win by luck, not by fast code
xD
give me the top answers and your answer and i'll benchmark them for you
:^)
sure I will send it once I am home
How do people have fancy descriptions for their bot?
You can achieve this using Markdown or HTML in your bot's description. You can ask in #development for help or use this HTML and Markdown cheatsheet for more resources.
-htmldesc -d 
how do people get the interactivity in their stuff?
I've seen pages where you can select buttons with animation and stuff
you can do animations with css alone
regarding buttons, you probably saw an iframe
which is a site embedded into the long description
ahhhh, the iframe. makes sense, ty
worth to note, iframes cannot access the parent, so whatever scripts u got into it will only work on the site itself
so I want to delete many rows using prisma, the thing is I also need some data of the deleted rows back, not just count (the only thing included by default). how can I do that without losing performance? Im mostly deleting around 200 items, maximum 500 at a time
currently I have
.http('POST', '/', (http) => http
.document((docs) => docs
.description('Cancel multiple Invoices')
)
.ratelimit((limit) => limit
.hits(3)
.window(time(1).s())
.penalty(time(2).s())
)
.onRequest(async(ctr) => {
const infos = ctr.validateZod((z) => ({
items: z.number().array().max(500)
}))
if (!infos) return
const { count } = await ctr["@"].database.invoice.updateMany({
data: {
status: 'CANCELLED'
}, where: {
status: 'PENDING',
userId: ctr["@"].user.id,
id: {
in: infos.items
}
}
})
FIX SIR
return ctr.print({ success: true, count })
})
)```
so the way you proposed would be
```ts
.http('POST', '/', (http) => http
.document((docs) => docs
.description('Cancel multiple Invoices')
)
.ratelimit((limit) => limit
.hits(3)
.window(time(1).s())
.penalty(time(2).s())
)
.onRequest(async(ctr) => {
const infos = ctr.validateZod((z) => ({
items: z.number().array().max(500)
}))
if (!infos) return
const invoices = await ctr["@"].database.invoice.findMany({
where: {
status: 'PENDING',
userId: ctr["@"].user.id,
id: {
in: infos.items
}
}, select: {
id: true,
// any other data I want to process with
}
})
for (const invoice of invoices) {
// do some stuff
}
await ctr["@"].database.invoice.deleteMany({
where: {
id: {
in: invoices.map((invoice) => invoice.id)
}
}
})
return ctr.print({ success: true, count: invoices.length })
})
)```
?
be glad you havent
I definitely have some regrets too, but migrating to somethig like drizzle would take too long
i have a question about Angular, so basically there is a group of students who are doing an Angular course but they are having trouble with some basic JS concepts like classes, oop, inheritance, polimorphism, typescript and shit. So i was tasked with giving them a reinforcement class on those concepts, which is fine, but also they want a few examples of how they are used in an Angular context.
i've never used Angular before, so if anyone here is experienced with Angular, can you explain a little bit and provide a few examples of how Angular works and how to particularly show a bunch of people how OOP is used in Angular?
i'll be looking at some Angular docs and tutorials tomorrow, but any input, tip or example would be nice
but the basic premise is "teach students about OOP and how its used in Angular"
tf is drizzle
an orm that aims to only send 1 query with every invocation (and use native join unlike prisma for some reason)
The devs are actually clowning rn
yes
Actually doesn't look all too bad
i'd likely use it over typeorm or prisma
prisma is still one of my go to choices tho
@civic scroll
AHAJAJAJAJ TF
what is the best way to display a big size image?
I have 20 images that weight about 10mb each
I think <Image> component from nextjs can compress it right?
Compress the images manually
Having to compress an image each time you serve it would suck up cpu power very quickly
Also serve them as webp if available
doesnt the framework cache the compressed images or something?
each angular component, service, directive is a class
@Component({ /* metadata goes here /* })
export class ExampleComponent {}
so by being a class it can do one of the stuffs like
- encapsulates data and its own logic (each property in the angular component class is a state)
which is also inheritance, due to the class implementing interfaces likeOnInit - or, it can also extend other classes / components to inherit structure / logic
similar cases to polymorphism: a class that implements an interface / another abstract class
i did this but tbh the code looks ugly
in short,
any angular-extended class property is a state
all of its dependency will be updated whenever those states change
for inheritance, you can have other component classes inherit base + implementing interfaces, like OnInit, OnChange functionality of a base component class
for polymorphism, same case of overriding abstract class methods
and don't forget depency injection
export class ExampleComponent {
constructor(private / public exampleService: ExampleService)
{
// After this component is constructed, you can access the service's methods and look at its states (this component update callback via `OnChange.ngOnChange` method would also get triggered when any of its dependencies (services)' state updates)
}
}
this also applies for services and other angular classes as well
i dont think i'll need to go in depth into angular and explain what is a decorator and how does it work, since they have a different teacher for that (i hope)
as long as the dependy is Injectable
or explaining state changes
yeah that's a typescript feature
isnt it still experimental in ts?
angular site has in-depth explanation of that iirc
still a feature nonetheless 
are angular decorators exactly the same as in ts?
can you use them in a version of ts that doesnt support decorators?
yes
or has them disabled?
they have to be enabled via a compiler flag
yeah
so i guess i'll have to go into that subject too
i dont really like decorators as a concept, i think they are confusing and hard to understand lol
the flag is experimentalDecorators
you can briefly introduce it
unless you want them to also make their own decorators
which is definitely helpful
nah, just so they know dafuq angular is doing when you type atComponent
from what i understood, they started an angular course, and the teacher started using components an classes and all that, and the students were like, uh... dafuq is a class?
i just explain that "angular would add this class to the component tree, adding necessary identifiers and some other metadata for rendering later"
oh
damn...
they will need to learn typescript and oop first before working with angular
yeah thats what i was tasked with
its just that they wanted me to also give some examples of how it looks like when applied to angular
so they get more familiarized
but for the most part i will not be going into angular, just sticking with oop and ts
i wonder how much can be done in mere 3 hours (thats how long the class is gnna be)
i sure hope they use vsc
encourage them to explore via hints
in vsc that is Ctrl + Space
ye
you can also show additional notes / docs of a suggestion as well
with vsc keymap yes
ah
not sure about others
well i'll just tell them if they use a different code editor to look into how to do that there
inb4 someone uses notepad
yeah that works
:^)
code js with physical transistors
with crafted cpus 
from sticks and stones
also another thing, since it's typescript
tell them to be aware of the kind of data they are working with at all times
like paying attention to typings and stuff?
esp. one created by their code, tell them to pay attention to types, function / method signatures
yeah, and maybe also teach them how to read errors as well
there are 2 types: compile error and runtime error
in this case we will do type error
ikr
just tell em to read carefully for 2 things:
- where it is happening
- why it errored
so at least they will know what to ask for help for when they are in trouble
typescript also have error code associated with an error, and you can google the error code up for examples, which is neat
i wish 
i will go to brazil when i can
ah tim
one more thing
just make it simple
only includes part of the code that relates to the topic
to reduce noise
yeah
im planning to go very basic on it
but i'll need to ask first how they feel about it and what exactly they have trouble with
with other part of the code (i suppose to show integrations later), just fade it to make the part you are talking about stands out more
that's a good one
so that you can see what are the main struggles and tackle one by one
ye
because supposedly they already had a basic JS course
so they should already know a few things
at least js has top-level statements 
xD
oh yeah
also encourage them to type the same thing in their editor
to show that it works like demonstrated
(only for simple examples)
something fun that i saw another teacher do, is have the students suggest what to type on his screen
so he just types what the students say
withtou correcting them
and then go over the mistakes
xD
ye
wah
localhost != 127.0.0.1 according to chrome/firefox
lmao
so i should have the app.js run on 127.0.0.1 instead
that wont make a different, just visit localhost:3001 within your code
aka within your fetch
oowh
if i host this with ngrok or something
would i be able to set a proper domain name
for my api
yes, or you just use localhost to visit your site
way easier
you're currently on 127.0.0.1 and not localhost, thats why cors says no
yeah but i mean once i bring the api out, it wouldn't be smart to run on localhost. Well i don't even think it would be possible without port forwarding it am i right?
if someone accesses your website outside of localhost then yes that wont work
i am actually doing it rn but it still throws me cors ahh issues
i see!
not 3001
oh where's your server
I dont understand your setup tbf
@eternal osprey okay so
if that is your server endpoint
you better add an OPTION handler for all the paths
or just go fuck all and cors allow everything during development
the app.listen is set to 3000
wait should i rpovide some code lmao
browsers often do preflight checking, which is sending an OPTION request to the endpoint beforehand to check for what is allowed to include
so in this case
you will need to add the corresponding header field on the OPTION handle
@eternal osprey
just you know, read the error carefully
i have no fucking clue what preflight is
then google it?
also i just explained above
app.option('*', (_, response) => {
response.header({
// required header here
}).send()
})
something like that idk express
it's kinda funny how you don't search something up when you know it

but yeah general tip is read the error carefully
read it twice
make it 3
just watched a tutorial about this subject
finally undestand how it works
app.use(
cors({
origin: "http://127.0.0.1:3001",
})
);
app.use("/tax", routes);
app.listen(3000);``` i got one last issue tho
why is this page not defined?
go you have a routes.get("/") ?
yup
let me send the actual code in the route
const express = require("express");
const routes = express.Router();
routes.get("/", (req, res) => {
console.log(req);
res.status(200).send("good");
});
module.exports = routes;
Hi guys, I don't ask questions here very often, but maybe you know a way to limit the size of a Set in javascript, let's say to 100? I've already looked online for some methods, but it wouldn't hurt to ask here as well
you can extend it and override the add method
looks good so idk
maybe my fetch is wrong
try /tax/
fetch("http://localhost:3000/tax", {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify({
country: this.getCountry(),
grossIncome: this.getGrossIncome(),
taxPercentage: this.getTaxPercentage(),
}),
})
.then((res) => {
if (res.ok) {
console.log("POST request successful");
return res.json();
} else {
console.log("Error sending POST request");
return new Error("Error sending POST request");
}
})
.then((data) => console.log(data));
});```
will try.
omg that was from practicing before, i forgot tot change iut
So which way would be the best way to store invoices of certain users?
Is it inserting in their table better than making a new one called Invoices and store all the invoices there and each one has a user id to whom it belongs to
as a general rule, if you have multiple copies of something, it should be in its own table
f i r s t n o r m a l i s a t i o n r u l e
i did learn something useful from computer science after all
anyone have tips for looking for a memory leak? i tried using the chrome debugger thing but it just crashes the bot with 100% cpu usage
memory leaks ain't very easy to find
some tools have a built-in profiler, which u could use to get a flame graph
ik webstorm does have it
it takes a few days for it to become noticeable though
im rly tempted to move to digitalocean for their droplet memory graph so i can see if its caused by a certain event or something
use this node --heapsnapshot-signal=SIGUSR2 index.js
when it becomes noticeable, use kill -USR2 <pid>
this will generate a heap dump in the folder you were at the moment
would it not make a difference if im using discord hybrid sharding
memory leaks dont happen like that
its always on the clusters though
is your code public?
would help to see the code yeah
why are u starting intervals and jobs inside timeouts?
or actually, doing everything inside timeouts
there was a job that relied on data that would only be available after the bot had started up so the timeout for that is to preven the job running without the data it needs
u can use .then for tasks that must run after the bot is online
using timeouts wont guarantee the bot is ready at execution time, as connection time isn't constant
it doesnt but ive never had a problem with using timeouts
that's still relying on luck, but up to u
well, I'll need a heap dump to be able to find anything wrong, too many files to check
yeah ik its a nightmare
hey can anyone help with postgres? Im using knex and currently due to high traffic on my discord bot, it suddenly disconnects Database and i get the error "connection timeout"
what can i do here, how do i debug and fix this
my pg max connections is 100
dotenv.config({ path: "../../.env" });
export default {
development: {
client: "pg",
connection: {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
},
pool: {
min: 1,
max: 5
},
migrations: {
tableName: "knex_migrations_ts",
directory: "migrations"
}
},
onUpdateTrigger: (table: string) => `
CREATE TRIGGER ${table}_updated_at
BEFORE UPDATE ON ${table}
FOR EACH ROW
EXECUTE PROCEDURE on_update_timestamp();`,
};
This my knex config
you need to ping the database ever so often
maybe i need to increase the max pool?
else the conn will get dropped
it is always connected to db
peoplel are active using it
it suddenly disconnects
it suddenly just throws the connection timeout error
I assume whichever lib (like pg) that knex uses handles the database connection
pool size is 5
max_connections is pg config is 100
which is normal ig?
mmm didnt check, i think it'll log in /etc/ or something no
ah yes, then ur max connections is 5 (in code)
as the pool will never go above that
yea
If you only have 1 shard then it definitely should be enough
5 is enough, that wont be the issue
so that probably connects 12 times?
Yes but pool size doesn't need to be the max connections you might get
in etc I think
nop
it says null lol xd so its not set in pg config
See /var/log/postgresql?
i had it here
could not receive data from client: Connection reset by peer```
this is the error i got
i see in the log
hmm
it's happening during some transaction, perhaps ur getting OOM
how's your ram usage?
and i get the error "connection timeout"
do u have a stacktrace?
ah nop, well the stack trace is from the current commands being trying to access DB then failing
but where is that error being logged?
so could be someone tried sql injection, and closed connection?
like, the line where u print to the console
Not what i mean
U have to be printing it somewhere
Or is it an uncaught exception?
In that block, make it print the stacktrace
but its not the command that broke the connection. any new commands after the connection breaks, it sits in connection timeout until i restart the app
kk
it might be because im not wrapping the db transaction in a try catch block
hmmm but weird nothing should break there
is there a way i can reconnect if the connection drops in knex? instead of me restarting the whole app
Poolers are supposed to reconnect automatically
But what command is it?
ic, https://github.com/knex/knex/issues/1833 i was reading this and it says they dont reconnect, weird
ping command
Hm
well i bascially make a db call to fetch some data whenever any command is called
so it fails initially without the connection
What data are u fetching?
How much data are we talking?
the crash happened way before
some 5 columns thats all
probably some data in where clause might've caused it
U could try finding another pool manager, to see if the issue is with it
2023-08-03 14:57:01.419 UTC [2517794] postgres@izzi STATEMENT: select * from commands where alias::jsonb @> '"didn't"' and is_deleted```
becuase i see this error
in pg log
Ur not using params?
Use params in 100% of the cases
If it doesn't allow params, find another way to make it allow
`select * from ${tableName} where alias::jsonb @> '"${key}"' and is_deleted = false`
)```
This the query
mm
Replace raw with the proper function
Raw doesn't sanitize params
Also why is tablename variable?
prepared statements dont support table name variables, so sometimes if you want to programmatically query different tables, you have to use raw
its jsut a global constant
at least in sqlite
The table name?
yeah,
Hardcode it then
i guess he wants it to be configurable from a json file
same in knex
yeah, im thinking thats probably why it happened
using raw
Hm, then use the regular query function but append the table name with + tableName +
It won't be caught as a param, so it'll still work on regular query
'"${key}"' this will never support the ' character
so you have to either remove it from all queries, or specifically find it and escape it
or use prepared statements for that part
yeah, im trying to serialize it pretty much
apparently it didnt
i just have to convert the query using knex query builder and should be fine
knex will take care of serialisation
@lyric mountain okay so i got this error this time
2023-08-03 15:30:20.784 UTC [2519253] [unknown]@[unknown] HINT: This may indicate that the client does not support any SSL protocol version between TLSv1.2 and TLSv1.3.```
pg is in same machine
Something related to your database connection string probably
weird
it happens after some time tho like wtf
when the app is up and running
it breaks suddenly in the middle after 30mins
Hey guys, I'm looking for a list of "bad words" in all the world's languages there's an public api or file idk ? because i found nothing
You are not alone
ahh don't relate to the automods, just working on a guild system but i need to allow player to give a name
I found something more youtube related
i just found that
500+ words in google document
i got a snapshot of the smaller cluster
did the issue happen?
yeah the memory usage had increased by about a gb before i did the snapshot
do u know how to read a heap dump?
nah idk what im looking for or what would be considered normal
send it
yeah idk about that its got the token in it
oh shit alr awesome 1 min
If I change the name of the bot,how long does it take to update it on top.gg?
or do I have to do this manually
where?
in the bot edit page, in topgg
ah thank you
hi
bye
Hello!
are there any good clustering libs in js
by that i mean something which can spawn and manage clusters and distribute load amongst them evenly
not confined to the same machine either
Maybe I'm misunderstanding, but I dont think you would want to use JS for something like that
For cluster management?
kubernetes
For kubernetes it just starts runs containers
like docker containers?
what about distributing messages/tasks/commands to those instances on the api level?
google is more focused on telling you why they should sell you it on GCP rather than explaining what it can do in detail
I'm assuming you're talking about runtimes that can run JavaScript everywhere and not vanilla JavaScript (AKA browser JavaScript)
If so then in Node.js we provide a built-in cluster module that you can use
the first damn time someone has used markdown appropriately in #development

Shit you're right
anyways time to ruin this moment
though I think Voltrex has used it before
haven't you?
Task distribution is a broad term. There are many different ways to manage tasks such as round robin, random, etc.
How exactly you would determine which one is doing the least amount of work as well can be code base dependent which would require you to make your own scheduler
A chain of tasks inter-dependent on each other should also go to the same node if necessary
For example, I encode cluster IDs in button custom_ids
I probably have, I don't quite remember
how do i send an embed in broadcast eval?
await client.shard?.broadcastEval(async (cl) => {
const channel = await cl.channels.fetch(id);
if (!channel || channel.type !== "GUILD_TEXT") {
return;
}
const embed = createEmbed(author, client)
.setTitle(title)
.setThumbnail(//image
)
channel.send({ embed });
});```
This is my current implimentation
i keep getting the error "embed" is not defined
i get a type error if i use string instead of function in broadcasteval tho https://stackoverflow.com/questions/62903204/discord-js-sharding-how-do-you-send-an-embed-message-with-broadcasteval
as seen here
broadcastEval only allows json serialisable objects to be passed in (apart from the client), I'd recommend serialising the embed into JSON outside of your broadcastEval and adding that json as context in the function
Also in your code you're not passing in any context at all, remember that inside the function you cannot access any local variables
gotcha, thanks lemme try this
So something like ```js
const json = generateEmbed(...).toJSON();
await client.shard?.broadcastEval(async (cl, { json }) => {}, { context: { json } });
yep that worked, so inside the func i can use json parse
to get back the object
yes
but djs already handles that for you
you dont have to pass in a string, you can pass in json as an object
so you can new EmbedBuilder().toJSON()
oo ic, thanks
i did mention docker so yeah :|
i had a flick through it and im not sure if its advanced enough
@earnest phoenix why is nodejs doing a github
if its because someone got offended i want to live on mars
its mostly because everyone else is also doing it, but basically yes
peer pressure offense
there are some weirdos who made it their life mission to go on every single repo and open source project ever, and yell at them "please change it, everyone else is also changing it, if you dont then you're evil"
@earnest phoenix rough rust implementation of the unicode bidirectional algorithm 
this does not include rendering each paragraph btw
should decancer implement bidi support is that too overkill
no idea what that is, but its big and complex, so i like it
it's an implementation of this https://unicode.org/reports/tr9/
3complex5me
i copied it from some library's code and try to stitch them together so i can see the rough approximation of how the algorithm works, but it just confuses me instead 😭
i want my library to have right-to-left text rendering support
the fact that the chromium browser secretly have this algorithm implemented whenever it renders text is crazy
ICU?
Doc deprecate isMaster and setupMaster in favor
of isParent and setupParent.
Signed-off-by: Michael Dawson mdawson@devrus.com
Given the effort to change the master branch to main, this may be appro...
@earnest phoenix
i just hate the fact that the way unicode text laid out in memory is not the same as how unicode text is read left-to-right

I mean, if you want to properly support RTL languages then sure, especially when LTR and RTL languages are in the same line
but
can decancer cure cancer?
the pseudocode is over 600 lines long 😭
yes
its funny because your real name isnt even timothy
yeah lmao
so I have a poll system, each poll has options and answers, whats the best way with this schema (even if you dont know prisma you should probably understand it enough) to get the percentage of answers that each option of poll X has?
id Int @id @default(autoincrement())
pollId Int
poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade)
title String @db.VarChar(255)
answers PollAnswer[]
@@map("pollOptions")
}
model PollAnswer {
id Int @id @default(autoincrement())
pollId Int
poll Poll @relation(fields: [pollId], references: [id], onDelete: Cascade)
userId Int
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
optionId Int
option PollOption @relation(fields: [optionId], references: [id], onDelete: Cascade)
chosen DateTime @default(now())
@@map("pollAnswers")
}
model Poll {
id Int @id @default(autoincrement())
title String @db.VarChar(30)
multiSelect Boolean
options PollOption[]
answers PollAnswer[]
created DateTime @default(now())
expires DateTime?
@@map("polls")
}```
🥄
im not asking for code, im asking for the best approach
so you want to get the percentage of all the total answers for each choice?
yes so like "30% chose option Y"
pollanswer shouldn't have an id
Poll and User are the primary keys
it's an M-N relationship
dont I need to reference it in each option so I can know what belongs to what?
like all fields with @relation dont actually exist, they are just abstractions
the middle table (PollAnswer) must have a reverence to both Poll and PollOption
as it's just making the connection between them
I sent an UML not so long ago here, lemme see if I find it
but with the FK on nutrition facts, not product
kinda messed this
basically you Poll will have and id, and so will PollOption
then PollAnswer will reference both Poll and PollOption, having 2 FKs as primary keys
select from PollOption
oo btree
im surprised it doesnt use b+ trees
its better suited for database indexing
Seems good
hash table best
hash tables are actually used in some databases still
but theyre inefficient
use too much space
and the rehashing/resizing procedure is extremely slow
if you forget collisions
not sure how that factors into the performance modelling
i think its not significant enough
robin hood hashing is pretty efficient at reducing collisions and also increasing load factor efficiency
with robin hood you can go up to ike 95% instead of the typial 75% load factor
chance is still there though
but yeah if there was no need for resizing hash maps would be op
i wonder how c++/js hash maps resize/decide when to resize+rehash
its quite a significant operation especially in large hashmaps
its usually based on load factors
when it reaches a certain % of filled hashmap
i think by default its 70%
90% may not be very efficient if you use linear probing
but tis fine if you use robin hood
actually 92% 💀
xD
also, table resizing doesnt need to be sync
its can be done asynchronously and/or multithreaded
yeahh but adds complexity
you probably also have to make the thread wait during resizing too if it wants to set a new item
although for fetching i dont see a big problem considering you can keep the old container active while you copy/rehash everything
but then when do you decide when to no longer allow writes
because it might conflict with the rehash/resize
like you said, you keep two containers
you create a new one with new size, and you can immediately start reading/writing to it
and you asynchronously fill it up from the old one
reads might need to check both tables for a little while, so they will be o(2) instead of o(1), mostly
but writes will be done to the new one immediatelly
true that makes sense
iterate over each old key and re-add it to the new one with some set function
and then add a mutex
yeah i implemented a separate mutex per table entry
although what if a case exists where you do so many sets so quickly that the new size of the container gets exhausted while its still copying over the old keys
Multithreaded data structures will always be an interesting thing to implement
either create a third table, or force a synchronous wait at that point
i think what i did was forcing a wait
i think at some point you need to keep track of the capacity and make it wait if adding a new key would no longer make the old keys fit
yeah
it gets quite messy but if you really wanted to you could implement it
it was fun working on it, using js buffers
but i shelved it because i didnt have a good serialization solution
for the actual data
also, memory fragmentation is a huge issue
if you also implement the memory alloc for the data
instead of using pointers/heap
serializing what?
honestly for a hash map i think what you could do is allocate an entire 4kb page from the operating system hence completely avoiding malloc therefore no memory fragmentation
yeah the key part is fine
the size is reasonable regardless
the problem was i wanted to also do the allocation for the values in js buffers
since js doesnt have pointers/heap
i scratched my head quite a lot regarding fragmentation
thats why i shelved the project
in the end i figured i had to implement something like what jemalloc does, arenas and buffers with diffrent sizes
too complicated
How do i update a single value in an object in an array? I'm using MongoDB, and i just can figure out how i (through code) can do so. For example, if someone buys Tesla stocks, i want it to update the quantity.
find the object in the array first, and then update the value for the property of that object
for example stocks.find(value => value.code === "TSLA").quantity = 6
you might just be the person that most uses buffers in javascript
... for the unintended reasons
lmao
recently i stopped using node buffers
and started using only uint8array
:^)
basically the same thing
although for utf8 encoding/decoding, node buffers are still faster
except uint8arrays are less flexible i think
and faster
whats the difference between uint8arrays and buffers anyways
i imagine the underlying storage is the same
Buffer extends uint8array and adds things to it
makes sense
but for some reason, some things are slower
because they are implemented in the nodejs cpp side
yes afaik
i think its because for ofs handle cases where the array gets mutated during interation
And to update it i do what?
for i does not
if you want to make a performant thing with buffers, you need 4 things, an ArrayBuffer, a uint8array, a Buffer and a DataView
The update part is what confuses me
i dont use mongo so idk, but it depents on how you setup your database
if you use stull like Models and Schemas
yeah
or if you use mongo queries directly
then the Model should have a .save() method, no?
what is an arraybuffer/dataview anyways
yup
then try that
ArrayBuffer = raw memory, like malloc
all others are views over that raw memory
What is there to save if i havent changed anything?
whats the point of being able to see but not touch
didnt you change the value?
you can touch
views as in, interpretations of that memory
both read and write
unit8 interprets it as bytes
Buffer also as bytes, but with additional stuff
DataView as numerical formats, ie int32, unit64, etc
ah okay so how to interpret the underlying bytes?
ye
DataView is the fastest way to read/write multi-bytes number formats, basically
including bigint
and doubles
node Buffer is the fastest when reading/writing string formats, like utf8 and ascii
arent they stored as strings underneath or is it that npm library that does that
nah, bigint is stored as a list of "words" in cpp
#development message does this update the value?
word is either 4 byte of 8 byte idk
yes, its a one-liner for finding and updating
but you can do it like this:
Never seen that before
assuming each object in that array is a mongodb Model/Schema ```js
const TSLA = stocks.find(value => value.code === "TSLA");
TSLA.quantity = 6;
TSLA.save();
Hmmm
word is 4 bytes iirc
bigint <-> buffer interop in js is limited to 64 bits, same way bitwise is limited to 32 bits. anything more than that needs multiple operations
so for example read/write bigint64 in DataView will always read/write 64 bits at a time
So if i were to buy 2 shares (or whatever they're called), i could do it like this?
const Stock = stocks.find(value => value.code === "TSLA");
Stock.quantity = Stock.quantity + 2;
Stock.save();
yeah that should work, assuming the object is a valid model with a .save() method
Stock.quantity += 2 should work too
ye
i just dont find the purpose behind Uint16Array, Int16Array, Uint32Array, and Int32Array
when node.js is dynamically typed
its for working with binary data
.readUint16LE(), .readUint32LE(), etc ???
for example if you wanna make an audio/video transcoder or whatever, where the format specifies data blocks being 2-4 bytes long, etc
so im currently adding my poll endpoints to my sdk, how should I name the method used for voting and for revoking a vote (really not an important question)
I currently thought of voteForOption(optionId: number) for voting
sure, some formats migh require LE or BE
i think the erlang/ETF specification uses both LE and BE for example
if there isnt a voteForSomethingelse, just voteFor(id) should suffice
what about revoking a vote
yeah its extremely useful for working with binary data
performance is huge
revokeVote
the only problem with DataView
is that its extremely slow to instantiate
idk how I just came up with this horrible name
its literally faster to copy a 14kb buffer than to create a new DataView
lmao
voteVote(vote: Vote): Vote
fr
okay now the most important question in the universe, where do I put my getPolls(page?: number, search?: string) method, following options:
import { API } from "asdgadsgasgfsigjwiasjgha"
const api = new API(...)
api.getPolls() // option 1
api.account.getPolls() // option 2
api.poll.getPolls() // option 3
// maybe something else?
well idk what the entire structure looks like, so wherever makes more sense to you
are polls account specific? then put them in account
are there other poll related things in .poll? then put it there
polls are the same for every user, you can only vote if logged in
if there is nothing else worth grouping it with, then put it in the root
ig that then
alr, time to do frontend now
good luck (i hate frontend)
i'll have to teach 21 people about Angular on monday
i've never used Angular before
lma
o
sounds like fun
i have no idea why, because they are already doing an angular course, but they said there are somethings they didnt get, and want someone else to explain it like they're 5
i hope i'll manage
Angular is weird af
but i think i got the hang of the basics at least
TypeError: Stock.save is not a function
It apparently isnt
Or
Could it be because Stock isnt the name of the document?
atleast I got this far already
show how you create that array
Just figured it out
Used another method
👍
how much current and coils around an iron core would i need to make a decent strength electromagnet
i have a feeling the current coming from my arduino is no where near the amount i need
may need to order a mini power supply
capable of at least 2 amps ig but i dont know how much i need or if it even matters
i dont think i asked :(
Yea, discord mobile app is shit
I'm going to download some apk from the net because what happens in this application after these updates is just ridiculous
i havent updated the discord app in like 6 months and im happy

I guess I should do that too
look how cool this is
i connected the products to a js code, and you can then using fetch requests add and delete products.
cool @eternal osprey
Hi
How strong you looking for?
This is the equation for a magnetic field strength of a solenoid, multiplied by N turns
u0 being the vacuum permeability constant (you can look it up), r being the radius of the loop (in meters), and I being the current (in amps)
One message removed from a suspended account.
Thank you
It was mainly to learn js and idk I think I fully know the key concepts by know
throw err;
^
Error: Cannot find module '/home/user/Downloads/tetris-bot-main/index.js'. Please verify that the package.json has a valid "main" entry
code: 'MODULE_NOT_FOUND',
path: '/home/user/Downloads/tetris-bot-main/package.json',
requestPath: '/home/user/Downloads/tetris-bot-main'
}
https://github.com/Richienb/tetris-bot
not my repo
help
2 things
its typescript, which needs to be compiled first
the "main" property in the package.json is wrong
how are you running it?
Should i change it to index.ts?
Like what?
like did you download the entire repo and ran node .?
Npm install
Npm run start
...yes-
add a new script to the package.json
"build": "tsc"
and try running node run build
then change the start script to "start": "node ./dist/index.js"
then should be able to use node run start
Ok
ye they have a tsconfig in the repo already with a /dist outdir
tip: check the files before attempting to run it
so basically the scripts in package.json should look like this:
"scripts": {
"start": "node ./dist/index.js",
"build": "tsc",
"dev": "nodemon --watch source --ext ts,json --exec \"node --loader ts-node/esm ./source/index.ts\""
},
then you can run ```shell
npm install
npm run build
npm run start
or you can run it with the dev script they already have in there, but it will auto-restart on every change
They really be using discord.js v13, ts-node/esm loader, and TypeScript v4
They should've also outlined those instructions 
Type 'NewsChannel' is missing the following properties from type 'VoiceChannel': editable, speakable, full, joinable, and 8 more.
1571 } & MessageComponentCollectorOptions<MappedInteractionTypes<Cached>[T]>;
what is mapped interaction
the code ancient
This is how it is with github code from a few years ago 
interesting thank you
except i dont think i have a good enough iron core and i do need to buy insulated copper wire
so need to do that first
kinda wanna make a transformer now
ill add that to my future project list
One message removed from a suspended account.
ill gate your star
One message removed from a suspended account.
One message removed from a suspended account.
yikes
Hey you have been warned by aurel already. This is your last warning
please stop mentioning the channel 
that hey was extremely anticlimactic considering the nature of the message
please change it into a capital
How is multi language usually done in bots? Are the strings moved to json files or something and then you use .replace on it?
usually you have a file or some database which holds all the strings for other languages
and for each string you assign some kind of token like WELCOME_MESSAGE_DMS
so instead of something like message.send("welcome user!"); you would have some system which fetches the string for the desired language, something like message.send(strings["WELCOME_MESSAGE_DMS"].us);
a very rough idea amongst the millions of possible implementations
yeah that's how I thought
but what if you have variables in the string that need to change?
like a username for example
do you use a token like {user} and then replace it?
yeah something like that, maybe a function which automatically does that and you provide an object to that function which replaces {var} with the actual values
it is messy and annoying though so many bots choose not to
yeah thats why I was looking for a cleaner solution
would be cool if discord added automatic translations or something like that
but I guess it's hard
templating system, it does replace but in a nicer fashion per se
mmmh, can you give an example? or like explain how it works?
actually
you could still use ${something} if you evaluated the string with eval
that would make the js engine actually compute and replace the variable with the actual variable
but that presents security risks if it has user entered input
language files usually only contain strings from the developer themselves
if you want to be extra safe you could use sandbox ig
Uhm, well it would still use {whatever} but it would have them as a duct and then when it's replacing it could use a for loop to go through and do them instead of having to replace everytime
Ever looked into i18n (internationalization) libraries?
no
A very popular one is https://www.npmjs.com/package/i18next
Sponsored by json
sponsored by jason
Oh look it's you 

@earnest phoenix make devs able to monetize their npm libraries
make npm display an ad while its installing

ez stonks
All languages: various popular frameworks
Php: php
php is so good it doesnt need a framework
@quartz kindle zig is js cousin
@bronze owl
Hi
Yo
zig is wack
@_@
I see that we can configure the shards. For you how many guilds max per shards would be optimal? (I have a bot that only uses command and button interactions)
Sharding is required at 2,5k guilds if I remember correctly
I guess 1k per shard should be good and it's default value
ohh so I still have time I'm around 500
Ok thank you for this information
You can read about it until then and think about which way you would like to go and which will suit your bot better
In discord.js, there are 3 ways to make sharding
I already made the system thinking that it was around the 1k guilds that it happened and in case it happens I'm not lost
const { ShardingManager } = require('discord.js');
const manager = new ShardingManager('./index.js', { token: '...token...'});
manager.on('shardCreate', shard => console.log(`Launched shard ${shard.id}`));
manager.spawn();```
I did like this
The above code utilizes the discord.js sharding manager to spawn the recommended amount of shards for your bot. The recommended amount should be approximately 1,000 guilds per shard
You have answer on discord.js guide
So everything is good 


