Hey guys does anybody know how to define function or methods for a class dynamically at creation ?
what I mean is,for example to do: class A(): def __init__(self,n): self.n=n def fillclass(self): for i in range(n): [create a function named function_n that prints n]
Are you sure you need n different functions? Why not a single function that takes n as an arg?
Here's an example that dynamically makes a dict of functions. This could be adapted to make instance methods named function_i, but I strongly advise against doing that.
stackoverflow.com/questions/69489441/… is this just a typo? OP tells "breaking the server" when all I can see is a syntax error with a extra ')' msg = s.recvfrom(82))
@python_user It might be a typo in the question, but not the actual code. However, that code uses port 82, which is <1024, so it requires root privileges on a sane OS.
Hete's some relevant discussion re the security implications of using the low number ports: serverfault.com/q/112795
"look at the source code for Apache or Lighttpd or something similar, where they use the root privileges to open up the port, but then immediately give up those privs and "become" a lower privileged user so that a hijacker can't take over your whole computer."
@PM2Ring Basically I'm defining this class to have some variables that are linked to some widgets in ipywidget. I am not a black belt by any chance here, but as I understand it when you interact with a widget i need to call a specific function with the observe method, so i need either N functions with different names or N linker functions to link to one updater function that takes N as a variable.
sorry for the messed up english but i am pretty brainmelted here :P
@PM2Ring Loving how the first few comments are locals and exec hacks. 😂
@user3458909 There still shouldn't be a need to define separate, named functions like this. Many frameworks using callbacks allow you to also specify the arguments with which to call functions. For those that don't, you can use a lambda expression or functools.partial to create the "function n" variants as needed.
Looking at the ipywidget docs, you want a method/function like def function(n, change): print(n) and register it to observe like my_widget.observe(lambda change: function(n, change), "some_trait").
I am actually trying to do it semi properly right now, but my head is exploding. The real problem is that I don't understand the damn observe function enough, If i could pass n along with change everything would be so much easier. Your my_widget.observe(lambda change: function(n, change), "some_trait") seems to be some kind of workaround to do exactly that, but I'm not sure what exactly it is doing
@MisterMiyagi very briefly, i just know that is used to apply a function to variables and that it is used with pandas to apply an operation to series or dataframes
Okay, so all that lambda does is that it allows you to create a function as part of an expression. The primary use-case for that is to create a function purpose-built for a specific call without having to prepare it in advance.
E.g. in your case, you need a function for each observe call but – as PM pointed out – it's not really suitable to create all of these up-front.
For the record, these two are practically equivalent:
# named function via def statement
def named(change):
return function(n, change)
# unnamed function via lambda expression
lambda change: function(n, change)
So in this case, we create a new function that only receives a change – which allows using it with observe. Because that new function calls our old function with changeand some n this behaves as-if we "told" observe to pass along n as well.
@MisterMiyagi Hmm so let me see if I understand. My problem is that a widget interactions generates only a change, not n and depending of which widget I am moving obviously n would be different. At the same time widget.observe deals only with one value, so i cannot tell widget1.observe(on_change(n)) .
So the lambda function is like a fitter in there that takes change but somehow has n . The way that it has n though is not really clear to me.
Like you writing: def named(change): return function(n, change)
"Let me tell you about late binding" was going to be the next lesson. ^^
@user3458909 The same where n would come from if you had a hypothetical function_n instead.
So you might end up writing some explicit n there, like lambda change: function(42, change).
Or you have an explicitly n because you call observe inside another function, then you can just re-use it.
Caveat: As PM pointed out, lambdas bind names just like regularly defined functions – that means they only know the name, not the value at definition time. When n is defined in a loop, you should set it as a default argument.
In that SageCell example I posted earlier I did lambda a=i: a, so a is set to whatever value i had when the lambda was created. I could've written that as lambda i=i: i, but that may be more confusing than having two separate names, i & a
And we definitely don't need any more confusion XD I think I'm gonna watch some videos on lambda functions, cause it seems like kinda of a fundamental that i gotta understand.
I was trying instead to set a dictionary of widgets, and a dictionary of linker functions to update the values of a cdictionary of variables stored in a class .
@MisterMiyagi I tested with the sleep 20s command, didn't give an error. So definitely a resources issue. It might have something to do with running this through wsl, now will check on debian without the sleep 20s. But I'll need to implement something to check this error and re-run those packages.
It should be due to wsl -- because its a 64gb, 8 core machine. I was thinking I'll do something crude like : read the stderr, check for this error with a regex pattern, fetch that package name and rerun it. I want the script to be able to run on any linux based system.
@MisterMiyagi I checked, ulimit is unlimited, and lsof report 1450 file count
arhghghg.... my machine has for some reason forgotten it's got a 2nd disk... I've had this before and it took a while to work out why and to find a simple shell command fix... can't remembmer what that command was or how I found it now arhghghgh
ahhh... the power cable for the 2nd disk had come loose... (guessing when I moved the computer a bit last night I must have bumped it a bit or something and since it's a shoddy build - it didn't take that much for that to happen... sighs)
Got a question but need to eat something before asking it or I will pass out
@JonClements haw about you? I have not seen you for a long time, none of you are forgotten, just have other people that I need to take care of first, now.
Okay... so turns out the disk is fubar'd. it was fairly new and didn't have a huge amount of stuff on it anyway - hadn't gotten around to moving stuff across to it properly yet. Been able to pull down what was on it from archives... so haven't suffered any actual data loss. Just bloomin' frustrating is all.
Plus side - should be able to get a replacement under the warranty... it's only 2 months old and the "limited warranty" is 3 years. Could be I just got a duff one.
argh... guess I'm going to have to contact support to arrange a return and find the box and all that now... sighs
I've noticed a number of questions recently that are trying to inspect the size of objects. I don't think this really was a concern much - is Python on some new embedded device? Even with an Arduino I don't think it'd be much of a concern?
One of them was actually quite interesting but I apparently closed the tab since, and it's wasn't from stdlib so it was really just a curiosity about some external library
Repeatable, though. I still have the code in my delete_me.py file so I should be able to surface it
Not sure why I'm struggling to dig this question out but the code is here. Basically, the order that you print the sizes appears to matter (note I haven't done any digging, only run it, so it's possibly a misleading setup)
Deleted questions should still be indexed on Google I thought?
The question that contained the code I've made a dpaste of. I thought there's be enough in that for me to get an exactly match but I don't seem to be able to do it, or from key search terms. I'm not sure I really care tbh, though it's now become a personal challenge
my gut feel would be that dataclasses wangle a bit with slots anyway... although thinking about it - I guess it couldn't as the class is still open to inheriting... ummm.
@AlexWaygood oh... that'd make sense
@AlexWaygood to be fair though... I'd take a punt that 99% of Python developers don't even know __slots__ is a thing... or even care that it's a thing or even need to ever consider using it as a thing :p
It's always been possible to manually specify __slots__ in a dataclass, like they're doing in ^that question, though in <=3.9 it breaks the dataclass if you try to specify a default value for an attribute, since you can't have a class attribute with the same name as a slotted attribute, and dataclasses use class attributes as a mechanism for giving attributes default values
@JonClements yeah probably. Wasn't a rebuttal of your point, just a tangential nugget of information!
The fun thing is that you can't add __slots__ to an already-defined class, so in order to auto-generate slots, the decorator chucks the class you've defined in the trash can and dynamically makes a new one just like it that has the specified slots github.com/python/cpython/blob/…
@JonClements thanks!
I'm alright, doing okay! It's a grey and rainy day here in the UK, but hey
Question: my aim is the following, for any date, I want to be sure that after 7 days, based on any date, that the date is still in that range of date. Thinking about it, maybe I can use a dictionnary
If tomorrow, on the 9th, I'm checking again, I want to know that a day has passed and that I still have 6 more days. And if I'm checking in 4 days, I have 4 days that passed and I still have 3 days to go until there is no more days to go
The thing is how to say that it stores the date like today is the 8th of November and that it is not using tomorrow as the starting date, all over again
I was wrong. Now I'm totally lost. This is not particularly computationally heavy stuff to compare datetimes (not cheap, but not too much). Are you now talking about database queries or something?
A fixed date for what, though? It could be a class attribute, it could be a global variable in a script (which has no concept of "today" other than a fresh call to the datetime library when it gets run)
"Keen to get JP’s opinion on this next week (srsly, I mean next week)" I just got told off for being on the work Slack on my holidays :'( I need to go find a naughty corner
@ParitoshSingh This was actually from one of my colleagues that's also a good friend, so he's just pre-empted me :P But indeed, I get where he's coming from
This will not accomplish anything but I think cryptographic hashes are a cool way of verifying the existence of a block of data without actually publishing the data
It's like mailing a letter to yourself so you get a legal official timestamp on it from the post office, except it doesn't cost you a stamp
Some people can say "meet me at sunrise tomorrow in the empty lot. bring 300 feet of plastic tubing, a pineapple, and a latin-to-english dictionary". And the other person will show up despite there being no incentive.
Because last week's adventure at the empty lot went horribly, horribly wrong
Either British or American English is fine. But listen very carefully. The dictionary must have no affiliation with early 19th century lexicographer Noah Webster.
I have a Dockerfile with the line: RUN pipenv install --system --skip-lock --dev --deploy
My Pipfile contains some packages, and they're all installed
But if I add Faker = "==9.2.0" to the Pipfile and rebuild the image & container, Faker is not installed
I can ssh to the container and see that Faker is in the pipfile, and if I pipenv install inside the container, I can see that Faker is indeed installed
Does anyone know what might cause this behavior?
(I can also pip install Faker==9.2.0 once I'm ssh'd inside the container)
Knowing little about pipenv....which env are pip, pipenv, and the env you see Faker not install in all referring to? Eg if pip install installs in a python3.7 env, but you're trying to use it in a python3.8 env, no, it won't be installed.
this is saying otherwise. But I don't know about pipenv here
All of my Docker builds just go through requirements.txt so I suspect I'm going to be useless in understanding this one. Docker and I don't mix very well
I'm guessing that Docker can copy virtual machine instances quite robustly, and this is loudly praised in all their marketing material, but you have to compromise when you hit real-world limitations like "I can't make 1000 instances in parallel if they each have a 1.0 GB numpy install. Can't I make them share?"
Just wait until you need to change something. And you forget to clear the image cache. Or the container cache. Or did you need to clear the network cache? Possibly dangling containers? Or was it the build cache?
(The Pipenv mystery was indeed hidden in one of those cache layers)
What were the two hard problems in computer science?
@Kevin You need to use something a little stronger than MD5 or SHA-1 though, because they're vulnerable to an extension attack. There's some info here & in the links on that page. crypto.stackexchange.com/q/29775 But you could use a MD5 or SHA1 HMAC, or a stronger hash like SHA-256 or Blake. Or just post both the MD5 & SHA-1 hashes. Getting a double collision on a 128 bit & a 160 bit crypto hash has a very low probability.
This is kind of a scenario where vulnerability could be beneficial to me... Here's a use case. On Jan 1 2022 I come up with the idea "facebook for dogs". I calculate hashlib.md5(b"facebook for dogs").hexdigest(), and in chat I say "cool idea: 'bd24dd2a88b83d63999dd99cc5b8506c'".
On Feb 1 2022, Facebook independently has the idea for Facebook for dogs, and on March 1 2022 they release the feature to the public. I say "hey, pay me royalties, because I had the idea no later than Jan 1, as proven by my cool idea's md5 hash". Then I retire to the bahamas.
Use case 2: same scenario as previous, except my idea is facebook for dogs and Facebook's idea is facebook for cats. On March 2 I iterate through a zillion different combinations of ways to write "facebook for cats" until I find one with the same md5 hash as "facebook for dogs". Now I can ask Facebook for royalties, even though I didn't really come up with the idea.
So it's profitable for me to choose a hash algorithm that's vulnerable to collision attacks, but not so vulnerable that Facebook's lawyers can figure that out by googling it
(To any Facebook legal team web spiders reading this: this is a work of satire)
@Kevin Admittedly, a length extension attack on such a short plaintext is unlikely. :) But it's well-known that MD5 is vulnerable, so you might as well use a HMAC, or a stronger hash.
Does HMAC require key exchange? I have no problem publishing a public key to the general public, but I don't think I can get Facebook to give me their keys so I can sue them more easily
@Kevin No. An HMAC is just a keyed hash constructed from 2 simple hash calls & XOR. See en.wikipedia.org/wiki/HMAC#Definition For this application, the key doesn't need to be secret. It's acting as a salt. But the point of using HMAC is that it's impervious to length extension shenanigans.
Facebook's cryptanalysis web spiders might break rot13 and implement facebook for dogs mere days after I post my hash, which makes it more plausible to the courts that they came up with the idea before I did
Perhaps I could publish my ideas encoded using cultural shibboleths that are incomprehensible outside of my local sphere. The cryptanalysis spiders can't break "facebook for jons"
Just looking for some ideas here, my Python isn't at a very high level. So I basically want to add some trace-level logging to a bunch of methods that just perform json transformations. The logging will all be the same, just like <method name><before/after> <json payload>. How would you go about this? Like ideally I would just write one method to do this, but the method needs to know who is calling it. Just pass that in, or is there a more clever way?
@Kevin meh... breaking rot13 is highly unlikely... the resources necessary to do so are phenomenal... it's an extremely complicated encryption algorithm after all :p
@Chuu If you want to get fancy, you can use functools.wraps so that the function created by @logged inherits the name & docstring of the original function.
@Chuu Here's probably the only post you'll ever need to read about decorators. Fair warning, it'll likely take you an afternoon to get through, the first couple of times: stackoverflow.com/q/739654/198633
@rb3652 To cut this short: The code you have shown above suggests you create a new brownian for each step of min, max and plotting. Do you actually do that in your "real" code as well?
Well, now I'm unsure if our "number of times the discussion continued even though Miyagi already figured out the problem" counter needs to be incremented to 2 or stay at 1
@PM2Ring I've never seen that on a vinyl or cd either... I was quite happy to find that. I am a complete Billy Joel fan - every Vinyl/every CD/every DVD etc... and that one I've not got on any of 'em.
I'm fairly sure anyway - everything he's ever done music wise - I've got a copy of in some way (heck - I've got all the albums on both vinyl and CD) - might even have some twice... but that track... no where to be seen on any of 'em.
@JonClements Yes, it doesn't quite have the punch of Billy's version. It's from a penthouse on the 99th floor, not down on the streets of New York. But that version was pretty popular here in Australia.
Here's a fun song by Michael Franks, with Joe Sample on Rhodes: Eggplant
Sarah Jarosz wrote this song about Jackie Kennedy Onassis while she was living in New York, near Central Park. Jacqueline
Brittany Haas played violin on that last track. Here she is doing a duet with her sister Natalie on cello. Kom Hem
Here's an impressive cover of Sweet Child of Mine by two young ladies, Jadyn Rylee and Jessica Lajner. Jaydn has done some songs with Sina, Chiara, and Emily.
@JonClements Success! youtu.be/3EqdRXuYQQQ Yes, it's similar, but the phrasing is different, and that chord progression sounds like it's used in a lot of songs.
I'm not sure if it's completely weird or not, but when I listen to some GnR - I also want to listen to some Metallica and their classic: youtube.com/watch?v=tAGnKpE4NCI
@PM2Ring I need to find a citation but fairly sure Billy Joel spent years training as a classical pianist (even before he considered he'd have a career in music) and then he went a bit RnR and then a bit R&B - his earliest work - you wouldn't even know it was him.
@PM2Ring fairly sure I've posted this before - youtube.com/watch?v=-xKM3mGt2pE&list=RD-xKM3mGt2pE - it's by the same guy that did the original - I consider it better than the original - I think the more laid back approach really works for it
Emily and Chiara teaming up with German drum prodigy Sina, doing an A-Ha song. (I should've posted this version before. Oh well). https://youtu.be/HJ1Biqhs3Qo
Some electric stuff from Marcus. His own song One Day She's Here, plus a couple of blues classics penned by Willie Dixon.