#development
1 messages · Page 236 of 1
the only correct way to make a cpu intensive task async, is to send it to another process/thread
99% of an async task is spent "waiting", therefore it has 0 cpu usage for 99% of the time
0.1ms to make some network call, then 50-100ms for the server to respond with some data
so first of all, what db do you use?
mongo 😓
so you wanna make 15 mongo calls, one for each user? or can you make 1 call that returns all 15 users?
one call
.find without a filter returns all documents
alright, so
the mongo call is already async, and its only 1 task, so no need for Promise.al
Promise.all(users.map((user) => user.asyncMethod()))
ah, what does the user method do?
will be caching this data for like a minute
lmao ok
it doesnt sound like a cpu-intensive task then
or is anything in there that is atually cpu-intensive?
not that i can think of
it mainly gets a bunch of documents from a different collection with a filter
then grabs all the values of a specific key, and adds it together
the you should be fine
yes
its gonna be waiting for 99% of the time
i managed to make it so i can write and read to the json and it be updated during runtime
you can have a million promises running at the same time, if all of them are waiting, then you have 0% cpu usage
im trying to get the last midnight with timezone offset in hours
for some reason the returned date is also on an offset of the host system's tz
first date is utc+2
second date is utc+12
my host system is utc+2
(currently 19:27, or 7pm)
i might just also be stupid
export default function getLastMidnight(timezoneOffset: number = 0): Date {
const now = new Date();
const timezoneOffsetMs = timezoneOffset * 60 * 60_000;
const localTime = new Date(now.getTime() + timezoneOffsetMs);
localTime.setHours(0, 0, 0, 0);
const lastMidnight = new Date(localTime.getTime() - timezoneOffsetMs);
return lastMidnight;
}
@quartz kindle got a sec to take a look at another game?
I have a "confessions" game .. basically everyone has 3 minutes to submit a confession and the bot will display the submissions anonymously, players have to @ mention who they think wrote it
but sometimes the modal gives and error, only a hand full of times
here's the game https://pastes.dev/j4D252LWbN
and this is the error
[ConfessionsGame] Modal submission error: DiscordAPIError: Interaction has already been acknowledged.
at RequestHandler.execute (C:\Users\Maurice\Desktop\Click War Bot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (C:\Users\Maurice\Desktop\Click War Bot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
at async ModalSubmitInteraction.reply (C:\Users\Maurice\Desktop\Click War Bot\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:103:5)
at async InteractionCollector.<anonymous> (C:\Users\Maurice\Desktop\Click War Bot\commands\confessionsgame.js:181:29) {
method: 'post',
path: '/interactions/1260283218536566785/aW50ZXJhY3Rpb246MTI2MDI4MzIxODUzNjU2Njc4NTpzYzFmcTUxc2p6UXA2ZnZsb2JYVHRyY2ZzYVRWTno4MVQ0TDBISXNaSHNDVkUxaTBIcWhKU2tUUUpsN0xubFlWZmN5b0RYc0pxbGZPNXcybnJXZVU0d05MRFNZNlVmWEMyUWRjZENZczZDMENxZVlpSDJLN05XSHpTa3ZQVUxMNA/callback',
code: 40060,
httpStatus: 400,
requestData: { json: { type: 4, data: [Object] }, files: [] }
}
so you want to get the Date object for the last midnight for a given timezone?
yes
hmm i dont see anything wrong on a first glance, i'd need to look deeper
nodejs does though to an extent correct?
libuv after all
otherwise io operations would kill it
how long are they going to make the interaction tokens goddamn
thats enough to thwart any brute force for more than a couple of lifetimes of the universe
const timezoneOffsetMs = timezoneOffset * 60 * 60_000 + now.getTimezoneOffset() * 60_000;
you have to correct for the host's own timezone (using Date with timezones is dumb and unintuitive)
yeah, it has a thread pool for managing I/O ports and streams
ye like what the heck, what even is an interaction token?
now i see why my function wasnt working..
what is this
thats the part i found
ah yes, the famous await() function
i forgot axios.get
:^)
to be honest i wrote that at 2 am
it happens
cant you use a lib like Luxon? thats a major pain in the ass to do in js
we still dont have the new Temporal api
xD
okayyyy sooo
my mongo model has a startedAt and endedAt
I have 2 date objects, dayStart and dayEnd
I want to get all documents where at least one of the date objects (startedAt and endedAt) are between dayStart and dayEnd
my poopy brain is too dum dum to know what operations i have to do
wait i mightve done it
this no?
uhhh no
(there are documents for every hour on the 9th)
only if you don’t mind!
it still functions like it’s supposed to, but when this error pops up, players get an error in the modal and it causes the bot to record the submission multiple times, so it’ll display during the guessing round multiple times
@quartz kindle So I have my array of database users
I want an array with it's items being
{
"day": "promise result here",
"week": "different promise result here"
}```
im not sure how to do this with promise.all though
how can i users.map correctly so that i can promise.all the result
is this right?
yeah looks fine
but if getDayStats and getWeekStats are methods that belong to the user already, wouldnt it make more sense to call them directly? and store the result inside the user itself instead of an external object?
should still be doable
for example
is this how User is defined? ```js
class HydratedUser {
async getDayStats() { ... }
async getWeekStats() { ... }
}
you could do this
class HydratedUser {
async getUserStats() {
if(!this.userStats) {
this.userStats = {
day: await this.getDayStats(),
week: await this.getWeekStats()
}
}
return this.userStats;
}
async getDayStats() { ... }
async getWeekStats() { ... }
}
const result = Promise.all(users.map(user => user.getUserStats()))
can you check if you have any duplicated logs? for example this one:
console.log(`${LOG_PREFIX} Confess button clicked by ${i.user.username}`);
i dont know how but the only explanation i can come up with is that the await i.awaitModalSubmit is catching the wrong modal, or the modal is somehow duplicated
you can try generating a unique id for each modal
const unique = Date.now().toString(36) + Math.random().toString(36).slice(2);
.setCustomId(`confessionModal-${unique}`)
const filter = interaction => interaction.customId === `confessionModal-${unique}` && interaction.user.id === i.user.id;
ok i’ll try this
what is the value for this? ( channel permissions, discord.py )
neutral. So it just takes the parent role's permission
oh ok
thx
Whatever your highest role right?
Like if you had one role giving you the perm, but another taking it away and it was much higher, do you still have that permission

yep, the higher role will always take priority
how do i set it to neutral tho ( discord.py )
because it will overwrite all other perms
?
you dont touch the permission at all
neutral is default
You dont touch them at all it is the default
then they are touched
just received the most disgusting leet code question for my tech interview at samsung
dont know if im just stupid or was it hard
what was it
given an array of numbers of any length, and a sum value which is the largest number in the array, return whether any combination of numbers can add up to the sum value, in C
the largest number part was very simple but i couldnt figure out a good enough solution for the sum part
you lost me at sum
absolute bs question
So basically
just keep adding numbers until you reach that largest number?
That sounds like a very expensive algo
basically yes except the combination can be any number and any amount of numbers in that array
i settled for a recursive solution but another one i thought was compute all possible combinations and see if any of them add up to the sum
the solution itself is simple but working it out is very tricky
a lot to think about
Indeed
the recursive one i wrote is basically a step better from the all possible solutions
but not by much
My first thought was just a loop of some sort adding up numbers until you reach the one you want
but uhm probably not the best

thats what i thought but it cant be that simple because not all numbers can be used to make a proper sum
you have to basically start from the end of the array and work your way up to the beginning trying different combinations along the way using recursion
hm yea
didnt we do something similar on here before?
with someone working on an ELO system
and matching teams by ELO
i remember doing a brute force loop by testing every possible comboination
but i dont remember what the final solution ended up being
this is sort of what the solution for this was
bool isSubsetSum(int arr[], int arr_length, int sum) {
if (sum == 0)
return true;
if (arr_length == 0)
return false;
if (arr[arr_length - 1] > sum)
return isSubsetSum(arr, arr_length - 1, sum);
return isSubsetSum(arr, arr_length - 1, sum) || isSubsetSum(arr, arr_length - 1, sum - arr[arr_length - 1]);
}
is the array ordered?
ah so sum is already the highest value in the array
no need to find what the highest value is first
yeah but you need to know it beforehand here?
otherwise it has no idea which combinations to flat out throw away
wait what exactly is n and sum lol im lost
yeah badly named ill change the names
but sum is the value that the combinations need to add up to
so the highest number in the array worked out beforehand
so array is always guaranteed to contain at least one item that is equal to sum
there
so basically {1,5,7,4,9} = true because 5 + 4 = 9
i mean, if the highest value is contained inside the array, why is sum a separate variable?
youd have to grab it each time?
its a recursive function grabbing it inside the function would be bad no?
so you can subtract it each time a combination is tried in each recursion
but in the final solution i had another parameter called max_value which made sure to ignore the biggest value which is the sum from being counted
it just feels weird having a function that requires two parameters when the second parameter exists inside the first one anyway
theres not even booleans by the way
so i had to use chars with values 1 or 0
thats the og boolean
you can include a header which has them but i couldnt
anyways ive had enough of this question
ever heard about the therac-25?
stupid stupid stupid question
i would honestly not be able to solve it, i would start overthinking and enter an infinite loop in my head
i think this type of thing youd have to come by beforehand by practicing leet code
in reality this type of problem wouldnt be an issue in the workplace since youd be able to look it up or use an existing solution
or even just have a real use case for it to guide you
sometimes you cant solve something if you look at it purely from a mathematical/algorithmical way
but you can if you relate it to some real use case scenario, it gets much easier to visualize it
recruiters when you cant solve an unrealistic leetcode question: 😧😮😦😯😑🫤
booleans weren’t standard in C until C99
And even then they were just a macro lol
technically they still are, no?
0 and 1
So basically just a define macro
It’s in stdbool.h
The header stdbool.h in the C Standard Library for the C programming language contains four macros for a Boolean data type. This header was introduced in C99.
The macros as defined in the ISO C standard are :
bool which expands to _Bool
true which expands to 1
false which expands to 0
__bool_true_false_are_defined which expands to 1
lmao
wtf
yeah theyve added them in now but most compilers stick to older more standardised versions
other than that you can either use stdbool, define your own macros or just dont use them
gotta love emails trying to detect whether youve opened them or not
i set up a CSP policy in my email client that blocks image urls from loading unless i explicitly allow them to
there were duplicated logs
getting rid of them
i mean, its not about getting rid of them, its about if they are appearing more than once per user/modal, then something is wrong
ah well yes there were a few that were duplicated
and i created the unique id’s
looks like it working smoothly so far, but then again i’m testing it by myself 😂
nice
nice try scammer
finna dm u right now. can't pass up 50k in 72 hours
its an r kelly
How should I handle fetching information from routes that require you to be logged in to access? Like my service doesn't require you to be logged in to use it, but if you login you get extra features. Problem is, I am now realizing my api design is bad because I am having to make extra routes just for those who aren't logged in to fetch the same information.
My first thought was a public api key used by anyone whos not logged in, but at the same time that can be bad if people wanted to just make arbitrary requests. Also not to mention I have to find a way to protect other routes that DO need you to be logged in if I went this route.
the standard way of doing it is to have an optional api key
no key = free access
key = special registered access
the way it works right now is if you access a protected route and you aren't logged in you can't access any of it. I am not sure how I will be able to pick and choose which routes are protected or not
especially if I have nested routes
like
/creators/settings -> logged in to access
/creators/:id -> doesnt need to be logged in to access
Also, if I do it that way, wont it mess up if they are logged in?
i always thought this was really stupid then i thought about it and it actually makes a lot of sense
since technically a boolean is quite abstract, you can't really represent a single bit value in a CPU
Like if they are logged in, and I still make a call to /creators/:id then it will deny it, because I am checking if they dont have one. I mean I guess I can check if they do or dont at the same time and allow both if the case is true but thats repetitive checks and I dont necessarily like that
the concept of a REST api is to be stateless, independent of login status

by login you mean session cookies right?
if your endpoints are acessed by browser pages, ie a dashboard, then the endpoints should indeed check for session cookie
but if the endpoints are accessible via arbitrary http request, ie node, etc, then there is no browser, therefore no session and no cookie
of course you can technically send cookies from a node http request, but thats pretty much a wonky design
i would do it like this:
public rest api accessible with or without key (no sessions)
private dashboard endpoints (with sessions) that make backend calls to the public rest api if needed
well as it stands now I was just going to make it send over via an auth header
like a Bearer auth header
sure
but the point is to have stuff like dashboard endpoints separate from the public api
because dashboard endpoints are not supposed to be called from outside a browser
what exactly do you mean by public?
public api = stuff you tell people they can make requests to from anywhere they want
private api = stuff that only your own website can access, only when the user visits via a properly logged in browser
i actually did something like this
example, the discord api and the discord app api
the discord api we all use is the public api
well I odnt have a public api
but the requests the actual discord app makes are different from trhe public api we use
but if they know the routes they can make requests to it
idk how to make a truly private api
💀
a private api is mostly just session cookie
optionally you can check for referral url and user agent, but those are not really secure
if you dont have a public api, then there is no such thing as api keys or auth keys
everything should be done with server-side cookies
even if the user is not logged in, you generate a session cookie when they visit your page
and use that
keys
basically you need 2 cookies
browser session and account session
when user visits your website, you generate a session cookie, which you will use to validate that your endpoints are being called from inside the browser
then if the user logs in, you generate an additional cookie for the account
the browser session cookie should be deleted when the browser is closed
the login cookie should be persistent (if you want to remember logins)
like connect.sid?
yeah i guess
i only really know about connect.sid bc of express session
I mean sure ig
hey guys, i am kinda new to environmental varialbles, i only used them in a mathemtical context like:
e1, e2, e3 _| P union X -> e2 etc etc
how exactly do they work? When i deploy a webapp are those variables not able to be tracked down using developer console etc?
Env vars arent global like in js you can do global.setTimeout or just setTimeout. They're usually accessed through a container like process.env or if you're loading from a file, js requires the dotenv npm module. You can access them through a repl assuming you're using the default eval. You'd have to specify a special customEval to disallow accessing things like process.env and even then wont work 100%
Env vars are usually containers for secrets like a config. Github runners make use of env vars for stuff like your gh access token and such
owh damn i see
how are people that create websites hiding their api keys? Using dotenv..?
That can be done for backend which is not accessible by your users
Nothing is secure in frontend
Yeah hiding stuff backend is super easy
With like Discord for example, you verify interactions with your client ID and a client secret
You dont need to send that info to the frontend anywhere
I just have everything in a js file so I can omit some config and build it later in the file like client ID can be inferred by token
Buffer.from(token.split(".")[0], "base64").toString("utf8")
I’ve been wondering
If people even use queues
Like there’s aws sqs but there no alternative outside right? The closest one is rabbitmq and celery
Would people even use something like sqs outside of Amazon

Something like consumer queues are pretty good even in Discord bot spaces. If you have a microservice which just handles Discord gateway connectivity, it can send events to a queue for a worker to process the event and cache relevant data then that cache worker sends the event as a whole or partial to another worker which depends on the cache to be there
oh shit i know what to do
i can just generate a public and private key pair
and use the public keys on frontend
But like rabbitmq already offers this mechanism why isn’t anyone building it
Wdym
If I offered a solution that takes care of routing etc and you just have to push the message and consume it. Will people use it
Rabbitmq offers queues, dead letters multi queue
Routing etc
Like sqs
This isn’t specific to discord bots tho
Likely not and building a system for that can be very expensive as the messages have to exist somewhere like in memory or on disk which depending on payload size can be extreme. It wouldnt be absurd for someone to pipe images through the queue for a worker to process either
images can be massive
I would just offer an sdk with the wrapper
Everything else is on you
So I don’t have to worry about expense
libamqp for js already exists
Yeah but you have to like figure out the routing key binding etc
Or do I not make sense hmm
What if I offered a serverless solution for rabbitmq cause rn cloud hosted rabbitmq seem expensive
I couldn’t find anything else other than this cloudamp
We offer flexible RabbitMQ and LavinMQ plans for all your needs. What are you looking for? Billed by the second, cancel any time. Free to get started.
Mmmm
Instead of you making api calls you just call the sdk method
Superset of libamqp
ofc i could make it open source
That’s what celery is doing
Queue Management
With different brokers
You are not making any sense
Mmm
A single amqp instance can handle multiple queues at the same time. While there are message consumers, the queue stays active. Of course you'd need a "routing key binding"
If you wanted a default queue, maybe, but that isnt worth making a whole lib for
i really love coroutines... makes my code so much cleaner
neutrino swear_check(event.from->creator, config::get("neutrino_user"), config::get("neutrino_password"));
swear_filter_t swear_filter = co_await swear_check.co_contains_bad_word(guild_name);
if (!swear_filter.clean) {
bot.log(dpp::ll_warning, "Potty-mouth guild name " + guild_name + " censored for id " + event.command.usr.id.str());
guild_name = swear_filter.censored_content;
}
auto exists = co_await db::co_query("SELECT id FROM guilds WHERE name = ?", {guild_name});
if (!exists.empty()) {
embed.set_description(tr("GUILD_EXISTS", event));
} else {
co_await db::co_query("UPDATE guilds SET name = ? WHERE id = ?", {g[0].at("guild_id")});
embed.set_description(tr("RENAMED_GUILD_TO", event, dpp::utility::markdown_escape(g[0].at("name"))));
}
this would be a nasty mix of a callback and several blocking calls, without
Async is cool
What if there’s a UI like sqs? With rabbitmq?
i just wish they'd called the keyword await not co_await
would that be worth building
What would you even show in this supposed UI
Same stuff what sqs shows

i somehow see async like pressing down the clutch in your manual car.
I have no idea what sqs is
detaching that bitch from the cpu's regular clock timers 🗣️
in C++ its like putting a bookmark in the book, and going to read a different chapter for a bit, or even putting down that book and picking up another
then later on, coming back to the bokmark (co_return)
You'd have to consume a message without actually consuming it to show things related to the queue
Welp ig what I’m trying to solve doesn’t make sense
C++ coroutine async has no built in runtime, you have to make that bit yourself, it just provides the keywords
Though tbf I havent touched libamqp in a minute
Based
Does anyone else have any ideas
For a start up
Saas
Just brain storming ideas

Can’t think of any atm. What do you think
I think I need someone to work on https://github.com/AmandaDiscord/Volcano
Lavalink
alternatively, make a js lib that transcodes audio formats to opus and can apply audio effects without using ffmpeg
Must make use of native bindings to convert formats to pcm then apply any filters then encode to opus
So basically to stream music?
Yeah. My main thing is that Volcano has to make use of ffmpeg which sucks for performance and I have to do weird hacks for ffmpeg to work properly and even then sometimes the ffmpeg process dies for no reason
LavaLink is a cool piece of software, but since it runs on the Java virtual machine, the memory usage is higher than I'd like
that would be sooooo slow
loops in js be like....
1..... 2............
access to AVX and other matrix math functions etc helps native transcoding go so fast. in js, you dont have access to any of that stuff
it would be hundreds of times slower
i mean parts of libopus are legit raw asm
Luckily, you can do everything in a native addon and then transfer the result to js
Id rather have the heavy audio processing be in native where it makes sense and then write my app in js
because js is fun and easier to work with imo
indeed, it would be crazy talk to do audio processing in an interpreted lang
unless you made a domain specific language for the task, and wrote it in that
there are such languages, you can find them in synthesizers and high end music hardware
Im very aware js is not meant for audio processing but god I wanna die when I write rust and I am not at all confident in my abilities with any clang
actually
a DSL for audio processing accessible from js would be really cool
so you can do effects and stuff without needing to write low level C
in the same way you wouldnt do raw files as dbs and youd use sql, would be cool if audio had "this"
There was some library that provided bindings for libavconf but it was so absurdly complex for me to get started that I dropped it entirely
Like I think it expected me to know the audio formats, but I can't really reliably probe them
The lib I used for probing wanted me to read to eof in some cases which sucks
especially when there sometimes isnt an eof with streams from icecast
I dont think it supported streams either
streams is another big thing the supposedly library would have to support
If it provided a callback where it pushed chunks, that wouldn't be the end of the world as I can just pipe them through a stream.Passthrough if I needed a stream.Readable/Writable somewhere
env is like:
my code uses env, so by itself it does not contain any keys
i can post my code anywhere, github, etc, it does not contain any sensitive info
i clone my code into X machine
i add env vars inside the X machine
when my code runs, it will use the sensitive info i defined inside that machine
i can copy paste my code into a different machine and it will use the env vars of the different machine, no code change required
What would be the best way to chunk upload videos?
actually it wouldnt be that bad, provided your js runs in v8
v8's compiled code is not as fast as cpp but its not an order of magnitude slower either
dawg this bot's literally called "nazis" what 💀 #mod-logs message
The current performance level of V8-produced assembly is a little bit below that of g++ -O0 — and an order of magnitude higher than any other “interpreted” language
(an article from 2021)
unacceptable performance
v9 engine better be faster
this is what we get when we decide to use languages like javascript instead of real men (and women) compiled languages
lmao
cut the bytes into chunks, prefix with metadata (part number, upload id, etc) and send
then at the server u reassemble it
<div id="output"></div>
document.getElementById('output').textContent = 55+"\n55";
why does this show as "55 55"?
like i know in reality i should be using innerHTML and use <br> but i am trying to maintain the html syntax.
So, "<p>test</p><br><p>hey</p>" ->
<p>test</p>
<p>hey</p>

because \n cannot become number
How do you cut these into chunks
that ain't the prolem
arent mp4 files notoriously hard to work with because they lose meaning when cut into chunks?
uh...bytes.split()
i am more like, how do i maintain html syntax while still accounting for \n:
"<p>test</p><br><p>hey</p>" ->
<p>test</p>
<p>hey</p>
you dont need the files to have meaning
another interesting article to read:
// #2
for (let i = 0; i < input.length; i++) {
const x = input[i];
output[i] = x * x + 2 * x + 1;
}
I dont get what u mean
ive seen many platforms stream mp4 files in chunks so i doubt it
as long as the browser or whatever youre using gets the initial header i dont think it really matters
but im not sure how the mp4 format works under the hood would need to have a look
I see
but i would assume its just a header at the beginning and the data following it (potentially compressed)
Also naother question, what all would I need to be able to stream my videos myself rather than relying on something like cloudflare streams or bunny.net streams
I eventually want to reach that point
i have a simple text area.
I input text -> it returns me html syntax.
but it should account for newlines as well:
assume my text area has the following input -> <p>test</p><br><p>test</p>
then the output should be:
<p>test</p>
<p>test</p>
but if i use inerHTML it is simply showing
test
test
and textContent is doing
<p>test</p> <p>test</p>
cdns are quite simple to design with modern langs like nodejs
I think thats what is holding me back
well, that's because your text area isn't returning html, it's returning markdown
or you can self host one which is probably more optimal in terms of performance ig
I dont have a CDN myself
theres things like open source aws s3 clones
probably for streams or media theres something like that too
My issue is running a CDN myself would be expensive
you cant simply grab the inner content of it and expect to be valid html
probably more than just outsourcing
Maybe
but it'd likely be expensive asf to run effectively
I mean at large scale something like cloudflare streams or bunny.net streams is going to be 300$ a month at best
you can convert from markdown to html relatively easily, but be wary of html injection
this is what it returns me:
<p>dsfsdf</p><p><br></p><p>sdfsdf</p>
i assume that <p><br></p> is an actual newline
it seems like valid html tho

p is paragraph
i see
its not too bad if youre not going to have too many videos and have limits on the size of the videos
but if you want large scale then yeah
youtube isnt cheap to run google is losing money supporting it
how would i then take the markdown from the textArea, and parse it in the resulting div?
but well, if you want to put that inside something, dont write to innerHTML
use append
oowh
append? how so?
...typing
all nodes have append method
use getElementById to get the enclosing node
then append to it
you can take advantage of techniques like "archiving" lesser viewed videos by compressing them highly and then decompressing once theyre needed and keeping them in some kind of cache
you can do that more aggressively on lower scale
but if i append data to it, doesn't it simply lose it's html syntax?
so <p>test</p> -> test.
and also once theyre uploaded do a lot of lossy compression and smart codec adjustments to lower the file sizes
my main issue is delivering the videos via HLS
innerHTML shouldn't ever be used for security reasons, unless you're the only one adding content to it
It'd honestly probably be better to just use one of the bigger companies
I mean if they let me use my own storage i'd 100% be down to use em to just deliver the videos
it's appendChild
the problem with this though is that my html tags get lost
yeah!
i am appending and it's still only showing the actual text
using append()?
appendChild.
...use append if you just want text literal
Would a vps be fine for a cdn server?
why not use cloudflare r2
yes
you can also have one on the same server as the app youre hosting
oh cool
Im streaming videos
for (let i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i].textContent);
outputContainer.append("< p >" + paragraphs[i].textContent + "< p >");
if (i < paragraphs.length - 1) {
outputContainer.append(document.createElement('br'));
}
}```
I am trying to follow what you told me, but for some reaosn it deadass prints the whole line includes the created lt and gt tags
did you use the <pre> and <code> tags?
oowh no
i see.
I should put it in this part here right?
outputContainer.append("< p >" + paragraphs[i].textContent + "< p >");```?
it aint working brev 
this is the whole code:
function parse() {
let cleanOutput = document.getElementById('outputHtml');
cleanOutput.textContent = ""
let inputText = quill.root.innerHTML.trim()
console.log(inputText)
let tempDiv = document.createElement('div');
tempDiv.innerHTML = inputText;
let outputContainer = document.getElementById('outputHtml');
let paragraphs = tempDiv.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
console.log(paragraphs[i].textContent);
outputContainer.append("<pre><code><p>" + paragraphs[i].textContent + "<p></code></pre>");
if (i < paragraphs.length - 1) {
outputContainer.append(document.createElement('br'));
}
}
}```
const > let btw
did u try writing the html text on the browser and then checking how it inserted into the tree?
yeah it is indeed working
but for some reason i think that the append is fucking is up here
maybe it only works with textContent =...
no that's stupid
why did the pre and code tags appear there?
outputContainer.append("<pre><code><p>" + paragraphs[i].textContent + "<p></code></pre>");
because it is reading and working with the tags like an actual string
not html code
yes, but you see, WHY did they appear and not become html
if your whole issue is that paragraphs[i].textContent was being parsed as html
that's strange indeed yeah
i quickly used typeof, it is reading it as string though (the paragraphs[i].textContent)
the 2nd one is the textContent
so your issue isn't that append is printing parsed html, you're parsing it beforehand
textContent wont print html, it'll pring text content
if you want the tags as they're written, use innerHTML
but you use that on the parent node
so if u want the paragraphs, get the innerHTML of the enclosing div
it's a read-write property
outputContainer.append("<pre><code><p>" + paragraphs[i].textContent + "<p></code></pre>");``` we should use ```js
outputContainer.append("<pre><code><p>" + paragraphs[i].innerHTML
+ "<p></code></pre>");```
that's still get u the text, because you're getting the innerHTML
as in, "what's inside"
you wont get the <p> tags
also your < are wrong
i see, but ain't i adding the tags later on with that pre code shit/
those are supposed to be replacements to < and >
i know
what u wrote there is <<the content>>
i still don't get why it ain't working.
function parse() {
let cleanOutput = document.getElementById('outputHtml');
cleanOutput.textContent = ""
let inputText = quill.root.innerHTML.trim()
console.log(inputText)
let tempDiv = document.createElement('div');
tempDiv.innerHTML = inputText;
let outputContainer = document.getElementById('outputHtml');
let paragraphs = tempDiv.getElementsByTagName('p');
for (let i = 0; i < paragraphs.length; i++) {
outputContainer.append("<pre><code><p>" + paragraphs[i].textContent + "<p></code></pre>");
if (i < paragraphs.length - 1) {
outputContainer.append(document.createElement('br'));
}
}
}```this seems to be taking the innerHTML already
ah tahnks!!
try just outputContainer.append(paragraphs[i].innerHTML);
yes, because your code is iterating the <p>s
what's inside a paragraph? the text
if you want to include the paragraph itself, you need to get the parent's innerHTML
imagine <p> being a cup
if you look inside the cup, you'll se what's inside it, not the cup
I mean, you'll see the cup in real life, but imagine the cup is invisible from inside
i see
no you dont
lmao, that was a joke, ur not supposed to see the cup
hahaha okay
ayoooo
or if u want to keep the loop, hardcode <p>
idk why ur doing this whole part instead of using inputText
that's what i done did
wait so it can be done easier?
I mean, if you append inputText directly it'll be the same as doing tempDiv.innerHTML
oh, I see, ur doing this to break newlines in case it was written as a single line
in this case u could just inputText.split(/(?<=\/p\>).*?(?=\<p)/g)
it'll split between the p's, without removing the >< chars
ahh regex i hate it
i think i'll just leave it like this
it works well, finally!
Thank you!!
do you know by any chance how i can transform multiple <br> tags to a single <br> tag?
<p>t3st</p>
<p>test how Is everyone doing!!!</p>
<p><strong>test</strong></p>
<p>sfsdfsdfsd</p>
<p><a href="google.com" rel="noopener noreferrer" target="_blank"><strong>this is a link!<br></strong></a></p>````
regex
/(<br>\W+)+/g
let inputText = quill.root.innerHTML.trim()
inputText = inputText.replace(/(<br>\W*)+/g, "<br>");```
this returns me
it basically fucked my shit
change <br> to whatever you want to coalesce
i deadass hate frontend so much
if your repetition is <p><br>p></p>, then use /(<p><br>p><\/p>\W+?)+/g
might need to do some escapes there
what the fuck
it'll replace all but one with nothing
inputText = inputText.replace(/(<p><br><\/p>\W*)+/g, "<p><br></p>");```
you see this right
[Log] <p>test</p><p><br></p><p><br></p><p>test</p> (html.html, line 46)
[Log] <p>test</p><p><br></p>p><br></p><p>test</p> (html.html, line 48)```
the 2nd ooe is the new output after the replace
it's not the same as what I wrote
chat
but the repeated sequence as you can see is <p><br></p>
no
bomboclat
no

man i am so done with frontend waddafuck
(this is backend tho, you're just incapable chittykat)

first, test on regexr not on code, it'll be easier if u can see what's being affected
hmmmm
second, send the input here
is this a bug in discord client?
?
input:
<p>test</p><p><br></p><p><br></p><p>test</p>
this mod got a profile here just for this server that has different pfp, image and everything, click their pfp and it shows it
but right click and 'show profile' it shows the global one
should it always show the local one, if the click to view profile was from here?
stoopid discord

I love blacklist
anyone using vercel/nextjs? how is support for native node addons?
i got someone trying to use my lib in vercel and getting errors
i never used vercel nor nextjs, no idea what to do about this
This feels like a user error, not your problem. I've never used vercel so I dont really know either.
ye i just linked them some node loader
One possible solution
if its vercel and a module not found error
typical culprit is git
oddly enough
that doesnt really seem related
vercel deploys via git
the dude's issue is about loading native addons
theres nothing about native addons on that issue
anyway i just linked them this
ye but there is a major difference between a native addon and everything else
Do you know if they were using vercel pkg?
It was a known issue in pkg that .node files could not be found
:^)
sigh
👀 for what you showed before. are you using canvas?
from what i remember yeah he's using canvas
Add a default offset, its easier to place things in the right spot.
IE whatever you need to put on top, offset it so the point is in the center.
It makes it much easier to place things in a grid
well
the numbers generating are canvas
the board is a png
so right now
with
const coordinates = Array.from({ length: 25 }, (_, index) => {
const rowIndex = Math.floor(index / 5);
const colIndex = index % 5;
const x = 150 + (225 * colIndex) + (11 * colIndex) + (225/2 - 128/2);
const y = 700 + (215 * rowIndex) + (11 * rowIndex) + (225/2 - 128/2);
return [x, y];
});
looks like
i need N G and O moved over just a little
bit
The last image you sent had the numbers more centered.
What did you change? 👀
the 11 was something else?
i made the numbers smaller
Try making it larger ^-^
Assuming you made the png, look at what your offsets actually are and use those numbers.
1 sec
const coordinates = Array.from({ length: 25 }, (_, index) => {
const rowIndex = Math.floor(index / 5);
const colIndex = index % 5;
const x = 200 + (225 * colIndex) + (11 * colIndex) + (225/2 - 128/2);
const y = 700 + (225 * rowIndex) + (11 * rowIndex) + (225/2 - 128/2);
return [x, y];
});
is what generated the first image i sent
how do i get those numbers again?
What software did you use to make the png?
i had a graphic designer make it
ah, then its going to be easier to guesstimate
number font was 100px here
80px here
I'd leave the 150 where its at, and mess with the 11, try setting it to higher, like 15.
It should hopefully send it too far by a bit, then just lower it until its centered.
do const x = 150 + (225 * colIndex) + (15 * colIndex) + (225/2 - 128/2); first and see what happens.
Yeah
figured the numbers sitting nicely in there would be a nice vintage touch lol
I mean maybe, but it looks too small to fit hte numbers properly
You will never be able to center it perfectly
const x = 150 + (225 * colIndex) + (11 * colIndex) + (225/2 - 128/2);
The first number(150 is the offset from the left or top
The second number(225) should be the exact width/height of the box.
The third number(11) should be the space between the boxes.
The last bit I'm not sure what its doing.
In a perfect world, your code would look something like this.
const coordinates = Array.from({ length: 25 }, (_, index) => {
const rowIndex = Math.floor(index / 5);
const colIndex = index % 5;
const base = (225 * colIndex) + (25 * colIndex) + (225/2 - 128/2);
const x = 150 + base;
const y = 700 + base;
return [x, y];
});
Then once you know what the numbers actually are; you can offset by half the width, and height of the numbers.
That way the numbers are as centered as possible.
But guestimating is good enough that no user would notice.
Man, I hate canvas 😄
That should be easier ^-^
is it the 128 that places the daubs?
I dont think so. I'm not really sure 👀
I feel like (225/2 - 128/2) is just for scaling things. Ideally it shouldnt be used, but if its working theres not really an issue.
for example, the daub on the free space
marked.forEach(({ row, col }) => {
const [x, y] = coordinates[row * 5 + col];
console.log('Dabbing at:', x, y); // Debugging coordinates
ctx.drawImage(dabImage, x, y); // Draw the dab image without resizing
});
honestly the numbers still aren't centered
yeahh i know, i'm guesstimating lol
Centering the text? the text has a dynamic width. that code is not accounting for it.
why aren't u just getting string width/height?
was supposed to
last time they came here we told them to get actual string dimensions
Ah
idk, i'm new to building bingo and using canvas - i'm not very knowledgeable of this math lol
i tried to in paint and i struggled a bit
I think for now just ignore that part, guesstimate for now.
its not a monospace font, so you'll have to do it though code
fixing the text would unironically fix the chip position too
all that's needed is a generic placeAtSlot function
but the daub is way off from the text no?
a generic function would place it centered on the slot regardless what you passed to it
The first time you go through this its so rough 👀
it is lol i should have waited before trying to build this
hmm let me look at this
you'd need to write it yourself, it's not a built-in function
canvas.measureText(text).width for string width
const metrics = canvas.measureText(text)
const height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
``` for height
all that's left is fitting those values in the formula u already have
also, for 99% of the fonts out there, height = font size in px
const slotSize = 225; // Define the slot size
const offsetX = 150; // X-axis offset for the first slot
const offsetY = 600; // Y-axis offset for the first slot
const spacing = 15; // Spacing between slots
YO we got a bingo update
btw it's worth to note, "bingo" is supposed to be aligned with the slots
it's not just a title
and the text isn't aligned because you're still not getting text width correctly
bump
bumping 15 minutes later wont really work
that's a very niche question I doubt you'll find answer here
😭
yeahh i’m gonna ask him to change this
there sure is demand, but good luck competing with google cloud pub sub, microsoft azure bus, amazon sqs, etc...
especially because demand is mostly heared towards high scale
small projects dont need message queues, only very large projects do
and very large projects require very large infrastructure
yeah i dont think its worth building since there's alreayd so many, but there arent any serverless ones tho. even for redis. upstash is the only platform that has serverless redis
i hate when isps use "better streaming quality" as argument. i hate corporate marketing
same
watch hd videos with our incredible 1000KB plan*
*quality may change depending on network conditions
what are good postgresql providers to use with my cloudflare worker
cfs sqlite is just horrendously slow
what is rabbitmq even for?
from what you said i assume its to be able to queue long tasks and distribute them to servers for processing?
and have the reply be fed back where its supposed to be
i swear redis can do this too
indeed it can
although proper message broker software has more tools for more advanced use cases
a good use case for something like this is probably chatgpt or ai image generation services where generations take ages and you might have multiple servers that can process these generations
and it makes distributing everything easier
indeed
yoi have a large queue and hundreds of consumers each taking one task
also rabbitmq is not the only such software, there are tons of others
rabbitmq is one of the slowest tbh xd
Tim
Do you have any ideas
let’s build a product
just brainstorming ideas for now
i hate product design lmao
i like the whole engineering part, but when it comes to actually convert/transform my engineering into a usable/commercial product, i absolutely hate it
even my libs, once i figure out the engineering part of it, packaging it into an actual js library for github/npm is so damn annoying to do
you need to write tests, types, docs, readmes, presentation, marketing, visuals, etc...
even organizing the code into reusable functions and classes is extremely annoying, you have to guard it against all possible types of misuse by idiots
so basically your average js dev
yup, im your average js dev
No. They meant the average js dev is an idiot who misuses things
also me (look at how i misused discord.js)
:^)
I mean. Sure you fuck around with the internals of node but god damn is that smart
wdym edit images with css
I also fucked around with discord.js and made a light addon but like lol
tbh djs deserves to be misused, abused, mistreated and fucked around with
:^)
So true
type safety be damned we're fucking with the raw api
which is also type safe…
i looked if theres any zig discord libraries and theyre all dead lol
makes sense
make your own
what even is the appeal behind zig
it just looks like a knockoff rust
zig builds much faster
i just spent a day debugging a zig library bug
the library isn't handling chunked responses. I had to modify line 255
if (req.response.transfer_encoding == .chunked) {
// For chunked encoding, we need to read and parse chunks manually
var buffer: [4096]u8 = undefined;
while (true) {
const bytes_read = try req.read(&buffer);
if (bytes_read == 0) break;
try payload.appendSlice(buffer[0..bytes_read]);
}
} else if (req.response.content_length) |length| {
const content_length = @as(usize, @intCast(length));
log.debug("Content length: {}", .{content_length});
try payload.resize(content_length);
// make a copy of the response data that we own
const data = try payload.toOwnedSlice();
errdefer self.allocator.free(data);
_ = try req.readAll(data);
} else {
log.warn("No content length and not chunked encoding", .{});
return null;
}
the lambda test UI sends events in without any transfer_encoding. when you actually invoke a lambda transfer_encoding=chunked
once i replace rust with zig my build times will be ~2m30s faster
Build times != good language
i'm also thinking about building the binary on my local machine instead of the pipeline build machine. the language has really good tooling and lets you cross compile
Language can build fast but if its terrible performance it doesnt matter
i've never seen anything about zig having bad performance. all else equal
Rust cant event compile without zig in some cases like with AWS lambdas
I never said it wasnt performant
I was simply saying having fast compile times does not mean its a good language
so all else equal it does make it a better language
I mean if all zig does is increase build times by a bit theres no point in using it imo
Just use rust
have any other langaues created a full toolchain like zig?
zig builds faster than rust
by a lot
Most of the build times with rust comes from installing all the features along with the crate
Most of which you dont need
People really just throw the deps into cargo.toml and wonder why they take so long to build
When they dont even use all the features of the crate
will tokio ever be built into the language
Likely not
I mean maybe one day
I doubt anytime soon though
Tokio is so vast itd take a while to natively support it
these are all the deps in my rust code.
[dependencies]
aws-config = "1.5.1"
aws-sdk-lambda = "1.32.0"
anyhow = "1.0.86"
ed25519-dalek = "2.1.1"
hex = "0.4.3"
http = "1.1.0"
lambda_http = { version = "0.12.0" }
serde_json = { version = "1.0.117" }
tokio = { version = "1", features = ["full"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["ansi", "fmt"] }
once_cell = "1.19.0"
serde = "1.0.203"
so much junk
ed25519 is built into zig
i dont need anything like tokio
i'll compare the code and performance after i finish the rewrite
oh great
the fines and consequences for businesses suffering these data breaches through sheer incompetence when it comes to security is basically none
so some companies have little incentive to be serious about security
i still use the deprecated desktop version
because
- it still works
- icba having to check my phone every time i need some stupid code
2fa code generation algorithm is always the same, so the codes should in theory work forever, regardless of app changes
how big is chromium lmao
i wanted to make one small change to the chromium browser for my specific dev use case but im still on the cloning stage
dude trying to build chromium lmao
everyone knows thou shal not build chromium
it takes literal days
i really hope not
what do i do if i cant build chromium
chromium might as well not be open source
since it takes so long to build
i think i can place chromium in a dev drive so windows defender doesnt slow it down too
can i possibly also exclude certain components of chromium from building
i dont need every single feature chromium has to offer in this case
On an 80-core machine with -j 72 you should be able to build Chromium in maybe 40 minutes. On a 4 core laptop it probably takes six to seven hours
It took an ARM Launchpad builder 100 h to build it once
How did we get here? Well, C++ and its stupid O(n^2) compilation complexity. As an application grows, the number of header files grows because, as any sane and far-thinking programmer would do, we split the complexity up over multiple header files, factor it into modules, and try to create encapsulation with getter/setters. However, to actually have the C++ compiler do inlining at compile time (LTO be damned), we have to put the definitions of inline functions into header files, which greatly increases their size and processing time. Moreover, because the C++ compiler needs to see full class definitions to, e.g., know the size of an object and its inheritance relationships, we have to put the main meat of every class definition into a header file! Don't even get me started on templates. Oh, and at the end of the day, the linker has to clean up the whole mess, discarding the vast majority of the compiler's output due to so many duplicated functions. And this blowup can be huge. A debug build of V8, which is just a small subsystem of Chrome, will generate about 1.4GB of .o files which link to a 75MB .so file and 1.2MB startup executable--that's a 18x blowup.
@offtopic
a paying client for my api is asking for help getting it to work on his website
show me his client side code (absolute mess)
i tell him to add a console.log to check what is actually being requested from my api (with a copy-paste example)
he says he doesnt understand much and asks me if i can do it instead
proceeds to send me a 497mb rar file containing the website's code
@_@
trojan incoming
want to test this binary i wrote in zig?
I mean hes paying

jesus christ what is this
code is full of global variables and weird ass code flow
and everything is in italian
but the mp3 files are in portuguese
and the code gives a bunch of 404's because of that
this is literally a guy trying to make a product to sell while having no idea how to make the product itself
but you know, making money is more important than your product actually working :^)
Bro couldnt decide what language to use
some files are in spanish
there is a name translator function with everything hardcoded
there are so many switch functions
dude doesnt know how to use arrays and objects
and uses global vars inside functions
@_@
hardcoded coordinates for countries
if you're not from one of those countries, it doesnt work for you
if you are from one of those countries, you were born exactly in the middle of it, or wherever that coordinate points to
:^)
man, reading this code is as fun as reading luca's code
ah yes, my age can only be a multiple of 10
need to make sure age >= 20 right after checking age < 20
yup
that makes it extra safe
you never know
might get a bit flip between lines
:^)
uses both axios and fetch in the same script
im sorry to tell you but even chatgpt doesnt generate this bad of code
are you sure?
I've had chatgpt generate virtually the same code, but it got worse each time
"This doesn't exist"
"Oh im sorry, let me regenerate that for you" uses the same fucking thing that doesnt exist but in a different way
lmfao
:^)
one of my most fun moments with chatgpt was working with math formulas
i give it certain parameters, and then see it use them all wrong
for example x = ..., y = ..., z = ... cartesian coordinates in AU
and then chatgpt randomly decides to use those values in other units
i'm using claude ai. it's supposed to be better at algorithm stuff
well ofc
or i give it input in degrees and chatgpt uses it as radians
how does it know what you want if you tell it directly what you want
it has to guess obviously
well
it keeps track of all of them
I still have some from 6 months ago
funny stuff
remember the sponge bob meme? the one with patrick's driver licence
it was something like this:
chatgpt: speed of light in AU per day equals WRONGVALUE
me: what is the speed of light in kilometers per day?
chatgpt: X
what is an AU in kilometers?
chatgpt: Y
how many AU do you go in one day at the speed of light?
chatgpt: Z
then how much AU per day is the speed of light?
chatgpt: WRONGVALUE
lmfao
💀
zig has null and undefined for some reason. weird.
likely were js devs at one point
zig probably forces you to initialize a variable at the declaration site
if you want to leave the memory uninitialized you have to do so explicitly
most likely
the comptime keyword is pretty tricky
i'm trying to read a JSON file and create a std.StringHashMap([]const u8) at compile time, but it cant use an allocator at comptime, but all the functions require an allocator.
tricky language
I will switch to Bitwarden. It is password manager but has TOTP too
- available everywhere
having null or undefined is useful. the type void is also undefined
undefined is self explanatory. If you have to initialize something without providing a value, leaving it up to the compiler/runtime based off type isn't fun
it makes more sense in a language like zig that has more control over memory
it shouldn't be in JS though
I strongly disagree
isn't undefine/null a legacy issue
they added null in for Java people at some point
In JSON, undefined isnt serialized but null is
Most places communicate in JSON nowadays
it never made sense to send the thing you aren't sending
like send null instead of just not sending it
just omit it
Oh no Ben is arguing over null/undefined again
Well then should the value be undefined or null when someone serializes it
the values can have different meanings depending on how the API is built
Like user.avatar is nullable
But also undefined doesnt exist in some languages
most languages dont have two values like that
that's why i was suprised that zig did it
yeah but some languages error when you try to access something that doesnt exist
undefined and null are both pretty necessary imo
what other languages beside JS and Zig have undefined and null?
Idk. Not like I care either since I stick to what I'm good at or need to know
Perhaps theres jank for situations like that in other languages
imagine not having null and undefined in your language
-# Only you can see this • Dismiss message
imagine not having null and undefined in your language
-# Only you can see this • Dismiss message
Rust just has Some and None right?
perl has both undefined and null
ye



