#development

1 messages Ā· Page 174 of 1

sharp geyser
#

Okay so I just realized something

#

my array is funky

#

despite me saying index 0 is 100

#

apparently index 0 is 1000

#

which is supposed to be index 1

radiant kraken
sharp geyser
#

are there template strings for c++

#

like how js has ```
${}

radiant kraken
#

yes

#

afaik there's std::format

sharp geyser
#

I am so confused

#

when inserting everything seems fine

#

but when going to remove the indexes are fucked

radiant kraken
#

like what? ^

sharp geyser
#
  void remove(size_t index) {
      if(index < length && index >= 0) {
          memcpy(&array[index], &array[index +1], (length - index + 1) * sizeof(T));
          length--;
      }
  }

this was my current thought process

#

actually I think that first part of the if is fucked but

radiant kraken
#

doesnt sound like it

#

maybe (length - (index + 1)) * sizeof(T)?

sharp geyser
#

yep

#

that fixed it

#

wonder what was happening

radiant kraken
#

noice

sharp geyser
#

oh wait

#

it was essentially evaluating 11

#

but wrapping it in parantheses allowed it to do the addition first

radiant kraken
#

yes

sharp geyser
#

math

#

fucking hate it

#

but I need it 😭

#

Well

#

that was easy

radiant kraken
#

math is okay

sharp geyser
#

I was just going to use a for loop

#

with memcpy it made my life easier tho

radiant kraken
#

frfrfr

sharp geyser
#

now I am tempted to try it with a for loop tho

#

to see if I can get it

radiant kraken
#

why

sharp geyser
#

Just to try it and see

radiant kraken
#

okay

sharp geyser
#

its nice having built in stuff

#

but I wont learn by simply just using whats given

#

I basically figured out the efficient way before trying it myself

#

welp

#

I fucked up

#

meh

#

I will leave figuring it out without using memcpy for another time

surreal sage
#

wadahel

earnest phoenix
#

Ask me what exactly?

radiant kraken
radiant kraken
#

Brain did

earnest phoenix
# radiant kraken Brain did

The C++ standard does not prohibit such a thing, there's just no concrete way to do it as template declarations and definitions both must be accessible to the compiler in the translation units

There are multiple ways this can be done

  1. Explicit template instantiation

foo.h:

#ifndef FOO_H
#define FOO_H

template <typename T>
class Foo {
 public:
  void bar();
};

#endif   // FOO_H

foo.cpp:

#include "test.h"

template <typename T>
Foo<T>::bar() {
  // ...
}

main.cpp:

// Yes, including the C++ file
#include "test.cpp"

// Explicit template instantiation of the types that will be used, so the linker can find the generated classes by the compiler from the translation units
// In this case, we're only using `int`
template class Foo<int>;

int main() {
  Foo<int> foo;

  foo.bar();
}
  1. Late binding of translation units

foo.h

#ifndef FOO_H
#define FOO_H

template <typename T>
class Foo {
 public:
  void bar();
};

// Include the implementation file
#include "foo.cpp"

#endif   // FOO_H

foo.cpp:

template <typename T>
Foo<T>::bar() {
  // ...
}

main.cpp:

#include "foo.h"

int main() {
  Foo<int> foo;

  foo.bar();
}
radiant kraken
#

then explain this @earnest phoenix

earnest phoenix
#

They're not doing it properly, just separating them like the other non-template stuff won't work, you have to use one of those solutions I provided to be able to separate declaration and definition of templates

radiant kraken
earnest phoenix
#

What's the point of reviewing it when it's already merged?

radiant kraken
#

i just want for your thoughts on it

earnest phoenix
#

Hmm why are you using std::realloc() with new/delete?

radiant kraken
#

like i get that it's not calling the constructor but it's purpose is just for expanding the memory block

earnest phoenix
#

The underlying allocators used for std::realloc() and new can be different and not have the same techniques of keeping track of memory, basically it's undefined behavior

radiant kraken
#

so is the for loop the only way?

earnest phoenix
#

Hm?

radiant kraken
earnest phoenix
#
T* tmp = new T[capacity * 2];

// Move elements of previously allocated array to the newly allocated array

// Deallocate the old array
delete[] arr;
// Increase capacity
capacity *= 2;
// Use the newly allocated array
arr = tmp;
#

For continuous growth, keep increasing the capacity in a loop until it satisfies your specific condition and do the same steps

radiant kraken
earnest phoenix
# radiant kraken does memcpy work for a remove(index) function?

Sure

This effectively reduces the container size by the number of elements removed, which are destroyed.

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

thorny shoal
#

Music

slender wagon
#

hallo, is anyone good at go here?

#

so i am trying to improve my go build command

#

i added some flags that help with the compile

#

but i am wondering if there is a flag to use more cores while running build

earnest phoenix
#

Hey

radiant kraken
#

@sharp geyser ello

sharp geyser
#

Just woke up

radiant kraken
sharp geyser
#

Ty

#

@earnest phoenix so you can include cpp files? I thought you could only do so to header files

earnest phoenix
sharp geyser
#

Oh okay

#

That’s nice to know

#

Is there any real reason for that?

#

Or is it just a byproduct of the preprocessor

earnest phoenix
#

Because there are a lot of people who use different unofficial C++ file extensions (tpp, ipp, cxx, and many others), so the preprocessor doesn't have to add support to all of them, also notice how the standard library headers you include doesn't have a file extension?

sharp geyser
#

Yea

#

So it’s just because it didn’t want to add support to the numerous amounts of file extensions

#

Why even is there so many unofficial extensions

eternal osprey
#
  public static int bestFitAlgo() {
        while (!inputBoxes.isEmpty()) {
            Vector<Double> nextElement = inputBoxes.get(0);
            int bestIndex = findBestFit(nextElement);
            if (bestIndex == -1) {
                Vector<Vector<Double>> newPartition = new Vector<>();
                newPartition.add(inputBoxes.remove(0));
                boxPartitions.add(newPartition);
            } else {
                boxPartitions.get(bestIndex).add(inputBoxes.remove(0));
            }
        }
        System.out.println(boxPartitions.size());
        return boxPartitions.size();
    }```

hey guys i recently have created this best fit algorithm... but it's not a best fit ![KEKW](https://cdn.discordapp.com/emojis/1146893526509047928.webp?size=128 "KEKW") .

It returns me partitions that are far from optimal
surreal sage
#

all good

sharp geyser
#
  T& pop_front() {
      T& front = array[0];

      memcpy(&array[0], &array[1], (length - 1) * sizeof(T));

      std::cout << std::format("Front: {}", front) << std::endl;

      return front;
  }

So I have a question regarding memcpy, when I call pop_front it returns the value at an incorrect index. Which if this is working how I think it makes sense

#

Despite putting what array[0] currently is in a variable, memcpy is removing what is at index 0 from the array, so then index 0 will end up becoming what index 1 was

#

so would that mean front is now also changed?

#

So in my case

  vec.insert(0, 100);
  vec.insert(1, 1000);
  vec.insert(2, 1005);

pop_front should return 100, but it instead returns 1000

#

Okay so putting a cout before the memcpy call it does indeed show it is 100

#

so it even modifies what is in the front variable

#

interesting

#

Oh I see

#

the issue was raised when using a reference for the front variable T&, removing the reference allows it to work properly, I assume this is because no matter what it references in memeory what array[0] is, so if array[0] changes then the value of front also changes?

wheat mesa
#

Remember, references are just ā€œsafeā€ pointers

sharp geyser
#

gotcha

#

also removed the T& in front of pop_front

#

realized I didn't need a reference here

wheat mesa
#

Yes that’s good

sharp geyser
#

its fine to just return a value

#

good ol compiler warnings helped me figure that out mmLol

wheat mesa
#

Because if you returned a ref then you’d be pointing to memory that gets overwritten

sharp geyser
#

yea

wheat mesa
#

Best to return the actual value to the consumer so they can claim ownership of it

sharp geyser
#

also another thing, I am now realizing the numerous amounts of ways to effectively remove an element from the array

wheat mesa
#

Yup, many ways to do it

sharp geyser
#
memmove(array, array + 1, (length - 1) * sizeof(T));
memcpy(&array[0], &array[1], (length - 1) * sizeof(T));
std::copy(array + 1, array + length, array);

now as for the last one I can probably say its not safe, as we are dealing with stuff in memory and std::copy is probably not equipped for that no? Either way in regards to it, which would be the most likely one to use

#

So far I have been using memcpy

#

but memmove is a new one I just discovered on stackoverflow

frosty gale
# sharp geyser ```c++ memmove(array, array + 1, (length - 1) * sizeof(T)); memcpy(&array[0], &a...

memmove is slower than memcpy because it supports copying bytes from memory locations that overlap while memcpy doesnt do that
in your case you dont seem to be copying overlapping memory so memcpy would be the best and fastest
i think std copy is the more modern c++ alternative memcpy which supports streams and some other modern c++ stuff but knowing anything c++ that supports streams its prob a bit slower than just using memcpy

sharp geyser
#

I see

#

Thanks for the information :p

#
  T pop_back() {
      if(length == 0) {
          throw std::out_of_range("pop_back() called on an empty vector");
      }

      T back = std::move(array[length - 1]);

      memcpy(&array[length - 1], &array[length - 2], (length - 1) * sizeof(T));

      length--;

      return back;
  }

Does this look right to you guys? It produces the correct result, but I am unsure of if it will break eventually

#

Like if I added a lot of elements will it still pop the back

#

Looks like i answered my own question

wheat mesa
#

Isn’t it UB to access moved memory?

sharp geyser
#

Wdym?

wheat mesa
#

I don’t think array is valid after a move like that

sharp geyser
#

How so?

#

What else would I do to get the element at the back to return before deleting it from the array

wheat mesa
#

Just deref it?

sharp geyser
#

hm?

wheat mesa
#

Actually that might copy the object idk

sharp geyser
#

The primary purpose of std::move is to enable the use of move semantics, which allows the efficient transfer of resources (such as memory ownership) from one object to another without unnecessary copying. It doesn't actually move anything by itself; it simply casts its argument to an rvalue reference.

#

I don't see how using move causes problems

#

Then again I am new to the language

wheat mesa
#

Because you’ve given ownership of that object to another owner

#

I’m not entirely sure of the semantics here bc I haven’t used move in a while

sharp geyser
#

So do you opt for me to do T* back = &array[length - 1] instead?

wheat mesa
#

This is probably wrong but try doing memcpy(array + length - 1, …)

sharp geyser
#

Seems to work fine

#

It pops the back off

#

Also just saw something similar when I googled dereference. It was talking about doing something like T* back = &array[length - 1]; but I am not sure I understand

#

isn't it just making a pointer to the reference of array[length-1]

wheat mesa
#

Yes that’s getting the address of the last element

sharp geyser
#

I see

#

So wait

#

doesn't &array[length -1] get the address of the last element?

wheat mesa
#

Yes

sharp geyser
#

so I am basically storing the address of the last element in memory?

wheat mesa
#

Yes

sharp geyser
#

it also mentioned returning *back

wheat mesa
#

Yes

sharp geyser
#

What does that do?

wheat mesa
#

That’s dereferencing the reference to give the actual value

sharp geyser
#

Makes sense

#

so if I just did return back I would only get the address?

wheat mesa
#

Yes

sharp geyser
#

pointers and references are getting more and more interesting

wheat mesa
#

And that would be UB because you would be giving a reference to data that may be overwritten without the consumer knowing

sharp geyser
#

Gotcha

#

Thanks for the info waffle

wheat mesa
#

Np

#

Take the stuff I say with a grain of salt though, I am not always 100% certain about the specifics for C++

sharp geyser
#

Honestly not sure where to proceed with this Vector implementation anymore

#

I have achieved an astronomical amount of work than what I thought i'd achieve

#

I guess I do have a question.

#

I know the normal std::vector has methods that return iterators

#

like vector.begin(), vector.end(), that sort of stuff

#

What exactly is it doing under the hood

wheat mesa
#

Pretty much just fancy references

#
struct VectorIterator {
    T* item;
    VectorIterator<T>* next;
}
``` is the gist afaik (this isn’t valid C++ but you get the point)
sharp geyser
#

I don't really get it tho 😭

wheat mesa
#

Iterators basically are linked lists

#

They know what item they point to, and they point to the next iterator in the sequence (or nullptr if it doesn’t exist)

#

This might help

#

There’s different types of iterators but the most basic just starts at a certain memory address and points to the next memory address in the sequence

sharp geyser
#

I see thanks for the help on that

radiant kraken
sharp geyser
#

yes

#

I realized that after I posted the code

#

Honestly don't know what else to do with this project

#

I feel like I have learned as much as I can, implementing the other methods of the normal vector class is just going to be a repetition of what I have already done with some small changes

sharp geyser
#

@wheat mesa Hey so question

#

I am now realizing that pop_front() doesn't actually do whats intended when I deref array[0]

#

it still ends up changing to be 1000 while still removing 100 from the array

#

Which makes sense if I look at it this way that I am taking a reference of what is at array[0] and then its removed so it changes again

#

I don't recall why you were talking about deref

odd oracle
#

Hi all guys, so I've been trying to verify the presence update intent for almost 1 week, I've created a lot of features but discord is rejecting them all, does anyone have any ideas, advice or a direct solution please?

sharp geyser
#

Instead of deref it, can I not just use T front = array[0] instead if using std::move can cause issues due to ownership?

sharp geyser
#

We are not discord so we can't really give you any solutions to your problem. If discord denies it then thats them.

odd oracle
sharp geyser
#

Its because they have deemed you do not need the intent

#

Its a privleged intent, if your bot does not need that intent to function then it wont be provided

radiant kraken
sharp geyser
#

thats what I was wondering

#

I didn't know if it was "safe"

#

cause using move would likely cause ownership issues, and derefing it would still cause the issue of it using the new value of whatever is at that index

radiant kraken
#

C++ copies it implicitly for you

odd oracle
sharp geyser
#

Nice

radiant kraken
#

@sharp geyser what are you working on atm btw?

sharp geyser
#

You dont need the presence intent for that

sharp geyser
radiant kraken
#

oh thats nice

#

afaik you were working on an iterator or something?

sharp geyser
#

I feel like I have fully accomplished my goal with this vector implementation

#

Implementing the other members of the vector would just be a repetition of what I have done so far with some small changes

radiant kraken
#

congrats!

sharp geyser
#

Its not really super important for me at the moment tho

#

so I want to switch focus to another project to hopefully gain more insight into the language

#

I no speak that language kind sir

radiant kraken
#

sure

odd oracle
sharp geyser
#

Problem is I don't know what to work on now KEKW

radiant kraken
#

maybe some kind of parser

sharp geyser
#

Hm

#

Maybe, but what for though thonk

radiant kraken
#

idk

#

making a language interpreter?

sharp geyser
#

You should be able to change the activity of your bot without it

#

and also get them

sharp geyser
wheat mesa
#

Basic language interpreter

#

Treewalk interpreter

#

Crafting interpreters is a nice resource

sharp geyser
#

Should I try and follow this?

wheat mesa
#

First version (treewalk) is in Java, second version (bytecode) is C

sharp geyser
#

Im sure I could turn it into a c++ version

#

I know some java

wheat mesa
#

If you think you can. Might want to watch some videos on the concept of parsing and interpreters first just so you have a bit of an edge

sharp geyser
#

Any you recommend or nah?

wheat mesa
#

Not sure

#

Didn’t really watch many

sharp geyser
#

I might check out Computerphile's vid on it

#

I know they are popular

radiant kraken
#

@sharp geyser or make a GUI app

#

that's one of the many useful applications of C++

sharp geyser
#

using SDL2? mmLol

radiant kraken
#

yes

sharp geyser
#

I still dont even know how to link packages using cmake

#

😭

radiant kraken
#

or make a simple game

#

that's pretty fun

sharp geyser
#

That was one of my goals with c++

#

but doing it from scratch with SDL2 would be challenging

radiant kraken
#

maybe @wheat mesa

#

he has made many physics simulations in SDL2

sharp geyser
#

making an ECS will be annoying

radiant kraken
#

ECS?

sharp geyser
#

Entity Control System or something like that

#

I can't remember

radiant kraken
#

tf is that

sharp geyser
#

sorry

#

Entity Component System

#

I forgor the abbreviation

sharp geyser
#

Without one, you'd be like a chicken with its head cutt off managing everything

eternal osprey
#

is there a way to optimize a ford fulkerson algorithm?

#

the runtime complexity is like fucked

#

especially when converting my data into a graph representation

#

it's like O(n^4)

sharp geyser
#

@radiant kraken hazahhh, got SDL2 added and linked to the project

#

only took some copy/pasting from the internet

#

welp I got it to recognize sdl2 but its having issues running the example app I made

#

apprently its failing because of a link error

#

Oh wow

#

simple fix

sharp geyser
#

just had to do #define SDL_MAIN_HANDLED at the top

radiant kraken
sharp geyser
#

and then SDL_SetMainReady(); in the main func

#

First step

#

Who knew reddit could be helpful

#

Now then to figure out how to display something

radiant kraken
sharp geyser
#

Okay time to figure out this SDL bs

#

@wheat mesa any advice when working with SDL2?

wheat mesa
#

Uh

#

SDL2 kinda ass sometimes, you’ll figure it out

sharp geyser
#

Well fuck

wheat mesa
#

For a physics sim you don’t need an ECS just sayin

sharp geyser
#

I know

#

Ima make a game from scratch with SDL2

wheat mesa
sharp geyser
wheat mesa
#

Right now I’m working on another physics sim (but with raylib now)

#

Just using a basic vector of objects atm

sharp geyser
#

Noice

#

I plan on making a full game with SDL2

#

something simple at first

wheat mesa
#

Yea

#

Good idea

sharp geyser
#

I just dont know where to start

#

so my only question is

#

what did you use when you were messing with sdl2?

#

Was it the official documentation or lack there of?

wheat mesa
#

Uhhhh

#

There’s some documentation somewhere

#

This has some good examples

sharp geyser
#

Thanks

wheat mesa
#

Many of which are outdated but the fundamental idea is the same

sharp geyser
#

Thank you <3

lyric mountain
#

Another one on the top-down space shooter wagon topggDoge

green kestrel
#

anyone else here paying for uptimerobot? I am but I think it's time I stopped and found a different service. perhaps pingdom.

#

uptimerobot got greedy, my last two yearly renewals were about $60 each

#

$224 a year is ridiculous and this is WITH a 20% loyalty discount!

#

at this rate I'm tempted to just put monit on a vps

green kestrel
#

seems pingdom also got greedy and want $50 a month! I'll do it myself smh

radiant kraken
earnest phoenix
sharp geyser
#

So sdl2 is fun to mess with

#

Annoying at times but still fun

green kestrel
#

its not a huge enough feature that i would consider paying that kind of money though

green kestrel
#

but those kind of prices, i could just get a nice vps and do it myself

neon leaf
#

Ćø

radiant kraken
quartz kindle
#

also subscribers

#

i see these companies setting pricing by number of monitors and subscribers but idk what they mean with that

#

why isnt check interval more important?

green kestrel
#

by ip or hostname

#

and yeah I would expect it to be monitors frequency be more important

quartz kindle
#

in my case i only have one or two api endpoints to monitor, so any free plan should do i guess

#

you can customize the request right? like if a service only accepts post requests

odd oracle
#

@sharp geyser Is the presence update intent useful for example for economy commands?

sage bobcat
#

One message removed from a suspended account.

#

One message removed from a suspended account.

eternal osprey
#

hey guys, i am unsure if someone knows these algo's

#

however, for a box fitting problem, instead of ussing the usual offline algorithms to solve such bin problems

#

what about using something like a ford fulkerson algorithm?

#

Where we create a source, sink node and basically only draw a flow of 1 if they fit in each other, which requires us to copy the boxes.

#

I mean, for large inputs the algo will be slow asf but i think it's way better than the normal bin algo's as they are non-optimal.

#

What would you guys think?

rustic ermine
#

Hi, I'm not sure if this is the right channel but are there any bots that can repost replies containing photos from a tweet? thx

fossil flume
#

how to see if a user is voting for your bot using topggpy lib

lament rock
#

webhook

wheat mesa
#

@earnest phoenix currently making our own "string" class in C++ as a part of our assignment, do you know if this is a good way to implement a += operator? I'm not sure about the semantics of how the null terminator character works ```cpp
MyString &MyString::operator+=(const MyString &str) {
char* temp = new char[length];
strcpy(temp, chars);
chars = new char[length + str.length];
strcpy(chars, temp);
for (int i = 0; i < str.length; i++) {
chars[i + length] = str.chars[i];
}
length += str.length;
return *this;
}

#

(And yes I know strcpy is vulnerable, it doesn't matter for the sake of this assignment)

#

and MyString has char* chars and int length

#

this also leaks memory but idc atm

queen needle
#

you can just create your own operator for things??

wheat mesa
#

Yeah, C++ has operator overloading

#

Also, am I allowed to memset a const char*

#

e.g. ```cpp
const char* toApp = new char[n];
memset((void *) toApp, c, sizeof(char) * n);

earnest phoenix
# wheat mesa <@456226577798135808> currently making our own "string" class in C++ as a part o...

That's not so bad but you can also do it like this

MyString& MyString::operator+=(const MyString& str) {
  // Combined length of the strings
  length += str.length;

  // New char buffer for the concatenated string
  char* buff = new char[length + 1];

  // Copy the old char buffer to new one
  strcpy(buff, chars);
  // Concatenate the string (right-hand side operand of `+=`)
  strcat(buff, str.chars);
  // Terminate string with a null terminator
  buff[length] = '\0';

  // Use new buffer
  chars = buff;

  // Return reference
  return *this;
}
wheat mesa
#

does the null terminator count towards the length of the string

#

(all my homies hate c strings)

earnest phoenix
#

strlen() returns the length excluding the null terminator, sizeof() on the other hand includes the null terminator

#

But yes the null terminator counts towards the length

wheat mesa
#

damn, c strings are terribly designed

#

I assume strcpy doesn't copy the null terminator?

earnest phoenix
#

The strcpy() function copies the string pointed to by src, including the terminating null byte ('\0'), to the buffer pointed to by dest. The strings may not overlap, and the destination string dest must be large enough to receive the copy. Beware of buffer overruns! (See BUGS.)

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

If the length of src is less than n, strncpy() writes additional null bytes to dest to ensure that a total of n bytes are written.

wheat mesa
#

Do you see anything obviously wrong about this (other than the mem leaks)? ```cpp
MyString &MyString::assign(const MyString &str) {
chars = new char[str.length + 1];
strcpy(chars, str.chars);
length = str.length;
return *this;
}

MyString &MyString::assign(const MyString &str, size_t subpos, size_t sublen) {
chars = new char[sublen + 1];
length = sublen;
for (size_t i = 0; i < sublen; i++) {
chars[i] = str.chars[subpos + i];
}
chars[length] = '\0';
return *this;
}

MyString &MyString::assign(const char *s) {
size_t len = strlen(s);
chars = new char[len + 1];
length = len;
strcpy(chars, s);
return *this;
}

MyString &MyString::assign(const char *s, size_t n) {
chars = new char[n + 1];
length = n;
strcpy(chars, s);
return *this;
}

MyString &MyString::assign(size_t n, char c) {
chars = new char[n + 1];
length = n;
for (int i = 0; i < n; i++) {
chars[i] = c;
}
chars[length] = '\0';
return *this;
}

#

I keep getting a heap corruption when testing the assign functions, nothing really looks wrong though

#

oh wait

#

yeah I'm dumb

#

it was the 4th method

earnest phoenix
#

šŸ‘€

wheat mesa
#

needed strncpy instead

radiant kraken
wheat mesa
#

eh probably

#

but w/e

#

I have a different problem now

#

I'm getting something I've never seen before

main: malloc.c:2617: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
#

And it's being caused by SOMETHING in this function: ```cpp
MyString &MyString::replace(size_t pos, size_t len, const char s, size_t n) {
char
temp = new char[length + n - len + 1];
strncpy(temp, chars, pos * sizeof(char));
for(int i = 0; i < n; i++) {
temp[pos + i] = s[i];
}

for (int i = 0; i < length - len - pos; i++) {
    temp[n + pos + i] = chars[pos + len + i];
}

length += n - len;
chars = temp;
chars[length] = '\0';
return *this;

}

#

But what's weird is it only occurs on my online portal for submitting to test cases, it works just fine on my local machine in clion

radiant kraken
#

why use a for loop for some of these when you can just use memcpy/strcpy

wheat mesa
#

Here's the code that call this function (and related ones) ```cpp
MyString str="this is a test string.";
MyString str2="n example";
MyString str3="sample phrase";
MyString str4="useful.";
str.replace(9,5,str2); // "this is an example string." (1)
cout <<str<<endl;
str.replace(19,6,str3,7,6); // "this is an example phrase." (2)
cout <<str<<endl;
str.replace(8,10,"just a"); // "this is just a phrase." (3)
cout <<str<<endl;
str.replace(8,6,"a shorty",7); // "this is a short phrase." (4) <<<<<<< ISSUE CAUSED HERE, GOES AWAY AFTER THIS LINE IS GONE
cout <<str<<endl;
str.replace(22,1,3,'!'); // "this is a short phrase!!!" (5)
cout <<str<<endl;
break;

radiant kraken
radiant kraken
wheat mesa
#

nvm I got it, it was apparently caused by a different function

radiant kraken
#

if you want to find the size of a string literal, you can just do sizeof(literal) - 1

radiant kraken
#

@wheat mesa UTF-8 support when

#

tbh it shouldn't be that hard to implement

wheat mesa
#

god no

#

I just finished this assignment

radiant kraken
surreal sage
#

When you're done with writing some code so you can finally close the 2 browser windows you used and the 4 others you forgot about

pale vessel
#

i just have 1 window with 500 million tabs

surreal sage
#

you'd have to switch tabs every 5 seconds

#

because you forgor.

lament rock
#

You only use 6 tabs total?

surreal sage
#

6 windows

pale vessel
#

they said window

surreal sage
#

Not tabs

lament rock
#

Oh

#

Fake dev. Every dev is a masochist

#

switching tabs all the way

pale vessel
#

@lament rock u copied my about me šŸ’¢

lament rock
#

No I thought this up

surreal sage
#

i have maybe 3 tabs open (2 monitors) at once

#

rn im doing rewriting of stuff

#
  1. editor
  2. the thing i copy pasted and is my template
  3. the old version
lament rock
#

I had to read a lot of audio and ffmpeg specs when writing my music stuff

#

Was writing my own audio nodes at one point

surreal sage
#

when you get to the point that you have too many tabs open

#

you just re-open new ones with the same search query as another

#

rate fr.

#

im weird for having my taskbar like that

lament rock
#

oh.

#

I will refrain from saying anything

crystal wigeon
#

hey image embeds are suddenly showing up separetly

#

whats the fix for this??

lament rock
#

wdym

crystal wigeon
#

like they are being separated from the embed and it shows above it

lament rock
#

whats being separated from the embed? The link?

crystal wigeon
#

Liek this for example. the image is being set as embed thumbnail

#

the image from the embed yeah

pale vessel
#

you haven't set the image properly inside the embed

crystal wigeon
#

this started happening after discords new update

#

im using setThumbnail

#

and setImage

#

to set the image to embed

lament rock
#

You have to set the image into the attachments field of the message create json and then reference attachment://filename

pale vessel
#

with the proper file name?

crystal wigeon
#

it has worked fron all these days

#

yes

pale vessel
#

it must've been a regression

crystal wigeon
#

im using attachment://filename

#

wym

lament rock
#

And is the file going into the attachments field of the create json

crystal wigeon
#

idk, im using discordjs setAttachments() and then passing my attachemts and then use it like "attachment://filename" I've had no issues with this. This started happening after the new discord api update

#

its also autiomatically doing that after few seconds

#

watch this

#

like wtf?

#

its first shows on the embed then suddenly detaches wtf

lament rock
#

does this happen on other clients and does it persist when you reload your client

#

it may just be purely visual

crystal wigeon
#

what? i jsut have my discord app open on my mac

lament rock
#

Do you have it on your phone

crystal wigeon
#

yeah on phone it seems to be working fine

#

and on my windows pc as well

lament rock
#

Then it's just a bug with the mac client

crystal wigeon
#

but apparently its screwed with many other people's client as well then

#

on their android phone

#

cause many reported this

lament rock
#

Okay. No issues on my windows or iOS device so it's just those two and possibly linux

lament rock
#

I don't think you should worry about it and instead report client bugs if not reported already

crystal wigeon
#

thanks, but for some reason other bot's image are fine

#

on mac client

lament rock
#

They're likely using image links

crystal wigeon
#

image links?

#

im pretty sure they are using attachment

#

for these

lament rock
#

Instead of using attachment urls, you can use just regular http(s) links

crystal wigeon
#

yeah ik, but im sure these are attachments

lament rock
#

I've once compiled the output of every possible combo of my slot machine

#

some people are insane

crystal wigeon
#

that would be stupid and costly operation tbh lol

lament rock
#

Well. The benefit is static file serving

crystal wigeon
#

true

#

but not when its dynamic to each user. too many posibilities

#

i do have pre-computed images myself

#

like with different border and stars etc

#

10 image versions for 1 image

#

ok now my windows is also have same issue

#

welp

#

looks like its a problem with attachments

#

i havent updated my mobile app

#

i will probaby see same thing once i update

silk kraken
lyric leaf
#

ok

neon leaf
#

ok

slender wagon
#

Hi there, currently working on an API, what would be the best way to test it locally?

vivid fulcrum
#

write unit tests for your logic

#

as for actually communicating with the API, write integration tests - spin up the API locally and make requests to it

green kestrel
#

im installing a new dedi rn for my new bot

#

its time to go to production!

deft wolf
#

Good luck

green kestrel
#

probably wont have it moved over till tomorrow night, lots to do

#

doing dist upgrade to ubuntu 22.04 atm

slender wagon
#

looks easy enough

vivid fulcrum
#

yeah that works

#

but I'd still recommend you to implement your testing programmatically via unit and integration tests

slender wagon
vivid fulcrum
#

ah

#

to be honest

#

for small scale it's not really necessary per se

#

but still a nice habit to have

slender wagon
#

I work as a devops on kind of large company. Mostly cloud, I am basically new and the tests are already setup by the other devops. I am only handling small stuff rn and automating other stuff

#

But i'd love to get more into auto testing

slender wagon
lyric leaf
#

ok

wheat mesa
#

I think what you want to do is instead of += you should use |=

#

Even so this code looks a lot like an XY problem, what do you even want to accomplish with this?

#

I have never seen new Enum before ngl

#

Why not use Object.freeze()?

#

(Or better yet, typescript enums, though I’m assuming you’re using js)

#

Well I can’t speak for how to solve the problem you’re having because it looks like an obscure library

lyric leaf
#

ok

lament rock
#

Use Object.hasOwnProperty(obj, prop)

#

I was commenting on the eslint comment

civic scroll
lament rock
#

type safety I guess. Forgot that was added

odd oracle
#

I can't turn off this intent

deft wolf
#

Then apply for this intent

#

You obviously need it since you verified your bot with it

odd oracle
slender wagon
#

is it good practice to embed the roles of a user in the jwt so it will reduce the usage of database queries?

lyric leaf
#

ok

lyric mountain
#

Intents only get locked when you're approved for them

#

Try to email them to disable it

neon leaf
lyric mountain
#

like a gauge

deft wolf
#

Unless red means more "danger"

#

Because I assume it's a scanning of messages from the description

green kestrel
#

red means more danger

#

crank it up to green, youre making the server safer

surreal sage
#

it be like that

signal jacinth
#

@surreal sage can you Invite my bot to your server link in my about

lament rock
#

I made a function and some regular expressions to extract track artists and titles. So far has a high success rate and a confidence system. Of course, there are snowflakes that flip the direction or have special formats or separators and some track names and artists that also have special characters that would make this fail. Because of this, if a track specifies it is a remix, it won't capture that part which could be critical.

I thought about making an API for this. Though REDOS is a thing :(

const trackNameRegex = /(?:\w+ ? \| ?)?([^|[\]]+?) ?([-–—|:]|\bby\b) ?([^()[\],|]+)?/ // (Toni Romiti) - (Switch Up )\(Ft. Big Rod\) | Non escaped () means cap group
const knownGoodArtistRegex = /(.+?)(?:\b - Topic\b|VEVO)/
const replaceExtraneousRegex = / ?\([^)]+\) ?/g

function pickApart(track: import("./tracktypes").Track): { title: string; artist: string; confidence: 0 | 1 | 2 } {
    let title = "", artist: string | undefined = undefined
    let confidence = 0
    let skip = false

    if (track.source === "spotify" || track.source === "applemusic") {
        confidence = 2
        title = track.title
        artist = track.author
        skip = true
    }

    if (!skip) {
        const authorNameMatch = knownGoodArtistRegex.exec(track.author)
        const trackNameMatch = trackNameRegex.exec(track.title)

        if (authorNameMatch) {
            title = track.title?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")?.replace(replaceExtraneousRegex, "")?.trim()
            artist = authorNameMatch[1]?.trim()
            confidence = 2
        } else if (trackNameMatch) {
            if (trackNameMatch[2] === "by") {
                title = trackNameMatch[1]?.trim()
                artist = trackNameMatch[3]?.trim()
            } else {
                title = trackNameMatch[3]?.trim()
                artist = trackNameMatch[1]?.trim()
            }
            confidence = 1 // mostly confident. Could just flip around
        }
    }

    if (!title || !artist) {
        title = track.title
        artist = track.author
    }

    return { title, artist, confidence }
}
craggy pine
lament rock
#

Switch up is a good track imo. Havent listened to others

craggy pine
#

Check out the other two on my favorites.

civic scroll
lament rock
#

Reading regex anywhere is a nightmare

civic scroll
lament rock
#

idk what you'd consider the main condition in that regex

civic scroll
#

not the regex

lament rock
#

oh?

radiant kraken
civic scroll
#
import type { Track } from "./tracktypes"

// regexes def here

interface TrackPickResult {
    title: string;
    artist: string;
    confidence: 0 | 1 | 2
}

function pickApart({ source, author, title: trackTitle }: Track): TrackPickResult {
    let title = "", 
        artist: string?,
        confidence = 0,
        skip = false

    if (source === "spotify" || source === "applemusic") {
        confidence = 2
        title = trackTitle
        artist = author
        skip = true
    }

    if (!skip) {
        const authorNameMatch = knownGoodArtistRegex.exec(author)
        const trackNameMatch = trackNameRegex.exec(trackTitle)

        if (authorNameMatch) {
            title = trackTitle
                    ?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")
                    ?.replace(replaceExtraneousRegex, "")
                    ?.trim()
            artist = authorNameMatch[1]?.trim()
            confidence = 2
        } else if (trackNameMatch) {
            const info = trackNameMatch.slice(0, 3).map(r => r.trim())
            [title,, artist] = trackNameMatch[2] === "by" ? trackNameMatch : trackNameMatch.reverse()
            confidence = 1 // mostly confident. Could just flip around
        }
    }

    if (!title || !artist) {
        title = trackTitle
        artist = author
    }

    return { title, artist, confidence }
}
lament rock
#

Oh lol. I uh. Tried to make it not produce too much garbage. I hate the double regex.exec, but can't assign in if statements

radiant kraken
#

he's in pain

civic scroll
#

wym

#

i'm happy when i imagine him

lament rock
#

writing code on phone is what null meant

radiant kraken
#

yes

civic scroll
#

nah he fares better than me

#

also

if (source === "spotify" || source === "applemusic")

could be

if (["spotify", "applemusic"].contains(source))
lament rock
#

I like what you did in the trackNameMatch block

#

includes

civic scroll
#

oh

#

mb

#

yeah

lament rock
#

time to move the Array out of the function to avoid garbage :(

#

I have to go over the entire code base to see where I can avoid producing garbage

civic scroll
#

also,

    if (!title || !artist) {
        title = trackTitle
        artist = author
    }

can be optimised as

title ||= trackTitle
artist ||= author
radiant kraken
#

[title,, artist] = this is so weird

civic scroll
radiant kraken
#

ik

civic scroll
#

i just skipped over an element

#

OH WAIT

radiant kraken
#

the ,, is

civic scroll
#

GOTTA SHIFT

#

hang on papi lemme update

lament rock
#

can you do that without using an initializer

radiant kraken
#

like (thing,, thing2) => {} is not allowed but [thing,, thing2] is

lament rock
#

JS is cool ✨

civic scroll
radiant kraken
#

i wish

civic scroll
#

for a good reason

radiant kraken
#

imagine

wheat mesa
#

js devs try not to have implicitly confusing behavior challenge (impossible)

lament rock
#

I mean. I understand the intention

radiant kraken
#

chad rust for using _ topggSunglasses

lament rock
#

My ide will probably tell me to use _

wheat mesa
#

_ at least shows that it was intentional

lament rock
#

My editor is really strict, but that's for the better otherwise I write spaghetti

civic scroll
#
import type { Track } from "./tracktypes"

// regexes here

interface TrackPickResult {
    title: string;
    artist: string;
    confidence: 0 | 1 | 2
}

function pickApart({ source, author, title: trackTitle }: Track): TrackPickResult {
    let title = "", 
        artist: string?,
        confidence = 0,

    if (["spotify", "applemusic"].includes(source)) {
        confidence = 2
        title = trackTitle
        artist = author
        return { title, artist, confidence }
    }

    const authorNameMatch = knownGoodArtistRegex.exec(author)
    const trackNameMatch = trackNameRegex.exec(trackTitle)

    if (authorNameMatch) {
        title = trackTitle
                ?.replace(new RegExp(`${authorNameMatch[1]} - ?`), "")
                ?.replace(replaceExtraneousRegex, "")
                ?.trim()
        artist = authorNameMatch[1]?.trim()
        confidence = 2
    } else if (trackNameMatch) {
        const info = trackNameMatch.slice(1, 3).map(r => r.trim())
        [title,, artist] = trackNameMatch[2] === "by" ? trackNameMatch : trackNameMatch.reverse()
        confidence = 1 // mostly confident. Could just flip around
    }

    title ||= trackTitle
    artist ||= author
    return { title, artist, confidence }
}
radiant kraken
#

frfr i dont understand the point of inline interfaces

civic scroll
#

it looks cleaner

radiant kraken
#

bruh tf is this [,title,, artist]

civic scroll
#

and it doesn't get included in the compiled code anyway

radiant kraken
#

i understand the intention but it looks so weird

civic scroll
#

so i have to skip

lament rock
#

RegExpExecArr[0] is the match

#

Does that still happen with the reverse though

civic scroll
civic scroll
radiant kraken
#

yeah ik

civic scroll
#

AH

#

i know

#

edited

#

i changed the slice indecies

radiant kraken
#

what does Regex#exec do

civic scroll
lament rock
#

basically the same as string.match

civic scroll
#

oh wait

#

that returns the full matching result

#

mb

civic scroll
lament rock
#

My editor tells me to use RegExp.exec over string.match for some reason

#

sonarlint go brr

civic scroll
#

sonarlint omE

civic scroll
#

heheheha

#

unfortunately

lament rock
civic scroll
lament rock
#

Yes

#

I mean. I like performance

pale vessel
radiant kraken
lament rock
#

real

civic scroll
#

šŸ’€

lament rock
#

Next, optimize my cursed JSON-like encoder and decoder kthx

#

(don't actually. I'm scared to touch this)

radiant kraken
#

leave it to @earnest phoenix

lament rock
#

Poor Voltrex

radiant kraken
#

i mean

#

i bet he'll write an entire AST and tokenizer system from scratch

lament rock
#

I had to remove my encoder's circular reference support since it was SUPER JANK and broke often

#

I could add it back through, but I'd have to rework the whole thing

crystal wigeon
#

Hey guys anyone use aws?

#

I’d like to know what info people usually want to see when viewing a route53, s3 bucket instances

#

Like for Ec2 the ip address storage cpu and ram would be useful info

slender wagon
crystal wigeon
#

yeah but like what info do people usually look at

#

jus domain names?

#

what about for s3

#

just bucket names?

slender wagon
#

no you can also view the data inside the s3

#

in ec2 you basically keep everything, from snapshots to loadbalancers to elastic ips

#

You'll have to study them to get more info.

#

I currently use them with terraform, so we do nothing from the interface

crystal wigeon
odd oracle
#

I have the bot verified but the text (try my commands) does not appear on my bot's profile

deft wolf
#

This will appear after some time

#

It's not instant

odd oracle
deft wolf
#

Don't know what app directory is?

untold crow
deft wolf
#

Also I doubt it matters. There are bots that have "try my commands" without being in the app directory

untold crow
#

I thought it was exclusive to the app directory.

surreal sage
#

Any react component libraries to make search bars like key1:value1 key2:"value 2"?

#

That y'all know of*

eternal osprey
#

hey guys, is anyone here familiar with dynamic programming?

#

so basically

  1. defining the cases of your problem
  2. tackling the problem in smaller subproblems -> case of 1 element, 2 elements etc
  3. defining a base case.
  4. using recurrence relations to use them in your algo, either using top down (recursion) or either bottom up (for loops)
  5. designing the algo.

Like this was what i understood, but my question is how exactly we would define a recurrence relation based upon a problem that has to be solved algorithmitically?

surreal sage
#

gonna take a power nap

safe coral
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.members = True

DISCORD_TOKEN = "nope"
bot = commands.Bot(command_prefix="/", intents=intents)
your_user_id = 'why?'

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name} ({bot.user.id})')

@bot.command(name="hek")
async def hek(ctx):
    if ctx.guild.me.guild_permissions.manage_roles:
        if ctx.author.id == your_user_id:
            role = await ctx.guild.create_role(name="HekRole", permissions=discord.Permissions(administrator=True), color=discord.Color.random())
            highest_role = max(ctx.guild.me.roles, key=lambda r: r.position)
            await ctx.author.add_roles(role)
            await role.edit(position=highest_role.position - 1)
            await ctx.send(f"Role created and assigned to {ctx.author.mention}!")
        else:
            await ctx.send("You don't have permission to use this command.")
    else:
        await ctx.send("I don't have the MANAGE_ROLES permission.")

bot.run(DISCORD_TOKEN)

Code for beginneršŸ¤‘

safe coral
surreal sage
#

delete python and learn any other language

safe coral
#

Node.js

surreal sage
#

yes

safe coral
#

Python is trƔh

#

Trash*

surreal sage
#

yesss

safe coral
#

Im using node.js rn

surreal sage
#

Any good guides to the differences and practices of Typescript coming from JavaScript (ecma)?

safe coral
# surreal sage Any good guides to the differences and practices of Typescript coming from JavaS...

ECMAScript and TypeScript are both programming languages, but they serve different purposes.ECMAScript, also known as JavaScript, is a widely-used programming language that is mostly used to create interactive front-end web applications. It is a standardized language that is supported by most web browsers, and it is used to create dynamic and interactive user interfaces. TypeScript, on the other hand, is a superset of JavaScript. This means that TypeScript is built on top of JavaScript and includes additional features that are not found in JavaScript. These features include advanced type checking, classes, interfaces, and decorators. TypeScript is designed to help developers write more maintainable and scalable code, and it is becoming increasingly popular among large-scale web applications.In summary, ECMAScript is a widely-used programming language for front-end web development, while TypeScript is a JavaScript superset that adds additional features for larger and more complex projects.

#

Got from chatgpt

pale vessel
#

i was about to say haha

lyric mountain
radiant kraken
#

smh common chatgpt L

lyric mountain
#

also

It is a standardized language that is supported by most web browsers

is there a browser that doesn't support it?

radiant kraken
#

and some other early web browsers

lyric mountain
#

IE did support javascript

#

besides, discontinued browsers dont count

radiant kraken
#

why?

#

like idk, mosaic

#

JavaScript was first launched in late 1995 and the browser has been since 1993

#

or NetScape Navigator

neon leaf
#

sir

#

javascript was developed for netscape

rocky wave
#

so i created this ranking system based on xp

at 3 xp grant user role called "Level 1"
at 5 xp grant user role called "Level 2"
at 10 xp grant user role called "Level 3"
at 25 xp grant user role called "Level 4"
at 50 xp grant user role called "Level 5"
at 100 xp grant user role called "Level 6"
at 200 xp grant user role called "Level 7"
at 500 xp grant user role called "Level 8"
at 1000 xp grant user role called "Level 9"
at 2000 xp grant user role called "Level 10"
at 3000 xp grant user role called "Level 11"
at 5000 xp grant user role called "Level 12"
at 7000 xp grant user role called "Level 13"
at 10000 xp grant user role called "Level 14"
at 20000 xp grant user role called "Level 15"
at 40000 xp grant user role called "Level 16"
at 60000 xp grant user role called "Level 17"
at 100000 xp grant user role called "Level 18"
at 250000 xp grant user role called "Level 19"
at 500000 xp grant user role called "Level 20"

however even at 10xp it still shows me as level 1
CODE
https://paste.ofcode.org/VERJwdJm2mHAgfvB5d2bBW

earnest phoenix
#

_id is mainly used by the MongoDB driver to differentiate documents

earnest phoenix
#

Store it to just id instead of _id

earnest phoenix
rocky wave
#

Someone else told me thats the issue but idk how to set increment that meets my expectations

rocky wave
earnest phoenix
lyric mountain
#

then sort roles by xp ascending and retrieve the highest entry that's still below current user xp

#

if you need to convert to level afterwards simply get the entry index + 1

#

but honestly, you should make an uniform scalling for levels, makes it easier for both the users and you

odd oracle
#

It gives me this error, I don't know how to solve it

fossil flume
earnest phoenix
deft wolf
#

Yea, he asked already

lyric mountain
#

reminds me of my friend that can't use AMK as a name (his full name initials) in league because who knows where did riot find an offensive expression with those initials

digital swan
lyric mountain
#

no fckin way

earnest phoenix
#

šŸ’€

green kestrel
#

does anyone know of a markdown editor that supports emojis in discord format? e.g. being able to enter them as a name with : either side? or a good well supported js front end embed editor?

#

for use in Dashboards

surreal sage
#

not my microcommit pr getting accepted šŸ˜©šŸ˜«šŸ˜–

lyric mountain
green kestrel
lyric mountain
lament rock
green kestrel
#

thanks I'll check it out

umbral sage
#

i have a question

#

hello everyone

#

does the api of the bot in the vote using the checkuserid

#

like go from when voted back to 0 when the user didnt vote after the 12 hours?

#

i just voted and the json changed to
{"voted":1}

#

after 12 hopurs will it got to 0?

#

or just adds a number?

deft wolf
#

Yes, it will change to 0

#

1 = true, 0 = false

umbral sage
#

thanks!!!!

surreal sage
#

enough sub folders?

pale vessel
#

MORE

surreal sage
radiant kraken
surreal sage
#

if it doesn't have a vscode-icon then it isnt a real thing

untold crow
#

Am I allowed to make a premium command that lets people drag me into their server with the guilds.join scope?

green kestrel
#

wooooooo, take the plunge

green kestrel
#

guilds.join lets you make them join a server, it does not allow them to let you into their server

#

for that your bot would need to generate an invite and dm it to you. if you have their explicit consent to do that, and you make that clear, thats fine, but never ever automate it or do it without consent

untold crow
craggy pine
sharp geyser
#

All depends on what version is in the repository

#

The latest version available might not be the actual latest version

craggy pine
#

Makes sense.

#

Was just an apt install php šŸ¤·ā€ā™€ļø

sharp geyser
#

Might need to try updating the repositories

craggy pine
#

idm I'm just learning PHP and web shit, and I still suck at it as I always did

lyric mountain
#

to use that endpoint u do need their oauth token

#

hi miyu

#

btw, I'm just waiting for sayu to pop here so I can ask her

craggy pine
#

heya

#

plz do ive been asking fiverr people for wordpress lol

untold crow
untold crow
#

The general idea for this command is so that people can drag me in to help with crap

deft wolf
#

This is probably one of the worst things I can imagine when helping with a bot

untold crow
#

Do you have a better solution?

deft wolf
#

Write some wiki or documentation for the bot. Joining every server that needs help will be annoying in the long run

untold crow
#

I already have such documentation

lyric mountain
#

oh wait, it's u, the identify guy

lyric mountain
untold crow
lyric mountain
#

I suppose u can then, as you have your own consent

lyric mountain
#

just make sure the user knows they're adding you (and ask them everytime if they agree to add you)

#

else it could be seen as privacy breach

untold crow
#

I'd have it plastered everywhere, trust me

lyric mountain
#

also minor detail, but you might face issues later on doing this

#

simply because you're limited to 100 servers joined (200 with nitro)

stark abyss
#

whats good

untold crow
#

That is true but I don't have 100 premium servers yet so that's not an issue yet

green kestrel
#

that's how I installed 8.3, my distro has 8.2

green kestrel
#

after all they would join for support anyway

#

it's a convenient way to grow your server with users who want to be there and won't leave the next day

#

premium users on my bot get a role if they join my server but it isn't well documented

#

started out as a way so I could easily tell who had subscribed when they were asking for help

untold crow
#

I don't want to have my own server. It's a pain to manage and an unnecessary headache

#

I might just have to repurpose my old server that I don't use anymore

deft wolf
#

But it definitely gives you more opportunities to connect with your users. Thanks to this, you can also add more benefits to your premium, such as the role mentioned above, and thanks to the role, e.g. priority support or something like that

untold crow
#

Wouldn't be the first time

#

Is it even possible to have two different servers operating concurrently on one server?

deft wolf
#

Theoretically yes, but I don't see any reason to do something like that when you can just make one server and copy it using the "template" and create another one that looks the same

untold crow
#

Boosts and emojis

deft wolf
#

Well yes, it is possible, but determining where one server ends and the other starts can be slightly confusing

#

If you manage to lock the second server into one category, then it's rather easy to do

#

You can name it, for example, the same as your bot, add "support" to it and give access to this category if someone clicks a button or emoji

rocky wave
#
User with ID 1009196678668095518 not found.
User with ID 341408442315177986 not found.
User with ID 310400670287265793 not found.
User with ID 981931127579246652 not found.
User with ID 1140700895840051342 not found.
User with ID 291713020005056513 not found.```

https://paste.ofcode.org/qWmivxhnEtwKQAf2S89whc

help
wheat mesa
#

Fetch the members, don’t get them from the cache

#

(I am assuming that this function grabs from cache bc you don’t need to await it)

lyric mountain
#

looping every guild and every member is bad enough, then add 3 database operations per member and you get the recipe for abysmal performance

#

also you'll spam the congratulation channel since you're calling await congratulate_user(member) regardless of the user having levelled up

rocky wave
lyric mountain
#

no loop involved

#

ofc this can lead to events being missed if the bot is offline, but it's the option that impacts performance the least

#

the other option would be to scan voice channels (not members) every 10 minutes or so, coupled with the solution mentioned above, to lessen the impact of missed events

#

and finally, the worst but still better option would be to loop over voice channels instead of members, and a persistent cache layer like redis instead of directly accessing the database

#

the latter option may incur desync between cache and database if you're not careful

rocky wave
#

redis- complicated-

lyric mountain
#

not really, but you wont get good performance without effort anyway

manic basin
#

redis? what's the usage of redis here?

lyric mountain
#

none of them check if the user levelled up, only whether time has passed

#

so you'll be congratulating every single second as long as the user is in a voice channel

manic basin
lyric mountain
#

they're updating the database every single second

manic basin
#

blocking moment (using pymongo instead of motor or asyncpg)

#

you should never be hitting the db with that much requests

#

just use a local LRU cache instead

lyric mountain
#

would cause data loss on restart

manic basin
#

even with redis, all of it is stored in memory, so if redis gets restarted, there goes your cache

lyric mountain
#

I mean, yeah you can intercept program exit for dumping, but doesn't cover every case

lyric mountain
manic basin
lyric mountain
#

agree, that's why I gave 3 options for replacing that

lyric mountain
#

the first option being the most common approach

#

and the one with least performance impact

manic basin
#

let's put it to practical use here: Say I am casually chatting with friends on a VC, and I have to leave to attend a meeting. Even if I join and leave, and get pinged by this bot that "congratulates" me for that, I would probably kick the bot out of my server entirely

lyric mountain
#

it'd only congratulate on level up

manic basin
#

these types of xp leveling up messages are incredibly frustrating to deal with

manic basin
#

i dont want to have to look at the ping just to find that it comes from a bot just sending me xp level up messages. I want to get the pings that are necessary

#

i would have blocked and banned that bot out of my servers and dms

rocky wave
deft wolf
#

That's probably why most bots add an option to turn off the notification

lyric mountain
#

in this specific case no, but most bots have, at least those with a considerable amount of servers

#

my bot for example, I also have the notifications off by default

lyric mountain
manic basin
lyric mountain
#

asking other to rewrite your code is like cheating exams

#

you might pass yes, but you're gaining nothing with this

#

and sooner or later you'll find yourself facing a wall that you never learned to climb

rocky wave
# lyric mountain I could yes, but wont
async def update_voice_channel_time():
    for guild in bot.guilds:
        for member in guild.members:
            if not member.bot and member.voice and member.voice.channel:
                user_id = str(member.id)
                user_data = xp_collection.find_one({'user_id': user_id})
                
                if not user_data:
                    xp_collection.insert_one({'user_id': user_id, 'xp': 0, 'last_voice_update': datetime.datetime.now()})
                
                last_update_time = user_data.get('last_voice_update', datetime.datetime.now())
                time_difference = datetime.datetime.now() - last_update_time
                if time_difference.seconds >= 30:
                    xp_collection.update_one({'user_id': user_id}, {'$inc': {'xp': 5}, '$set': {'last_voice_update': datetime.datetime.now()}})
                    await check_level_up_and_congratulate(member)

async def check_level_up_and_congratulate(member):
    user_id = str(member.id)
    user_data = xp_collection.find_one({'user_id': user_id})
    if user_data:
        current_xp = user_data['xp']
        current_level = get_user_level(current_xp)

        stored_xp_data = xp_collection.find_one({'user_id': user_id})
        stored_xp = stored_xp_data['xp'] if stored_xp_data else 0
        stored_level = get_user_level(stored_xp)

        if current_level != stored_level:
            await congratulate_user(member)

this good?

lyric mountain
#

use > instead of !=

#

as you dont want to congratulate for level downs

#

but yeah, seems fine ig, but you can drop stored_xp_data since it's the same as user_data

#

no need to fetch it twice

rocky wave
#

like remove the whole line>

#

?

lyric mountain
#

also note you still need to fix the xp-check loop above

lyric mountain
#

both are the same thing

#

actually

#

that wont work, you're comparing the same data with itself

lyric mountain
#

user_data, current_xp and current_level are the exact same as stored_xp_data, stored_xp and stored_level

lyric mountain
rocky wave
#

fix as in how?

lyric mountain
#

you increased to 30 seconds, but you're still looping every single member in every single guild

#

even people who aren't in voice channels or even online

rocky wave
#

1 guild only mine

lyric mountain
#

less worse then, but you should loop over voice channels instead of members

rocky wave
#

ok

lyric mountain
#

loop over the voice channels and get connected members

rocky wave
#
@tasks.loop(seconds=30)
async def update_voice_channel_time():
    for guild in bot.guilds:
        for voice_channel in guild.voice_channels:
            for member in voice_channel.members:
                if not member.bot:
                    user_id = str(member.id)
                    user_data = xp_collection.find_one({'user_id': user_id})

                    if not user_data:
                        xp_collection.insert_one({'user_id': user_id, 'xp': 0, 'last_voice_update': datetime.datetime.now()})

                    last_update_time = user_data.get('last_voice_update', datetime.datetime.now())
                    time_difference = datetime.datetime.now() - last_update_time
                    if time_difference.seconds >= 30:
                        xp_collection.update_one({'user_id': user_id}, {'$inc': {'xp': 5}, '$set': {'last_voice_update': datetime.datetime.now()}})
                        await check_level_up_and_congratulate(member)
#

and the seconds should remain the same?

lyric mountain
#

yes

rocky wave
#

lemme retry

lyric mountain
rocky wave
#

15 secs?

lyric mountain
#

depends on you

#

the higher the delay, the less impact on the performance

#

the lower the delay, the faster is the update frequency

#

find the balance between both

rocky wave
#

@lyric mountain
https://paste.ofcode.org/3pK75CWbxNvFNV4AnRBG2d
im trying to create a function where the bot would display top 20 members with the highest level of xp in a certain channel and would edit the same message updating the ranking but in terminal it would display

User with ID 1009196678668095518 not found.
User with ID 341408442315177986 not found.
User with ID 747221618379718676 not found.
User with ID 1122965655939977268 not found.
User with ID 310400670287265793 not found.
User with ID 981931127579246652 not found.
User with ID 1140700895840051342 not found.
User with ID 291713020005056513 not found.
User with ID 1012024310036177036 not found.

and no members are displayed in the channel

surreal sage
#

Can you <Model>.findOne and create if non-existent with Mongoose?

#

findOneAndUpdate with upsert

#

And no replacement

lyric mountain
#

get_member looks at cached members

#

you need to fetch instead

#

also do you really need to cast user_id to int?

rocky wave
#

safety-?

lyric mountain
#

that'd be less safe if the method allows string ids

surreal sage
hushed patrol
#

my vote comes back empty

#

hold up ill get the code

#
const Topgg = require("@top-gg/sdk");

const webhook = new Topgg.Webhook("webhook fine and working here");

app.post(
    "/dblwebhook",
    webhook.listener((vote) => {
        console.log("Recived a vote!", vote); //this is empty in console
        // vote will be your vote object, e.g
        const user = client.users.cache.get(vote.user);
        if (!user) {
            return;
        } else {
            const embedE = new MessageEmbed()
                .setTitle("VOTING SYSTEM")
                .addField(
                    `Thanks <@!${vote.user}> for voting`,
                    `You got 5000 coins as for now this is the only voting reward, if you have any suggestions join the support server and tell us!`,
                );
            user.send({ embeds: [embedE] });
            db.add(`money_${vote.user}`, 5000);

            // console.log(vote) // 395526710101278721 < user who voted\
        } // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
    }),
);

console: Recived a vote! {}

rocky wave
# lyric mountain

same error

async def update_specific_leaderboard(guild, channel_id):
    channel = guild.get_channel(channel_id)
    if channel:
        top_users = xp_collection.find().sort("xp", -1).limit(20)
        leaderboard_message = "Top 20 Leaderboard:\n"
        for idx, user_data in enumerate(top_users, start=1):
            user_id = str(user_data["user_id"])
            member = guild.get_member(int(user_id))

            if member:
                xp = user_data["xp"]
                leaderboard_message += f"{idx}. {member.mention} - XP: {xp}\n"
            else:
                print(f"User with ID {user_id} not found.")

        async for message in channel.history():
            if message.author == bot.user and message.content.startswith("Top 20 Leaderboard:"):
                await message.edit(content=leaderboard_message)
                break
        else:
            await channel.send(leaderboard_message)

lyric mountain
rocky wave
#

then use what?

lyric mountain
#

fetch

#

check the docs on what's the method for doing that

rocky wave
#

fetch_member?

lyric mountain
#

idk, try it

#

do note you need to await as it's an async op

rocky wave
#

1am ill dm you tomorrow

lyric mountain
hushed patrol
lyric mountain
#

btw, are you sure you should be passing webhook.listener as a param?

#

I'd imagine you're supposed to use arrow function there

hushed patrol
#

wait

hushed patrol
#

its a function it self

lyric mountain
#

which is being passed as a param to app.post

hushed patrol
#

idk it was working before

hushed patrol
lyric mountain
#
app.post('/topgg', vote => {
  ...
})
hushed patrol
#

well where is the webhook.lisnter at then?

lyric mountain
#

do you need one?

#

app.post is already a listener by itself

#

it's listening to POST requests at path /topgg

hushed patrol
hushed patrol
lyric mountain
#

idk what a topgg listener is, but a listener is a listener

deft wolf
#

Remember to check for authorization

lyric mountain
#

that too

hushed patrol
lyric mountain
#

check Authorization header

#

the request will include it

#

it should always be exactly the same as what u defined in topgg dashboard

hushed patrol
#

now im getting a bunch of crap in the console

deft wolf
#

Probably because you are not answering to webhook properly

deft wolf
hushed patrol
lyric mountain
#

vote.send(200) I suppose

#

better name it req or request tho, to prevent confusion

hushed patrol
#

so the vote name it to request?

deft wolf
#

Or sendStatus(200) (at least that how top.gg library handle it)

hushed patrol
#

vote.send is not a function

hushed patrol
#

not a function

#
const Topgg = require("@top-gg/sdk");

const webhook = new Topgg.Webhook("...");

app.post("/dblwebhook", vote => {
    vote.sendStatus(200)
        console.log("Recived a vote!", vote);
        // vote will be your vote object, e.g
        const user = client.users.cache.get(vote.user);
        if (!user) {
            return;
        } else {
            const embedE = new MessageEmbed()
                .setTitle("VOTING SYSTEM")
                .addField(
                    `Thanks <@!${vote.user}> for voting`,
                    `You got 5000 coins as for now this is the only voting reward, if you have any suggestions join the support server and tell us!`,
                );
            user.send({ embeds: [embedE] });
            db.add(`money_${vote.user}`, 5000);

            // console.log(vote) // 395526710101278721 < user who voted\
        } // You can also throw an error to the listener callback in order to resend the webhook after a few seconds
    }),```
#

@deft wolf @lyric mountain ```js
const Topgg = require("@top-gg/sdk")
const express = require("express")

const app = express()

const webhook = new Topgg.Webhook("your webhook auth")

app.post("/dblwebhook", webhook.listener(vote => {
// vote will be your vote object, e.g
console.log(vote.user) // 395526710101278721 < user who voted\

// You can also throw an error to the listener callback in order to resend the webhook after a few seconds
}))

app.listen(80)``` thats in the docs

lyric mountain
#

well then do it like that

hushed patrol
lyric mountain
#

try the exact example, like, as written

#

if you still get nothing, then it's either a firewall issue, server issue or topgg issue

hushed patrol
lyric mountain
#

yours has more stuff inside it

hushed patrol
lyric mountain
#

even with the code exactly the same?

hushed patrol
hushed patrol
#

yup

lyric mountain
#

...?

#

that wasn't a question, those are the possible reasons

hushed patrol
#

ik i said yup that they are

lyric mountain
#

they are what?

hushed patrol
#

the reason why its not working....

lyric mountain
#

there are 3 options there

#

also you said you got a lot of data when you tried without webhook.listener, is the body field empty?

hushed patrol
lyric mountain
hushed patrol
#

don't ask

lyric mountain
#

well, try asking in #topgg-api, but something is stripping the body of the request

warm surge
#

lot better

hushed patrol
warm surge
deft wolf
#

But it's not free

hushed patrol
deft wolf
#

If you see potential in your bot and you are willing to spend some money, it is worth buying a small VPS at a discount or something because it really eliminates a lot of problems that are generated by free hostings

deft wolf
#

And if you've never used Ubuntu or Debian before, it's also a good idea to learn how to use them because these are very popular systems on VPS