#development

1 messages · Page 176 of 1

surreal sage
#

im only using 750mb

#

nvm

#

11gb

#

minor miscalculation on my end 😇

#

aight bud

craggy pine
#

Anyone good with HTML CSS know how to make my background image just staticly in the middle without this weird push up. Setting position to fixed causes it to always be pushed up.

body {
    margin: 0;
    font-family: 'Aclonica';
    background-image:url();
    height: 100%;
    width: 100%;
    background-position: center;
    background-repeat: no-repeat;
}

2k monitor: https://scs.twilightgamez.net/j/G6ka3.jpeg
1920 monitor: https://scs.twilightgamez.net/FBbBQ.png

#

not sure where the 3rd images is coming from for discord there christmasthink

surreal sage
#

and 100% is not always the way to go in css

craggy pine
#

Pretty sure ive tried absolute. Mainly trying to replicate what I've made in wordpress in html / css. I'll try more things later

surreal sage
#

try an img element

#

make sure to put content in a div

#

and give the div a higher zindex

craggy pine
#

I have also tried to do this and it didn't do anything.

#

Maybe I'm just dumb

craggy pine
#

I figured it out, I was indeed dumb. Thx

lyric mountain
#

hi miyu

#

did u see the ping earlier?

rocky wave
#

How long should I wait if 429 error occurs

solemn latch
craggy pine
#

Because my notifications said it wasn't a thing in top.gg

lyric mountain
#

^ here

spark flint
#

does anyone have any tips for optimising postgres

#

i have a database with 160 million records (and increasing), but its taking like 5 minutes to query rn

#

its on a 64 gb ram, 8 core i7, 8tb hdd server

i've already adjusted the config to allow higher resource usage, etc but its still slow

spark flint
#
SELECT * FROM data WHERE domain LIKE '%$1%' OR hostname LIKE '%$1%' LIMIT $2 OFFSET $3```
#

thats my domain query

#

IP query is hella speedy, mostly under a second SELECT * FROM data WHERE addresses @> $1 LIMIT $2 OFFSET $3

quartz kindle
spark flint
#

Yes

quartz kindle
digital swan
#

could it not be related to using a hdd instead of an ssd

neon leaf
#

Not really in this case

oak merlin
#

this always happens with me bruh why? the page is just loading and loading any solution? this is not my pc issue or anything from my browser

earnest phoenix
#

can some one help how to set vote logs using webhook

real rose
earnest phoenix
#

leave done

#

i did it from docs.

slender vector
frosty gale
#

odd question but does anyone know if theres a database which lists linux kernel vulnerabilities for specific versions?

#

context is im trying to root an older android phone likely running older linux firmware and maybe try exploit some privilege escalation to root it

#

se linux doesnt help

sage bobcat
#

One message removed from a suspended account.

pale vessel
#

use one of those chinese spyware TE_TrollDespair

#

kingroot

#

god i remember using that

solemn latch
#
class webSocketTests {
  constructor() {
    this.client;
    this.status = "Idle";
  }

  connect() {
    this.status = "Connecting";
    this.client = new WebSocket("ws://localhost:8080/");

    this.client.on("close", function close() {
      this.status = "Disconnected";
      console.log("connection closed");
      clearTimeout(this.pingTimeout);

      console.log("Attempt reconnection in 5 seconds");
      console.log(this); // logs the websocket
      setTimeout(this.connect, 5000);
    });
  }
}

const ws = new webSocketTests();

ws.connect();

I want the instance of the class itself in this

#

If i add .bind(this)

it works flawlessly the first time, but on reconnect it goes back to the websocket

#

removed some code that I think is irrelevant

sharp geyser
#

Wait what is the issue

radiant kraken
#

I want the instance of the class itself in this

sharp geyser
#

I don't see anything wrong with the code though, so I am confused on what the issue is. Its doing what it is intended.

#

as long as you use this in the scope of the class it will be the class scope, so any properties attached to the class will be attached to this

#

Also realisitcally you should be having the websocket server sending the reconnect status and handling it appropraitely

#

Like how discord sends an op code to let you know you should be handling a reconnect.

solemn latch
#

So, this.connect is undefined. Callback must be a function. Received undefined
on this line. setTimeout(this.connect, 5000)

but instead "this" on that line is my websocket, not webSocketTests

radiant kraken
#

afaik ```js
function thing() {
return this;
}

#

try using arrow functions

#

dont use the function keyword

sharp geyser
#

oh well yea now I see the issue

#

you can't use a normal function that way it overrides the scope and puts it in the scope of the function

#

therefor this is now the close function

solemn latch
#

If this is just a scoping issue I might cry lmao

sharp geyser
#

using arrow functions perserve the scope as null said

radiant kraken
#

function does some weird shit to this

sharp geyser
#

so () => {} instead of function close()

solemn latch
#

Thanks ❤️ I think that was it

radiant kraken
#

obviously

eternal osprey
#
function switchPage(path, pastItem, pastPath, id) {
  window.location.href = path;
  let item = document.getElementById(id);
  let secondItem = document.getElementById(id + "-changer");
  secondItem.href = pastPath;
  item.textContent = pastItem;
}```

does anyon know why after setting the htref my item and secondItem are not being set for some reason?
sharp geyser
radiant kraken
#

nah i'm sure woo is fine

sharp geyser
#

force of habit smh

solemn latch
#

give me all the sass and making fun of me making stupid mistakes ^-^

Helps me remember them

sharp geyser
#

Out of curiosity what are you doing woo?

solemn latch
#

Just considering adding websockets to my webhook site.

top.gg webhook in, websocket to the bot.

sharp geyser
#

I see

solemn latch
#

I'm pretty sure someone was working on it, but never finished

sharp geyser
#

Any real reason for this? Top.gg doesn't really give any data that would be important for real time transfer

solemn latch
#

Some people stuggle with webhooks, a websocket should be easier for a lot of people.

sharp geyser
#

That's fair

radiant kraken
#

you should make a feature that lets people write JS code as a middleware between the Top.gg and Discord webhook request

sharp geyser
#

It would be as easy as just connecting and receiving the data

solemn latch
#

to do it safely at least

radiant kraken
#

yea

#

at that point just write webhook code directly

solemn latch
#

with websockets, hopefully they will just be able to handle everything on their own.

But theres a good chance I wont follow through with this anyway.

sharp geyser
#

It shouldn't be too bad

#

Just make sure if there is a reason to reconnect, let em know, iirc it doesn't do it automatically or at least it shouldn't

#

Cause if there is a server issue it should try and reconnect, if not make a new connection.

solemn latch
#

Right now its just a 5 second timer, which will increase until it hits a limit.

Hoping to add a reconnect after feature for server reboots.

It'll be nothing fancy at first because I dont know what I'm doing ^-^

sharp geyser
#

Fair enough, I am not the most experienced either, but I am sure I can possibly help

#

if not me then tim would, he's fucked with websockets more than anyone here

solemn latch
#

for now I'm just trying to play with everything, but I'll reach out if I need it.

#

I almost pinged tim to ask about what I should use. But I settled on ws for now

#

tried to avoid socket.io, felt it would be too straightforward

sharp geyser
#

ws is ideally the best imo

#

its a framework/wrapper on the ws lib

solemn latch
#

yeah, not a ton of opportunity for me to learn there

radiant kraken
#

@sharp geyser how's C++ been going btw

sharp geyser
#

honestly not too terrible, haven't had the chance to mess with it too much, but its not bad

wheat mesa
#

Do advent of code with C++

#

You’ll learn a lot

radiant kraken
#

you'll get confused more with the questions rather than writing the actual C++ code

wheat mesa
#

Exactly

sharp geyser
#

advent of code?

wheat mesa
#

Yes

#

You haven’t heard of it?

sharp geyser
#

nope

radiant kraken
wheat mesa
#

It’s an advent calendar but for programming questions

#

1 question, 2 parts per day for 25 days

sharp geyser
#

sounds like fun

#

How long do they stay up?

wheat mesa
#

iirc forever but not sure

sharp geyser
#

Are you able to continue doing them even after 25 days?

wheat mesa
#

Yup

sharp geyser
#

Seems like I can go pretty far back

wheat mesa
#

If you change the end of that link to 2022 you can see last year’s questions

sharp geyser
#

even 2015

wheat mesa
#

This year has been notably harder than years previous

radiant kraken
solemn latch
#

I like that we all went to check

wheat mesa
#

You can set up private leaderboards as well

#

I’m competing against a few people from a student organization at my school

#

Rank 2 rn (#1 dude is sweating so hard, he has AOC++ and everything)

sharp geyser
#

AOC++?

solemn latch
#

angeryBOYE I'm having the issue still

radiant kraken
warm surge
#

null++

sharp geyser
#

Bro I am stuck on the first one

#

tf are these riddles

#

😭

#

oh wait

#

nvm

solemn latch
#

It connects twice fine, but when I restart the server the third time "this" becomes timeout 😔

sharp geyser
#

I realize now, I didn't see the button that says "get your puzzle input"

solemn latch
#
class webSockets {
  constructor() {
    this.client;
    this.status = "Idle";
  }

  connect() {
    console.log("connect function called");
    this.status = "Connecting";
    this.client = new WebSocket("ws://localhost:8080/");
    this.client.on("close", () => {
      this.status = "Disconnected";
      console.log("connection closed");
      clearTimeout(this.pingTimeout);

      console.log("Attempt reconnection in 5 seconds");
      console.log(this); // logs the timeout from below
      setTimeout(this.connect, 5000);
    });

    this.client.on("message", function message(data) {
      console.log("received: %s", data);
    });
  }
}
sharp geyser
#

So I just have to write a program that will combine the first and last digit in a thing

solemn latch
#

logs it on the third connection

radiant kraken
#

try using arrow functions

solemn latch
#

like connect as the arrow function?

sharp geyser
#

again I wouldn't use function at all in something like this

solemn latch
#

or also on message, because thats not even being used yet

radiant kraken
#

wait whats this.connect?

solemn latch
#

it should be itself

#

connect() {

#

it is the first two times it runs

sharp geyser
#

you could try and bind this see if that works.

#

iirc I had to do something similar when fucking with the discord websocket.

radiant kraken
sharp geyser
#

?

radiant kraken
#

i mean

sharp geyser
#

how else are you making methods in a class

radiant kraken
#

im not talking about that

sharp geyser
#

then what are you talking about, because you replied to how he does the method definition and said it looked weird

radiant kraken
#

i mean using setTimeout(this.connect, 5000);

#

as it's calling a class method

solemn latch
#

is there a better way to do that?

#

I got my recconect code from a random stackoverflow answer irrc

sharp geyser
#

If so then setTimeout might be overriding what this is as well

#

so you will have to bind it

#

though I doubt it, cause I've never run into this issue with setTimeout

solemn latch
#

I cleaned it up to just, none of my heartbeat code, authorization, anything.

It connects the first time fine.
restart server & it reconnects fine
restart server again & it fails to reconnect with this logged

import WebSocket from "ws";

class webSockets {
  constructor() {
    this.client;
    this.status = "Idle";
  }

  connect() {
    this.client = new WebSocket("ws://localhost:8080/");

    this.client.on("close", () => {
      this.status = "Disconnected";
      console.log("connection closed");
      clearTimeout(this.pingTimeout);

      console.log("Attempt reconnection in 5 seconds");
      console.log(this);
      setTimeout(this.connect, 5000);
    });
  }
}

const ws = new webSockets();
ws.connect();
#
connection closed
Attempt reconnection in 5 seconds
Timeout {
  _idleTimeout: 5000,
  _idlePrev: null,
  _idleNext: null,
  _idleStart: 3221,
  _onTimeout: [Function: connect],
  _timerArgs: undefined,
  _repeat: null,
  _destroyed: true,
  client: [WebSocket],
  status: 'Disconnected',
  [Symbol(refed)]: true,
  [Symbol(kHasPrimitive)]: false,
  [Symbol(asyncId)]: 29,
  [Symbol(triggerId)]: 26
}
node:internal/validators:214
    throw new ERR_INVALID_CALLBACK(callback);
    ^

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received undefined
    at setTimeout (node:timers:141:3)
    at WebSocket.<anonymous> (file:///D:/Dev/Javascript/webhooktopggfolder/Websockets/Pre-alpha/Client/index.js:50:7)
    at WebSocket.emit (node:events:394:28)
    at WebSocket.emitClose (D:\Dev\Javascript\webhooktopggfolder\Websockets\Pre-alpha\Client\node_modules\ws\lib\websocket.js:260:10)
    at Receiver.receiverOnFinish (D:\Dev\Javascript\webhooktopggfolder\Websockets\Pre-alpha\Client\node_modules\ws\lib\websocket.js:1181:20)
    at Receiver.emit (node:events:394:28)
    at finish (node:internal/streams/writable:750:10)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ERR_INVALID_CALLBACK'
}
#

am I going mad? 👀

#

.bind doesnt seem to want to go on the arrow function inside the close event.

if I swap to

this.client.on("close", function test() {
} /* bind(this) will go here */ )

this.client.on("close", () => {
} /* bind(this) will NOT go here */ )

With the top one it still errors on the third connection

sharp geyser
#

yea always use arrow functions if you want to use stuff from the class inside

#

else you will have to use .bind sorry forgot

solemn latch
#

I can take it out of the class, but thats not ideal.
Id like people to be able to have multiple websocket connections if they have multiple entities(server and bot votes) going into one bot.

#

Just to clarify, if its not in a class structure it works no issue.

sharp geyser
#

I haven't used js in a while so I don't remember if this is valid but setTimeout(() => {this.connect()}, 5000)

solemn latch
#

No way that worked

sharp geyser
#

Yea

#

you don't even need the {}

#

it can just be () => this.connect

solemn latch
#

lets not get our hopes up, but I'll let you know if it breaks again

sharp geyser
#

I don't think js likes you using another function as the function for setTimeout

#

might be a signature difference or smth idk

solemn latch
#

Time to put everything back together and hope for the best ^-^

sharp geyser
#

hope it works

solemn latch
#

yeah, no issue now.

I dont understand this, but if it works it works.

#

bad developer mentality lets go

sharp geyser
#

I think js just refuses to just take any function in the setTimeout callback

#

it has to be something like () => instead of a class method.

#

That would be my only guess

sharp geyser
#

According to the docs that should work

#

the way you were doing it before that is

#

Now I am also curious as to what was happening

solemn latch
#

It works outside a class, it's just when I put it in a class.

sharp geyser
#

Okay so I was right

#

setTimeout expects a function, and you are using a class method which has a different signature from a function I think at least according to my research of stack overflow articles

radiant kraken
#

^

#

thats what i meant

solemn latch
#

Ah

sharp geyser
#

also don't know if you knew this

radiant kraken
#

by a different signature they were referring to this

sharp geyser
#

if you wanted to use a function that takes in params it'd be setTImeout(nameOfFunction, delay, firstparam,secondparam) useless knowledge but now you know

#

:D

radiant kraken
#

or just scopes

sharp geyser
solemn latch
#

I guess my only question is why would it connect twice and not the third time.

Was it(I assume the signature) moving each time up in scope?

frosty gale
#

theres no open source alternatives as far as i looked

#

but its funner being able to do it yourself anyways

#

and another issue is that a lot of linux kernel vulnerabilities cant even be applied to android bc android doesnt use them or whatever

lyric mountain
#

android so bad that it doesn't even know how to properly be vulnerable /s

quartz kindle
#

task failed successfully

fossil flume
#

Looking for a discord. Py dev, dm if interested

real rose
#

nice

#

-needdev

gilded plankBOT
#

You seem to be asking for something you don't have experience for or something that hasn't been done yet, but really need for your bot/server.
You can hire developers from Fiverr or Freelancer to code the things you need for your bot/server.

fossil flume
#

I'm not hiring 😭 just need someone to work with

#

But undedstood

lyric mountain
#

Hiring a volunteer mmLol

fossil flume
quartz kindle
#

youre gonna have a hard time finding someone who will actually want to work on someone else's project without a well defined reward

#

its like the whole "paid with exposure" all over again

fossil flume
sharp geyser
#

@quartz kindle question for ya mr js man

sharp geyser
#

im part of that 5%

sharp geyser
#

I know what to do just not how I should execute it. It seems to me I gotta use a loop or something but idk if thats efficient

wheat mesa
#

Efficiency doesn’t matter as long as you can solve the problem with the right answer

#

My day 5 part two solution took 3 minutes to run

quartz kindle
#

its not about signatures in this case, its just scope and binding

sharp geyser
#

Thanks for clarifying

sharp geyser
#

Though I could probably do this in a much better and easier way

wheat mesa
#

@sharp geyser what language are you using

#

C++?

#

If so, C++'s string class has a find and rfind method that you may find extremely useful for this

#

Although actually those might not be as useful as I'm making them out to be

#

Might just need to do a loop forwards until first num and a loop backwards until first num

sharp geyser
#

I see

wheat mesa
#

with rust's find and rfind methods you can pass a closure to it which makes it easy to solve this problem with just those methods but c++ doesn't have that

sharp geyser
#

I see

#

I was planning on putting the puzzle input into a list and treating it like a queue of sorts and just looping till I get the right answer and adding it to a sum variable

wheat mesa
#

my solution was about 10 lines of code

#

it's a pretty easy one but part two is much more difficult

sharp geyser
#

How are you handling the input?

#

Im just putting it directly into the code KEKW

wheat mesa
#

I just read it all into a string and split by line

sharp geyser
#

1000+ lines of code baby

wheat mesa
#

I suppose that's a bit more difficult with C++ though given there's no split method in the stdlib for some god forsaken reason

sharp geyser
#

Ima just scrape the input page mmLol

#

Nah I’m kidding tbh I just don’t have the motivation today, pretty shitty day at work

wheat mesa
#

you can just read the file into an ifstream with C++

sharp geyser
#

File?

#

What file

wheat mesa
#
std::ifstream s("filename.txt");
#

the one you get when you click on the input

#

I just copy paste it all into a txt file

sharp geyser
#

I don’t get anything I just get a web page

#

Oh bout to say

#

Shit unfair if you just get a file

#

I’ll think about doing it tomorrow

#

I just don’t have the motivation today

wheat mesa
#

wow today's was super easy

crystal wigeon
#

hey anyone use aws? @wheat mesa @quartz kindle ? @solemn latch Im looking for someone to be part of early beta testing and get some feedback on a cloud management tool

#

if you know a start up or anyone who is willing to participate pls dm me

#

kuuhaku

hardy tangle
#

hi

quartz kindle
lyric mountain
grim aspen
#

my face when i see AWS on my browser 🙁

wheat mesa
proven lantern
radiant burrow
#

anyone have experience with localhost:3000 saying This site can’t be reached even when i have a terminal hosting it? I can access the working page on an incognito window, so i think theres just something messed up with my chrome settings? but everything on google didn't work

lyric mountain
#

Open your firewall

#

Or rather, are u typing http://?

radiant burrow
#

yeah

#

bc its just a self hosted site atm to design it

lyric mountain
#

Ik

#

If u can open in incognito then there's no reason not to be able to do so on regular browser

#

Maybe try refreshing with ctrl f5

radiant burrow
lyric mountain
#

To purge the cache

radiant burrow
#

i did that and also ctrl shift r but no luck

lyric mountain
#

It's not site can't be reached

radiant burrow
#

Oh oops that's the one I meant to type

lyric mountain
#

Ok, there u have the issue

#

One of your headers is way too big

radiant burrow
#

yea thats what i found online but nothing I did fixed it

lyric mountain
#

Press f12, go to network and click the red circle to start tracking

#

Then refresh the page

#

Check if any of the requests is using a long header

radiant burrow
#

oh yeah theres one

lyric mountain
#

There's the culprit

radiant burrow
#

out of curiosity, why does incognito work?

lyric mountain
#

Maybe incognito is stripping that specific header

#

What is it's name?

radiant burrow
#

ohh its a cookie i think

lyric mountain
#

Ah yeah, then that's the reason

#

Incog doesn't store cookies

radiant burrow
#

though when i found the reason for the 431 error, i did clear the cookies a bunch of times but they didn't go away. I wonder if it's an old cookie

lyric mountain
#

Try ctrl f5

radiant burrow
#

no dice, so i guess not

#

though i did just clear my cache and cookies on chrome as well angeryBOYE

#

wooo i got it to get rid of the stupid cookie

#

ty for the help with inspecting the header!!

lyric mountain
#

Yw

lament rock
#

http.cat based

lyric mountain
#

F12 helps a lot for debugging site issues

lyric mountain
lament rock
#

So true

lyric mountain
#

What's mozilla near net cats?

lament rock
#

Who needs to know the specifics of a spec, just make your own implementation! :)

#

When I make an API, I'll just use I am a teapot over 429

bitter heart
#

Hello, I am using nodejs and discord.js v14. After selecting something from the select menu, the selected option is not cleared, how can I clear it?

stark abyss
#

if someone is bored, here is a challenge i came across, its interesting
Reduced Row Echelon Form. Write your own program that takes in an augmented matrix of any size (perhaps to be read from a file) and returns the reduced row echelon form of the matrix, as well as either "NO SOLUTION" (if there's a pivot in the last column) or the vector-parametric form of the solution. Call the parameters s_1, s_2, ..., s_999 if necessary. You may assume the matrix won't have more than 1000 columns total.

eternal osprey
#
from sklearn.model_selection import train_test_split as tt

from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier as rfc
from sklearn.metrics import confusion_matrix, roc_curve, auc
columns =  ['year', 'month', 'date', 'children', 'hospital tier', 'city tier', 'state id', 'bmi', 'hba1c', 'heart issues', 'any transplants', 'cancer history', 'number of major surgeries', 'smoker']
random_state = 1337
train_errors = []
test_errors = []
X_train, X_test, y_train, y_test = tt(scaled_data, charges_column, test_size=0.33, random_state=random_state, stratify = charges_column)
for depth in range (2, 21):
    
    dtc = rfc(max_depth=depth, criterion = 'gini', min_samples_split = 100)
    dtc = dtc.fit(X_train, y_train)
    y_train_pred = dtc.predict(X_train)
    y_test_pred = dtc.predict(X_test)
    accuracyTrain = accuracy_score(y_train, y_train_pred)
    accuracyTest = accuracy_score(y_test, y_test_pred)
    errorTrain = 1 - accuracyTrain
    errorTest = 1 - accuracyTest
    train_errors.append(errorTrain)
    test_errors.append(errorTest)
    print("Depth", depth)
    print("Train data error", errorTrain)
    print("Train Accuracy", 1 - errorTrain, "\n")
    print("Test data error", errorTest)
    print("Test Accuracy", 1 - errorTest, "\n")

plt.figure(figsize=(8,6))
plt.plot(range(2,21), train_errors, label ="training_error", marker = ".")
plt.plot(range(2,21),test_errors, label = "test_error", marker = ".")
plt.xlabel("Tree Depth")
plt.ylabel("Classification error")
plt.legend()
plt.title("Training Error / Test Error")
plt.show()```

hey guys this is my python random forest data:

this is the graph that belongs to it, the blue is the train error and the red the test error
#

are these results any good? It seems to be close... a bit too close i think

grim aspen
#

can i ask what you're trying to accomplish? i'm not sure of what you're entirely doing

#

nvm

#

i don't have much information to go off of but it seems that the classification errors below 0.15 (15%) which didn't change depth much as the tree updates.

#

it looks very close if that's what you're asking

lyric mountain
#

i'm not sure of what you're entirely doing
buddy that's always the case lmao

#

I'm not even impressed anymore after the stuff we went through

#

and he was only at 1st year, guy cranked difficulty to 11

surreal sage
#

What are all the ways to convert a string (an uuid) to a number in JavaScript?

#

Trying to 'reverse engineer' without src

grim aspen
#

Parsing integers from parts of UUID, Hash Function, BigInt, Bitwise Operations, or Custom Encoding

fossil flume
#

Are you able to get the url of a discord file object before sending it?

fossil flume
grim aspen
#

the url of the file can be obtained after being sent

#

otherwise before is not possible

lyric mountain
deft wolf
#

But then the photo will probably only be available for a short period of time. I think we need more context as to why he needs this link and so on

lyric mountain
#

But yeah, if the intention is a "Download" button then it won't work

neon leaf
#

what is better? ipv6 short function

new

let ip = '', doubleIx = false

            for (let i = 0; i < this.rawData.length; i++) {
                const segment = this.rawData[i]

                if (!segment) {
                    if (!doubleIx) {
                        ip += ':'
                        doubleIx = true
                    }

                    continue
                }

                ip += `${i ? ':' : ''}${segment.toString(16)}`
            }```



old
```ts
let ip = [ ...this.rawData ]
        .map((seg) => seg.toString(16))
        .join(':')

            ip = ip.replace(/(^|:)0+([0-9A-Fa-f]+)/g, '$1$2')
            ip = ip.replace(/(^|:)(0(:|$)){2,}/, '::')```



it should be as fast as possible
neon leaf
#

a Uint16Array for ipv6

lament rock
#

Can you use Array.from instead of spreading it

neon leaf
#

yes but arent regex in this case way slower than the other way?

lament rock
#

What is the regex for specifically

neon leaf
#

for shorting a long version of the ip

#

2a00:1450:4001:813:0:0:8:200e to 2a00:1450:4001:813::200e>

neon leaf
#

?

lament rock
#

I'll write things a different way when I get home in 3 hours

lyric mountain
#

If the full switch happens at all, that is

lament rock
#

You have to admit that ipv4 was not meant for a global IOT future

#

The fact that local IPs exist is one thing

#

Multiple people can have 192.168.0.1

bitter heart
#

Hello, I am using discord.js v14. When you post @ everyone, no one is tagged. Can you solve this?

lyric mountain
#

but if it had one thing superior to ipv6 t'was how easy it is to remembed and type it

bitter heart
tulip ledge
frosty gale
#

a massive portion of isps still do not support ipv6

neon leaf
#

finally its done

#

my ip & subnet parser is complete

#

last things to add were checking if a subnet includes another subnet / ip and fixing some subnet mask shit

surreal sage
#

alright

#

so

#

visual studio fuckin code

#

remote viewer

#

whatchamacallit

#

ssh extension

#

i open a folder on remote

#

it asks for password

#

i enter

#

it accepts and directories get listed

#

but then it asks again.

#

im done with it

#

how can i fix

#

ima just reset my vsc configs

sharp geyser
#

You could just use an ssh key

radiant burrow
#

ok bear with me for this react/next question:

so I want to fetch user profiles from my mongodb database to show info on my website. I can fetch the user, and console.log things like user.coins. but the website and my vscode console seems to be receiving different things.

as the screenshots show, the vscode console is correctly viewing the user object, but the website/inspect console are showing it as false so it's doing no coins found. why they heck is this happening? I've tried useEffect too, with similar results

#

another ss of the vscode terminal, and also a view of the website console

sharp geyser
#

how are you setting the user

#

oh nvm

radiant burrow
#

ya its a function that returns the obj

sharp geyser
#

Where are you doing this at?

#

are you doing this in a hook or smth?

radiant burrow
#

ik my screenshots are a little messy, sorry. i can get better images of whatevers needed

#

well in a component, I tried useEffect as well but right now it's just like this:

components/profile.tsx

import React from 'react';
import Image from 'next/image';
import styles from './serverlist.module.css';
import { useEffect, useState } from 'react';
import { useSession } from "next-auth/react";
import { getuser } from '../pages/api/getuser';

export default function Profile() {
    const { data: session, status } = useSession();
    const [user, setUser] = useState("");

    getuser("461318192321789962").then((user) => {
        console.log("setting coins to ", user.coins);
        setUser(user.coins || "no coins found");
    });

    let image = <Image
        src="/images/icons/discord.png"
        alt="User Image"
        className={styles.pfpblank}
        width={212}
        height={212}
    />
    if (session?.user?.image) {
        image = <Image
            src={session?.user?.image || "/images/icons/discord.png"}
            alt="User Image"
            className={styles.profilepicture}
            width={212}
            height={212}
        />
    }
      
  return (
    <>
      <div className={styles.userbar}>
        {image}
      <span className={styles.name} >{session?.user?.name || "please log in"}</span>
      </div>
      {user}
    </>
  );
};
sharp geyser
#

where are you using this state?

#

also

radiant burrow
#

like in the return, the {user}? or do you mean where is this component being used as a whole or something

sharp geyser
#

I think the issue might be naming

#

you have your state thing which defines user and setUser, then your getuser has a placeholder variable also called user

#

so technically user.coins doesn't exist

#

so it will always be no coins found

#

also just saying

#

if you are only storing the coins for the user use coins and setCoins not user and setUser its confusing

radiant burrow
#

i just tried making it u and it has the same result, here is the vscode console (it has the correct user object)

#

eventually I want the whole user object, but I just wanted one thing first before trying all of it

sharp geyser
#

gotcha

radiant burrow
#

the whole object is kinda big so i figured lets just start with one thing until it works haha

sharp geyser
#

yea

#

So does changing that make any difference when viewing it on html?

radiant burrow
#

nope

sharp geyser
#

hm

#

Might be a lifecycle issue then

#

the html is rendering before the state is set

#

This is why I prefered classes over functions cause its harder for me to control the life cycle in a function based react app

#

classes it was much easier

radiant burrow
#

is that something I can switch now charmShycharmWorried

#

i had no preference in the setup, I just used what i could find documentation for the discord oauth in next for

sharp geyser
#

its not much different from functions, its just using classes that extend the React.Compoenent class and then using the class name to render

#

Im not saying you should though as idk if its a life cycle issue

radiant burrow
#

Oh i think i maybe saw how that works but didnt pay much mind to it

sharp geyser
#

the idea with classes is you do the state stuff in the constructor

radiant burrow
#

anyways yeah regardless of what getuser returns it just doesn't think it's defined, but only on the inspect console (i just tried forcing it to return other things instead of the user obj)

sharp geyser
#

I am like 90% sure its a life cycle issue that the html is rendering before the state is set but I am not too certain

#

I don't even know how you would manipulate the life cycle of a react component when using functions

#

Oh wait

#

you have to use the useEffect hook right

radiant burrow
#

yeah I did try it, same issue

sharp geyser
#

Show the code of that

radiant burrow
#

(it shows -1 on the site)

sharp geyser
#

Okay uh

radiant burrow
#

oh wait

sharp geyser
#

well I wouldn't bother setting the state originally

radiant burrow
#

i dont need the setUser("0")

sharp geyser
#

you already have useState("")

radiant burrow
#

yea rip that was just a testing thing

sharp geyser
#

the stuff inside is the default value

radiant burrow
#

actually I think this would work but its not running the getuser function. that was the issue I was having before I think nvm

#

let me try with then and catches

sharp geyser
#

I would do something like

const [user, setUser] = useState(null);

useEffect(() => {
  const fetchUser() = async () => {
    const user = await getuser("123");
    setUser(user.coins);
  };
  fetchUser();
}, [])
#

also make sure you are placing this inside the function btw dk if I needed to mention that

radiant burrow
#

yeah dw it is inside it

sharp geyser
#

and if you wanted to you could use try/catch and put the getuser and setUser inside the try and log any errors inside the catch obv

radiant burrow
#

same result, let me do a try catch. but theres generally not been errors, just user is undefined on the website

#

yeah no errors, it just is not defined

sharp geyser
#

hm

radiant burrow
#

in this version though I'm not sure it's connecting to the database, and thus it would return an undefined object. It doesn't make sense that in this context, getuser wouldn't function as intended though

#

can the class system be set up for just this component?

sharp geyser
#

I don't get why you can use it outside of the setUser but when you go to set it its automatically undefined

radiant burrow
#

im gonna give the class thing a shot bc it actually looks really nice for this dynamic stuff

sharp geyser
#

I prefer classes over functions in react anyways

#

its a lot easier to work with imo

radiant burrow
#

yeah cuz if the state stuff can all reside in the classes methods this seems way better haha

radiant kraken
sharp geyser
radiant kraken
#

i dont think thats how you declare a function

sharp geyser
#

Oh shoot

radiant kraken
radiant burrow
#

:) it works

sharp geyser
#

No problem

sharp geyser
#

If only there was a way to copy the decorations over

sharp geyser
#

Well I was talking about rendering the decoration from discord over to the pfp cause I can only assume that’s what’s happening unless he’s using his exact pfp from discord

#

Turns out you can though as discord gives you the decoration on the user object

radiant kraken
#

ooo icic

#

@radiant burrow what are u working on?

eternal osprey
#

Uncaught _DiscordAPIError DiscordAPIError[10062]: Unknown interaction


const {
  SlashCommandBuilder,
  EmbedBuilder,
  PermissionFlagsBits,
  AttachmentBuilder,
} = require("discord.js");
const fs = require("fs");
const { editDashboard } = require("../../helpers/extractor");
module.exports = {
  data: new SlashCommandBuilder()
    .setName("download")
    .setDescription(`Download all data.`),

  async execute(interaction) {
    await interaction.deferReply();
    if (
      !interaction.member.permissions.has(PermissionFlagsBits.Administrator)
    ) {
      return interaction.editReply({
        ephemeral: true,
        content: `> :x: You must be an admin to use this command.`,
      });
    }
    const attachment = new AttachmentBuilder("./data.xlsx", {
      name: "data.xlsx",
    });
    return interaction.editReply({
      ephemeral: true,
      content: `> :white_check_mark: Successfully created the download link:`,
      files: [attachment],
    });
  },
};
#

what is this unknown interaction error that i receive?

#

It's uncaught too so not sure where the fuck it's from.

lyric mountain
#

Maybe you're taking more than 3 seconds

radiant burrow
#

then i can display the user profile if they log in, leaderboards, i can make a ticket system and forum if I want, etc

wicked pivot
#

Hello,
I have some fairly basic JavaScript code with a problem. Could a kind soul help me? (I'm not sending the code directly because I put it on a sharing site and I know if I can share it here (on codeshare io the code)

vivid fulcrum
#

yeah it's fine

wicked pivot
#

Can I send the link here? it's authorized ?

vivid fulcrum
#

yes

wicked pivot
vivid fulcrum
#

i don't understand the problem in the comments well

#

how does the code behave like currently? and how should it behave?

wicked pivot
#

It’s quite complicated to explain, but to make it simple from level 0 to 10 you need stone for level up. and then only iron for level up. On the example it gives 0 stone but if I go for example from level 20 to 30 it gives me a number of iron I need when it is not supposed to need

#
[
  {
    emoji: '![bottle](https://cdn.discordapp.com/emojis/1183010270449238117.webp?size=128 "bottle")',
    name: 'bottle',
    TotalXP: 627,
    TotalXPWithDoubleXP: 157,
    TotalXPWithTenDoubleXP: 7
  },
  {
    emoji: 's',
    name: 'stone',
    TotalXP: 0,
    TotalXPWithDoubleXP: 0,
    TotalXPWithTenDoubleXP: 0
  },
  {
    emoji: 'i',
    name: 'iron',
    TotalXP: 10098,
    TotalXPWithDoubleXP: 5049,
    TotalXPWithTenDoubleXP: 1010
  },
  {
    emoji: 'g',
    name: 'gold',
    TotalXP: 4917,
    TotalXPWithDoubleXP: 2459,
    TotalXPWithTenDoubleXP: 492
  },
  {
    emoji: 'a',
    name: 'amethyst',
    TotalXP: 16886,
    TotalXPWithDoubleXP: 8443,
    TotalXPWithTenDoubleXP: 1689
  }
]```
20 to 30
#

it marks me iron and gold while it’s amethyst that makes me level up

vivid fulcrum
#

i can't pinpoint the problem just by reading the code unfortunately, there's too much scattered logic

#

have you tried debugging it

#

place a breakpoint somewhere inside the for loop and keep track of what's happening with your variables

wicked pivot
#

For me the problem just comes from this "if"

if (currentLevel >= xpLimit && targetLevel > currentLevel) {}```

I admit that my code is not very easy to understand, I should get into the habit of commenting on it
vivid fulcrum
#

i'd say it's easy to get the gist of what your code is doing, comments aren't the problen, it's the way the code is written - generally whenever your logic branches in a function, it means that the branched logic should be a function on its own... tldr it's hard to read not hard to understand

#

to add onto that clean code 101 is that every function has a specific purpose

#

anyway, i'd suggest debugging it

#

also try rubber duck debugging!

#

speak to yourself about how your code should behave and go through it step by step

wicked pivot
#

I've never really used debug, I'm looking to do that

vivid fulcrum
#

seems like the perfect situation to try it out :)

#

if you're struggling with the docs you can always hit up youtube

wicked pivot
#

I fixed the problem by creating another one xD

#

In fact I think that the part below my comment is rewritten

solemn latch
# vivid fulcrum

I have no idea how this is happened with the message you sent 👀

radiant burrow
sharp geyser
#

@radiant kraken @radiant burrow I am now attempting to make a mock dashboard with rust trollface

radiant burrow
sharp geyser
#

Oh my god making http requests with rust is so fucking annoying

#

😭

#

I still am not used to how rust lib docs are

radiant burrow
sage bobcat
solemn latch
#

Its a regex, supposed to block a specific scam url format.

sharp geyser
#

but rust has no std http thing so I have to use a 3rd party lib, which I am using reqwest rn

#

but there are so many things i have to even do beforehand and it seems the docs are outdated or smth cause I am trying it but it is saying it wont take that type

#

like why does it take this specific headermap

#

😭

radiant burrow
#

ripp I used next auth

sharp geyser
#

im not using js

#

I am using rust

radiant burrow
#

no I know I was just commenting

sharp geyser
#

omg

#

I think I figured it out

solemn latch
radiant kraken
#

also if u need questions about rust u can ask me

solemn latch
#

^-^

radiant kraken
#

im not a chem type of person

#

.-.

sharp geyser
#

and didnt wanna do it in js

#

plus its helping me get my mind off some things

radiant kraken
#

most of the time you can infer it

sharp geyser
#

its not me adding the type

#

its the method expecting that type

radiant kraken
#

add use http::header::map::HeaderMap; then

sharp geyser
#

doesn't exist

radiant kraken
sharp geyser
#

yea

#

I figured it out tho

#

thats not the problem now

radiant kraken
#

bruh

sharp geyser
#

its that I don't remember how to use Result 😭

radiant kraken
#

like what

sharp geyser
#

I can't use await? in a function that doesn't return a result

#

I would rather use await? over just await as I don't really care about handling the result I just want the value

radiant kraken
#

.unwrap() then

sharp geyser
#

the `?` operator can only be used in an async function that returns `Result` or `Option` (or another type that implements `FromResidual`)

radiant kraken
#

.await.unwrap();

#

dont copy the example one to one

sharp geyser
#

I wasn't copying the example one to one

#

I just forgor you could use unwrap on await

radiant kraken
#

no

#

(thing).await just does the same as await (thing) in js

sharp geyser
#

I know

#

I forgot you could use unwrap on await

radiant kraken
#

you only .unwrap() on an Option or Result

sharp geyser
#

Yes I know this null

radiant kraken
#

good

sharp geyser
#

I just forgot that it was valid syntax to do it that way, tho I guess it doesn't matter as after await is called it just returns a result anyway

radiant kraken
#

ye

sharp geyser
#

I love and hate the compiler for rust

#

I don't know what type response.json().await.unrwap() could be, so idk what to set it to

radiant kraken
#

i love the compiler for rust

#

well read the docs regarding on what .json() returns

sharp geyser
#

but it wont let me continue past it unless I specify an explicit type

#

it returns a Result<T>

#

so it just depends on the type I give it by the looks of it

#

I mean

radiant kraken
sharp geyser
#

I guess I can make a struct that will outline what the data looks like from discord

solemn latch
#

@past orchid no ads please

radiant kraken
#

you have to

past orchid
#

It wasn't an ad lol I was asking for help

radiant kraken
past orchid
#

sorry about that

sharp geyser
#

yea

#

Just saw that on the docs

#

Didn't notice you could make your own struct

radiant kraken
#

99% of the time of you coding in rust will be reading docs.rs anyway

sharp geyser
#

yea

radiant kraken
#

why

sharp geyser
#

idk I just have trouble reading it

#

it seems like I have to search for a while before I can find what im looking for

#

@radiant kraken Oh my god, I don't remember this being an issue the size for values of type `str` cannot be known at compilation time

#

The compiler is recommending Box<str> but that doesn't seem right for my use case

#

should I use String over str?

sharp geyser
#
#[derive(Deserialize)]
struct Token {
    access_token: String,
    token_type: String,
    expires_in: i8,
    refresh_token: String,
    scope: String
}
#

I have it set to String now

#

but it was str previously

#

idk if String is appropriate to use here

radiant kraken
#

yes it has to be a String

#

a &str is a string slice, it cannot be grown, only be read, and it's size is fixed

#

like a char *

sharp geyser
#

gotcha

radiant kraken
#

a String is your typical growable string like in other languages, like std::string

sharp geyser
#

gotcha

#

Also now the fucking discord api is confusing me

#

its telling me I am using an unsupported grant type when in fact I am not

#

I have checked the spelling, even copy and pasted the grant type name for the grant type I want to use

radiant kraken
#

send code

sharp geyser
#

Unless the json is being fucked up

#

wait

#

how does discord expect you to send the auth info like client secrent and id

#

I don't think its in the body data anymore

sharp geyser
#

also reset my client secret

#

forgot I even had it there

radiant kraken
#

too late

#

also you can use String::new() over String::from("") btw

sharp geyser
#

gotcha

#

but I still dont understand why the discord api is responding that it is an unsupported grant type

#

unless the json is fucked

radiant kraken
#

i dont think so

radiant kraken
sharp geyser
#

didnt you could nest like that

radiant kraken
#

yuhh fastnod

sharp geyser
#

ima ask in the discord api server in regards to this wonky response from the api

#

they might be more equipped to answer cause I dont see anything I am doing wrong

radiant kraken
#

sure

sharp geyser
radiant kraken
#

they both do the same thing

#

the former is more preferred ig

sharp geyser
#

I don't even see how you would use string::new is it just String::new().add() or smth

radiant kraken
sharp geyser
#

Yea but I don't plan on letting it return an empty string always

#

thats just a placeholder

radiant kraken
#

ye

sharp geyser
#

@radiant kraken so apparently discord wont take in json despite it saying it will on the docs

#

it has to be form url encoded

#

😭

#

so I have solved that issue, now its an issue of redirect uri

radiant kraken
#

uh oh

sharp geyser
#

I have specified the redirect uri in the application settings but why is it invalid 😭

radiant kraken
#

ask again

sharp geyser
#

ugh

#

I am confusion

#

do I have to use the same url from my authorization url cause for that one I used /callback

#

but I don't want it to go back to /callback after its successfully authed and got a token, else it will just do it again

#

nvm

#

I am being dumb

#

Uh oh

wheat mesa
sharp geyser
#

Okay I am confused on what is happening

wheat mesa
#

String::from is for if you need an owned string from a string slice

sharp geyser
#

Rocket keeps exiting saying its overflowed its stack

#

idk why tho

wheat mesa
#

Lemme see

sharp geyser
#
thread 'rocket-worker-thread' has overflowed its stack
error: process didn't exit successfully: `target\debug\rust-web.exe --stack-size 16M` (exit code: 0xc00000fd, STATUS_STACK_OVERFLOW)
wheat mesa
#

Sounds like a recursion issue to me

#

Are you following the docs?

sharp geyser
sharp geyser
#

docs + stack overflow when I run into errors

wheat mesa
#

I highly doubt this has anything to do with it but make sure your const CLIENT_SECRET stuff is marked as &’static str

#

The compiler probably already infers that but just in case

sharp geyser
#

yea

#

I personally dont see the issue unless its continously calling on /login/callback

radiant kraken
#

omg waffle hai @wheat mesa

wheat mesa
#

hi

radiant kraken
#

hru?

wheat mesa
#

Good

#

Studying for discrete math exam

#

Hating every second of it

radiant kraken
#

glgl

wheat mesa
#

Totally don’t have 243 slides to go over before Monday

radiant kraken
#

i'm sure you're galaxy brain at maths

wheat mesa
#

Not on this

#

😭

sharp geyser
#

Okay I am losing my mind over here

#

I dont see what is causing this issue

wheat mesa
radiant kraken
#

have you asked in the discord dev server

sharp geyser
#

this isnt a discord dev issue anymore

radiant kraken
#

try asking in the Rust discord

wheat mesa
#

Try logging some stuff to see where the stack overflows

radiant kraken
sharp geyser
#

Okay

#

it seems to error at me unwrapping the body of the response

#

at least that is what logging tells me

radiant kraken
#

nice

sharp geyser
#

I dont see what I am doing wrong tho

#

Can I not unwrap it like this let body = response.json::<Token>().await.unwrap();?

radiant kraken
#

what's the error

sharp geyser
#

it seems to overflow once it reaches that

#

anything before works fine

radiant kraken
#

huh

sharp geyser
#

I am trying another method of doing it which is just handling the result as is

#
        let result: Result<Token, reqwest::Error> = response.json().await;
        let token: Token = match result {
            Ok(t) => t,
            Err(err) => {
                error!("Error decoding JSON: {:?}", err);

                return String::from("");
            }
        };
``` as such
#

but it seems that if I do something like token.access_token it is blank

#

oh wait

#

nvm

#

I am dumb

#

I read it wrong

sharp geyser
#

Okay I give up on this cookie shit with rocket

#

It makes no sense

#

at first it was setting it but not getting it, now its doing neither

#

😭

pale vessel
#

that doesn't look like c++ to me

radiant kraken
#

maybe you're right

sharp geyser
summer hemlock
#

Cridit please

sage bobcat
summer hemlock
#

Give me cridit please

sage bobcat
#

One message removed from a suspended account.

summer hemlock
#

I want a way to get credit for free.

#

@sage bobcat 🙏

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

summer hemlock
#

@sage bobcat I need it to buy something

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

#

One message removed from a suspended account.

summer hemlock
#

Yeah

solemn latch
sharp geyser
lament rock
#

100 social credits deducted

warm surge
lament rock
#

So true

warm surge
#

💀

sage bobcat
#

One message removed from a suspended account.

sharp geyser
#

@wheat mesa @radiant kraken so I have a config file that I am loading data from, I don't want to have to keep loading the data every time I want to access it as its static information that doesn't change. Anyway I can load the data and then use it across the entire project or will I have to reluctantly load each time I need it.

wheat mesa
#

You can use it across the whole project

#

Look into lazy_static!, might be what you're looking for here

pale vessel
#

i use once_cell's Lazy. it's much better than lazy static since it's not a macro. rust also has once_cell built-in now so you can use that too

#

Lazy is much easier to instantiate, but it's not built-in yet. you can use the original once_cell package for that

sharp geyser
#

so doing CONFIG: Lazy<Data> = Lazy::new(|| { load_config().unwrap() } ) and then using CONFIG I don't get the actual data

#

It seems to be Lazy<Data> but that doesn't really help me much

pale vessel
#

hm, why wouldn't you get the actual data?

sharp geyser
#

It seems to only pop up with methods and not any properties

pale vessel
#

you can use Lazy<Config> just as you would for Config

sharp geyser
pale vessel
#

did you make everything you need in Data public?

sharp geyser
#

yes

pale vessel
#

the properties aren't public

#

pub discord e.g.

sharp geyser
#

You have to make the properties public even with the properties?

pale vessel
#

yes

sharp geyser
#

Then what is the point of making the fucking struct public

#

You wont have a public struct with private properties, or at least that shouldn't be the default

pale vessel
#

so that it's accessible only within the set scope

sharp geyser
#

IT makes no sense

pale vessel
#

you'd want a public struct with some public properties, or let a struct not be accessible at all outside the set scope

sharp geyser
#

Yea but like, if you make the struct itself public it makes no sense that by default its properties are private

pale vessel
#

it would

sharp geyser
#

I feel like i'd rather have to specify private properties than public ones inside of a struct thats already been deemed public

pale vessel
#

not all properties should be public, that'd give unexpected behavior

#

it's not public until you say so

#

it's less complicated that way

sharp geyser
#

Okay, so you just say that those properties are private thonk

#

Idk I just feel its a hassle to have to write public for each and every property

#

That would get extremely annoying for large structs

pale vessel
#

there's a reason why macros exist Trol

#

(that's dumb though, don't do that)

sharp geyser
#

So for some reason it isn't loading my config anymore

sharp geyser
#

Cause it was working just a few seconds ago until I changed the values in the config file that I am loading

#

its still using old config vals

wheat mesa
#

Did you not restart the program?

sharp geyser
#

I did several times

radiant kraken
#

it's like a C++ class

#

most of the time you would only need private struct members

pale vessel
pale vessel
sharp geyser
#

it is being saved

#

But the config is just not being loaded anymore

#

I have a print that gets called when it has successfully loaded, and if it doesn't it errors. so far I am getting nothing and it is using old values

pale vessel
#

yeah that's weird, especially when you restarted the program

sharp geyser
#

yea, idk what is happening

sharp geyser
#

I don't see why its no longer being called after restarting and instead treats it as if it already had been loaded from a previous time

pale vessel
#

that looks totally fine. i really don't think it's the code

crystal wigeon
#

Whatchu bois cookin

pale vessel
#

check where you're running the executable too

crystal wigeon
pale vessel
#

you might have two config files somewhere, who knows

crystal wigeon
#

Rust?

sharp geyser
#

The only config file I have is the one I edited

#

this is so strange

pale vessel
#

what command do you use to run the code?

#

also, try deleting/renaming your config file. see if it errors

sharp geyser
pale vessel
#

i see

sharp geyser
#

Yea idk man, it seems to me that it is just not calling and populating the config variable for some reason

pale vessel
sharp geyser
#

yea

#

same thing

pale vessel
#

so there's like a ghost file lmao

#

if you add something like a print inside the code, do you see it in the console?

sharp geyser
#

unless it is being copied over into the debug stuff because its being used

sharp geyser
#

if not it will error and exit

#

but idk if it will even exit because before it wasn't loading because the path was wrong, then I fixed that and it started loading the config properly. Now that I have made changes to the config file tho it wont load it anymore

pale vessel
#

that's some weird behavior

#

try deleting your target folder

#

run everything again, let it build all over again

#

...unless you tried that already

sharp geyser
#

actually not since I made changes to the config file

#

let me see if that works this time

#

nope

#

still uses old values and doesn't even say the config is loaded

#

Is it possible it is still in memory?

#

Like it wasn't deleted for some reason

pale vessel
#

lol tf. nothing like an if statement or any funny loc you added without realizing?

sharp geyser
#

nope

pale vessel
sharp geyser
#

I can show you both the config loader file and the main file

pale vessel
#

im not home atm but maybe someone else can help, yeah

sharp geyser
#

No one else who uses rust is online 😭

pale vessel
#

oh yea its a Monday

#

isnt null at school

#

it's like almost 4pm there

#

my driving instructor had to do something so i had to wait for him. now its pouring down hard and he's still not back KEKW

#

lizard's here but he's playing league WeirdChamp

sharp geyser
#

Okay

#

so

#

uh

#

Weirdly enough its not even calling load_config at all

#

I just put a print outside of any possible stuff that can block it

pale vessel
#

maybe its somehow running an old executable?

sharp geyser
#

and its just not running

#

I can try and delete the executable that was built

#

but no

#

I deleted the target folder remember

pale vessel
#

yeah

sharp geyser
#

Hm

pale vessel
#

at this point just make a backup of your code, delete the entire project directory, create a new one, put back all the code and config, and run cargo run again

#

if that still doesn't work, it's most likely your code

sharp geyser
#

Well just now I found it it could possibly be how I am specifying the file name as before it was using blah/project/../conf.toml

#

now it is 100% using the correct file path, but still not working, so ima do what you suggest

pale vessel
#

../ should still be relative to where you ran cargo run

sharp geyser
#

yea I logged to see what the path was and turns out I was doing it wrong

#

I simply just needed to give it the name of the file, the path was already at the right place

pale vessel
#

yup

sharp geyser
#

Still

#

Even after debugging, it does not seem to be even running the load_config function

#

and debugging hasn't shown any reasons to this

lament rock
#

abs paths my beloved

pale vessel
#

if it does, its time to check ur code thoroughly

#

otherwise you're fucked, idk lmao

sharp geyser
#

It does

#

Somewhere in my code it is breaking but not reporting

pale vessel
#

possibly

sharp geyser
#

At this point I cant think of any other reason than it is just not erroring

pale vessel
#

i believe it might have errored inside the lazy function

sharp geyser
#

Okay well

#

using Lazy::force(&CONFIG) got it to do something in the console at least

#

yet it still uses old config values

#

Okay well I give up for tonight

#

I am too tired to continue fucking with this bullshit

radiant kraken
wheat mesa
#

It looks like you’re using Intellij but still

sharp geyser
pale vessel
#

maybe it was a jetbrains skill issue

#

have you tried vsc

sharp geyser
#

not a ide issue

#

it doesn't matter where I run it

lyric mountain
#

it might provide useful hinting at what the issue might be

sharp geyser
lyric mountain
#

neither do I lul

#

what lang is it?

sharp geyser
#

Rust

lyric mountain
#

and most importantly, what logger?

#

or is it the default?

compact pier
#

how can I declare this in typescript

'1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '10' | '11' | '12'
#

like a type

lyric mountain
#

uhhh...u could use an enum

#

I suppose u want to allow only values from 1 to 12

#

optionally just throw an exception if it's outside the range

compact pier
#

how can I do that

lyric mountain
#

idk, just answered from a general coding perspective

#

I dont use TS

#

shouldn't be too hard to google tho

wheat mesa
desert verge
#

why my bot is still pending ?

surreal sage
#

like

#

u can just use jsdoc?

#

assert?

lyric mountain
#

typing

#

helps wonders when debugging or just generally coding

digital swan
#

can also be a huge headache

#

but when it works its lovely

lyric mountain
#

not really, when you code already taking into account types it just becomes natural

#

it's hard to convert to it later tho

sharp geyser
#

@pale vessel hey so, I am logging stuff in the load_config function I have and it is indeed grabbing the correct data and I can only assume when I return it as a result it is also doing so, but for some reason its not actually using that data

#
[2023-12-11T20:42:36Z INFO  beedle::config] Loaded config: Data {
        discord: DiscordData {
            client_secret: "",
            client_id: "1128600826752008192",
            redirect_url: "http://localhost:8080/callback",
            discord_api_url: "https://discord.com/api/v10",
            discord_auth_url: "https://discord.com/api/oauth2/authorize?client_id=1128600826752008192&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauth%2Fcallback&scope=identify",
            discord_auth_url_email: "https://discord.com/api/oauth2/authorize?client_id=1128600826752008192&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauth%2Fcallback&scope=identify+email",
        },
        actix: ActixData {
            secret: "",
        },
    }
pale vessel
#

not using? wdym

sharp geyser
#

Now the link it is showing here is the correct one but the one being used to redirect is still an old link

#
#[get("/login")]
async fn login() -> impl Responder {
    info!("Here is the auth url: {}", &CONFIG.discord.discord_auth_url);
    Redirect::to(&CONFIG.discord.discord_auth_url).permanent()
}
pale vessel
#

yeah i genuinely don't get that

pale vessel
sharp geyser
#

No way?

pale vessel
#

oh, the logged url is old?

sharp geyser
#

That wouldn't make sense as the server is telling it what to redirect to

#

I mean no, it doesn't even log that stuff in the login func which I thought was also weird

#

Maybe you just can't log like that using the env logger

#

Ima try with a nromal print

#

yea no, it doesn't even run a println in that function

#

ima try and clear browswing cache just in case

sharp geyser
pale vessel
sharp geyser
#

it was browsing cache

#

😭

pale vessel
#

lol

sharp geyser
#

also wait

#

why am i even specifying it as permanent

#

its not

#

they get redirected to discord then back to the app

pale vessel
#

i tend to avoid 301

sharp geyser
#

permanent is 308 no?

#

oh okay so

pale vessel
#

The main difference between the 301 and 308 redirects is that when a 308 redirect code is specified, the client must repeat the exact same request (POST or GET) on the target location. For 301 redirect, the client may not necessarily follow the exact same request.

sharp geyser
#

308 is when it uses whatever uri was used previously

#

which makes sense why it kept using the old one

#

and 301 just means it will use whatver uri is directly given

#

😭

pale vessel
#

i haven't used 308 ever afaik

#

didn't know that was a thing KEKW

sharp geyser
#

for some reason actix uses 308 over 301

#

Okay

#

well now that it is fixed I can move on

#

but not now, ima enjoy my last few hours before work by watching some netflix

sharp geyser
pale vessel
#

is there anything wrong with it?

sharp geyser
#

Yea, it does all the stuff correctly but when it comes to setting the session data it doesn't seem to do that properly, and then on my index part where I am getting it and then displaying the username if it exists or just a default message it then says that localhost:8080 at path / is unreachable

sharp geyser
sharp geyser
#

@pale vessel fixed the issue

#

Only issue is right now I dont have a way to refresh the token if it expires but thats for another time

pale vessel
radiant kraken
sharp geyser
#

Now I’m just stuck wondering how the hell does actix actually handle expirations of the cookies and if I should even set an expiration time or handle it myself

frosty gale
#

gcc linker errors are the worst thing known to man

#

they might as well be printed in binary based on how unreadable they are

#

clang is becoming more delicious day by day

radiant kraken
#

so true

sharp geyser
#

@radiant kraken @wheat mesa please help 😭

#

I am rewriting my oauth2 stuff to use the oauth2 lib but I am running into async issues

#
static DISCORD_CLIENT: Lazy<BasicClient> = Lazy::new(|| {
   BasicClient::new(
       ClientId::new(CONFIG.discord.client_id.to_owned()),
       Some(ClientSecret::new(CONFIG.discord.client_secret.to_owned())),
       AuthUrl::new(CONFIG.discord.discord_auth_url.to_owned()).unwrap(),
       Some(TokenUrl::new(CONFIG.discord.discord_token_url.to_owned()).unwrap())
   )
       .set_redirect_uri(RedirectUrl::new(CONFIG.discord.redirect_url.to_owned()).unwrap())
});

#[get("/callback")]
async fn callback(query: actix_web::web::Query<CallbackQuery>) -> Result<HttpResponse> {
    let code = AuthorizationCode::new(query.code.to_string());
    let token_result = DISCORD_CLIENT
        .exchange_code(code)
        .request(http_client)
        .map_err(|e| {
            error!("Failed to spawn blocking task: {:?}", e);
            HttpResponse::InternalServerError().finish()
        }).unwrap();

    let refresh_token = token_result.refresh_token().map(|t| t.secret()).unwrap();

    info!("Token result: {:?}", token_result);
    info!("Refresh Token: {:?}", refresh_token);

    Ok(HttpResponse::Ok().body("Successfully authed"))
}

So when I do the callback I have to give the oauth2 a request client, thing is http_client is a synchronous client so it blocks at runtime. Now oauth2 happens to have a handy async_http_client but idk how I would use it because request takes in Result<HttpResponse> not a future

#
error[E0271]: expected `async_http_client` to be a fn item that returns `Result<HttpResponse, _>`, but it returns `impl Future<Output = Result<HttpResponse, Error<Error>>>`
    --> src\main.rs:60:18
     |
60   |         .request(async_http_client)
     |          ------- ^^^^^^^^^^^^^^^^^ expected `Result<HttpResponse, _>`, found future
     |          |
     |          required by a bound introduced by this call
     |
note: calling an async function returns a future
    --> src\main.rs:60:18
     |
60   |         .request(async_http_client)
     |                  ^^^^^^^^^^^^^^^^^
note: required by a bound in `CodeTokenRequest::<'a, TE, TR, TT>::request`
    --> C:\Users\dyeaaaronjr\.cargo\registry\src\index.crates.io-6f17d22bba15001f\oauth2-4.4.2\src\lib.rs:1309:35
     |
1307 |     pub fn request<F, RE>(self, http_client: F) -> Result<TR, RequestTokenError<RE, TE>>
     |            ------- required by a bound in this associated function
1308 |     where
1309 |         F: FnOnce(HttpRequest) -> Result<HttpResponse, RE>,
     |                                   ^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `CodeTokenRequest::<'a, TE, TR, TT>::request`
help: consider `await`ing on the `Future`
     |
60   |         .request(async_http_client.await)
     |                                   ++++++
wheat mesa
#

await the future

sharp geyser
#

I don't know how

#

I have tried what I know but like

sharp geyser
#

async rust is still new to me

#

I am basically making it up as I go

wheat mesa
#

.request(async_http_client.await)

sharp geyser
#

that is not a thing

wheat mesa
#

line 60

sharp geyser
#
error[E0277]: `fn(oauth2::HttpRequest) -> impl std::future::Future<Output = Result<oauth2::HttpResponse, oauth2::reqwest::Error<reqwest::error::Error>>> {async_http_client}` is not a future
  --> src\main.rs:60:36
   |
60 |         .request(async_http_client.await)
   |                                   -^^^^^
   |                                   ||
   |                                   |`fn(oauth2::HttpRequest) -> impl std::future::Future<Output = Result<oauth2::HttpResponse, oauth2::reqwest::Error<reqwest::error::Error>>> {async_http_client}` is not a future
   |                                   help: remove the `.await`
   |
   = help: the trait `std::future::Future` is not implemented for fn item `fn(oauth2::HttpRequest) -> impl std::future::Future<Output = Result<oauth2::HttpResponse, oauth2::reqwest::Error<reqwest::error::Error>>> {async_http_client}`
   = note: fn(oauth2::HttpRequest) -> impl std::future::Future<Output = Result<oauth2::HttpResponse, oauth2::reqwest::Error<reqwest::error::Error>>> {async_http_client} must be a future or must implement `IntoFuture` to be awaited
   = note: required for `fn(HttpRequest) -> impl Future<Output = Result<HttpResponse, Error<Error>>> {async_http_client}` to implement `IntoFuture`
   = note: the full type name has been written to 'C:\Dev\discord-app\target\debug\deps\discord_app.long-type-17403919131916426491.txt'