#voice-chat-text-0

1 messages · Page 228 of 1

high mantle
#

`import datetime

users_queue = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel = ["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"]

ready_users = []
not_ready_users = []
for member in voice_channel:
if member in users_queue:
ready_users.append(member)
else:
not_ready_users.append(member)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
`

mystic lily
#
voice_channel = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = users_queue.intersection(voice_channel)
not_ready_users = voice_channel.difference(users_queue)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
rapid chasm
high mantle
#

In Python, a set is created using curly braces {}.

mystic lily
#
voice_channel = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

not_in_queue = set(voice_channel) - set(users_queue)

print("Users in Voice Channel but Not in Queue:", not_in_queue)```
high mantle
eager thorn
#

!e

set_example = set(["This", "is", "a", "set"])
print(set_example)

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

{'set', 'This', 'a', 'is'}
high mantle
#

@mystic lily congrats !

eager thorn
#

!e

import time

start_time = time.time()

set_example = set(["This", "is", "a", "set"])
print(set_example)

end_time = time.time()

execution_time = end_time - start_time

print(f"The execution time is {execution_time} seconds")

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | {'set', 'a', 'This', 'is'}
002 | The execution time is 0.00020313262939453125 seconds
mystic lily
#

!e

users_queue = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Get the users in both queue and voice_channel
in_queue_and_in_voice_channel = set(users_queue) & set(voice_channel)

# Get the users only in the queue
only_in_queue = set(users_queue) - set(voice_channel)

# Get the users only in the voice channel
only_in_voice_channel = set(voice_channel) - set(users_queue)

print("Users in both Queue and Voice Channel:", in_queue_and_in_voice_channel)
print("Users only in Queue:", only_in_queue)
print("Users only in Voice Channel:", only_in_voice_channel)

wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Users in both Queue and Voice Channel: {'User5', 'User10', 'User6', 'User8', 'User2'}
002 | Users only in Queue: {'User9', 'User4', 'User3', 'User7', 'User1'}
003 | Users only in Voice Channel: {'User44', 'User96', 'User75'}
#

@high mantle :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Ready Users: ['User10', 'User2', 'User5', 'User5', 'User6', 'User8', 'User10']
002 | Not Ready Users: ['User44', 'User75', 'User96']
eager thorn
#

!e

import timeit

start_time = timeit.default_timer()

set_example = set(["This", "is", "a", "set"])
print(set_example)

end_time = timeit.default_timer()

execution_time = end_time - start_time

print(f"The execution time is {execution_time} seconds")

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | {'a', 'is', 'set', 'This'}
002 | The execution time is 0.0002896131481975317 seconds
rapid chasm
#
import datetime

users_queue = ["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"]
voice_channel = ["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"]

# Separate users into "Ready" and "Not ready"
ready_users = []
not_ready_users = []
for member in set(voice_channel):
    if member in set(users_queue):
        ready_users.append(member)
    else:
        not_ready_users.append(member)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
mystic lily
#
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set.intersection(voice_channel_set))
not_ready_users = list(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
eager thorn
#

Time for first code snippet: 0.2325702999951318
Time for second code snippet: 0.2009637000010116

mystic lily
#
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = set(users_queue_set.intersection(voice_channel_set))
not_ready_users = set(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
eager thorn
#

execution Time: 0.202438100008294

#

execution Time: 0.045195496175438166

left drum
#

I got RAT'ted yesterday 💀

#

I deleted the registry files for the RAT, should I be safe?

eager thorn
#

Execution time: 0.0023366520181298256 seconds

idle vector
#
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = tuple(set(users_queue_set.intersection(voice_channel_set)))
not_ready_users = tuple(set(voice_channel_set.difference(users_queue_set)))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
#

try this

#

@eager thorn

rapid chasm
lethal tiger
#

hello everyone

mystic lily
#
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = users_queue_set.intersection(voice_channel_set)
not_ready_users = voice_channel_set.difference(users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
lethal tiger
#

I have problem with my code

somber heath
#

!timeit ```py
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users = users_queue_set.intersection(voice_channel_set)
not_ready_users = voice_channel_set.difference(users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 9.34 usec per loop
lethal tiger
#

guys if you could help `import threading

def solve_recaptcha_with_timeout(solver, timeout=6):
def solve_recaptcha():
solver.solve_recaptcha()

thread = threading.Thread(target=solve_recaptcha)
thread.start()
thread.join(timeout)
if thread.is_alive():
    print("Checking if CAPTCHA is solved after timeout...")

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(options)
driver.get(URL_Login)
time.sleep(4)

pageState = driver.execute_script('return document.readyState;')
print(pageState)

email_entry = driver.find_element(By.NAME, value="username")
password_entry = driver.find_element(By.NAME, value="password")
email_entry.send_keys(EMAIL)
password_entry.send_keys(PASSWORD + Keys.ENTER)
time.sleep(2)

solver = Recaptcha_Solver(
driver=driver,
debug=False
)

solve_recaptcha_with_timeout(solver)

solver.solve_recaptcha()

time.sleep(3)
pageState = driver.execute_script('return document.readyState;')
print(pageState)

password_entry.send_keys(Keys.ENTER)
print("login successful")`

rapid chasm
#

@mystic lily Code 3

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set.intersection(voice_channel_set))
not_ready_users = list(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```

@somber heath Code 7
```py
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users = users_queue_set.intersection(voice_channel_set)
not_ready_users = voice_channel_set.difference(users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
somber heath
#

!timeit ```py
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users = users_queue_set & voice_channel_set
not_ready_users = voice_channel_set - users_queue_set

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 9.49 usec per loop
rapid chasm
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set.intersection(voice_channel_set))
not_ready_users = list(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.75 usec per loop
mystic lily
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = set(users_queue_set.intersection(voice_channel_set))
not_ready_users = set(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 10.2 usec per loop
somber heath
#

!timeit py set([])

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

1000000 loops, best of 5: 312 nsec per loop
somber heath
#

!timeit py set()

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

2000000 loops, best of 5: 152 nsec per loop
mystic lily
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

500000 loops, best of 5: 728 nsec per loop
mystic lily
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

1000000 loops, best of 5: 381 nsec per loop
mystic lily
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
sett = set(users_queue_set)
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

500000 loops, best of 5: 798 nsec per loop
mystic lily
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
sett = list(users_queue_set)
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

500000 loops, best of 5: 728 nsec per loop
somber heath
#

!timeit ```py
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}

voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users, not_ready_users = users_queue_set & voice_channel_set, voice_channel_set - users_queue_set

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.22 usec per loop
mystic lily
#
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
rapid chasm
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set.intersection(voice_channel_set))
not_ready_users = list(voice_channel_set.difference(users_queue_set))

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.43 usec per loop
rapid chasm
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 7.65 usec per loop
mystic lily
#
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
rapid chasm
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.95 usec per loop
somber heath
#

🔬🥔💢

eager thorn
#

@mystic lily i think sum() and zip u can compare strings for similarity. haven't done it in a while.

somber heath
#

!dis

mystic lily
#
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
users = list(users_queue_set & voice_channel_set), list(voice_channel_set - users_queue_set)

print("Ready Users:", users[0])
print("Not Ready Users:", users[1])
somber heath
#

!e py import dis print(dis.dis(''' a = 1 b = 2 '''))

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   2           2 LOAD_CONST               0 (1)
004 |               4 STORE_NAME               0 (a)
005 | 
006 |   3           6 LOAD_CONST               1 (2)
007 |               8 STORE_NAME               1 (b)
008 |              10 RETURN_CONST             2 (None)
009 | None
eager thorn
wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

The similarity between 2 strings is : 0.8
somber heath
#

!e py import dis print(dis.dis(''' a, b = 1, 2 '''))

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 |   0           0 RESUME                   0
002 | 
003 |   2           2 LOAD_CONST               0 ((1, 2))
004 |               4 UNPACK_SEQUENCE          2
005 |               8 STORE_NAME               0 (a)
006 |              10 STORE_NAME               1 (b)
007 |              12 RETURN_CONST             1 (None)
008 | None
rapid chasm
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
users = list(users_queue_set & voice_channel_set), list(voice_channel_set - users_queue_set)

print("Ready Users:", users[0])
print("Not Ready Users:", users[1])```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.12 usec per loop
somber heath
#

!timeit py a = 1 b = 2

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

10000000 loops, best of 5: 31.6 nsec per loop
somber heath
#

!timeit py a, b = 1, 2

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 timeit job has completed with return code 0.

5000000 loops, best of 5: 43.5 nsec per loop
somber heath
#

@mystic lily Same number of instructions, different time outcome.

#

Different instructions.

#

See dis.dis above

round stratus
eager thorn
round stratus
#

@somber heath @mystic lily all this should be completely negligible by itself and also taken care of by cpythons jit no?

#

if you want to optimize python always look at your use of loops. loops in python are horrendously slow

mystic lily
#
not_ready_users = list(voice_channel_set - users_queue_set)
rapid chasm
#
users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
#

{}

#

set()

somber heath
#
{1, 2, 3, 4}
{1: 2, 3: 4}```
round stratus
#

Try something like this:

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users = users_queue_set.intersection(voice_channel_set)
not_ready_users = voice_channel_set.difference(ready_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
rapid chasm
#

@somber heath
verification_ongoing = {}
verification_ongoing[user_id] = True

round stratus
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

ready_users = users_queue_set.intersection(voice_channel_set)
not_ready_users = voice_channel_set.difference(ready_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
wise cargoBOT
#

@round stratus :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 9.02 usec per loop
mystic lily
#

!timeit

voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = [users_queue_set & voice_channel_set]
not_ready_users = [voice_channel_set - users_queue_set]

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 9.55 usec per loop
somber heath
#

!e py print(type({}))

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

<class 'dict'>
eager thorn
#

!e

print(type({}))
print(type({1, 2, 3}))

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | <class 'dict'>
002 | <class 'set'>
mystic lily
#

not_ready_users = list(voice_channel_set - users_queue_set)

round stratus
#

yeah it avoids copying the data which might be very expensive

#

i think you should benchmark these on larger datasets

mystic lily
#

!timeit ```
users_queue_set = ["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"]
voice_channel_set = ["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"]

Separate users into "Ready" and "Not ready"

ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```

wise cargoBOT
#

@mystic lily :x: Your 3.12 timeit job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/lang/python/default/lib/python3.12/timeit.py", line 330, in main
003 |     number, _ = t.autorange(callback)
004 |                 ^^^^^^^^^^^^^^^^^^^^^
005 |   File "/lang/python/default/lib/python3.12/timeit.py", line 226, in autorange
006 |     time_taken = self.timeit(number)
007 |                  ^^^^^^^^^^^^^^^^^^^
008 |   File "/lang/python/default/lib/python3.12/timeit.py", line 180, in timeit
009 |     timing = self.inner(it, self.timer)
010 |              ^^^^^^^^^^^^^^^^^^^^^^^^^^
011 |   File "<timeit-src>", line 48, in inner
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/MFAA4RW6AERKKCIALCNPX43Z4E

eager thorn
#

!e

s1 = {1, 2, 3, 4, 5}
s2 = set([6, 7, 8, 9, 10])

print(f"s1: {s1}")
print(f"s2: {s2}")

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | s1: {1, 2, 3, 4, 5}
002 | s2: {6, 7, 8, 9, 10}
mystic lily
#
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
eager thorn
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

Separate users into "Ready" and "Not ready"

ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 9.2 usec per loop
mystic lily
#

!timeit

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 8.01 usec per loop
round stratus
#

!timeit

def generate_users(num_users):
  for i in range(num_users):
    yield f"User{i + 1}"

users_queue = generate_users(1000000)
voice_channel = generate_users(800000)

ready_users = set(users_queue).intersection(set(voice_channel))
not_ready_users = set(voice_channel).difference(ready_users)
wise cargoBOT
#

@round stratus :warning: Your 3.12 timeit job timed out or ran out of memory.

[No output]
round stratus
#

haha

#

tried on bigger dataset

rapid chasm
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Multiply sets by 100
users_queue_set = set(list(users_queue_set) * 100)
voice_channel_set = set(list(voice_channel_set) * 100)

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

10000 loops, best of 5: 36 usec per loop
round stratus
#

on my local machine i'm noticing a slight improvement with the above:

[vb@buckbeak:~/py_test]$ time python test1.py

real    0m1.507s
user    0m1.328s
sys     0m0.173s
[vb@buckbeak:~/py_test]$ time python test2.py

real    0m1.952s
user    0m1.724s
sys     0m0.186s
[vb@buckbeak:~/py_test]$
#

nano seconds @rapid chasm

#

you might be right

#

yeah

#

you're right

#

i'm waffling

#

hah

round stratus
#
[vb@buckbeak:~]$ time python test.py
Ready Users: ['User6', 'User5', 'User2', 'User8', 'User10']
Not Ready Users: ['User96', 'User44', 'User75']

real    0m0.377s
user    0m0.281s
sys     0m0.092s
[vb@buckbeak:~]$
#

@rapid chasm meanwhile in rust...

Ready Users: ["User6", "User5", "User2", "User10", "User8"]
Not Ready Users: ["User75", "User44", "User96"]

real    0m0.003s
user    0m0.001s
sys     0m0.001s
round stratus
#

it's a language

#

not python :)

#

haha it's good yeah but it's a learning curve

mystic lily
#
users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)
eager thorn
#

!timeit

users_queue_dict = {
1: "User1",
2: "User2",
3: "User3",
4: "User4",
5: "User5",
6: "User6",
7: "User7",
8: "User8",
9: "User9",
10: "User10",
}

voice_channel_dict = {
10: "User10",
2: "User2",
5: "User5",
44: "User44",
6: "User6",
75: "User75",
8: "User8",
96: "User96",
}

users_queue_set = set(users_queue_dict.keys())
voice_channel_set = set(voice_channel_dict.keys())

ready_users_ids = list(users_queue_set & voice_channel_set)
not_ready_users_ids = list(voice_channel_set - users_queue_set)

ready_users = [users_queue_dict[id] for id in ready_users_ids]
not_ready_users = [voice_channel_dict[id] for id in not_ready_users_ids]

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 11.5 usec per loop
mystic lily
#

7.65 usec

somber heath
#

@clear socket 👋

#

@fluid steeple 👋

sturdy panther
#

Hi!

modern yacht
#

Is there a walk around to avoid this repettion in python classes

    @property
    def width(self) -> int:
        """Simple width getter"""
        return self.__width

    @property
    def height(self) -> int:
        """Simple height getter"""
        return self.__height

    @property
    def x(self) -> int:
        """Simple x getter"""
        return self.__x

    @property
    def y(self) -> int:
        """Simple y getter"""
        return self.__y
clear socket
somber heath
#

If you're not, though, you could do away with name scrambling altogether and just have x, y, height, width as regular attributes.

#

and dump the property decorators and getter methods

modern yacht
#

thought there could be a way considering if the instance has alot of attributes
well that would be really make my class static

sturdy panther
#

Hmm. One vote for just using attributes.

somber heath
#

Indeed, name scrambling is rarely worth it. If you want to say "don't touch", you can use a single preceding underscore instead of a double.

modern yacht
#

mmh you are right but would that make it less secure since am only using protected instance variable or is that not even a thing??

somber heath
#

Python doesn't do protected.

#

It does scrambling and it's a bit pointless.

#

!e ```py
from dataclasses import dataclass

@dataclass
class Thing:
x: int
y: int
height: int
width: int

thing = Thing(1, 2, 3, 4)

print(thing)```One approach.

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

Thing(x=1, y=2, height=3, width=4)
sturdy panther
#

I think... namedtuple can help with the immutability, but that does not allow even the class itself from modifying the attribute directly.

modern yacht
#

well i know of public _protected and __private so the naming mangling has no much effect as suggested

stark river
#

/usr/share/X11/xkb/

modern yacht
#

!stream 999482770957021204

#

appeary my update is not working when i pass **kwargs

        if args is not None:
            for indx, ag_r in enumerate(args):
                if indx == 0:
                    self.id = ag_r
                elif indx == 1:
                    self.width = ag_r
                elif indx == 2:
                    self.height = ag_r
                elif indx == 3:
                    self.x = ag_r
                elif indx == 4:
                    self.y = ag_r
        else:
            for key, value in kwargs.items():
                if key == "id":
                    self.id = id
                elif key == "width":
                    self.width= value
                elif key == "height":
                    self.height = value
                elif key == "x":
                    self.x = value
                elif key == "y":
                    self.y = value
warm jackal
modern yacht
#

class instatiation
r1 = Rectangle(10, 10, 10, 10)
print(r1)

when i call it like this nothing seems to happen

r1 = Rectangle(width=1, height=2, x=5, y=0)
    print(r1)
sturdy panther
#

!e (lambda *args, **kwargs: print(args))()

wise cargoBOT
#

@sturdy panther :white_check_mark: Your 3.12 eval job has completed with return code 0.

()
sturdy panther
#

Problem is the first if condition, I think.

#

It is unlikely to ever be None.

modern yacht
#

update method

    def update(self, *args, **kwargs):
        """Updates all the instances variables
        Args:
            args (tuple): a list of tuple that will be used to assign
            values for the instance variable
        """
        if args is not None:
            for indx, ag_r in enumerate(args):
                if indx == 0:
                    self.id = ag_r
                elif indx == 1:
                    self.width = ag_r
                elif indx == 2:
                    self.height = ag_r
                elif indx == 3:
                    self.x = ag_r
                elif indx == 4:
                    self.y = ag_r
        else:
            for key, value in kwargs.items():
                if key == "id":
                    self.id = id
                elif key == "width":
                    self.width= value
                elif key == "height":
                    self.height = value
                elif key == "x":
                    self.x = value
                elif key == "y":
                    self.y = value
#

rectangle class

class Rectangle(Base): """docstring for Rectangle"""

    def __init__(self, width, height, x=0, y=0, id=None):
        """Initializes all the instance attributes
        Args:
            width (int): an integer value holding the with of the Rectangle
            height (int): height of the rectangle
            x (int): just an x value
            y (int): just a y int value
            id (int): id value
        """
        super().__init__(id)
        self.width = width
        self.height = height
        self.x = x
        self.y = y

i am using both getters and setters

#
from models.rectangle import Rectangle

if __name__ == "__main__":

    r1 = Rectangle(10, 10, 10, 10)
    print(r1)

    r1.update(height=1)
    print(r1)

    r1.update(width=1, x=2)
    print(r1)

    r1.update(y=1, width=2, x=3, id=89)
    print(r1)

    r1.update(x=1, height=2, y=3, width=4)
    print(r1)
warm jackal
somber heath
#

!d dataclasses.dataclass

wise cargoBOT
#

@dataclasses.dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)```
This function is a [decorator](https://docs.python.org/3/glossary.html#term-decorator) that is used to add generated [special method](https://docs.python.org/3/glossary.html#term-special-method)s to classes, as described below.

The [`dataclass()`](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass) decorator examines the class to find `field`s. A `field` is defined as a class variable that has a [type annotation](https://docs.python.org/3/glossary.html#term-variable-annotation). With two exceptions described below, nothing in [`dataclass()`](https://docs.python.org/3/library/dataclasses.html#dataclasses.dataclass) examines the type specified in the variable annotation.

The order of the fields in all of the generated methods is the order in which they appear in the class definition.
eager thorn
#

god i need to go to bed lmao

sturdy panther
#

Opal has an amazing sixth sense, to follow the conversation without being in voice chat!

somber heath
#

Patterns repeat.

#

Seemed to be an appropriate action.

sturdy panther
#

I think... Mk might wanna start using a debugger. To follow what goes into update.

warm jackal
sturdy panther
toxic arch
#

@warm jackal hello x10an14

#

@warm jackal my name is file link dunder underscore end

#

yahya

#
class File(Protocol):
    def read_bytes(self) -> bytes:
        ...
    
    @property
    def name(self) -> str:
        ...

what should i name this protocl

#

i think File is too vague

#

@warm jackal

#

good idea

#

FileHandler

#

well i use it to read a file and its filename

#

since pathlib.Path

#

yeah but i want one thats in memory

#

i just need theese 2 attrubites

#

how would i do that?

warm jackal
toxic arch
modern yacht
#

@warm jackal and @sturdy panther i made a list which is ordered on how i want the attributes to be set
But something weird happens when i happen to place the kwargs function as the last one, no attributes are updated.
Otherwise when i place it at the beginning of the function it work why?

    def update(self, *args, **kwargs):
        """Updates all the instances variables
        Args:
            args (tuple): a list of tuple that will be used to assign
            values for the instance variable
        """
        attr_list = ['id', 'width', 'height', 'x', 'y']

        for key, value in kwargs.items():
            if key in attr_list:
                setattr(self, key, value)

        if args is not None:
            for indx, ag_r in enumerate(args):
                setattr(self, attr_list[indx], ag_r)
sturdy panther
#

Have you checked what args is?

modern yacht
#

a tuple

modern yacht
warm jackal
modern yacht
#

[Rectangle] (1) 10/10 - 10/10
[Rectangle] (1) 10/10 - 10/1
[Rectangle] (1) 2/10 - 1/1
[Rectangle] (89) 3/1 - 2/1
[Rectangle] (89) 1/3 - 4/2

warm jackal
#
def update(self, **kwargs):
  approved_attrs = set('id', 'foo', 'bar', 'baz') # Not 100% sure if I remember how to instantiate a set correctly
  update_values = {
    attr_name: attr_value,
    for attr_name, attr_value
    in **kwargs # Or `kwargs.items()`
    if attr_name in approved_attrs
  }
  for name, value in update_values.items():
    setattr(self, name, value)
sturdy panther
#

I suppose you can can enforce that with
if args and kwargs: raise ValueError("Position or keyword arguments only, but not both. )

#

... Really not by day, with all the typos.

#

Yea, I would recommend just keyword arguments too.

warm jackal
whole bear
sturdy panther
#

Real life whiteboards...!

whole bear
#

lol

willow light
#

I was expecting to see a kanban tbh

lavish ferry
modern yacht
#

version that works

def update(self, **kwargs):
  approved_attrs = {'id', 'foo', 'bar', 'baz'} # Not 100% sure if I remember how to instantiate a set correctly
  update_values = {
    attr_name: attr_value,
    for attr_name, attr_value
    in kwargs.items()
    if attr_name in approved_attrs
  }
  for name, value in update_values.items():
    setattr(self, name, value)
sturdy panther
#

Is it doing what you want?

#

Do they need a default value?

modern yacht
#

yess

#

it does it perfectly avoiding the case of duplicate values

modern yacht
#

here is my version

#
    def update(self, *args, **kwargs):
        """Updates all the instances variables
        Args:
            args (tuple): a list of tuple that will be used to assign
            values for the instance variable
        """
        # avoid duplicate values
        approved_set = {'id', 'width', 'height', 'x', 'y'}

        updated_attrs = {
                         attrs_key: attrs_value
                         for (attrs_key, attrs_value) in kwargs.items()
                         if attrs_key in approved_set
                         }

        for key, value in updated_attrs.items():
            setattr(self, key, value)

eager thorn
#

How's everyone.

cinder dawn
#

hows u cy

eager thorn
cinder dawn
#

u doing much for xmas

eager thorn
#

probably take the mrs and the girls on a vacation or something.

cinder dawn
#

thats nice thats nice

eager thorn
#

yeah, unsure of where to go though.

#

🤔

cinder dawn
#

@whole bear i thought ur voice was coming thru my musicn

eager thorn
#

!paste

wise cargoBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

eager thorn
dull sluice
#

how can an array have negative len?

lavish rover
#

.

eager thorn
dull sluice
#

oh wait thats why its an error not bc it dont work with one like that but bc one like that dont exist

#

there is an eval func in python id guess its that

wind raptor
#

!e

wise cargoBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

Currently only 3.12 version is supported.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

wise loom
#

@terse garden sup?

#

Wow nice

#

I think it has a name.

#

Was really famous when it came out a few years ago, the paper for it

#

Carving it was called

#

Seam Carving

cold heart
#

hello

wise cargoBOT
#

:incoming_envelope: :ok_hand: applied timeout to @cold heart until <t:1702153386:f> (10 minutes) (reason: burst spam - sent 8 messages).

The <@&831776746206265384> have been alerted for review.

wind raptor
# cold heart hello

Hey, so yeah, please don't spam to get voice perms. I hope that's not what you were doing.

wise loom
#

here it is

terse garden
#

test

cold heart
#
              (UwU)
       _ノ ヽ ノ\_ 
    / `/ ⌒Y⌒ Y  \
 (  (三ヽ人  /   |
| ノ⌒\  ̄ ̄ヽ  ノ
ヽ___>、__/
          |( 王 ノ〈 
          /ミ`ー―彡\ 
          |╰         ╯   |   
          |       /\       |
          |      /  \      |
          |    /     \     |```
#

⠀ (\ __ /)
(UwU)
_ノ ヽ ノ\_
/ / ⌒Y⌒ Y  \ (  (三ヽ人  /   | | ノ⌒\  ̄ ̄ヽ  ノ ヽ___>、__/ |( 王 ノ〈 /ミー―彡\
|╰ ╯ |
| /\ |
| / \ |
| / \ |

wind raptor
cold heart
wise loom
#

@left leaf
Return is what Romeo told Juliet

#

Spoiler: ||she was dead already||

wind raptor
# cold heart why?

Because it takes up a lot of the chat and doesn't really contribute to the conversation.

wise loom
#

@left leaf it's almost like being excited for having learned how to make lemonade 🍋 + 🍯 + 🚰 = lemonade

wind raptor
wise loom
#
  • If you want to learn Node.JS, which is commonly used nowadays
  • Arrow functions is garbage... man
  • The course was like 160 hours, I took only 40 hours
    -- @left leaf circa 2023
#

words of wisdom

#

🤣

wind raptor
round stratus
#

g++ is the c++ frontend for the gnu compiler collection :)

wind raptor
#

!stream 745015733238497330

wise cargoBOT
#

✅ @terse garden can now stream until <t:1702156234:f>.

round stratus
#

@terse garden I realise I joined in the middle of a convo. What exactly is the topic?

#

@coarse turret it's completely fine to compile from vscode. My understanding is you can choose the compiler you want to compile your software with in vscode so just make sure it is right :)

#

program output in terminal might look weird though I'm not familiar

#

@terse garden just FYI it's still very much possible to reverse engineer a compiled binary. You can even decompile programs and get relatively human readable code from your final executable. Be careful using compilation as a security layer!

#

reverse engineering requires some know-how but decompilation is also very effective and much easier to do

#

@terse garden are you at all involved in the large language model space?

wise loom
round stratus
sweet lodge
#

Dog?

round stratus
#

haha

stuck furnace
#

Oooh, who is your advisor? 👀

#

Sorry, nosey 😄

#

How many years does it typically take to complete a phd in the US?

#

I have no grit. I am gritless :C

amber raptor
#

4 for Bachelors, 2 for Masters, 2 for PhD

#

but it's extremely variable depending on program and such

random copper
harsh bough
#

!post

wise cargoBOT
#
Positional vs. keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Sometimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info

harsh bough
#

!post

wise cargoBOT
#
Positional vs. keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and 'world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Sometimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info

harsh bough
#

while gamerunning:
hit = input("Would you like to hit? (yes/no)")
if hit == "yes":
card = deck.pop()
if card == 11: card = "Jack"
if card == 13: card = "King"
if card == 12: card = "Queen"
if card == 1: card = "Ace"
player_hand.append(card)
cardtotal = calculate_hand_value(player_hand)
print("You drew",card,"your total is",cardtotal)
if cardtotal > 21:
gamerunning = False
print("You Busted!")
elif hit == "no":
print("You chose to stand")
else:
print("Invalid Option!")
break
#if dealer less than 17 it has to hit
while dealertotal < 21:
if dealertotal < 17:
card = deck.pop()
dealerstartinghand.append(card)
print(f"The dealer drew {card} and now has ??? points")
#if dealer has more than 17 then he stands
else:
print("Dealer stands")
break
dealertotal = calculate_hand_value(dealerstartinghand)

#

You drew [6, 'King'] your total is 16
The dealer drew two cards, one of them is 5
Would you like to hit? (yes/no)yes
You drew 4 your total is 20
You Win! - Dealer Busted
Dealer's final hand: [5, 8]
your total points are 120
Would you like to play again? (yes/no)

#

score increase and decrease + card decision making

if cardtotal > 21:
print("You Lose! - Busted")
totalpoints -= 10
elif cardtotal == 21:
print("You Win! - You hit 21!")
totalpoints += 10
elif 21 - dealertotal > 21 - cardtotal or dealertotal>21:
print("You Win! - Dealer Busted")
totalpoints += 10
elif 21 - dealertotal <= 21 - cardtotal:
print("You Lose! - Dealer hit 21")
totalpoints -= 10
print(f"Dealer's final hand: {dealerstartinghand}")
print("your total points are",totalpoints)

#

print("Would you like to play again? (yes/no)")
playagain = input()
if playagain =="yes":
gamerunning = True
if totalpoints<= 0:
print ("Sorry! You are out of points.")
break
cardtotal = 0
print("You Chose to play again")
deck = makeDeck([])
gamerunning = True

#starting hand
startinghand = deal(deck)
player_hand = startinghand 
dealer_hand = startinghand 
dealerstartinghand = deal(deck)

cardtotal = calculate_hand_value(player_hand)
dealertotal = calculate_hand_value(player_hand)

#your hand
# card_values 

cards_as_int = [card_values.get(card,card)for card in dealerstartinghand]
startingtotal = sum(cards_as_int)
cardtotal+=startingtotal
cardtotal = calculate_hand_value(player_hand)

#dealer hand
cards_as_int = [card_values.get(card,card) for card in dealerstartinghand]
dealerstarttotal = sum(cards_as_int)
dealertotal += dealerstarttotal

print("You drew",startinghand,"your total is",cardtotal)
print("The dealer drew two cards, one of them is", dealerstartinghand[0])

else:
print("Goodbye!")
break

terse garden
#

until ---> user inputs (string no) repeat Would you like to play again? (print this on repeat)

#

if user input is not bool (string yes or no) then print (not a valid input)

#

dealer final hand > your final hand then print (either you win or dealer wins)

#

void soft_seventeen ---> def soft_seventeen (if dealertotal < 17, then hit)

#

#if dealer less than 17 it has to hit
while dealertotal < 21:
if dealertotal < 17:
card = deck.pop()
dealerstartinghand.append(card)
print(f"The dealer drew {card} and now has ??? points")
#if dealer has more than 17 then he stands
else:
print("Dealer stands")
break
dealertotal = calculate_hand_value(dealerstartinghand)

#

def dealerstartinghand

harsh bough
#

def deal(deck):
hand = []
for i in range(2):
random.shuffle(deck)
card = deck.pop()
if card == 11: card = "Jack"
if card == 13: card = "King"
if card == 12: card = "Queen"
if card == 1: card = "Ace"
hand.append(card)
return hand

#

def calculate_hand_value(hand):
card_values = {'Jack':10, 'King':10, 'Queen':10, 'Ace':11}
hand_value = 0
for c in hand:
if type(c) == int:
hand_value += c
elif c !="Ace":
hand_value += card_values[c]
#adding the ace logic
for _ in [i for i in hand if i == "Ace"]:
if hand_value + 11 > 21:
hand_value += 1
else:
hand_value += 11
return hand_value

terse garden
#

for card in hand:

#

if isinstance(card, int):

#

hand_value += card

#

elif card != "Ace":

#

hand_value += card_values[card]

#

for ace in [i for i in hand if i=="Ace"]:

#

if hand_value + 11 >21:

#

hand_value +=1

#

ekse:

#

else:

#

hand_value += 11

#

return hand_value

wise loom
#

@acoustic urchin step by step teh bird is making its nest?

wise loom
acoustic urchin
wise loom
acoustic urchin
wise loom
# acoustic urchin Yes

oh cool, can you summarize the layout or.. like, idk, if you like to talk about your nest, maybe you don't

acoustic urchin
#

Perfectly put

ivory stump
#

👀

faint ermine
rapid chasm
#

@somber heath Which method should I use?

    # Separate users into "Ready" and "Not ready"
    ready_users = []
    not_ready_users = []
    for member in voice_channel.members:
        if member in users_queue_sorted:
            ready_users.append(member)
        else:
            not_ready_users.append(member)

vs

    # Separate users into "Ready" and "Not ready" using list comprehension
    ready_users = [member for member in voice_channel.members if member in users_queue_sorted]
    not_ready_users = [member for member in voice_channel.members if member not in users_queue_sorted]```
sweet prism
#
not_ready_users = set(voice_channel.members) - (ready_users := {member for member in voice_channel.members if member in users_queue_sorted})

?

rapid chasm
#

@sweet prism Which one would you pick if it wasn't for the set?

sweet prism
#

using the set avoids doing the loop twice and all checks in python. otherwise, i'd probably prefer the readability of the 2nd over the performance of the first. though it depends on application.

#

it's "readable" because that list comp can be trivially converted to a function

somber heath
#

Is it a queue or a pool?

rapid chasm
#

Queue

somber heath
#

Only x maximum people can engage at a time in the activity?

gentle flint
#

may I introduce you to vim

#

notepad on my ubuntu work machine

#

of course

sweet prism
whole bear
#

Hey why cant i talk in the vc

#

!voiceverify

#

yea

#

thanks

#

says i still cant

#

but hey i got a question right

#

where is a good place to learn how to use tkinter

#

thanks

rapid chasm
sweet prism
#

i've already deleted that, sorry. it was just the lambda version of the list comps you wrote

sweet prism
# rapid chasm Can you share this code?
def users(members, *, is_ready):
    return {member for member in members if member in members_queue_sorted == is_ready}
ready_users, not_ready_users = (users(voice_channel.members, is_ready=x) for x in (True, False))

found it in the recycle bin. (fn form, instead of lambda. same thing, just without the pylint* warning)

toxic arch
#

hello guys

#

doing good @wind raptor im on mobile in bed rn

#

what are you streaming? Haven

#

@verbal zenith

#

probably afk

verbal zenith
#

Yep afk

toxic arch
#

well ima leave vc

#

cya

wind raptor
#

Hey @glad breach 👋

glad breach
#

hi, what's up?

#

all good, thx for asking

vocal basin
#

I wonder how live-reload handles globals

#

(also idk if Django has live-reload at all, since I'm not using it)

#

wait, what is usr.groups?

#

does it pull stuff from another table?
or is it an array/set/etc. field?

vocal basin
still lava
#

yo

vocal basin
#

I guess it is an auxiliary table then

#

there still needs to be a commit at some point (so it should be saved anyway)

#

I'd expect it to have an extra table

vocal basin
vocal basin
#

@admin.register

#

coach_group, when created, isn't yet saved, I guess

#

as another failure reason, it might be trying to save an outdated version

#

so, like, overwriting after adding to the group

#

idk

#

it may be simpler to not have is_coach at all, and have the group as the primary and only source for that value

#

is_coach can still be selectable from something like a materialised view

strong arch
daring swift
#

@somber heath 👋🏼

lavish rover
cinder dawn
#

morning

stark river
#

🦗 🦗

stark river
cinder dawn
#

howdy

stark river
#

i dont know what's the response to that

#

seems like a 400

rapid chasm
#
a, b = [], []

for i in range(100):
    if i % 2 == 0:
        a.append(0)
    else:
        b.append(1)
a = [0 for i in range(100) if i % 2 == 0]
b = [0 for i in range(100) if i % 2 != 0]
#

@warm jackal

#

Checking users in a voice channel and in the queue versus those who are not in the queue but still in the voice channel

#

!timeit

a, b = [], []

for i in range(100):
    if i % 2 == 0:
        a.append(0)
    else:
        b.append(1)```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 10.2 usec per loop
rapid chasm
#

!timeit

a = [0 for i in range(100) if i % 2 == 0]
b = [0 for i in range(100) if i % 2 != 0]```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 14.5 usec per loop
warm jackal
rapid chasm
#
    # Get the voice channel
    voice_channel = ctx.guild.get_channel(712072729406472374)

    # Sort users_queue by ready_time
    users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))

    # Separate users into "Ready" and "Not ready"
    ready_users = []
    not_ready_users = []
    for member in voice_channel.members:
        if member in users_queue_sorted:
            ready_users.append(member)
        else:
            not_ready_users.append(member)

    # Create strings for "Ready" and "Not ready" users
    ready_string = '\n'.join([f'{member.mention}' for member in ready_users])
    not_ready_string = '\n'.join([f'{member.mention}' for member in not_ready_users])
vocal basin
#

I'd probably prefer just storing a list in order of readiness (so no time/datetime)
but that's not necessarily simpler

warm jackal
# rapid chasm ```py # Get the voice channel voice_channel = ctx.guild.get_channel(7120...

My two cents of how I'd do it:

--git a/users_queue.py b/users_queue.py
index 7964762..aadc704 100644
--- a/users_queue.py
+++ b/users_queue.py
@@ -1,18 +1,15 @@
 # Get the voice channel
 voice_channel = ctx.guild.get_channel(712072729406472374)
+# Get the users
+users = (,)
 
 # Sort users_queue by ready_time
-users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))
+users_queue = sorted(users, key=lambda x: x.get("ready_time", datetime.datetime.min))
 
 # Separate users into "Ready" and "Not ready"
-ready_users = []
-not_ready_users = []
-for member in voice_channel.members:
-    if member in users_queue_sorted:
-        ready_users.append(member)
-    else:
-        not_ready_users.append(member)
+users_ready = set(user for user in users if user in users_queue)
+users_not_ready = set(user for user in users if user not in users_queue)
 
 # Create strings for "Ready" and "Not ready" users
-ready_string = '\n'.join([f'{member.mention}' for member in ready_users])
-not_ready_string = '\n'.join([f'{member.mention}' for member in not_ready_users])
+ready_string = '\n'.join([f'{member.mention}' for member in users_ready])
+not_ready_string = '\n'.join([f'{member.mention}' for member in users_not_ready])
#

Huh, discord doesn't have git diff highlighting

vocal basin
#

missing newline

#

seems like

#
+ 123
- 321
#

time.time and datetime also have a problem of not being monotonic (in some circumstances)

warm jackal
vocal basin
#
  1. missing after diff
  2. extra before
warm jackal
#

Oh, I needed to mark the markdown codeblock as a diff? I just copy-pasted the output of git diff

vocal basin
#

ah

mystic lily
#

!timeit

not_ready_users = set(["User1", "User2", "User3"])
voice_channel_users = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(not_ready_users & voice_channel_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", list(voice_channel_users - not_ready_users))
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.76 usec per loop
vocal basin
#

for small counts, performance would be quite insignificant

mystic lily
#

!ti

not_ready_users = set(["User1", "User2", "User3"])
voice_channel_users = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(not_ready_users & voice_channel_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", list(voice_channel_users - not_ready_users))
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.7 usec per loop
mystic lily
#

!ti

users_queue_set = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])
voice_channel_set = set(["User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", list(voice_channel_set - users_queue_set))
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

20000 loops, best of 5: 9.35 usec per loop
vocal basin
#

inputs, if I remember correct what the setting of the question is, are <100, since it's about a regular VC not a stage

warm jackal
rapid chasm
#

!timeit

users_queue_set = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}
voice_channel_set = {"User10", "User2", "User5", "User44", "User5", "User6", "User75", "User8", "User96", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = list(users_queue_set & voice_channel_set)
not_ready_users = list(voice_channel_set - users_queue_set)

print("Ready Users:", ready_users)
print("Not Ready Users:", not_ready_users)```
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 7.93 usec per loop
vocal basin
#

library rather, it isn't as framework-ish as it could've been

mystic lily
#

!timeit

not_ready_users = set(["User1", "User2", "User3"])
voice_channel_users = set(["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"])

# Separate users into "Ready" and "Not ready"
ready_users = list(not_ready_users & voice_channel_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", list(voice_channel_users - not_ready_users))#
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 8.75 usec per loop
vocal basin
#

list-to-set adds extra

#

it took me some time to remember how to store that queue efficiently

#

(borrowing ideas from LRU cache)

#

the difficult part for storing it as a list is unreadying
(leaving the queue)

mystic lily
#

!ti

not_ready_users = {"User1", "User2", "User3"}
voice_channel_users = {"User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9", "User10"}

# Separate users into "Ready" and "Not ready"
ready_users = list(not_ready_users & voice_channel_users)

print("Ready Users:", ready_users)
print("Not Ready Users:", list(voice_channel_users - not_ready_users))
wise cargoBOT
#

@mystic lily :white_check_mark: Your 3.12 timeit job has completed with return code 0.

50000 loops, best of 5: 7.33 usec per loop
vocal basin
#

it might be a reasonable idea to have a task running per each active queue
since asyncio tasks are relatively cheap

#

... though, if you want to make the bot as stateless as possible, maybe not

wise loom
wise loom
rapid chasm
#
a, b = [], []

for i in range(100):
    if i % 2 == 0:
        a.append(0)
    else:
        b.append(1)
a = [0 for i in range(100) if i % 2 == 0]
b = [0 for i in range(100) if i % 2 != 0]

@soft dawn

vocal basin
#

fault-tolerance for Erlang isn't an inherent characteristic, but rather something that can be achieved with the tools it provides and restrictions it places

#

there are things that can go totally wrong with Erlang, especially from code upgrade

vocal basin
vocal basin
#

(or 1 for b to match first block's behaviour)

#

two blocks in the original message don't match in what they output

#

this would be slightly extreme, and may have parsing costs

a = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
rapid chasm
#
    # Get the voice channel
    voice_channel = ctx.guild.get_channel(712072729406472374)

    # Sort users_queue by ready_time
    users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))

    # Separate users into "Ready" and "Not ready"
    ready_users = []
    not_ready_users = []
    for member in voice_channel.members:
        if member in users_queue_sorted:
            ready_users.append(member)
        else:
            not_ready_users.append(member)

    # Create strings for "Ready" and "Not ready" users
    ready_string = '\n'.join([f'{member.mention}' for member in ready_users])
    not_ready_string = '\n'.join([f'{member.mention}' for member in not_ready_users])
vocal basin
#

get_channel relies on caching, iirc

#

you should handle cache misses somehow

rapid chasm
#

So if you are getting a ratelimit for example, it will wait

vocal basin
#

it can't break laws of physics
if the channel gets created, you don't get it instantly, and may have to wait for it to be fetched

#

e.g. if get_channel returns None and you're sure the channel exists, you may attempt to use fetch_channel

rapid chasm
#

The channel already exists

vocal basin
#

bot might also get it permissions changed so it only now can see the channel
(same failure case)

rapid chasm
#

But yeah you are right about if the channel don't exist or get deleted by accident

#

True

vocal basin
#

get_message runs into false negatives more often, because it's infeasible to have all messages cached

warm jackal
#
import discord

from collections import deque

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)
TARGET_CHANNEL = ctx.guild.get_channel(712072729406472374)
USER_QUEUE = deque()


@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')


@client.event
async def on_queueing(message):
    # if message.author == client.user:
    #     # Not sure if you want/need this
    #     return

    if not message.content.startswith("I'm ready"):
        return

    if message.author.voice.channel != TARGET_CHANNEL:
        await message.channel.send(f"You need to be connected to #{TARGET_CHANNEL.name}")
        return

    if message.author in USER_QUEUE:
        await message.channel.send("You're already added to the queue!")
        return

    USER_QUEUE.append(message.author)
    await message.channel.send("I've added you to queue!")


@client.event
async def on_get_ready_users(message):
    # if message.author == client.user:
    #     # Not sure if you want/need this
    #     return

    if not message.content.startswith("List ready users"):
        return

    users_in_voice = TARGET_CHANNEL.members
    ready_users_in_voice = set(member for member in USER_QUEUE if member in TARGET_CHANNEl.members)
    await message.channel.send(f"The following users signed up but are not in the voice channel!\n{
        '\n'.join(
            member.mention
            for member
            in USER_QUEUE
            if member not in ready_users_in_voice
        )
    }")
    await message.channel.send(f"The followign users signed up and are ready in the voice channel!\n{
        '\n'.join(
            member.mention
            for member
            in ready_users_in_voice
        )
    }")


if __name__ == '__main__':
    client.run('your token here')
warm jackal
#

Feedback is welcome from anyone who wants to share it.

vocal basin
#

I think it would crash

#

with NameError

warm jackal
warm jackal
# warm jackal ```py import discord from collections import deque intents = discord.Intents.d...

Here's the diff to reset/empy the queue:

diff --git a/users_queue.py b/users_queue.py
index 470c1e9..a14ddca 100644
--- a/users_queue.py
+++ b/users_queue.py
@@ -64,5 +64,27 @@ async def on_get_ready_users(message):
     }")
 
 
+@client.event
+async def on_empty_queue_for_next_game(message):
+    # if message.author == client.user:
+    #     # Not sure if you want/need this
+    #     return
+
+    if not message.content.startswith("Start next game"):
+        return
+
+    # Remove the people who got into the match
+    with suppress(IndexError):
+        users_joining_game = set(USER_QUEUE.popleft() for _ in range(5))
+
+    await message.channel.send(f"The following users removed from queue!\n{
+        '\n'.join(
+            member.mention
+            for member
+            in users_joining_game
+        )
+    }")
+
+
 if __name__ == '__main__':
     client.run('your token here')
warm jackal
obsidian dragon
#
function getColorBasedOnSize($sizeInGB) {
    if ($sizeInGB >= 100) {
        return 'darkred'; // 100 GB or larger (dark red)
    } elseif ($sizeInGB >= 10) {
        return 'red'; // Between 10 GB and 100 GB (red)
    } elseif ($sizeInGB >= 1) {
        return 'yellow'; // Between 1 GB and 10 GB (yellow)
    } elseif ($sizeInGB >= 0.1) {
        return 'green'; // Between 0.1 GB and 1 GB (green)
    } else {
        return 'lime'; // Smaller than 0.1 GB (lime)
    }
}
brisk bridge
#

hi

random copper
#

Anyone wants a HTML assignment?

sorry know its a bit off topic, as it's HTML..

#

I say it's experience...

#

GW2..

All these punks with their "Black-tide server" discord..

It belongs to the admins, ArenaNet...

Python..

It's a thing..

Not a company...

#

Like "shoes"

But Nike is a company

#

Well Python might be a company somebody invented it, but you know..

somber heath
#

PSF.

random copper
#

Hehe video games beef..

somber heath
#

Python Software Foundation.

random copper
#

Ah alright 😄

#

"And inspiration, you can't repeat"

#

Isnt there somebody who wants an assign to make me a basic simple css/html/js what you can do? 😄

Like myself..

When i started..

#

Besides nobody gave me no assignment..

Okay, i met some good friends already.. 😄

#

Hello 😄

wind raptor
#

!stream 386307484740222987

wise cargoBOT
#

✅ @rapid chasm can now stream until <t:1702215622:f>.

random copper
#

Show

#

Or ask

#

/compile

#

compile:

#

compile;

#

Anyway, w hats what the code?

#

there is no question it's a code

with 2 errors

#

import matploblib.pyplot as pl
Import numpy as np

from sympy.parsing.sympy_parser import prase_expr

That is libs

#

libaries, you install by writing pip install matploblib and pip install numpy in prompt

#

I get error line 8

#

What is lambdify

#

oh it's sym and x not defined

#

Can you show me SS of your code editor

#

It's a module, i think that might means it's an lib issue as well, the sym not defined

#

it's a sum

#

func=sum.lambdify(x,b,"numpy")

#

Now we define X

#

Let me see the terminal where it says problems

#

oh it's not visual studio code

#

why?

#

Put it in studio code mate

#

It's also wrong in jupyter

#

whatever your code editor says

#

i have the curve here

#

Mate...

#

i want to teach you

#

put it in Microsoft visual studio code, i tell you whats wrong and how to fix it

#

Im here

#

Then take SS & show me "Problems"

#

sur e

#

But sure like to walk it through here

#

others might gain from it

#

You're in school i assume, it's actually something some people in world can't afford.. 🙂

#

Not here..

But you know, it's very helpful what you have there

#

Good assignment, you're declaring a variable, installing libs & syntax error

#

I say it's a syntax error

#

Show me the problems.. 😄

eager thorn
#

what's going on here?

random copper
#

I didn't school it..

But i walk you through that assignment & show you what you learn..

It's a good one you finished your assignment..

Let me see it in Studio code mate

#

Didnt recieve any, but cant you show here?

#

Alright...

#

Assignment:

import matplotlib.pyplot as plt
import numpy as np

from sympy.parsing.sympy_parser import parse_expr
z = "-2*(x4)+5*(x3)+4*x+7"
b= parse_expr(z)
print(b)
func=sym.lambdify(x,b,"numpy")
x_num=np.linspace(0,10,1000)
y_num=2
plt.plot(x_num,func(x_num))
plt.show()

So there is 3 errors/problems in the problem terminal of studio code.

Import matploblib

x is not defined
sym.lambdify is not defined

First install the libaries:

Open a cmd/prompt and write:

pip install numpy
pip install matplotlib
pip install sympy

Next problem, x is not defined, so you declare x as such:

x = symbols('x')

last problem, says sym.lambdify is not defined.

sym is not a function

It's sum.

But it's also not what we looking for, it is prewritten lambdify only.

Not an operation on it.

So we also need to import the lib, lambdify, from the sympy

result:

import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols, lambdify ## < From symport we are importing Lambdify a module in matploblip
from sympy.parsing.sympy_parser import parse_expr

x = symbols('x') ## < Declaring Variable X, that was previously not declared
z = "-2*(x4)+5*(x3)+4*x+7"
b= parse_expr(z)
print(b)
func=lambdify(x, b,"numpy") ## < Fixing syntax error it's just func=lambdify, a module prewritten in matploblib ## X is now declared
x_num=np.linspace(0,10,1000)
y_num=2
plt.plot(x_num,func(x_num))
plt.show()

#

I call it a syntax error,

func=lambdify(x, b,"numpy") ## < Fixing syntax error it's just func=lambdify, a module prewritten in matploblib ## X is now declared

That is a nice assignment

#

you say that...

#

Matploblib, is a pre-written libary that you can import, it's usually curves and math stuff related to that lib

#

GL..

If anybody wants i could use some time taken off my hands..

I need HTML&CSS website templates

Just a basic, homepage, or what inspiration you have..

hallow warren
#

I really like this 12 minute video on OOP tips and tricks: https://youtu.be/Z4WupQQdMsQ

  1. reflected arithmetic operators
  2. getattr vs getattribute
  3. an alternative to super().init()
  4. checking for child classes
  5. multiple inheritance & MRO
  6. invert & other binary magic methods
  7. creating a class with the 'class' keyword

Medium Python Blog: zlliu.medium.com
Personal site: https://zlliu.co

Ebooks I've writ...

▶ Play video
raw kraken
#

@hallow warren Would you say its easy to make money with web devolopment without any advanced systems just like a nice looking website

hallow warren
hallow warren
raw kraken
hallow warren
hallow warren
hallow warren
#

Fiverr is generally going to have less demanding clients. Upwork is fraught with people who don't really always know what they want and will get upset if you can't predict it correctly, which is frustrating

raw kraken
#

I was thinking of how I can learn more python as thats something I am quite interested in as well. Not necessarily getting hired by clients just making some cool programs perhaps in the future sell some applications.

#

And somewhere in betgween learn basic web development

hallow warren
#

Leetcode

#

ChatGPT 4 will tutor you in web dev

hallow warren
raw kraken
#

Currently Im using PyCharm for python but previously used VSC for web dev.

hallow warren
#

I love both but Replit will save you from yourself in ways they can't

#

Also Replit Autoscale deployments give you warmable Google Cloud Run for fractions of a penny over a week of intensive dev and test

#

(warmable meaning use a keep-alive monitor to load an empty file every five minutes and your app is ~120ms latency for a penny per year)

#

If you need a fast DB use ReplitDB for key-value store up to 50MB, or the free ElephantSQL plan for the latest managed Postgres up to 20MB

#

If you need more DB storage, Neon.tech is cool but get their $5/month plan because their free tier is sloooooow

#

Actually, if you're going to spend $5/month, Render.com is a better deal

#

Render will also give you the easiest OAuth logins (via Google, Facebook, LinkedIn, GitHub etc.) which are a royal pain for even very senior web devs to do themselves. The auth provider APIs change without notice all the time

#

@raw kraken if you're on a very very tight budget starting out, the Google Cloud free tier gives you an instance suitable for a fast, warm 25GB Postgres, Cloud Run awesomeness, and all the bells and whistles you can dream of (except easy OAuth logins) but you have to manage it all yourself to keep your monthly bill under $1. But you need to learn those skills anyway, and they give you $200 credit for the first year to experiment with all the expensive goodies.

#

Just don't get hooked on their managed services which you can set up on your free instance in minutes to hours, like Postgres

#

Also you need to think about reliable backups, which Replit and Render do seamlessly in the background

#

If you need heavy GPU stuff, Modal.com has the best deal and starter credits last time I looked, and they can pull cloud function-like from dockerhub, for which you are only charged while they run, which is very rare in the hosted GPU space

#

@raw kraken Modal's $30 free offer is a LOT of GPU compute, where it might be a day or two of keeping them warm with traditional GPU hosting. https://modal.com/pricing

Modal helps people run code in the cloud. We think it's the easiest way for developers to get access to containerized, serverless compute without the hassle of managing their own infrastructure.

#

They have A100s, A10Gs, T4s, and L4s with lots of VRAM you can put on web endpoints and stuff

karmic obsidian
#

BLoom

hallow warren
# karmic obsidian Thank you <@209031094631137280>

Start with their tutorial, https://m.youtube.com/watch?v=rimFb9gRPOc let me get the specific model you want

Vertex AI Model Garden is your one-stop-shop to over 100 cutting edge LLMs and task-specific models, from Google's own Palm 2 to open-source models like Llama 2 and Stable Diffusion.

Even if you've never deployed or managed a model before, Vertex makes it simple for any developer to find, deploy, and maintain foundation models.

In this s...

▶ Play video
karmic obsidian
cinder dawn
#

good evening

scarlet halo
#

so i made my code wrong on purpose so i could test this error message.

woeful salmon
#

@stark river

Separate Backend + Vanilla javascript

your html page is already there (or maybe you're using some templating for some dynamic stuff), you send that to the user and some javascript runs on events and so on and its very fast and there's not too much to download even for older / slower devices but you do need to write more code generally, there's no standardized way of doing things so it can be hard to keep your code consistent and newer devs have to read through more javascript to find where to do what they want to do (which react can alot of times avoid just by having components, for eg. you can to edit how a button animates when you click it with javascript just find the PrimaryButton component)
Separate Backend + React

your react renders to vanilla javascript but your html just has an empty root tag which you send to the user, they then have to download all the rendered javascript which can be multiple megabytes which can be slow on older / weaker devices and networks, and while they are downloading and running that javascript the user sees nothing on the page which depending on how slow it is can be really bad experience
Next.JS

your react code now has 3 ways of being rendered, either you render your jsx to react components like base react, or you can do render them on the server and send the rendered html directly to the client, or the third thing you can do it static site generation where you pre-render your entire page into html and any javascript needed for interactivity and just send that to the user, and you can mix and match these between different routes and sometimes even partially serverside render a page and render other part on the client, also since it is a framework it gives you a standard for how to structure your code and also allows you to put your backend and frontend in the same repo at the cost of making them somewhat tightly coupled

there's tradeoffs everywhere choose what works better for you

cinder dawn
#

good evening

#

hello 😄

#

flutter is proving to be a bitch to learn

craggy bloom
#

!e
‘’’py
class Q:
x = 1

def do(self):
    self.x = 0

th = Q()
th.do()
print(th.x, Q.x)
‘’’

wise cargoBOT
#

@craggy bloom :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     ‘’’py
003 |     ^
004 | SyntaxError: invalid character '‘' (U+2018)
craggy bloom
#

!e

class Q:
    x = 1
    
    def do(self):
        self.x = 0

th = Q()
th.do()
print(th.x, Q.x)
wise cargoBOT
#

@craggy bloom :white_check_mark: Your 3.12 eval job has completed with return code 0.

0 1
craggy bloom
#

Does anyone know why 0 1

#

Isn’t should be 0 0

#

@wise loom

sweet prism
#

can i use !e?

#

!e

class Q:
    x = 1

    def set_instance_variable(self, x):
        self.x = x

    def set_class_variable(self, x):
        self.__class__.x = x
        # or Q.x = x

th = Q()
th.set_instance_variable(2)
print(th.x, Q.x)

th.set_class_variable(9_000)
print(th.x, Q.x)
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 2 1
002 | 2 9000
sweet prism
#

nice

#

@whole bear looking make 50 messages for voiceverify. ama.

#

how do i tell?

stuck furnace
#

If that's what you meant, you can use the !user command.

sweet prism
#

he said about 30. i'm guessing 17 or 18 more to go now

stuck furnace
#

!user 146119390813880320

wise cargoBOT
#
tener
User information

Created: <t:1454907977:R>
Profile: @sweet prism
ID: 146119390813880320

Member information

Joined: <t:1600011455:R>
Roles: None

Activity

Messages: 34
Activity blocks: 15

Infractions

Total: 0
Active: 0

sweet prism
#

i wan't able to get that information about myself

sweet prism
#

if you hate frontend, i heard about https://v0.dev/ a while ago. might help

Generate UI with simple text prompts. Copy, paste, ship.

#

flask has templating too

lucid brook
#

I'm new in python

sweet prism
sweet prism
#

is there something specific you want to ask about?

lucid brook
#

I'm new

#

So ig not

sweet prism
#

okay.. so strings in python3 are utf8 because the whole file you write in are utf8. but there's a caveat on Windows, as it's default encoding on the OS is CP-1252 (i think?) so you can get into a situation where reading japanese or mandarin from a file (or in a filename) can make python throw the toys out the pram if that's your situation. otherwise, have fun!

#

!e

a = "💃"
b = "🎉"
print(a + b)
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

💃🎉
eager thorn
#

also as well

#

!e

print("🐍" + "🍎", flush=True)

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

🐍🍎
sweet prism
#

eval run's in a separate process, right? so there shoulnd't be any need to pass flush=True to the bot, but i'm not sure

#

strings are immutable in python

#

!e

s1 = "asdf"
try:
    s1[1] = "b"
except TypeError as exc:
    print(f"Got exception: {exc}")
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

Got exception: 'str' object does not support item assignment
sweet prism
#

do containers have an obvious id?

#

!e

import os
print(os.system("uname -a; lscpu"))
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

32512
sweet prism
#

i can't think of an id..

eager thorn
#

!e

s1 = list("asdf")
try:
s1[1] = "b"
except TypeError as exc:
print(f"Got exception: {exc}")
else:
print("No exception")

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

No exception
sweet prism
#

yea,. if you convert the immutable str type to a mutable type first, you can mutate it, sure

#

!e

s1 = "asdf"
try:
    s1[1] = "b"
except TypeError as exc:
    print(f"Got exception: {exc}")

print(s1)
s2 = list(s1)
s2[1] = "b"
print("".join(s2))
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Got exception: 'str' object does not support item assignment
002 | asdf
003 | abdf
sweet prism
#

but that's lots of extra memory ^. idk if @lucid brook is coming from a C-family language where a "string" is an array or vector of char/u8's and are mutable.

#

!e

try:
    s = "a̸͋̓ṕ̷̒p̷͊̓l̷͑͝e̷̓͠s̷͐͝ ̴̿̑a̴̚͝ñ̴̽d̷̆̽ ̶͗͘b̷̎ananas"



    print(s[4])
except IndexError as exc:
    print(f"Got exception: {exc}")

i'm looking for the letter "e"

wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

p
sweet prism
#

python can index string with the [] syntax, which is weird, because you have to think about how utf8 works.. and utf8 works in weird ways. i used the zalgo generator to make that string, then asked python give the index of 4, which in the string of "apples" should be "e". but because of all the bits and bytes between the last "p" and the "e" i wanted, it got lost and gave me the wrong answer. zalgo isn't the only place where this happens, but any time there's a circumflex or umlot or whatever applied to the previous character, then the "index" gets weird.

#

locally, it gave me the answer ', but the Python bot removed most of the zalgofication.

wind raptor
#

!voice @vapid yarrow

wise cargoBOT
#
Voice verification

Can’t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

rapid chasm
#

@wind raptor Hey

#

No mic sorry

#

😅

#

Yeah

#

Do you know why?

#

Sounds about right

#

Hi @verbal zenith

#

No

#

!e

import timeit

def list_comprehension_test():
    x = [1, 2] * 1000
    q = {1}
    y = [n for n in x if n in q]
    z = [n for n in x if n not in q]

def for_loop_test():
    x = [1, 2] * 1000
    q = {1}
    y = []
    z = []
    for n in x:
        if n in q:
            y.append(n)
        else:
            z.append(n)

number = 1
repeat = 100

list_comp_time = min(timeit.repeat(list_comprehension_test, repeat=repeat, number=number))
for_loop_time = min(timeit.repeat(for_loop_test, repeat=repeat, number=number))

print(f"List comprehension: {list_comp_time * 1e6:,.2f}us")
print(f"For loop: {for_loop_time * 1e6:,.2f}us")
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | List comprehension: 159.12us
002 | For loop: 126.14us
whole bear
#

hi 👋

sweet prism
#

!e

import timeit

def list_comprehension_test():
    x = [1, 2] * 1000
    q = {1}
    y = [n for n in x if n in q]
    z = [n for n in x if n not in q]

def for_loop_test():
    x = [1, 2] * 1000
    q = {1}
    y = []
    z = []
    for n in x:
        if n in q:
            y.append(n)
        else:
            z.append(n)

def sets_reduction_test():
    x = [1, 2] * 1000
    q = {1}
    y = set(x) & q
    z = set(x) - q

number = 1
repeat = 100

list_comp_time = min(timeit.repeat(list_comprehension_test, repeat=repeat, number=number))
for_loop_time = min(timeit.repeat(for_loop_test, repeat=repeat, number=number))
sets_reduction_time = min(timeit.repeat(sets_reduction_test, repeat=repeat, number=number))

print(f"List comprehension: {list_comp_time * 1e6:,.2f}us")
print(f"For loop: {for_loop_time * 1e6:,.2f}us")
print(f"Sets reduction: {sets_reduction_time * 1e6:,.2f}us")
wise cargoBOT
#

@sweet prism :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | List comprehension: 175.99us
002 | For loop: 138.46us
003 | Sets reduction: 42.48us
sweet prism
#

also this

#

my guess as to why the list comps are losing here is that it includes the time to initialize the populate the list the first time around, but after that, the for loop version of the variable points to the instnace of x that already exists from another function. even if it's garbage collected (which is hit or miss, so idk), then the memory is still free, congruent and "unitialized", so when the brand new docker container runs it, and nothing else, then the memory is, like, right there. whereas in the local version, you get the full gammot of ASLR and each array needs to be reinitialized. but... that's just a guess. who knows.

#

local speeds:

sweet prism
#

^

#

he says it weird

somber heath
#

@regal bolt 👋

vocal basin
#

strsep seems to be non-standard

vocal basin
lavish rover
vocal basin
#

glibc thing maybe

lavish rover
#

In computer science, the Floyd–Warshall algorithm (also known as Floyd's algorithm, the Roy–Warshall algorithm, the Roy–Floyd algorithm, or the WFI algorithm) is an algorithm for finding shortest paths in a directed weighted graph with positive or negative edge weights (but with no negative cycles). A single execution of the algorithm will find ...

vocal basin
#

still not sure if this or 0b syntax is the most surprising thing to be standardised in C23

#

I wonder if there's something preventing _ used as digit separator

#

and both named vector?

lavish rover
#

so you can make a _km postfix to allow you to do stuff like 12_km

#

same for strings / other literal types

vocal basin
#

so it's to keep whatever compatibility left between C and C++

lavish rover
#

probably

vocal basin
#

if you limit yourself to writing 0 non-test code, it might be fun because of how bad GPT is if you don't fix its errors

little pond
#

Hi guys,
How can we select a specific character in a string in python?
For instance, I want to select 4th character in "hahaha". What code should I write?

somber heath
#

Subscription by index.

#

!e py print('abc'[0]) print('abc'[1]) print('abc'[2]) print('abc'[-1]) print('abc'[-2]) print('abc'[-3])

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | a
002 | b
003 | c
004 | c
005 | b
006 | a
somber heath
#

@little pond

little pond
#

yes sir

#

oh nice!

#

Thanks

little pond
somber heath
#

//

#

%

little pond
#

I see so divide by 10^3 to convert them into thousands

somber heath
#

divmod

little pond
#

could you elaborate the last sentences

#

yup

somber heath
#

!e py print(10^3)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

9
little pond
#

wait what?

#

how does power work then in python

somber heath
#

!e py print(10 ** 3)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

1000
little pond
#

ohh I see

#

interesting

somber heath
#

!e py v = 1234 a = v // 10 b = v % 10 print(a, b)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

123 4
somber heath
#

!e py v = 123 a = v // 10 b = v % 10 print(a, b)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

12 3
somber heath
#

!e py a = 'abc' b = 'abc'[::-1] print(a, b)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

abc cba
somber heath
#

!d slice

wise cargoBOT
#

class slice(stop)``````py

class slice(start, stop, step=None)```
Return a [slice](https://docs.python.org/3/glossary.html#term-slice) object representing the set of indices specified by `range(start, stop, step)`. The *start* and *step* arguments default to `None`.
somber heath
#

!e py print('abc'[None:None:-1])

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

cba
somber heath
#

!e py s = slice(None, None, -1) print('abc'[s])

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

cba
little pond
#

!e
s = slice(None, None, 2) print('abc23e23r'[s])

somber heath
#

!e ```py
from string import ascii_lowercase as alphabet

print(alphabet)
print(alphabet[::2])```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | abcdefghijklmnopqrstuvwxyz
002 | acegikmoqsuwy
little pond
#

!e
's = slice(None, None, 2)
print('abc23e23r'[s])'

wise cargoBOT
#

@little pond :x: Your 3.12 eval job has completed with return code 1.

001 |   File "/home/main.py", line 1
002 |     's = slice(None, None, 2)
003 |     ^
004 | SyntaxError: unterminated string literal (detected at line 1)
somber heath
#

!e

wise cargoBOT
#
Missing required argument

code

#
Command Help

!eval [python_version] <code, ...>
Can also use: e

Run Python code and get the results.

This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.

If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.

Currently only 3.12 version is supported.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!

somber heath
#

!code

wise cargoBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

somber heath
#

!e ```py
print('Hello, world.')
```

#

!e ```py
print('Hello, world.')

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello, world.
little pond
#

!e
print('Hello, world')

wise cargoBOT
#

@little pond :white_check_mark: Your 3.12 eval job has completed with return code 0.

Hello, world
somber heath
#

~

little pond
#

!e
print('hello world')

wise cargoBOT
#

@little pond :white_check_mark: Your 3.12 eval job has completed with return code 0.

hello world
little pond
#

!e

print('abc23e23r'[s])```
wise cargoBOT
#

@little pond :white_check_mark: Your 3.12 eval job has completed with return code 0.

ac32r
somber heath
#

!e ```py
from string import ascii_lowercase as alphabet

print(alphabet)
print(alphabet[::2])```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | abcdefghijklmnopqrstuvwxyz
002 | acegikmoqsuwy
somber heath
#

!e ```py
from string import ascii_lowercase as alphabet

print(alphabet)
print(alphabet[::3])```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | abcdefghijklmnopqrstuvwxyz
002 | adgjmpsvy
somber heath
#

!e ```py
from string import ascii_lowercase as alphabet

print(alphabet)
print(alphabet[1::2])```

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | abcdefghijklmnopqrstuvwxyz
002 | bdfhjlnprtvxz
little pond
#

!e

print("abcdefghijk"[::0])```
wise cargoBOT
#

@little pond :x: Your 3.12 eval job has completed with return code 1.

001 | abcdefghijk
002 | Traceback (most recent call last):
003 |   File "/home/main.py", line 2, in <module>
004 |     print("abcdefghijk"[::0])
005 |           ~~~~~~~~~~~~~^^^^^
006 | ValueError: slice step cannot be zero
somber heath
#

!d range

wise cargoBOT
#

class range(stop)``````py

class range(start, stop[, step])```
The arguments to the range constructor must be integers (either built-in [`int`](https://docs.python.org/3/library/functions.html#int) or any object that implements the [`__index__()`](https://docs.python.org/3/reference/datamodel.html#object.__index__) special method). If the *step* argument is omitted, it defaults to `1`. If the *start* argument is omitted, it defaults to `0`. If *step* is zero, [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) is raised.

For a positive *step*, the contents of a range `r` are determined by the formula `r[i] = start + step*i` where `i >= 0` and `r[i] < stop`.

For a negative *step*, the contents of the range are still determined by the formula `r[i] = start + step*i`, but the constraints are `i >= 0` and `r[i] > stop`.
little pond
#

!e

         print(i)```
somber heath
#

!e py for _ in range(5): print('Hello, world.')

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Hello, world.
002 | Hello, world.
003 | Hello, world.
004 | Hello, world.
005 | Hello, world.
somber heath
#

!e py for i in range(5): print(i)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
somber heath
#

!e py import random v = random.randint(0, 100) print(v)

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

39
somber heath
#

!d random.randint

wise cargoBOT
#

random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
somber heath
#

!e py import random seed = 5678 random.seed(seed) print(random.choices('abcdefg', k=10)) random.seed(seed) print(random.choices('abcdefg', k=10))

wise cargoBOT
#

@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | ['e', 'a', 'g', 'd', 'f', 'd', 'd', 'f', 'd', 'd']
002 | ['e', 'a', 'g', 'd', 'f', 'd', 'd', 'f', 'd', 'd']
craggy bloom
#

!e


L = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s = 0

for row in L:
    if row[0] > 2:
        s = s + row[1]

print(s)
wise cargoBOT
#

@craggy bloom :white_check_mark: Your 3.12 eval job has completed with return code 0.

13
craggy bloom
#

How its 13 ?

eager thorn
# craggy bloom How its 13 ?

(row[0] > 2) is True for the second row only (row[1] = 5 and row[1] = 8) and s is 0 at the beginning. So, s = 0 + 5 + 8 = 13

mystic lily
#
win = 0

def game_won()
  won += 1
vocal basin
#

at first I thought it would fail with NameError because of lack of global
but it's just two separate names (win/won)

eager thorn
#

!e

s = 0 + 5 + 8
print(s)

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

13
vocal basin
#

there are three errors, at least

#

!e

won = 0

def game_won():
    won += 1

game_won()
wise cargoBOT
#

@vocal basin :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 6, in <module>
003 |     game_won()
004 |   File "/home/main.py", line 4, in game_won
005 |     won += 1
006 |     ^^^
007 | UnboundLocalError: cannot access local variable 'won' where it is not associated with a value
vocal basin
#

oh, that's not NameError

#

!e

won = 0

def game_won():
    # bad, very bad, never do this
    global won
    won += 1

game_won()
wise cargoBOT
#

@vocal basin :warning: Your 3.12 eval job has completed with return code 0.

[No output]
vocal basin
#

@rapid chasm __lt__?

rapid chasm
#
# Get the list of member IDs in team 1 and team 2
team_member_ids = [user['member'].id for user in team_1 + team_2]

# Get the current time minus 15 minutes
time_threshold = datetime.now() - timedelta(minutes=15)

# Update the last_activity and games_played fields for all users in team 1 and team 2
# where the last_activity is not within the last 15 minutes
await collection.bulk_write([
    UpdateMany(
        {
            "discord_id": {"$in": team_member_ids},
            "last_activity": {"$lt": time_threshold}
        },
        {
            "$set": {"last_activity": datetime.now()},
            "$inc": {"games_played": 1}
        }
    )
])

return
vocal basin
#

!e

print(1 .__lt__(2))
print(2 .__lt__(1))
print(2 .__lt__(2))
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | True
002 | False
003 | False
vocal basin
#

less than, I'd expect

#

<time_threshold

#

recent?

#

(opposite of recent rather)

#

that's just what the code seems to describe
does it work?

rapid chasm
#

1. Check last_activity for all users; if it's older than 15 minutes,
2. If true, update last_activity to the current datetime.now() and increase games_played by 1.
3. If false, then skip this process.

vocal basin
#

last_activity < now - 15 minutes

#

that's what the code describes, if it runs without errors

#

less than

#

is it mongodb?

rapid chasm
#

Correct

vocal basin
#

it's probably doing it inside mongodb

#

$lt just represents <

#

I'd just put all players that were in teams at the start of the queue, when the pairing is cancelled

#

(they'd stay at the top of the queue, as if no pairing happened)

rapid chasm
vocal basin
#

ctr is to not have to move data a lot when someone leaves the queue

#

@modern yacht what do you mean by "dummy object"?

modern yacht
#

To use the update method to assign all attributes, you must create a “dummy” instance before:

mystic lily
#
class MyClass:
    def __init__(self):
        # Create a dummy object
        self.dummy_object = None

    def set_dummy_value(self, value):
        # Set the value of the dummy object
        self.dummy_object = value

    def get_dummy_value(self):
        # Get the value of the dummy object
        return self.dummy_object
vocal basin
vocal basin
#

> double pointer
wtf

#

it's not a double pointer

modern yacht
vocal basin
#

a more correct term is variadic keyword arguments

lucid brook
#

iM NEW IN CODING

#

Oh sorry

#

Im new in coding

#

I downloaded python im starting to learn like scripts and print

modern yacht
lucid brook
#

this is what ive gotten so far

#

what was that

vocal basin
#

first attempt failed

#

!e

class Vec2D:
    def __init__(self, **kwargs):
        self.x = 0
        self.y = 0
        self.update(**kwargs)

    def update(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return f'Vec2D({", ".join(f"{name}={value!r}" for name, value in self.__dict__.items())})'

vec = Vec2D()
print(vec)
vec.update(x=1.0, y=2.0)
print(vec)
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | Vec2D(x=0, y=0)
002 | Vec2D(x=1.0, y=2.0)
vocal basin
#

@modern yacht something like this?

lucid brook
#

cool

vocal basin
#

it's quite a hacky approach, but it doesn't involve eval

#

another thing that might be useful is setattr

lucid brook
vocal basin
#

this also doesn't check for whether a key is actually allowed

#

so a better way may be to use __slots__+setattr

modern yacht
vocal basin
#

__dict__ dynamically stores attributes of an object

vocal basin
#

if __slots__ is defined, __dict__ is undefined, iirc

#

!e

class Vec2D:
    __slots__ = ('x', 'y')

    def __init__(self, **kwargs):
        self.x = 0
        self.y = 0
        self.update(**kwargs)

    def update(self, **kwargs):
        self.__dict__.update(kwargs)

    def __repr__(self):
        return f'Vec2D({", ".join(f"{name}={value!r}" for name, value in self.__dict__.items())})'

vec = Vec2D()
print(vec)
vec.update(x=1.0, y=2.0)
print(vec)
wise cargoBOT
#

@vocal basin :x: Your 3.12 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 15, in <module>
003 |     vec = Vec2D()
004 |           ^^^^^^^
005 |   File "/home/main.py", line 7, in __init__
006 |     self.update(**kwargs)
007 |   File "/home/main.py", line 10, in update
008 |     self.__dict__.update(kwargs)
009 |     ^^^^^^^^^^^^^
010 | AttributeError: 'Vec2D' object has no attribute '__dict__'. Did you mean: '__dir__'?
rapid chasm
#

users_queue_sorted = sorted(users_queue, key=lambda x: x.get("ready_time", datetime.datetime.min))

vocal basin
#

depends on how you store/get the list

#

if you fetch it from mongodb, you can probably specify sorting there

rapid chasm
#

# Custom Games Queue users_queue = []

vocal basin
#

depends on how you insert values into it

rapid chasm
#
    summoner = await collection.find_one({"discord_id": member.id})

    summoner_name = summoner.get("summoner_name")
    tagline = summoner.get("tagline")
    tier_and_rank = summoner.get("tier_and_rank")
    elo = summoner.get("elo_rating")
    ready_time = datetime.datetime.now()
    users_queue.append(
        {"member": member, "summoner_name": summoner_name, "tagline": tagline, "tier_and_rank": tier_and_rank, "elo_rating": elo, "ready_time": ready_time})
vocal basin
#

if it's only .append, then it's sorted

#

if you never rebuild that list from external sources

#

datetime.now() is also non-monotonic

#

which causes errors in some regions once a year

#

it's not guaranteed to always go forward

#

for monotonic time, there is time.monotonic and time.perf_counter

#

they're valid and only increasing for the runtime of the process

#

values those functions provide only have meaning when you compare/subtract them (assuming two values are created within the same process)

#

this always works:

t1 = time.monotonic()
# do stuff
t2 = time.monotonic()
assert t1 <= t2

this in very rare circumstances fails:

t1 = time.time()
# do stuff
t2 = time.time()
assert t1 <= t2
rapid chasm
#

datetime.datetime.utcnow()
discord.utils.utcnow()

vocal basin
#

!d datetime.datetime.utcnow

wise cargoBOT
#

classmethod datetime.utcnow()```
Return the current UTC date and time, with [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.datetime.tzinfo) `None`.

This is like [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now), but returns the current UTC date and time, as a naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) object. An aware current UTC datetime can be obtained by calling `datetime.now(timezone.utc)`. See also [`now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now).

Warning

Because naive `datetime` objects are treated by many `datetime` methods as local times, it is preferred to use aware datetimes to represent times in UTC. As such, the recommended way to create an object representing the current time in UTC is by calling `datetime.now(timezone.utc)`.

Deprecated since version 3.12: Use [`datetime.now()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.now) with [`UTC`](https://docs.python.org/3/library/datetime.html#datetime.UTC) instead.
vocal basin
#

discord.utils.utcnow uses datetime.datetime.now inside

vocal basin
wise cargoBOT
#

discord/utils.py line 780

return datetime.datetime.now(datetime.timezone.utc)```
vocal basin
#

eh

#

why does it show only one line

#

ah, because I failed to copy properly

wise cargoBOT
#

discord/utils.py lines 767 to 780

def utcnow() -> datetime.datetime:
    """A helper function to return an aware UTC datetime representing the current time.

    This should be preferred to :meth:`​datetime.datetime.utcnow`​ since it is an aware
    datetime, compared to the naive datetime in the standard library.

    .. versionadded:: 2.0

    Returns
    --------
    :class:`​datetime.datetime`​
        The current aware datetime in UTC.
    """
    return datetime.datetime.now(datetime.timezone.utc)```
vocal basin
#

allegedly, has something to do with timezone-awareness

#

i.e. datetime.datetime.utcnow does something wrong

#

!e

from datetime import datetime, timezone
print(datetime.utcnow().tzinfo)
print(datetime.now(timezone.utc).tzinfo)
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:2: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
002 |   print(datetime.utcnow().tzinfo)
003 | None
004 | UTC
vocal basin
#

first doesn't know it's UTC

#

!e

from datetime import datetime, timezone
print(datetime.utcnow())
print(datetime.now(timezone.utc))
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:2: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
002 |   print(datetime.utcnow())
003 | 2023-12-11 10:31:15.626373
004 | 2023-12-11 10:31:15.626473+00:00
vocal basin
#

there are two separate concepts that are mixed in Python:
naive datetime
timezone-aware datetime

#

!e

from datetime import datetime
print(datetime.now() - datetime.utcnow())
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:2: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
002 |   print(datetime.now() - datetime.utcnow())
003 | -1 day, 23:59:59.999483
vocal basin
#

at some point

#

!e

from datetime import datetime, timezone
print(datetime.now(timezone.utc) - datetime.utcnow())
wise cargoBOT
#

@vocal basin :x: Your 3.12 eval job has completed with return code 1.

001 | /home/main.py:2: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
002 |   print(datetime.now(timezone.utc) - datetime.utcnow())
003 | Traceback (most recent call last):
004 |   File "/home/main.py", line 2, in <module>
005 |     print(datetime.now(timezone.utc) - datetime.utcnow())
006 |           ~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~
007 | TypeError: can't subtract offset-naive and offset-aware datetimes
vocal basin
#

naive and aware datetimes are separate, even though they have the same type

little pond
#

Guys,
How do you change a format of a the text in an string.
Like I would like to bolden 'not' in the string "This is not an apple". How would I do that?
"This is not an apple" is the response

vocal basin
#

in a terminal?

little pond
#

yes

vocal basin
vocal basin
little pond
vocal basin
vocal basin
#

other ANSI escape codes should work too

#

(some other)

vocal basin
#

difference is +00:00 at the end

little pond
leaden elk
#

Hello again guys. I'm back

oblique reef
#

me its 10:57 am

#

can you share screen

vocal basin
#

+00:00 means it's UTC
without that part, the datetime is "naïve" (timezone-unaware)

eager thorn
#

!e

from datetime import datetime, timezone

print(datetime.utcnow())
print(datetime.now(timezone.utc))

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | /home/main.py:3: DeprecationWarning: datetime.datetime.utcnow() is deprecated and scheduled for removal in a future version. Use timezone-aware objects to represent datetimes in UTC: datetime.datetime.now(datetime.UTC).
002 |   print(datetime.utcnow())
003 | 2023-12-11 10:57:53.836225
004 | 2023-12-11 10:57:53.836320+00:00
rapid chasm
#

discord.utils.utcnow()

vocal basin
#

same as datetime.now(timezone.utc)

vocal basin
#

datetime.datetime.utcnow is getting removed because it returns a partially invalid result

#

it's missing tzinfo in the returned datetime

#

and they can't add that tzinfo because that would break backwards-compatibility

rapid chasm
#
        thirty_days_ago = discord.utils.utcnow() - datetime.timedelta(days=30)
        if user.get('last_activity') and user['last_activity'] >= thirty_days_ago:
            # Elo rating (calculating MMR)
            elo_rating = await asyncio.create_task(calculate_mmr_async(summoner_puuid, api_key))
vocal basin
#

!e

from datetime import datetime, timezone, timedelta
print(datetime.now(timezone.utc) - timedelta(days=30))
#     ^^^^^^^^^^^^^^^^^^^^^^^^^^ same as discord.utils.utcnow()
wise cargoBOT
#

@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.

2023-11-11 11:04:02.860174+00:00
vocal basin
#

and it stays timezone-aware

rapid chasm
#

!e

from datetime import datetime, timezone, timedelta
print(datetime.now() - timedelta(days=30))
print(datetime.now(timezone.utc) - timedelta(days=30))
wise cargoBOT
#

@rapid chasm :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 2023-11-11 11:06:20.972102
002 | 2023-11-11 11:06:20.972392+00:00
vocal basin
#

this should work too

elo_rating = await calculate_mmr_async(summoner_puuid, api_key)
#

calculate_mmr_async calls should never overlap, right?

rapid chasm
#

elo_rating = await asyncio.create_task(calculate_mmr_async(summoner_puuid, api_key))

async def calculate_mmr_async(summoner_puuid, api_key):
    await calculate_mmr_lock.acquire() # waits until the lock is unlocked, and locks it

    elo_rating = await calculate_mmr(summoner_puuid, api_key)

    calculate_mmr_lock.release() # unlocks the lock

    return elo_rating

async def calculate_mmr(summoner_puuid, api_key):
*** CODE HERE***
vocal basin
#

does calculate_mmr have side-effects?

#
async def calculate_mmr_async(summoner_puuid, api_key):
    async with calculate_mmr_lock:
        return await calculate_mmr(summoner_puuid, api_key)
vocal basin
#

acquire/release is too low-level

#

async with is the preferred way

#

because it also handles errors

#

without async with, it should've been

async def calculate_mmr_async(summoner_puuid, api_key):
    await calculate_mmr_lock.acquire()
    try:
        return await calculate_mmr(summoner_puuid, api_key)
    finally:
        calculate_mmr_lock.release()
#

there is also a lock-less approach, but it uses a task, a queue and futures

#

it's not as relevant here, but useful sometimes

vocal basin
#

these two are almost identical:

await coroutine
await asyncio.create_task(coroutine)
#

in both cases, the outer coroutine is blocked on the completion of the inner one

#

there are performance differences, but you're very unlikely to witness them

#

iirc, error handling is similar enough too

#

(as far as my theoretical understanding of this goes)

first is generally "faster" if both the outer and inner coroutines are simple
and it's always more memory efficient

second is "faster" if either or both coroutines are "complex"

#

latter happens because each time the inner coroutine progresses there is no need to dig into outer coroutine's state

#

so the outer just gets notified when the inner completes, and is completely idle until that happens

#

at least that behaviour might be expected from generators-based async/await (e.g. Python and Rust)

#

I don't remember how JavaScript does it

#

it seems to be that everything there is like a task (represented as a Promise)

#

async with does acquire/release internally

#

sometimes acquire/release calls are from different functions

rapid chasm
#

if verification_completed: elo_rating = await asyncio.create_task(calculate_mmr_async(summoner_puuid, api_key))

vocal basin
#

e.g. define custom behaviour of async with for your classes

wise cargoBOT
#

Lib/asyncio/locks.py lines 12 to 20

class _ContextManagerMixin:
    async def __aenter__(self):
        await self.acquire()
        # We have no use for the "as ..."  clause in the with
        # statement for locks.
        return None

    async def __aexit__(self, exc_type, exc, tb):
        self.release()```
vocal basin
#

yes, == as the only operator to represent equality

#

=, in contrast, has more than one use

vocal basin
#

!e

x = 1

def func(*, y=2):
    pass

func(y=3)
wise cargoBOT
#

@vocal basin :warning: Your 3.12 eval job has completed with return code 0.

[No output]
vocal basin
#

you can ignore *,

vocal basin
#

pass does nothing

#

!e

pass
wise cargoBOT
#

@vocal basin :warning: Your 3.12 eval job has completed with return code 0.

[No output]
vocal basin
#

takes keyword-only argument y and does nothing

little pond
vocal basin
#

where do you call the function?

#

missing "

#

before )

#

the problem is that there might be genuine reasons for re-joining

eager thorn
#

!e

def ways(N, K):
dp = [0] * (N + 1)
dp[0] = 1

for row in range(1, K + 1):
    for col in range(1, N + 1):
        if col >= row:
            dp[col] += dp[col - row]

return dp[N]

print(ways(5, 3))

wise cargoBOT
#

@eager thorn :white_check_mark: Your 3.12 eval job has completed with return code 0.

5
vocal basin
#

I think it'd be more reasonable if discord itself had a mechanism to reduce effects of rejoining

#

all new bots I make are with Cogs

#

Cogs can handle any events, I think

#

I actually don't use on_ready for cog loading

#
await bot.login(token)
await bot.load_extension("stuff")
await bot.connect()
#

(as can be seen, not using bot.run)

rapid chasm
#

So, if a user’s last_activity is within the last 15 minutes (i.e., it’s greater than or equal to time_threshold), the update operation will not be executed for that user?

time_threshold = utcnow() - timedelta(minutes=15)

        await collection.bulk_write([
            UpdateMany(
                {
                    "discord_id": {"$in": team_member_ids},
                    "last_activity": {"$lt": time_threshold}
                },
                {
                    "$set": {"last_activity": discord.utils.utcnow()},
                    "$inc": {"games_played": 1}
                }
            )
        ])
vocal basin
#

I'd expect so

#

if mongodb works the obvious way

#

Jupyter isn't really an IDE

#

PyCharm, especially free, is inferior in some aspects of it, compared to VS Code

#

mostly remote Docker support

#

docker provides containerisation

#

and it's simpler, I'd expect

mystic lily
vocal basin
#

PM2 also seems to be for Node.js specifically

#

so far, docker compose was the most trivial way for me to run stuff

#

docker compose specifically

#

iirc, it used to be an external tool, but now it's more integrated into docker itself

#

you can run database in docker too

#

fun fact: we don't have McDonald's here

#

no

#

we still have KFC

#

it's getting rebranded

#

sounds like half of what I have

#

except for bandwidth

#

2 cores is very not enough for Minecraft

#

paper (which is optimised) consumes over 4 cores

#

depends

#

database might also cache data in RAM

#

(what I use)

#

100% silent

#

0 fans, 0 HDDs