« first day (4103 days earlier)      last day (835 days later) » 

12:06 AM
@MattDMo No probs :)
 
 
9 hours later…
9:01 AM
Anyone can help me out on toggling the same button for it to change the icon upon clicking it. I'm trying to change the icon of a play and pause button when the user clicks on it, and the song should ofc play and resume.

This is just a part of the program: https://dpaste.org/c4SE

I only managed to let it play and repeat, which it shouldn't, it should resume not restart...
 
What's up with the
if not self.music_paused:
elif self.music_paused:
else:
Since when does a boolean have 3 states?
 
the variable music_paused is False initially, so I thought of declaring a variable and work with it. So if it's False, the icon should change to pause icon and the music should be playing.
 
But how can that else branch ever be reached?
 
9:21 AM
It's not reaching, that's why it's not resuming but restarting instead, and that's where i can't figure it out. I'm gonna try to just split them up
 
No, that's not why. There are only 2 cases. Either the music is paused or it's not. It makes no sense to have 3 if branches there
I don't know why it's restarting, and judging from the pygame docs it looks like your code should actually crash with an AttributeError, but there's also this problem:
    self.music_paused = True
    mixer.music.play()
    self.music_paused = False
    mixer.music.pause()
Did you assign a Sound object to mixer.music somewhere?
Oh never mind, the pygame documentation is just terrible
 
no, mixer is only being used inside "toggle_play_pause". There's no other line of code containing audio stuff
 
@Aran-Fey Let me rephrase that. It does make sense to have 3 branches there, but not if you're checking a boolean value. You need some other condition.
 
9:51 AM
I think the flag variable has to be there, it'll at least help me check whether the music hs been paused or not.
 
But there are more than 2 states. There's "unitialized", "playing" and "paused"
 
10:28 AM
@CoreVisional does this help?
There are literally no other options.
 
10:39 AM
That kind of makes it look like not music_paused is a superset of music_paused :P
 
then clearly you're looking at it wrong
Should I use the same font colour as the corresponding subset? :P
 
Should've used a pie chart
 
yes, an interactive one with plotly
 
Actually, a pie chart isn't quite right either. It should've been 2 non-overlapping circles
 
no, because there's always an implied containing superset
you would be demonstrating that there's one circle, the other circle, and what's outside both
it's just that "not music_paused" in my figure refers to the blue region rather than the entire (simply connected) rectangle
see also the textbook representation of complements
 
10:45 AM
Point taken
 
@CoreVisional Snippet not available
@Aran-Fey Mmmm play() will prolly start the music from start, I think the right one is unpause()
 
Depends on what state the mixer is in :P
 
Ah well ofc :p
 
It's the same as the one I sent here, still trying to figure out: dpaste.org/Qxds
 
if self.music_paused:
    ...
elif self.music_paused:
    ...
oh boy
I think this is my exit
 
10:59 AM
I changed it to this, but ofc it keeps restarting

    def toggle_play_pause(self):
        mixer.init()
        mixer.music.load(self.music_file)
        mixer.music.play()

        if self.music_paused:
            self.unpause_music()
        else:
            self.pause_music()

    def pause_music(self):
        mixer.music.pause()
        self.play_button.config(image=self.icons["play_pause_icon"][0])
        self.music_paused = True

    def unpause_music(self):
        mixer.music.unpause()
 
That's not much of a surprise if you init() and load() and play() every time the button is clicked, is it?
 
init when the GUI starts
 
 
1 hour later…
12:23 PM
601th day in stackoverflow and its been one of the greatest experience in life, all the learning that has happened here was greater than what I had in school. Definitely the best Q&A platform :P
 
1:02 PM
For some definitions of "best" :P
 
1:18 PM
Hmm, I have a question about the interaction between dundermethods and descriptors. When python looks up a dundermethod and notices it's a descriptor, it invokes its __get__ method. But... __get__ is also a dundermethod and a descriptor, so now we're back to square one. Why doesn't this cause endless recursion? What's the exit condition?
 
@Aran-Fey Indeed :P
 
2:28 PM
@Aran-Fey Not everything has a __get__ and not everyting is looked up via object.__getattribute__ (which invokes descriptors).
Try [].__len__.__get__
 
Right, but there are cases where you can go infinitely deep
obj = lambda: 0
while True:
    obj = type(obj).__get__
 
Hey Everyone, I'm trying to find an awaitable condition in asyncio. I have an external MQTT program, which takes commands in one topic and sends the response after doing its thing into a different topic - the command and response can be correlated later with a message id, which I have to do on my side. Since I'd like to abstract this behavior away in my code, I'm currently doing this:


from asyncio import sleep

class MyCode:
_pending = {}
async def doThing(self, id, **options):
self._pending[id] = None
 
You cannot have both regular text and code format in one chat message.
@Aran-Fey You're not actually invoking __get__, though. Is that what you are wondering about?
 
@Aran-Fey Ah, the text above and below was the problem then. Thanks!
 
Four spaces in front, and no text that isn't code in the same message
@MisterMiyagi The point is that I could. Every __get__ method I see has its own __get__ method. At what point do I stop calling it?
 
2:44 PM
from asyncio import sleep

class MyCode:
  _pending = {}
  async def doThing(self, id, **options):
    self._pending[id] = None
    self._sendToTopic('/command/', json.dumps({**options}))

    # SMELL: there must be a better way to do this??
    while id not in self._pending:
      sleep(0.1)

    response = self._pending[id]
    del self._pending[id]
    return response

  def on_receive(self, msg):
    self._pending[msg.id] = msg.payload
That looks more like it.
 
@Aran-Fey Immediately. object.__getattribute__ only calls the first.
 
Of course, I can easily find the point where it stops making a difference if I do get(instance) or call_dundermethod(get, '__get__', instance). But I don't know if that's the correct point to stop. How does CPython do it?
 
Anyone knows how to get rid of that ugly codesmell?
 
@MisterMiyagi Not sure if that's becuase function.__getattribute__ doesn't, though.
@Lars Are you looking for an event or future perhaps?
 
@MisterMiyagi Okay, look, it's about calling a dundermethod. Someone executes foo(). Python finds the corresponding __call__ thing, notices it's a descriptor, so it has to call its __get__ method. Now you're back to square one: You want to call a dundermethod, but in order to do so, you must call another dundermethod. Where does it stop?
 
2:48 PM
@MisterMiyagi possibly - so the on_receive() would send an event, and doThing would await it?
 
It's a bit confusing because you add id to self._pending and then you have a while id not in self._pending: loop right after
 
@MisterMiyagi I see... asyncio.Event seems to be the way to go. Now I found docs.python.org/3/library/asyncio-sync.html to read more on. Thanks for the help - wonder why I didn't find that page before...
 
@Aran-Fey There's a __get__'less thing some way down. Builtins can be invoked without looking up their __call__.
 
@MisterMiyagi one more question: Any hints for further reading on how to timeout while waiting for an Event or Condition?
 
@Aran-Fey Here's the object.__getattribute__ part for descriptors. It doesn't bother checking whether __get__ has a __get__, it just calls it.
@Lars asyncio.wait_for should do what you want.
@MisterMiyagi You could try and experiment with a __get__ that is a custom object with a __get__.
 
2:54 PM
I'd do something like this:
class MyCode:
  async def doThing(self, id, **options):
    future = asyncio.get_running_loop().create_future()
    self._futures[id] = future

    self._sendToTopic('/command/', json.dumps({**options}))

    await future
    del self._futures[id]
    return future.result()

  def on_receive(self, msg):
    self._futures[msg.id].set_result(msg.payload)
 
@MisterMiyagi thxalot!
 
@Lars If you want to send in a payload, use Aran's approach. A Future is much faster than an event and value-lookup.
 
@MisterMiyagi If I understand this line correctly, then it doesn't invoke __get__ if the descriptor it found is a function?
 
@Aran-Fey @MisterMiyagi I'll try out both - thanks, both of you!
 
Oh, but it also returns 1 instead of 0 in that case. Not sure what difference that makes...
 
3:13 PM
Wow, it really just calls the descriptor's __get__. That's lame
 
@JonClements Sorry Jon, missed this one. We've already got enough material for the early access edition, and we're scheduling (about) a chapter every two weeks and a publication date late 2022/early 2023, hopefully the former. Let me inquire of our editor how to get you early access ... ping me if (when) I forget!
 
3:53 PM
@holdenweb No worries :)
@holdenweb probably happier to review "as you go" rather than a stonking great bit in one go... but... whatever
Umm... something in chat just made a "ping" noise... not sure where though... umm...
nvm - sorted
 
4:42 PM
@Aran-Fey I've restructured the code to your example, but the `await future` is never resolved. I've looked through the documentation: https://docs.python.org/3/library/asyncio-future.html
is creating a coroutine or task a precondition to be able to await a future - or that everything runs in the same event loop? The library that ultimately calls on_receive() is starting its own loop at the moment.
 
The future is bound to a specific loop, yeah
But so are all other synchronization objects, like Events or whatever. You really should run everything in the same loop if possible. Otherwise polling is the only solution, I think
 
Good to know - the library is a bit strange to me. I would have expected that I'm able to set the event loop from the outside somewhere. But the docs just say to call a "loop()" method regularly... so I guess I start the event loop outside the library and call it regularly with a recursive loop.call_soon()?
 
That's one heck of a weird API O.o Mind dropping a link to the docs so I can take a look?
 
Here's the sourcelink to the loop()-method - alternatively. it starts its own thread via loop_start() or loop_forever()
 
5:01 PM
That library isn't doesn't use asyncio at all, are you sure it's a good idea to combine the two?
Oh, there's actually a demo showcasing how to use it with asyncio here
 
Looks quite complicated just to get it to work properly with asyncio... maybe I'll check for an alternative.
 
Wait a minute, you already have a working setup, right? You just need a way to do future.set_result() from outside the asyncio event loop?
If so, you can just do future.get_loop().call_soon_threadsafe(future.set_result, result)
 
5:35 PM
Hi all, I have a question.
I'm trying to create a billiards ball simulation.
As you can see, the ball bounces off pretty well off this wall:
But when it comes to this wall, it leaves a lot to be desired:
The algorithm I'm currently using to make the ball bounce is:
1. Find the incoming angle (angle between orange normal vector & red incoming vector) . Call it $a$
2. Rotate the red vector by twice that incoming angle $a$.
 
you probably messed up the angle calculation
 
3. Rotate it by pi.
That's it.
@AndrasDeak Yup
 
or you are using the wrong axis
 
Gonna go ahead and guess you rotated in the wrong direction
 
See, I want to tell the program reflect the red vector around the orange vector (and flip it, so you get the right orientation), but I don't quite know how.
 
5:44 PM
that's pretty easy to do
 
@AndrasDeak I calculate the incoming angle and then rotate the orange vector by that amount, but once again, it gives me the wrong trajectory.
 
it would seem so
 
If anyone can suggest what I'm possibly doing wrong, or a better way to reflect/bounce the ball, that would be great.
The program is indeed doing what is intended:
it rotates the red vector by twice the incoming angle to get the new direction, but the problem is, it's not doing it with respect to the orange normal vector
This is what happens when I try to rotate the orange normal vector instead of the red incoming vector:
It rotates it the wrong direction ...
You may ask why can't you just rotate it the other way? But the problem is, that would be an ad-hoc fix. If I force it to rotate the other way for just this "red wall", who knows what other manual fixes I'll have to add for the other bounces.
 
How do you do the rotation?
As in, what's the code for it?
There's a myriad of ways this can go wrong.
Is it 3D or 2D?
 
@MisterMiyagi I've tried to approaches for the rotation.
And this is 2D, as I'm simulating a triangular billiard ball table
Here's the first approach I tried:
1. Find the incoming angle (angle btwn. red & orange vector)
2. Rotate the red vector by twice that angle (since I'm trying to reflect it over the normal, orange vector)
3. Rotate by 180 degrees (so it points "out" of the wall, not into it)
That's the first approach.
This approach works great when it comes to this wall, for instance:
But not so well when it comes to the wall I showed above.
 
5:54 PM
You said as much already.
 
if angle_between_orange_and_red >= 180°: angle_between_orange_and_red = 360° - angle_between_orange_and_red
 
@Aran-Fey Hmm ... that may quite be it.
Let me try that out. Thank you for the suggestion.
In the interim, if anyone finds this useful, here's a big picture view:
 
Since it seems to work for two out of three edges, have you already figured out what makes the third one "special"?
How is your coordinate system oriented?
 
@Aran-Fey But all of the incoming angles are acute, so none of them are greater than 180, including the weird side.
@MisterMiyagi That's indeed what I'm trying to figure out.
 
That depends on how you calculate them.
 
5:58 PM
@Aran-Fey The incoming angle is calculated using diff_angle(red, orange)
So they're all acute, and none are obtuse (in this case, at least)
@MisterMiyagi The coordinate system is just the xy plane, since I'm working in 2D
 
I've never seen anyone try so hard to avoid showing any code
3
@rb3652 Which is a function imported from where...?
 
@Aran-Fey VPython. In fact, here is the Jupyter Notebook if anyone is interested in running the code:
The code itself is quite short, only ~70 lines (if you don't count the imports)
 
The only documentation I can find for diff_angle is "diff_angle(A,B) = A.diff_angle(B), the angle between two vectors, in radians". Doesn't say anything useful, really
 
Yup, do you have any questions? It's really just an angle-calculator (better than the hassle of dot product)
I don't think that's where the problem is, because it works for two of the walls
The problem with the third wall is that the program is rotating the normal vector by the correct angle, but in the wrong direction ...
 
You're assuming that it returns the smallest angle between the two vectors. Meanwhile, I'm pretty sure it returns the angle in a counter-clockwise direction.
 
6:07 PM
@Aran-Fey Oh
That's a good idea. Ok, let me use a print-statement to check.
`Hit Red A Wall`
`Incoming angle: 26.565051177077994`
Yeah, nope -- I used a workaround (trueAngle = min(pi - incomingAngle, incomingAngle)) to get around that
 
Shouldn't that be 2*pi - incomingAngle?
 
@Aran-Fey I can try that, but I don't think that will give the right bounce for the two walls I already have
I've also tried adding an if statement so that if the ball hits that annoying wall, it will bounce just the right way:
 
I think you should cut this down to just having a testbed of two arbitrary 2D vectors and calculating the mirroring of either on the other.
 
@MisterMiyagi Hm ... that's a good MWE idea. Let me test that out.
Should have thought of that before.
 
You might also want to just not use angles at all and go for pure vector math: math.stackexchange.com/a/13263
Euler rotations can be pretty mind bending for little gain, even in 2D.
 
6:20 PM
> Exception: The non-notebook version of vpython requires Python 3.5 or later.
 
Wow!! This is my exact problem. Thanks for the reference.
 
Yeah I'm only running 3.10, my bad >_>
__require_notebook = (not __ispython3) or (__p[2] < '5')
Thanks devs, amazing work
 
You can just run the Jupyter Notebook from the myBinder link
 
So evidently diff_angle does always return the minimum angle. So then the question is how the rotation works, and I'm not really willing to figure that out
 
Thank you both @Aran-Fey @MisterMiyagi for all the help. The program works beautifully now!
 
6:51 PM
Today "progress" for me means going from "undefined symbol: _Py_ZeroStruct" to "undefined symbol: _Z11cblas_dgemv11CBLAS_ORDER15CBLAS_TRANSPOSEiidPKdiS2_idPdi"
 
@Aran-Fey in the on_receive() instead of self._futures[msg.id].set_result(msg.payload) ? doesn't work as well...
*either
 
7:06 PM
@AndrasDeak I know that feel :(
@Lars In that case, I'm gonna go ahead and guess there's something wrong with the way you made the library work together with asyncio
 
the problem is I don't even know what I can do at this point
 
500 rep bounty on SO?
 
As soon as I can fire up this MCVE involving an HPC cluster in "best effort" mode before decommissioning :'|
 
@Lars I don't know the first thing about MQTT, but there are promising-looking results for "mqtt async" on pypi
 
7:30 PM
$ c++filt _Z11cblas_dgemv11CBLAS_ORDER15CBLAS_TRANSPOSEiidPKdiS2_idPdi
cblas_dgemv(CBLAS_ORDER, CBLAS_TRANSPOSE, int, int, double, double const*, int, double const*, int, double, double*, int)
even more progress!
 
7:49 PM
OK, I could switch to statically linked blas...
 
and I don't seem to be the only one: https://github.com/mossblaser/aiomqtt
It's hard to find an mqtt client that is properly supported and not a dead project.
Well, polling still feels wrong, but I'll stick with it for the moment. And I take from your helpful comments, that I need to take some time to create some experiments to get some more in-depth knowledge of asyncio and it's ecosystem. Thanks for your help!
 
The meaning I was going for was more like "It's not easy to combine a callback-based library with asyncio", but if your takeaway is "I should learn more about asyncio" that's fine too (:
 
9:00 PM
If my download fails with an aiohttp.ClientPayloadError, is it reasonable to retry after a few minutes or does that indicate more of a permanent problem?
I can imagine that (3) can happen if the server decides "this dude's been sending me too many requests, I'm gonna stop sending him data". But the other 2? Not so much
 
@AndrasDeak I was actually going to mention that earlier, but I guess I got distracted. Ooooh, something shiny!
When I'm building libraries on my own, I tend to statically link them. Yeah, it makes them a lot bigger, but I have disk space to burn and I hate dealing with errors like you're seeing.
 
9:15 PM
Unfortunately I wasn't building anything :P
 
 
1 hour later…
10:38 PM
Found a HTTP library that doesn't mention exceptions in its docs even once. I assume that means nothing can ever go wrong.
Internet goes down? Fall back on carrier pigeons
 
11:01 PM
hey
import requests
import numpy as np
import re, json
from bs4 import BeautifulSoup

###########################
# Loop of all the pages
###########################

#Loop to go over all pages
pages = np.arange(0, 13)
data=[]

for page in pages:

page="https://www.mediamarkt.com.tr/tr/category/_cep-telefonlar%C4%B1-504171.html?searchParams=&sort=&view=&page=" + str(page)
page1 = requests.get(page)

soup = BeautifulSoup(page1.content, "html.parser")
data = [json.loads(m.group(1)) for m in re.finditer(r'var product.+ = ({.*})', page1.text)]
How can I choose variables?
I would like to choose name,id and price
 
You mean you want to search by name, id and price? Or you want to extract the name, id and price of the results you found?
 
11:26 PM
@Aran-Fey extract the name, id and price of the results
 
[{'name': product['name'], 'id': product['id'], 'price': product['price']} for product in data]?
 

« first day (4103 days earlier)      last day (835 days later) »