#voice-chat-text-0
1 messages ยท Page 248 of 1
Maybe use a VPN if it ticks you off
@whole bear ๐
and they're gone
(or, in other words, I'm too lazy to edit)
Wear a mask. Wear it on your face.
where else does one wear a mask, may I ask
that negates the whole point
Doctors must complete a four-year undergraduate program, along with four years in medical school and three to seven years in a residency program to learn the specialty they chose to pursue. In other words, it takes between 10 to 14 years to become a fully licensed doctor.
!paste
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.
!code
what's up with the comments
@somber heath no it doesn't
comments visually make it look unprofessional
yeah
I didn't know that.
Understood
comments are also not checked by the language, which leads to situations like this:
https://paste.pythondiscord.com/KZZA#1L76-L77
it's adding lowerbound to random_int not other way around
there's an error in the comment
is upperbound inclusive or exclusive?
that should be written in docs
(line 40)
# shift random_int's range from [0;upperbound-lowerbound-1] to [lowerbound;upperbound-1]
random_int += lowerbound
if you do need to explain that line, this might be a better way
just as an example
it's more descriptive than "Add the random integer to the lowerbound"
(since it explains high-level effects and purpose of that statement)
this is an error
https://paste.pythondiscord.com/KZZA#1L191-L191
and Python should warn about it
!e
x = 1
x is 1
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | /home/main.py:2: SyntaxWarning: "is" with 'int' literal. Did you mean "=="?
002 | x is 1
is isn't same as ==
it only works sometimes
this can be simplified
https://paste.pythondiscord.com/KZZA#1L194-L204
Will the while loop at line 161 ever exit? Does it affect the indices list?
yes
append
indices = [self.randint(0, len(items)) for _ in range(num_selections)]
what's the difference between choices and sample?
(this is for choices)
sample's loop may end up waiting forever
I don't remember how to efficiently sample unique
collections.abc isn't used later on
Container isn't, Iterable is
there are some Iterable-related type errors
it should be Sequence instead
because Iterable doesn't have __len__
these don't seem to do anything
https://paste.pythondiscord.com/KZZA#1L158-L159
https://paste.pythondiscord.com/KZZA#1L191-L192
(no return)
You used the Any type, I think you would need to import it from typing first
on 3.12, there is [T] notation which is probably better than Any
in this case
def identity[T](value: T) -> T:
return value
Nice
yes, it's an invalid annotation
Sequence allows to call len on it
use Sequence for annotation instead of Iterable
if you can len on it
this is type error
def test(value: Iterable):
len(value)
yes, tell users that they need to pass Sequence in
if you need len
Sequence also allows indexing
typing.Sequence
collections.abc.Sequence should work too
maybe that's even preferred
yeah, use collections.abc.Sequence
typing one is deprecated since 3.9
it used to be a generic alias
but now collections.abc.Sequence supports generics itself
random.sample seems to use different algorithms for different sizes
https://github.com/python/cpython/blob/3.12/Lib/random.py#L432-L451
collections.abc.MutableSequence allows, iirc
maybe not
are you using an IDE?
with Pylance?
def MCX(self,
control_indices: int or Iterable[int],
target_indices: int or Iterable[int]) -> None:
""" Apply a MCX gate to the circuit.
Parameters
----------
`control_indices (int or Iterable[int]):
The index of the control qubit(s).
`target_indices` (int or Iterable[int]):
The index of the target qubit(s).
"""
# Ensure control_indices and target_indices are always treated as Iterables
control_indices = [control_indices] if isinstance(control_indices, int) else control_indices
target_indices = [target_indices] if isinstance(target_indices, int) else target_indices
# Apply the MCX gate to the circuit at the control and target qubits
for i in range(len(target_indices)):
self.circuit.append(qml.ControlledQubitUnitary(qml.PauliX(0).matrix(), control_wires=control_indices, wires=target_indices[i]))
# Add the gate to the log
self.circuit_log.append({'gate': 'MCX', 'control_indices': control_indices, 'target_indices': target_indices})
correction: ignores the other part
I forgot how or works
and would ignore int
it doesn't work
whereas | works correctly
what do you mean by "works"?
runtime errors?
well of course it wouldn't
type-wise it fails
type annotations do nothing during runtime
in this case
MCX(1, [2, 3])
so you can't judge based on runtime errors
MCX([1, 2], 3)
!d typing.Union
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Using that shorthand is recommended. Details...
output doesn't matter
runtime errors don't matter
it's not about runtime
it's about types
int or str is int
int and str is str
the type annotation is wrong
if you want union, use |
!e
print(int or str)
print(int and str)
print(int | str)
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | <class 'int'>
002 | <class 'str'>
003 | int | str
the latter is same as typing.Union[int, str]
what happens if control_indices and target_indices are of different type?
option1:
int, list[int]
option2:
np.ndarray, list[int]
list[int]
set[frozenset[str]]
...
a: list[int] = [1, 2, 3]
since 3.9, list itself is generic
this is the signature I'd expect
def choices[T](
self,
items: Sequence[T],
num_selections: int,
) -> list[T]: ...
why list:
- implementation will have to create list anyway
- provide more functionality to whoever uses the output
- make it clear that all values are computed before returning
last point means that it's not a generator-like thing
Traceback (most recent call last):
Cell In[11], line 2
test_qc.MCX(np.array([1, 2]), [3, 4])
Cell In[7], line 489 in MCX
self.circuit.append(mcx, control_indices[:] + [target_indices[i]])
File /opt/conda/lib/python3.10/site-packages/qiskit/circuit/quantumcircuit.py:1273 in append
expanded_qargs = [self.qbit_argument_conversion(qarg) for qarg in qargs or []]
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
!e
def example():
while True:
print("before yield")
yield 1
print("after yield")
for value in example():
print(value)
break
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | before yield
002 | 1
if choices was generating output element-by-element, Iterable would be a reasonable output type
Iterable[T] covers both Iterator[T] (something you can call next() of) and list[T];
if the intent is to not have the implementation tied to specifics, Iterable[T] might be appropriate
what, again?
(didn't understand yet)
starting from this?
@command
def click(x: int, y: int): ...
so the problem is that arguments aren't the same?
@command
def click(x: int, y: int): ...
@command
def drag(startx: int, starty: int, endx: int, endy: int): ...
@command(**args1)
@option(**args2)
@option(**args3)
def click(x, y):
...
first option relates to x and second to y?
what is passed as arguments to it?
name/description/default?
@command
def click(
x: Annotated[int, Option(name = "x", description = "click position's horizontal coordinate")],
y: Annotated[int, Option(name = "y", description = "click position's vertical coordinate")],
): ...
!d typing.Annotated
typing.Annotated```
Special typing form to add context-specific metadata to an annotation.
Add metadata `x` to a given type `T` by using the annotation `Annotated[T, x]`. Metadata added using `Annotated` can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a `__metadata__` attribute.
If a library or tool encounters an annotation `Annotated[T, x]` and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as `T`. As such, `Annotated` can be useful for code that wants to use annotations for purposes outside Pythonโs static typing system.
I've seen it somewhere recently but I don't remember where
(I knew about it for longer but there is some tool that uses it quite extensively for which I need to write that)
yes
to then parse from __annotations__
!e
from typing import Annotated
def click(
x: Annotated[int, "x argument"],
y: Annotated[int, "y argument"],
): ...
print(click.__annotations__)
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'x': typing.Annotated[int, 'x argument'], 'y': typing.Annotated[int, 'y argument']}
it might've been FastAPI but not sure
it was discord.py, I remembered
!source e
Run Python code and get the results.
code: Annotated[list[str], CodeblockConverter]
@stark river greetings
to make types same there's generics
and to limit what those are, there are bounds
def test[T: (int, list[int])](left: T, right: T) -> T:
match (left, right):
case (int(), int()):
return left + right
case (list(), list()):
return right + left
case _:
raise TypeError
so for that function's case:
def MCX[T: (int | Iterable[int], np.ndarray)](
self,
control_indices: T,
target_indices: T,
) -> None: ...
if target_rows != int(target_rows) or target_cols != int(target_cols):
!e
"" or ""
"" | ""
@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 2, in <module>
003 | "" | ""
004 | ~~~^~~~
005 | TypeError: unsupported operand type(s) for |: 'str' and 'str'
they're not equivalent
!e
def one():
print("one")
return 1
def two():
print("two")
return 2
one() | two()
one() or two()
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | one
002 | two
003 | one
!e
print({1} or {2})
print({1} | {2})
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | {1}
002 | {1, 2}
a or b is mostly equivalent to temp if (temp := a) else b
it's analogous to sets:
!e
print({"int"} | {"str"})
print(int | str)
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | {'str', 'int'}
002 | int | str
Do :
int | Iterable[int]
Instead of :
int or Iterable[int]
!e
print({"int"} | {"int"})
print(int | int)
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | {'int'}
002 | <class 'int'>
yes, because the second one is just int
a=1, or a=[1,2,3].
def func(arg: int | list[int]): ...
func(1) # ok
func([1, 2, 3]) # ok
func("1") # error
def func(
arg0: int | list[int],
arg1: int | list[int],
): ...
# all these are valid:
func(1, 1)
func([1], [1])
func(1, [1])
func([1], 1)
def func[T: (int, list[int])](
arg0: T,
arg1: T,
): ...
func(1, 1) # ok
func([1], [1]) # ok
func(1, [1]) # error
func([1], 1) # error
Yeah like this
data_arg = Iterable[float] | Iterable[Iterable[float]] | Data
nested works too, yes
Use Sequence instead of Iterable (How to best annotate and write methods with generic iterables in mind)
def MCX(self,
control_indices: int | Iterable[int],
target_indices: int | Iterable[int]) -> None:
""" Apply a MCX gate to the circuit.
Parameters
----------
`control_indices (int | Iterable[int]):
The index of the control qubit(s).
`target_indices` (int | Iterable[int]):
The index of the target qubit(s).
"""
# Ensure control_indices and target_indices are always treated as Iterables
control_indices = [control_indices] if isinstance(control_indices, int) else control_indices
target_indices = [target_indices] if isinstance(target_indices, int) else target_indices
# Apply the MCX gate to the circuit at the control and target qubits
for i in range(len(target_indices)):
self.circuit.append(qml.ControlledQubitUnitary(qml.PauliX(0).matrix(), control_wires=control_indices, wires=target_indices[i]))
# Add the gate to the log
self.circuit_log.append({'gate': 'MCX', 'control_indices': control_indices, 'target_indices': target_indices})
hi everyone
what
@whole bear you may be unaware, but these voice chats are offtopic. Talking about random topics is the standard; if you want ontopic, go to #python-discussion .
If you choose to mute me, that's certainly your prerogative. Pretty petty but whatever.
christ
@somber heath hai
who said that
oh mayor
ehh im being lazy
i really wanna finish what im doing rn but i have nothing good for it ๐ญ
idk i just picked a random word and tuna came up
@runic nimbus ๐
hes japanese because he/she's tuna
hi:)
yep
blue fin tuna
you could use they but im a guy
ok
(im not into pronouns or idk)
!mute 293195225734840320 4d if you have an issue with another user, do not resort to insults. this is your final warning for such behavior and the next time you do this you will be removed from the community.
:incoming_envelope: :ok_hand: applied timeout to @whole bear until <t:1706537250:f> (4 days).
Are you Vc'ing today?
@hallow oxide @torpid shard ๐
@gentle flint
๐
@strong pebble ๐
hey there !! wassup man
To do what? What's up?
Show my kitty..
Alr Imma go workout
@stoic sparrow ๐
!stream 425552190283972608
โ @peak depot can now stream until <t:1706195311:f>.
@fathom fox ๐
Hemlock, would you like to see the finished QRNG?
py -m pip install [package_here]
@north pawn @trail mulch ๐
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Numpy dropped out of Snekbox and got recently put back in.
Okay boomerang.
@jaunty turret What site are you trying to get info from
scrape it
@jaunty turret post it here
what i do for my whatsapp bots
Pesquise em vรกrias bases textuais disponรญveis no TCU.
[mid_point[0], *[mid_point[i] + perturbations[i-1] for i in range(1, len(mid_point))]]
Sazk is this a stupid way of doing this?
mid_point is a list of float.
perturbations is also a list of float, whose length is one less than mid_points's.
I almost have an answer
Ohh thank you!
it's a bit difficult to read but if it's working do it
bro just thanked hemlock for an almost answer
break it up n assign it to variables
You'd need to use something like Selenium. Selenium lets you navigate a site as if it was by a user, and since the site is JavaScript mainly, it's not really possible to do it using things like the requests library
@obsidian dragon https://en.wikipedia.org/wiki/Jakarta_Server_Pages That?
Jakarta Server Pages (JSP; formerly JavaServer Pages) is a collection of technologies that helps software developers create dynamically generated web pages based on HTML, XML, SOAP, or other document types. Released in 1999 by Sun Microsystems, JSP is similar to PHP and ASP, but uses the Java programming language.
To deploy and run Jakarta Serve...
95% Retro Mechanical Keyboard with Knob and Mini Display 97-key (ISO-UK: 98 Keys)+ 1 Multi-media Knob Smart Mini Display/TV Gasket-mounted & Ergonomic Design Powerful Software: Remapping Keys, Macros, RGB Backlights & Customizing Mini TV Displays 5-pin Hot-Swappable Kailh Socket Bluetooth 5.0, wireless 2.4G con
@sudden wyvern Better if you ask in here
mp_length = len(mid_point)
first_mp_element = mid_point[0]
answer = []
answer.append(first_mp_element)
for iterator in range(1, mp_length):
sum = mid_point[iterator] + perturbations[iterator-1]
answer.append(sum)
OKay yea. I think I have to send 50 messages to register the voice chat.
heh
I'll be back later, wanting to focus more on fixing this
what are pop tarts
have not tried this but I think I would like it: confetti cupcake -flavour
How It's Made: Pop-Tarts
The taste of biscuit cakes with sweet icing and delicious fillings will certainly leave an impression on your tongue and change the meaning of breakfast itself. But do you know how it's prepared?
In today's video we look at How It's Made: Pop-Tarts
Subscribe for how it's made full episodes, documentaries, and short f...
nah too corporatey
probably taste like cardboard like all corporate products
it does
few seconds in the microwave and boom
ur set
what do u eat sazk
what is ur 2 days of rations consist of
i eat a variety of thigns
rn it's just 2 days of ration left
which is worrying
vegetables
permission to speak
seals are creatures that live in the ocean not your computer silly
is it in a jupyter notebook?
lol are you a bot
yes
notebook
you may need to use a magic method to access pip.. iirc it was !pip install .....
yeah i did that
was there an erro?
wait let me show you the error
this
if you could allow me to talk in VC i can explain
faulty package?
While working with Python packages, programmers may encounter a specific error โ โpython setup.py egg_infoโ failed with error code 1. This error is related to the package installation process and can arise due to several reasons, such as outdated or improperly installed pip or other package installation tools. You can fix the โpython setup.py eg...
give me perk to speak in VC
ok ok
imma gonna check the blog , thanks for the help btw
i really love your support
I love you too
What did I just walk into?
it's not what it looks like
ask a programming question or something
True
fr
it's not like they're gonna run out
what happend to if we have to much of something it doesn't have value?
just give it away
i mean money wise
can someone help me with my graphics card issue?
maybe
meh.. wish i had time to hangout more.. between meetings and projects.. just cant sit at the pc for my free time ๐ฆ
add in the normalization hell im in.. why cant vendors normalize their own data.. its like wtf dont they use this data also... mimd boggiling
Hey
!voice
Canโt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
Yes
Do messages here count lol
Yes
What are you guys talking about
Bro just read the channel
?
what does "discord token account generator" mean?
!rule 5 if for any reason you're trying to access user tokens:
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
yeaah
idk
@stark river do you never leave voice chat
you're always there
but mostly don't respond if I join and speak to you
stalker
and you never speak to me
@somber heath i mean it in jest
besides me explaining the speaking is a moot point.. mostly i'm on my desktop so i don't have a mic there
my ๐ง is fried ๐ฎโ๐จ
git squashed without testing ๐ฆ
@empty spruce ๐
๐
"They" do. It's just that if you want a block, you have to show that you know what to do with it.
Which is a good idea because, or example, I have two contiguous IPv4 Class C blocks, but I haven't kept up my contact info so they are in limbo and no one else can use them.
@golden sonnet , @rugged root , in North America the IPv6 registrar is Arin
https://www.arin.net/resources/guide/ipv6/first_request/
@main spade ๐
First in first out - FIFO - queue
First in last out - FILO - stack
Yeah?
Stack - I have a vertical, ordered pile of things on the floor. Each time I add or take from it, I'm adding or taking it from the top.
Queue - I have a tube. I shove things in one end and take them out from the other in the same order they went in.
@languid solstice ๐
Scutelleridae is a family of true bugs. They are commonly known as jewel bugs or metallic shield bugs due to their often brilliant coloration. They are also known as shield-backed bugs due to the enlargement of the thoracic scutellum into a continuous shield over the abdomen and wings. This latter characteristic distinguishes them from most othe...
@rigid brook ๐
hi @somber heath
From turtle.py```py
Copyright (C) 2006 - 2010 Gregor Lingl
email: glingl@aon.at
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.```
@modest adder ๐
Bother.
That's what the server is for.
(With a correct interpretation of "bother")
Bother with questions about Python, yes.
I am currently working on a Discord, but within the constraints of the discord, API, and trying to find many workarounds to create a thread using a discord bot. The goal is to have this bot automatically create a thread, dependent on different variables. And I have attempted the simulate command, the API described code and other various options. Currently at loss. I am using Replit to deploy this bot. And I have adjusted my code accordingly, but to no avail.
I am truly just trying to create a thread automatically with the bot
๐ซ
Yeah, discord thread within the text channel
Like a sub channel
but they have a separate form channel archetype
I thank you for that
Will, I need to wait the entirety of the three days before I can ask for help?
Iโve had a separate bot running for over 30 days at this point
So Iโm feeling confident that Replit should be able to provide what I need
As I said earlier, the three days only applies to our voice verification system so you won't be able to talk in VC until then.
You're still free to talk (text) in the rest of the server until then though!
Understood that is good information. Thank you!
I will seek out the answer, and hopefully come up further than I have recently
It does appear that I can text in these chats
So I shouldnโt have issues seeking the answers with your peers
Thank you for all the help!
I wish you the best and have a wonderful day/night
๐
๐
2,570$ USD after tax
@somber heath I don't get it surri
_ _
class Phonebook:
def init(self):
self.contacts = {}
def add_contact(self, name, number):
self.contacts[name] = number
print(f"Contact {name} added successfully.")
def search_contact(self, name):
if name in self.contacts:
print(f"Contact {name}: {self.contacts[name]}")
else:
print(f"Contact {name} not found.")
def display_contacts(self):
print("Phonebook Contacts:")
for name, number in self.contacts.items():
print(f"{name}: {number}")
def main():
phonebook = Phonebook()
while True:
print("\n1. Add Contact\n2. Search Contact\n3. Display Contacts\n4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
name = input("Enter the name: ")
number = input("Enter the phone number: ")
phonebook.add_contact(name, number)
elif choice == '2':
name = input("Enter the name to search: ")
phonebook.search_contact(name)
elif choice == '3':
phonebook.display_contacts()
elif choice == '4':
print("Exiting phonebook.")
break
else:
print("Invalid choice. Please enter a valid option.")
if name == "main":
main()
!code
def __init__(self):
self.contacts = {}
def add_contact(self, name, number):
self.contacts[name] = number
print(f"Contact {name} added successfully.")
def search_contact(self, name):
if name in self.contacts:
print(f"Contact {name}: {self.contacts[name]}")
else:
print(f"Contact {name} not found.")
def display_contacts(self):
print("Phonebook Contacts:")
for name, number in self.contacts.items():
print(f"{name}: {number}")
def main():
phonebook = Phonebook()
while True:
print("\n1. Add Contact\n2. Search Contact\n3. Display Contacts\n4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
name = input("Enter the name: ")
number = input("Enter the phone number: ")
phonebook.add_contact(name, number)
elif choice == '2':
name = input("Enter the name to search: ")
phonebook.search_contact(name)
elif choice == '3':
phonebook.display_contacts()
elif choice == '4':
print("Exiting phonebook.")
break
else:
print("Invalid choice. Please enter a valid option.")
if __name__ == "__main__":
main()
IBM Quantum Lab
built-in python IDE
VSCode is basically just a text editor with extensions combined with the command line
Mabel is a spoiled rotten house pig, and she sleeps in the bed with her humans, which means that she requires a bath from time to time as she does not live outside like most pigs.
Mabels owners are on a mission to educate people on how to care for their pot belly pig, and bring awareness to dishonest breeders who lie about selling "mini pigs." ...
@torn adder ๐
hi
def define_distance_matrix(self) -> Iterable[Iterable[float]]:
""" Function to define the distance matrix for the given coordinates.
Returns
-------
`Distance_matrix` : Iterable[Iterable[float]]
The distance matrix.
"""
# Distance Matrix
Distance_matrix = []
temp_set = []
# Function for calculating the euclidean distance
def distance_between_points(point_A, point_B):
return np.sqrt((point_A[0] - point_B[0]) ** 2 + (point_A[1] - point_B[1]) ** 2)
# Generating the distance matrix
for i in range(len(self.coordinates)):
for j in range(len(self.coordinates)):
temp_set.append(distance_between_points(self.coordinates[i], self.coordinates[j]))
Distance_matrix.append(temp_set)
temp_set = []
return Distance_matrix
v: int = 5```
indexable immutable:
Sequence[Sequence[T]]
you can make a wrapper that indexes it the same way numpy allows to
with tuples
Mapping[tuple[int, ...], int]
indexed like
multidimensional[a, b, c]
(lists don't allow that)
!e
class MultiDimensional:
def __init__(self, inner):
self.inner = inner
def __getitem__(self, key: tuple[int, ...]):
inner = self.inner
for index in key:
inner = inner[index]
return inner
md = MultiDimensional([[1,2],[3,4]])
print(md[0, 1])
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
idk if it's a good idea at all to have arbitrary dimensions and not using np.ndarray
probably not
I think this is roughly what ndarray does
class Axis:
step: int
length: int
class NdArray[T]:
data: list[T]
start: int
axes: list[Axis]
@whole bear ๐
and indexing goes something like:
position = start
for axis, index in zip(axes, indices, strict=True):
assert index in range(axis.length)
position += axis.step * index
return data[position]
(trying to remember for myself how that works)
!e
from dataclasses import dataclass
@dataclass
class Axis:
step: int
length: int
@dataclass
class NdArray[T]:
data: list[T]
start: int
axes: tuple[Axis]
def __getitem__(self, indices: tuple[int]):
position = self.start
for axis, index in zip(self.axes, indices, strict=True):
assert index in range(axis.length)
position += axis.step * index
assert position in range(len(self.data))
return self.data[position]
array = NdArray(data=[0,1,2,3], start=0, axes=(Axis(step=2, length=2), Axis(step=1, length=2)))
print(array[0, 0])
print(array[0, 1])
print(array[1, 0])
print(array[1, 1])
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
@pallid peak ๐
isn't that basically an array
!d numpy.ndarray
class numpy.ndarray(shape, dtype=float, buffer=None, offset=0, strides=None, order=None)```
An array object represents a multidimensional, homogeneous array of fixed-size items. An associated data-type object describes the format of each element in the array (its byte-order, how many bytes it occupies in memory, whether it is an integer, a floating point number, or something else, etc.)
Arrays should be constructed using [`array`](https://numpy.org/devdocs/reference/generated/numpy.array.html#numpy.array), [`zeros`](https://numpy.org/devdocs/reference/generated/numpy.zeros.html#numpy.zeros) or [`empty`](https://numpy.org/devdocs/reference/generated/numpy.empty.html#numpy.empty) (refer to the See Also section below). The parameters given here refer to a low-level method (*ndarray(โฆ)*) for instantiating an array.
For more information, refer to the [`numpy`](https://numpy.org/devdocs/reference/index.html#module-numpy) module and examine the methods and attributes of an array.
like i don't think an array can be resized
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:
this Python array
Rust array can't be resized because they're const-sized
I don't remember what else calls them arrays
JS I guess too
there it's resizable
Java's arrays are fixed size (this I had to look up)
@fair geyser ๐
!d builtin
Most of the information of this page has been moved over to API Reference.
For information on plugin hooks and objects, see Writing plugins.
For information on the pytest.mark mechanism, see How to mark test functions with attributes.
For information about fixtures, see Fixtures reference. To see a complete list of available fixtures (add -v to also see fixtures with leading _), type :
what
why is it pytest
(I meant this)
!e
a_list = []
a_tuple = (a_list, a_list)
print(a_tuple)
a_list.append(None)
print(a_tuple)
@vocal basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ([], [])
002 | ([None], [None])
this is why I don't really like calling tuples immutable
or using notion of immutability in Python generally
hashability is closest Python has to immutability, imo
!e
print(hash((1, 2, 3)))
print(hash(([1], [2], [3])))
@vocal basin :x: Your 3.12 eval job has completed with return code 1.
001 | 529344067295497451
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 2, in <module>
004 | print(hash(([1], [2], [3])))
005 | ^^^^^^^^^^^^^^^^^^^^^
006 | TypeError: unhashable type: 'list'
@vocal basin I'm gonna go with my own class, and use the code you sent, and try that.
Thank you so much!
I feel your way is more reliable, at least I'd know what I can and can't do.
Easier to commit.
Hey why did the tuple scream into its mic?
better scream at tuples instead lyrics from Tallah -- Shaken:
"you couldn't be changed"
@whole sierra ๐
meme-oriented programming
It's okay
Why do programmers confuse Halloween with Christmas? Because OCT 31 == DEC 25. --pyjokes
This is my favourite package on pypi
strange
I already have it installed, so I can read dumb python jokes whenever I'm burnt out
That's every english joke
@whole bear ๐
Pyjokes has an entire category just for Chuck Norris
I mean, it is created by developers
True
Sorry, truth-y
Statements aren't techically True or False, but they evaluate to either one. So voila, they are truth-y
expressions
true, false, other
ok
can some learn me how to use pyinstaller
i wont work
just make py files exe files
say if you read this
wanna learn togeter
i mean making py exe files
o ok
il find it out then but stil thx
tomorow i can finaly talk in this channel
dont exuse yourself
no problem
i have an error while using pyinstaller
i mean installing
can we privatecall
you dont have to help me but then i can atleast talk back
did it
@neon osprey ๐
hi opal
this was good.
@somber heath sorry I joined by wrong
@uneven brook ๐
@somber heath hello
if 5 > 2:
print("Five is greater than two!")
if 5 > 2: print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!\n")
@somber heath :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | abc
002 | def
@ashen plover ๐
Hello
hi
let me spam 50 messages
Please don't. It will happen naturally.
Have a read of the first instruction in #voice-verification.
smh
Is there any program that will give me new challenges every day to learn python
No.
What would you like to learn?
How to make a game with python
What type of game?
Although I have very limited knowledge
!kindling May be of interest to you.
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
but they are actually
Something like hades, always been a dream!
Thank you!! Thisโll help!!
@turbid sandal please stop , genuinely asking nicely
Those are games built from dedicated engines, which are often written in C++.
Maybe try something a bit easier?
How about a card game?
btw...I am confusing to learn coding like sometimes I watch web dev tutorials and when I see my friend coding in python I do that...there's very uncertainity
Well there are some great resources to learn python if you need some basics.
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
If you have the basics, then try to learn through the project itself. You'll learn better by facing issues and questions, and then solving/answering them through it.
I can give you a project, or you can use the kindling ones Opal sent. They are likely much better.
aah back then I tried some questions and projects to do it by myself...and I failed to do that, then my confidence broke
Well you'll learn through the project.
yep it will be good ig
If you are doing sth that is too hard, try sth simpler, and build your way up.
hmm
@whole bear Greetings
matplotlib
plt.show() or plt.imshow()
import matplotlib.pyplot as plt
me too
does anyone know how to print in python whithout using the "print()" function??
console.log
in pyton
python
who have put that fucking flag on my message!
fuck isreal
isreal is losing the war
have put*
its irregular verb
!silence
โ silenced current channel for 10 minute(s).
@whole bear @noble rose This is not the way to interact in the server. If you are not able to stay civil then your time here may be limited. Both of you take a break and read the #rules and #code-of-conduct
!unsilence
โ unsilenced current channel.
Thanks
alnurr didn't do anything
yeah
Apologies, then @turbid sandal please read my message above
yeah
oh
@noble rose catching strays
Please read #rules @whole bear like @candid panther said
@candid panther @noble rose didn't do anything
Spamming reactions is not appropriate
i did
he got it
the problem is much bigger than you think
@whole bear @turbid sandal drop it, alright? We're moving on.
thanks you!
life goes on
hell yeah
I am not moving on then are killing babies and women
who didn't doc anythingg
please not politics
!mute 882233326704930837 Take a break
:incoming_envelope: :ok_hand: applied timeout to @whole bear until <t:1706282959:f> (1 hour).
jesus
Again, apologies for the ping
Greetings Brad!
no problem
Great meeting your acquaintance sir. Please do drop into the call sometime.
I don't do voice chat, too many meetings
brad be like.. i don't mix with the plebs /jk
I see. Well I wish you a blessed weekend ahead good sir.
๐ง

yo what happened here?
People misbehaved, and now it stopped
yepp
lol, no I just find the text channel portion of discord easier to access
@hollow totem ๐
@frosty token ๐
๐
i gtg food searching ๐ฆ
i may have to resort to eating from outside โน๏ธ
i mean a food stall.. not a dumpster
@tawdry kernel ๐
food searching ?
i have no food i have to purchase from outside.. i dont like eating non home cooked food
i think subway provides healty food
๐คฃ
BTW starship 3rd launch maybe in Feb, excited.
that reminds me there's a marathon coming up in the start of feb.. i need to check the dates to register and participate
@rugged root ordered some small bike stuff
the contents
it was mostly filled with wadding
damnnn
why they had to use such a huge box I do not know
they needed that giant box so it fits exactly in the truck
maybe separate a section of the truck that can fit small box
if you thought your johnson was enough, well, you'd better check this shit out.
Fish-henge.
Rotate pages clockwise and counterclockwise
Fuck. You. Adobe
I use LibreOffice if I need to do pdf stuff.
LaTeX
10 print "Hello, world."
20 Geauxteaux 10```
well let me know if you need anything made @rugged root
As part of Mercedes-Benz Intelligent Drive, MAGIC BODY CONTROL ensures optimum driving comfort. Watch the โChickenโ advertisement here. More information about the Mercedes-Benz S-Class: http://mb4.me/sclass_website
โบSubscribe to Mercedes-Benz on YouTube: http://www.youtube.com/subscription_center?add_user=MercedesBenzTV
โบExperience the world o...
Great ideas are everywhere!
How did the Tyrannosaurus Rex and it's kind come to dominate their prehistoric world? Palaeontologist Dr David Hone explores the evolution, ecology and behaviour of these amazing dinosaurs, and explains what Jurassic Park got wrong.
Watch the Q&A here: https://www.youtube.com/watch?v=eTWG5WY_XoM
Subscribe for weekly videos http://bit.ly/RiSubscR...
Eh, it's already done
ngl, he's kinda bad.
Seeing Stacy's mom in his arms, it makes me beyond sad
But one day he'll see my charms, and it will make him mad,
maaad with love
Someday LOVE will find YOUUU
- Guitar solooo
Making of "The Prodigy - Voodoo People" in Ableton by Jim Pavloff
list[]
def define_distance_matrix(self) -> List[List[float]]:
""" Defines the distance matrix for the given coordinates.
Returns
-------
`Distance_matrix` (List[List[float]]):
The distance matrix.
"""
# Initialize the distance matrix
distance_matrix = []
def distance_between_points(point_A: List[int],
point_B: List[int]) -> float:
""" Function for calculating the euclidean distance.
Parameters
----------
`point_A` (List[int]):
The first point.
`point_B` (List[int]):
The second point.
Returns
-------
`distance` (float):
The euclidean distance between the two points.
"""
return np.sqrt((point_A[0] - point_B[0]) ** 2 + (point_A[1] - point_B[1]) ** 2)
# Calculate the distance matrix
for a in self.coordinates:
distance_matrix.append([distance_between_points(a, b) for b in self.coordinates])
# Return the distance matrix
return distance_matrix
Type matrix = List[List[float]]?
from typing import List
list[]
Yo
@typing.overload```
Decorator for creating overloaded functions and methods.
The `@overload` decorator allows describing functions and methods that support multiple different combinations of argument types. A series of `@overload`-decorated definitions must be followed by exactly one non-`@overload`-decorated definition (for the same function/method).
`@overload`-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-`@overload`-decorated definition. The non-`@overload`-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an `@overload`-decorated function directly will raise [`NotImplementedError`](https://docs.python.org/3/library/exceptions.html#NotImplementedError).
!d typing.Sequence
class typing.Sequence(Reversible[T_co], Collection[T_co])```
Deprecated alias to [`collections.abc.Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence).
Deprecated since version 3.9: [`collections.abc.Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence) now supports subscripting (`[]`). See [**PEP 585**](https://peps.python.org/pep-0585/) and [Generic Alias Type](https://docs.python.org/3/library/stdtypes.html#types-genericalias).
!d typing.Iterable
class typing.Iterable(Generic[T_co])```
Deprecated alias to [`collections.abc.Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable).
Deprecated since version 3.9: [`collections.abc.Iterable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterable) now supports subscripting (`[]`). See [**PEP 585**](https://peps.python.org/pep-0585/) and [Generic Alias Type](https://docs.python.org/3/library/stdtypes.html#types-genericalias).
Did I die?
NdimList(shape, dtype)
Yeah, that'd work then
God forbid
I did ask there.
They said to use List, but I didn't really fully comprehend, so I waited until you would be available.
Radio commercial from "Vampire: The Masquerade - Bloodlines".
?
Yeeeeeeeeeeeeeeeeeeeeeeeeeeeep
one finger typing?
that's my only setting.
learn on my keyboard layout instead of qwerty. it's the best keyboard layout in the world
smh these luddites
outperforms qwerty on distance covered, same finger bigrams and home row usage metrics
ok
NDA Jam: Tournament Edition
!e
from dataclasses import dataclass
@dataclass
class Axis:
step: int
length: int
@dataclass
class NdArray[T]:
data: list[T]
start: int
axes: tuple[Axis]
def __getitem__(self, indices: tuple[int]):
position = self.start
for axis, index in zip(self.axes, indices, strict=True):
assert index in range(axis.length)
position += axis.step * index
assert position in range(len(self.data))
return self.data[position]
array = NdArray(data=[0,1,2,3], start=0, axes=(Axis(step=2, length=2), Axis(step=1, length=2)))
print(array[0, 0])
print(array[0, 1])
print(array[1, 0])
print(array[1, 1])
@upper basin :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
Why am I getting this error when I run this in my notebook?
Traceback (most recent call last):
File /opt/conda/lib/python3.10/site-packages/IPython/core/compilerop.py:86 in ast_parse
return compile(source, filename, symbol, self.flags | PyCF_ONLY_AST, 1)
Cell In[10], line 9
class NdArray[T]:
^
SyntaxError: invalid syntax
Is this a python version thing?
@rugged root Here is my aircheck if you want to take a look 
Nifty
@rugged tundra so I'm trying to correct how I should use type hinting for generic lists.
you may need to define T?
I don't know how to do it well, so I've been asking for opinions from the guys, and trying to learn.
!code
Do the hightlighting
here.
Trying to fix a bug ATM

Beg your pardon?
Using the overloading decorator I pointed out earlier
I was sort of following on the ND class way you suggested.
Ohh
How would that work for Ndarray?
I am not sure how I should use it in this context.
another way to expressed what I showed with TypeVar bounds
also works for different numbers of arguments
Ooo ooo ooo veggie tray in the kitchen brb
What do you mean by fixed-size? I forgot.
of arguments
Ooh
So what I would like to have would be the dimension (or shape, whatever) and dtype.
That's all.
I think dimension is better?
For type annotating at least.
Like NDArray(dim=2, dtype=float) would be same as list[list[float]].
Those mud guards are so intense for that car
It's like it's wearing shin guards backwards
@mild quartz Yo
@vocal basin is this considered fixed size?
Greetings @mild quartz
yoyo
i asked in the lobby why do we need pydantic when typing stdlib has NewType
i got ans: ur pfp is js
smh
Data validation using Python type hints
@mild quartz Are you in the headspace to take a crack at my question?
Python typing question.
@warm jackal Buddyyyyyyyyy
sure what is it
Oooh thank you!
o/ 'time no talk! Much change on your end?
Ok, so I would like to know what is the best way to type hint (and how to write the code) for generic lists in python.
Let's say using sth like this code :
def define_distance_matrix(self) -> list[list[float]]:
""" Defines the distance matrix for the given coordinates.
Returns
-------
`Distance_matrix` (list[list[float]]):
The distance matrix.
"""
# Initialize the distance matrix
distance_matrix = []
def distance_between_points(point_A: list[int],
point_B: list[int]) -> float:
""" Function for calculating the euclidean distance.
Parameters
----------
`point_A` (List[int]):
The first point.
`point_B` (List[int]):
The second point.
Returns
-------
`distance` (float):
The euclidean distance between the two points.
"""
return np.sqrt((point_A[0] - point_B[0]) ** 2 + (point_A[1] - point_B[1]) ** 2)
# Calculate the distance matrix
for a in self.coordinates:
distance_matrix.append([distance_between_points(a, b) for b in self.coordinates])
# Return the distance matrix
return distance_matrix
def foo(bar: list[T]):
pass
No?
I would like to know what's the best way to do this, in a way that is readible (user would know if the variable is a vector, or matrix, or some tensor of rank N. Also a way that if a professional developer looks at wouldn't think I'm a stupid person.
Well how would you represent matrix and vector? Would they be different, or the same?
you can use numpy and numpy types
or torch and torch types
or a generic container
or a union type of list, NDArray, Tensor
A vector is a list of set size.
A matrix is a list of n vectors of m length each.
This is what I would like. A generic, mutable, iterable object.
Well that's my question, if you would do list[list[T]], then you would have to nest them for N.
object? i think you mean list?
Yes.
I was doing a class for representing this, so that's why I said object.
I was thinking of making a class like this to make this representation. Not my code, Alisa kindly wrote this for me, and I liked it since I would know the supported methods this way.
FInd out (I don't know myself) if python supports typehinting an iterable of a given size/length. Then use that if it exists.
abc.MutableSequence?
The rest you can compose yourself w/type aliasing.
you probably just want a generic list
Someone suggested that in #type-hinting and said to use list instead with python 3.12.
Yeah, something that would show the dimension, and dtype.
i dont think python can do dimension
But then how would I express an N dimensional list?
This code example does not define a vector in any way (formally). Because it does not constrain or hint at any size. So there's nothing stopping you from making a matrix of multple NDArrays of differing lengths/sizes
I don't believe you can do that with typing
Ok, so let's say I make a class for this. Is it sth I can do but shouldn't or sth that is good to do given my circumstance?
Well I would do sth like NdArray(dim=1, dtype=float) for vector, and NdArray(dim=2, dtype=float) for matrix, and so on.
I am not familiar with pydantic. I'll have a look at it right away!
But what do you guys think of this?
Is it a bad practice?
Wife's been sick still (since Oct 2022), work is going the same, still gaming a lot, recently signed up for some coding courses that also assist with making a portfolio and getting freelance work
well it doesn't exist
@upper basin Here, I did your googling for you. You can do with this what you will. But this seems like you should be able to implement something that match any formal definition of a vector/matrix: https://stackoverflow.com/a/49434182
numpy.typing has NDArray
What doesn't exist?
He's talking about NDArray type
Yes, but I was under the impression that using a very specific type would be relying too much on numpy.
its a type defined in numpy.typing
Arbitrarily deep arrays that's what she said
I was hoping for sth more generic.
Okay
I'm just saying that NDArray in np.typing isn't sized
Yeah, sth like np.ndarray, but with syntax similar to list?
you should try what x10an14 suggested or Pydantic
This?
Tbf, a tuple is designed to be of a specific size, with a specific type variable T.
I apologize if I am asking a question multiple times, I believe I missed it, what does pydantic do basically?
you can define types with validators
Now I see my mistake. It would only work for type hinting, but would fail with actual variable making which would need specific size.
You can feed it a JSON or what have you and it'll validate the data, making sure it conforms to the spec
This would only work at runtime though
I don't think the hints would work
like wouldn't detect wrongly sized array in your ide
Well the hints are more of being a good programmer.
I know it doesn't affect the code.
Like runtime-wise.
There are ways to make it do so
But it's... weird
discord.py does it
I think they're called converters?
Also, what I would REALLY hope for is to allow it to take in numpy.ndarray, or list, etc. and convert it to its own format?
Subscribe and ๐ to the BBC ๐ https://bit.ly/BBCYouTubeSub
Watch the BBC first on iPlayer ๐ https://bbc.in/iPlayer-Home http://www.bbc.co.uk/thursdays
Thursdays at 9.30pm on BBC Two
Comic actor Peter Serafinowicz (Look Around You, Hardware, Spaced) morphs into a visual cacophony of characters in this new, off-the-wall comedy sketch show on BBC ...
Like maybe sth like :
if not isinstance(list_passed, NdArray):
list_passed = NdArray.convert(list_passed)
Am I over-complicating it?
Like I feel I'm going on a tanget that makes everyone slap their foreheads, smh style.
Because from what I experienced, numpy has its own specific methods and syntax, and I dominantly use list, mainly because it's more generic and straightforward to use, and also feel like when users think of a list of let's say indices, they do [1, 2, 3], not np.array([1, 2, 3]).
I know it's a very flawed reasoning, but it's why I haven't really fully depended on numpy.
If you're making something like this, pick one
Can someone please help me with this - https://discord.com/channels/267624335836053506/1200489481686483015
Trying to cover too many cases is just going to bog down your code and actually overcomplicate things
Yeah, "Make up your mind already." is the right advice.
I think that's why I am so confused.
I am thinking of way too many things.
but you're doing linear algebra stuff right?
so lists will be slow
numpy has built in vectorization and other optimizations
Mainly yes, but not necessarily. Some of the functions and methods use list, but the list is not a LA object.
Huh, hadn't heard of JAX before
You mean when you do np.array([1, 2, 3]) is more efficient than [1, 2, 3]? Did I misunderstand?
I've told you about jax ๐ข
no, but when you do any operation with the vector
Correction: My ADHD brain did not properly abosrb information about JAX because I don't have a usecase
Oh.
this is why numpy exists
I understand.
numpy itself is super super efficient
just rewrite everything in numpy
So enforcing or pushing your users to use it is only benenficial
or if you need GPUs use Jax or torch
Let's see, I use padding and normalization and flattening , so in those cases numpy is better?
oh yeah
Very much so
So I should adopt numpy as the generic iterable/list interface?
Well mine would likely suck since I don't use any optimizations in that regards.
Ok, so I have to adopt numpy.ndarray as my generic interface, and use np.array as vector, and np.ndarray for N dimensional lists?
Yes, that's sth I have been thinking of.
That makes more sense. Thank you so much for that.
use the numpy typing module
@rugged root @mild quartz @vocal basin thank you guys!
Any idea why JAX fails with joblib?
Yeah, I'll get on that, and start using that by default.
are you trying to serialize something that is still on device?
This is what I'm doing -
# This experiment showed that more CPUs (from 2 to 6) did help speedup JAX code
from joblib import Parallel, delayed
import gym
import os
from sbx import SAC
import multiprocessing
def my_func():
env = gym.make("Humanoid-v4")
model = SAC("MlpPolicy", env,verbose=0)
model.learn(total_timesteps=7e5, progress_bar=True)
Parallel(n_jobs=6)(delayed(my_func)() for i in range(6))
@prisma swallow @prime coral Yo to you both
jax has its own parallelism modules
vmap?
Could you please tell me the name of the JAX function that helps with parallelization? I am a newbie and most of these terms on the documentation don't make sense to me ๐
Because I am doing Reinforcement Learning.
unfortunately you need to read and learn the docs about this
No, the gym library is the data for RL. The sbx library needs JAX
this library youre using should have this built in
brb standup
How goes it