« first day (3180 days earlier)      last day (1769 days later) » 
00:00 - 17:0017:00 - 00:00

12:07 AM
For the sake of speeding up my learning, could you tell me what is the difference between

class Animal():
def __init__(self):
print("Animal created")


and

class Animal:
def __init__(self):
print("Animal created")

??
The first with () and the last without it.
 
12:29 AM
cbg
@GoldDiggingProgrammer I don't think there is any difference, just the () is usually containing another class, for metaclasses.
 
How do I find the ip address of a mac address on a network?
 
@U9-Forward Thank you very much!
 
Your welcome
:-)
 
 
1 hour later…
1:58 AM
recbg
 
Jab
2:09 AM
@U9-Forward
I'm good haha how are you?
 
I am good as well
 
Jab
I'm almost to 9k! Excited
 
I created a room for us
 
 
1 hour later…
3:43 AM
@GoldDiggingProgrammer also take a look here
 
 
1 hour later…
4:50 AM
@ReblochonMasque We have a few targets for that. But I gave you an upvote anyway. ;) See sopython.com/canon/30/…
 
5:24 AM
Cabbage
@PM2Ring, yes, thank you, I know there are dupes for the infamous lambda/args passing in a loop O_o - I first answered in the comments, then I tried to find a dupe that would also pass the event to the callee, but I could not find one.
 
Cabbage. I've been browsing the Python tag. I haven't done that for a while. I may have to stop soon before I get too depressed. ;)
@ReblochonMasque No worries.
 
haha - the same happened to me yesterday after venturing into the toxic area of MSO... I felt dirty afterwards!
Thanks for the upvote BTW, appreciated.
 
I mostly avoid MSO, it's a bit too political for me, but I do check the Hot Meta questions from time to time.
 
5:48 AM
@DeveshKumarSingh I'm not a fan of the dupe target here. I realise it was someone else's suggestion. But 3 of the answers there recommend using globals()! I've done a bit of a search for a better target, but I couldn't find a good match, but I linked to a question about dispatch dictionaries in a comment.
stackoverflow.com/a/45266621/4014959 20k+ only. 1 more vote needed
 
^ gone
 
6:06 AM
@PM2Ring thanks, added the answer you suggested as well
How is the reverse argument applied in sorted ? Is it first sorted by key and then reversed? doesn't seem like it because the docs say reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
but I couldn't quite understand the comparison reversed part? Is it talking about reversing the sign?
e,g I have a list like this li = [['c',1],['a',2],['b',1]]
 
If the comparison is usually lst[i] < lst[j] then reverse changes that to lst[i] > lst[j]
(and then sorted does lst[i], lst[j] = lst[j], lst[i] or whatever)
 
okay, the same with things like key=lambda x:x[i],x[j] for a list of lists?
 
@DeveshKumarSingh Ok. I could've added it myself. The reason I didn't is because it's not a very good match to the OPs question. But it does contain info that should be useful to them. But don't worry about removing it from the dupe target list, I guess it doesn't hurt.
 
my main confusion was I have a list [['c',1],['a',2],['b',1]] where I want to sort it by decreasing order of 2nd element, and then lexicographic order of 1st element in case of ties
In [47]: sorted(li, key=lambda x:(x[1],x[0]), reverse=True)
Out[47]: [['a', 2], ['c', 1], ['b', 1]]
This doesn't work though
 
yeah, you can't do that with reverse
 
6:19 AM
then how can I get [['a', 2], ['b', 1], ['c', 1]] ?
 
reverse reverses the whole thing, but you only want to reverse the integers
 
@DeveshKumarSingh So you descending order on the numbers, then ascending on the strings?
 
key=lambda x: (-x[1], x[0])
 
that works, so if you want to sort on individual keys which are integers, use a negative sign if descending is needed
 
6:22 AM
And if you add reverse=True to that you get ascending on the numbers followed by descending on the strings.
 
@PM2Ring so sorted(li)[::-1] == sorted(li, reverse=True) for any list li? irrespective of the key?
 
@DeveshKumarSingh If the key is a single number, it's better to use reverse to get a descending sort. The negative trick is handy when you have more than ome key & you want ascending & descending at the same time. And of course it only works on numeric keys (or objects that behave sensibly when negated).
@DeveshKumarSingh Correct.
 
@PM2Ring got it, and if descending of strings and ascending on numbers is needed, then sorted(li, key=lambda x:(-x[1],x[0]), reverse=True) works But is there a negative trick for descending order of strings?
 
If you need to do a complicated mixture of ascending & descending, and you can't use the negation trick, then you'll have to sort in 2 or more passes. That works because TimSort is a stable sort, i.e., it doesn't disturb the order of stuff with equal keys. And it's optimized to be very efficient at dealing with subsequences that are already in order.
 
@PM2Ring but then how do I relate this to the statement in the docs of sorted If set to True, then the list elements are sorted as if each comparison were reversed.
@PM2Ring okay because any combination of indexes defined in key can be broken down in sort with multiple passes
 
6:32 AM
@DeveshKumarSingh Aran-Fey covered that:
17 mins ago, by Aran-Fey
If the comparison is usually lst[i] < lst[j] then reverse changes that to lst[i] > lst[j]
 
@PM2Ring okay, so in case of list of lists , we can have lst[i][0], lst[i][1] < lst[j][0],lst[j][1] changed to lst[i][0], lst[i][1] > lst[j][0],lst[j][1] and so on
 
@DeveshKumarSingh Correct
 
@PM2Ring and hence the ascending on int and descending on str reversed to descending on str and ascending on it, now that makes more sense. This looks trivial now, but I somehow got stumped by it :(
 
@DeveshKumarSingh Yes. But you have to be careful with the order. To keep thing simple, let's sort tuples like ('a', 1) in 2 passes. To get the same result as the normal sort with the default keyfunction, which sorts by letters & then numbers, we actually have to do it the other way around: first sort on the numbers. Then on the second pass sort on the letters.
 
7:22 AM
Hi guys I came across an article of pandas telling how to optimize pandas code further
It specified that vectorized numpy arrays were the fastest to get executed upon by a function provided that the function can be applied as a whole on the array
def clean_postal_codes(a):
    if re.findall('^[0-9]|[dfioqu]|^[wz]|^[a-z][a-z]', str(a)) and str(a) != '':
        return ''
    try:
        if  a[3] != ' ' and a[3] != '-' :
            return a[:3] + ' ' + a[3:]
        if a[3] == '-':
            a = a.replace('-', ' ')
            return a
    except IndexError:
            pass
    return a
This is the function I intended to apply on a specific column
Here is my attempt to apply the function in the form of a vectorized numpy array
# Applying the function
adr_data['postal_code'] = clean_postal_codes(adr_data['postal_code'].values)
Here is the link to that page for reference as well :engineering.upside.com/…
This is the error I am getting :
ValueError: operands could not be broadcast together with shapes (3,) (60767565,)
 
8:04 AM
@U9-Forward parent classes are much more common than metaclasses
@GoldDiggingProgrammer please see our code formatting guide for chat
@RaphX unfortunately passing a scalar functiion a numpy array won't magically vectorize your function for you.
what you said is
> vectorized numpy arrays were the fastest to get executed upon by a function provided that the function can be applied as a whole on the array
what it probably said is
> numpy arrays were the fastest to get executed upon by a vectorized function provided that the function can be applied as a whole on the array
Emphasis on "vectorized function". There's no such thing as a vectorized array.
half-relevant comment:
Unfortunately, vectorization is not a recipe involving magic wands and pixie dust:) If you're calling a function 1000 times and the function can only work one at a time, then there's not much you can do. There is one thing: rewriting the function in MEX and pre-compiling it. — Andras Deak Mar 5 '16 at 20:51
and if you find numpy.vectorize: it changes nothing, there's no free lunch
 
@PM2Ring The telling thing about the current dupe target is that it's not got an accepted answer, and that's because the question was posed using def syntax in an apparent attempt to bind the function to each of the names in the list. Your suggestion is a better link.
 
8:41 AM
@DeveshKumarSingh Thanks!
@AndrasDeak Thanks.
 
8:55 AM
@GoldDiggingProgrammer you have this in your profile:
> In order to appreciate your effort, I always vote your answer up no matter the correctness of your answer.
Please don't do that! Votes are the primary tool for quality assurance on SO, and upvoting crap/downvoting useful content is very harmful.
if you want to be nice to someone who leaves a bad answer on your question, abstain from voting instead
 
Ok how do I know when to use vectorized functions and when not to ?@AndrasDeak
I am getting a bit confused since the site used the example of haversine distance
Isn't that also calculating value by value?
 
I don't know but (geometric) distances usually vectorize trivially
Always use vectorization if you can
re.replace won't vectorize for you
 
Ok @AndrasDeak
 
9:55 AM
cbg
hey Andras, I managed to fetch a bounty with some of the help you gave me on sys.flags. I ended up still having to parse its repr to get the argument order right, but the answer is a hack anyways
the amount of votes on that post and the bounty are kind of undeserved given that I don't see how it's useful to anyone except OP, but rep is rep ¯\_(ツ)_/¯
 
Hey, glad to hear that, good job
Though that doesn't seem like needing my help :)
In other news, I'm melting :'(
 
using namedtuple instead was your idea :p
@AndrasDeak I could skip over the worst part of the heatwave
but now I'm back to melting in my office =(
 
10:18 AM
cbg
 
@Arne ah :)
 
10:38 AM
Hi guys I have another doubt
li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0, encoding='utf-8', dtype = str)
    li.append(df)

clnd_data = pd.concat(li, axis=0, ignore_index=True)
Why are we doing 'concat' here? This is somebody else's code that I am trying to understand
 
To get a dataframe from a list of dataframes
 
pd.concat() takes a sequence or mapping of Series, DataFrame, or Panel objects , so this is concating the list of dfs to a single df
pd.concat([pd.read_csv(filename, index_col=None, header=0, encoding='utf-8', dtype = str) for filename in all_files],ignore_index=True) should also work
you don't need to create a list and append i believe
 
I thought concat is for only concatenating dataframes
So does that mean I can directly convert a list to a pandas dataframe as we do for dicts?
Or even a tuple?
 
you anyways have a list of datafremes when doing read_csv()
will be right back
rbrb
 
10:53 AM
@anky_91 you're creating the same list with that listcomp
@RaphX it is. Concatenating a collection of dataframes. You have a list of dataframes, which is a collection of dataframes.
try pd.concat([[1], [2]]) and read the error message
 
Got it @AndrasDeak
 
okay
 
Thanks @anky_91@AndrasDeak
 
if I have an array [6,2,9,3,10] and a cutoff of 8, I want to return [6,2]. is there a function in numpy to do that?
 
@Anush probably not. Use logical indexing.
why is 3 not included?
arr[arr <= cutoff] would give you [6,2,3] (inside an array of course)
 
11:10 AM
@AndrasDeak I want it to stop the first time the condition fails
 
@Anush Ah, then definitely not.
 
ah ok.. I think takewhile does this is in regular python, right?
 
indeed
 
With Python, is it possible to find out which ip address a mac address belongs to?

With the following function I can find mac address from ip address.

import scapy.all as scapy

def get_mac(self,ip_adress):
    arp = scapy.ARP(pdst=ip_adress)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp
    answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    return answered_list[0][1].hwsrc

On the contrary, is it possible to find ip address from Mac?
 
@AndrasDeak I thought list comp will be efficient than creating a list and appending
:)
 
11:11 AM
@Anush if your array is huge then it may be worth trying the performance of index = (arr > cutoff).nonzero()[0][0]; cut_array = arr[:index] (sorry about all the pings)
@anky_91 I didn't say it won't be more efficient or concise. I said it's not "you don't need to create a list and append"
 
@AndrasDeak I guess that would make three passes over the array?
one for arr > cutoff, one for nonzero and then one for arr[:index] ?
 
@AndrasDeak ah.. okay bad sentence construction :)
 
@Anush the last step is for free, so twice
 
ah ok, thanks
 
and the first two are in C speed, though I guess the same holds for takewhile if you can pass it a fast function
you really have to time them to see if there's a significant difference
 
11:15 AM
true.. thanks for this
 
no worries
@HibritUsta I'm completely a layman when it comes to networking, so this is a very naive question: does it make sense to try and find an IP for a mac? Every IP must have a mac attached to it, but there are way more mac addresses than IP addresses in the world.
Isn't this like trying to find "the postbox that is red with blue stripes"? The address of the house specifies where the house is, and if you use the address to find the house you can see that the postbox is red with blue stripes. But if you know that the postbox is red with blue stripes you don't know where it is. Is this not the case with IP vs mac?
 
@HibritUsta do you mean for an arbitrary IP address or for something in, say, your local network?
 
I'm doing ARP Spoof detection.
I just wanted to find out which IP address it belongs to when it attacks a mac address.


I'm not very good at networking either.
I just wanted to get your opinion.
 
I wanted to tell you for the local area network.
 
11:22 AM
there are various google hits that look promising
 
I have looked at this link, but I have a C class ip address.
I have a class A ip address.
I will also examine this. again
 
@MisterMiyagi from what I can tell it looks at a bunch of IPs and checks if the MAC matches, right?
which would mean that my impression was correct
def find_host_with_mac_address(host_elems, mac_address):
    """Return the first host element that contains the MAC address."""
    for host_elem in host_elems:
        if host_has_mac_address(host_elem, mac_address):
            return host_elem
 
yeah, you have to scan a range of addresses and check their mac address
good god, I hate network jargon :/
 
Sorry .
I said it wrong.
 
OK, thanks
 
11:29 AM
All right, I'il check.
 
12:22 PM
cbg
 
12:51 PM
A recent question asks "is there a function in the stdlibs that does <thing>?" and I wrote an answer basically saying "it's trivial to do yourself in three lines so there isn't much demand for a function like that" and I'm trying to find an alternative wording that won't elicit a reply like "you're wrong, there is demand, I polled every programmer in the room I'm in right now and 100% of them want this function"
"It's easy to do yourself, so the stdlib devs probably don't feel much pressure to include such a function" is one possible dodge, since it's practically unfalsifiable
 
there certainly isn't much point to having such a function in the stdlib
 
Not that "you can do it yourself in a few lines" is an automatic disqualification for a stdlib function. Counterexample: nearly all of itertools
 
itertools has a lot of dirty C hacks to it
 
I wouldn't generalize about the usefulness of 3-liner functions... people will go to awful lengths to avoid writing a 3-line function (or sometimes they just don't bother and end up with tons of duplicate code)
 
I guess print is probably doable in 3 lines, so...
what was that <thing> anyways?
 
oh, I hate those "<x> JSON <y>" questions
they are practically NEVER about JSON
 
Yep :-)
The non-me answerer does point out a json-specific module that might do what the OP wants, interestingly
I'll give them my upvote as soon as they edit in an example demonstrating how to use the module on the OP's data.
 
I need to stop clicking links to SO questions/answers
 
time for a new userscript
 
[skeleton.png]
 
1:02 PM
@AndrasDeak yeah, I need some technological support for this feat
 
Update your HOSTS file to redirect stackoverflow.com to a more productive site, such as reddit
 
I kinda still need to look at useful SO posts found on google
so I can't block it outright
 
this should just be duped with "merge two lists, eliminate duplicates"
but my dupe force is weak today, it seems :/
 
The last time I tried writing a userscript that manipulated chat messages, I found it pretty frustrating to detect new messages/edits. I could call getElementsByClassName every 1000 ms, or I could hook into the "on DOM change" page event (which has a rather unfriendly interface), and neither one was any fun. Can't remember if I ever got anything satisfactory working.
 
I'll probably just trigger on stackoverflow.com/questions/* and check if the referrer was chat.stackoverflow.com
 
"What is the expected number of iterations needed for a random number generator to generate all N unique outcomes?" is an interesting question, if not entirely programming related.
 
Time complexity of "maybe infinity"
 
Yeah, worst case is "forever", but what's the average case? N factorial?
 
Wouldn't N factorial include duplicates as well ?
 
N factorial sounds right
 
1:31 PM
@Kevin seems like a deceptively difficult question to me
 
I rate the difficulty at "can be found as an exercise halfway through a college textbook on probability"
 
does "deceptively difficult" mean "it seems difficult, but is easy" or the opposite?
 
The textbook says "it is easy to see that the answer is <answer>" and the reader scoffs and says "I don't think it's that easy"
 
Python sin confession: Last Friday I shared an MCVE. In that MCVE I assigned to built-in. I called my dictionary “dict” (probably noticed by no one). I will read the documentation on Python data structures twice as my penance. Phew, I feel better already.
 
@Dodge You can use del to erase your sins... at least as far as python is concerned. Your peers may still loathe you.
 
1:35 PM
Peace be with you :)
 
Unpopular opinion: I think it's fine to overshadow builtins if you're not in the global scope.
 
@Aran-Fey opposite
@Dodge sorry, I noticed
 
You should have mentioned it. It was a millicringe moment when I noticed and now I'll never forget
 
wim
@Kevin +1
 
just as I thought yesterday: meh
 
1:39 PM
It would be nice if I could bottle the substance that creates a cringe worthy moment and introduce that to my blood stream as I am studying at specific points. Then, certain topics would be burned into memory.
 
I think it's fine to shadow builtins in functions if you're sure you'll never need that particular builtin... so basically never ¯\_(ツ)_/¯
 
@Kevin that's all fun and games until someone picks an RNG with too low period
 
from itertools import accumulate, groupby
l = [45, 55, 100, 4, 41, 10, 45]
a = accumulate(l)
print([[*g] for v, g in groupby(l, lambda k, i=iter((next(a)-1) // 100 for _ in l): next(i))])
Can this be written more clear/simpler? Output is [[45, 55], [100], [4, 41, 10, 45]]
I want to group the list l to chunks where sum of each chunk is 100
 
the Mathematics chat has patiently informed me that the expected number of draws to see all N unique balls in an urn is "N times the sum of the first N harmonic numbers"
 
@AndrejKesely longer, but clearer:
def sum_to(iterable, target):
    total = 0
    nums = []
    for num in l:
        total += num
        nums.append(num)

        if total >= target:
            yield nums
            total = 0
            nums = []
 
1:51 PM
The harmonic numbers diverge, but really slowly, so I'm not sure how to turn this into big O notation... More than O(N) but less than O(N^2)?
 
@Aran-Fey Yup, this seems to be more clear to explain to beginners. Thanks :)
 
@AndrejKesely factoring out groups = [(running - 1) // 100 for running in accumulate(l)] would help a lot to see what is going on
 
Ah, wikipedia says that the partial sums of the harmonic numbers grows logarithmically. So it's O(N log N).
That's way better than my original estimate of O(N!)
 
@MisterMiyagi Thats true
 
@Kevin : Nice, thanks for your efforts
 
2:00 PM
for finding all permutations of a sequence of size Q, it's O(Q! * log(Q!)), which... Isn't great.
 
I at first thought Factorial N/ Factorial (N-1) should be it for uniqueness
 
24 * math.log(24) is 76ish, which is near the middle of the OP's observed distribution, so I feel pretty good about it
 
@Kevin called it
 
I think you can reduce O(log(Z!)) to O(Z log Z) if anyone is really burning to reduce the runtime of Q to its constituent parts
Hmm, can you reduce O(Q! * Q * log(Q)) to just O(Q!)? Since factorial completely dominates the other components?
If so, then OP's "bogoPermute" has the same computational complexity as just iterating over permutations in a sensible order.
 
@Kevin technically no but doesn't matter
It's approx Q ln Q exp(Q ln Q)
If the prefactor is big the exponential is bigggggg
but it's always strictly larger than Q!
 
2:18 PM
@Aran-Fey I'm a pretty big fan of groupby, and itertools and Raymond H in general, but groupby+accumulate is twisting my brain around. That said, your clearer version does not handle sub-lists that exceed the target the same way as the original.
(change last element of 'l' from 45 to 46 to exceed the target)
print([[*g] for v, g in groupby(l, lambda k, i=iter((next(a)-1) // 100 for _ in l): next(i))])
[[45, 55], [100], [4, 41, 10], [46]]
vs
print(list(sum_to(l, 100)))
[[45, 55], [100], [4, 41, 10, 46]]
 
shouldn't be too hard to fix
 
To be fair, this original brief ("I want to group the list l to chunks where sum of each chunk is 100") isn't totally accurate in the face of input values that don't nicely sum to multiples of the target.
 
@PaulMcG In my case the values always sum to 100, but it can be generalized for allowing not multiples of 100
 
2:38 PM
cabbage
 
garlic bread
 
🤔
 
Some additions to the salad language?
 
Something one eats to ward off the HV's?
 
Given a bunch of png files, how do I make a gif using python? I'm wading through ffmpeg-python documentation at the moment but someones answer might save me some time.
 
2:52 PM
Someone said gifsicle
Search gif in the transcript perhaps
 
I use imagemagick for that. here is how I invoke it with subprocess.
You should probably modify it so that it accepts filenames rather than PIL.Image instances, or else it will uselessly make temporary copies of all the frames
... Or maybe it's easier to leave it as-is, so you don't have to figure out how to specify filenames individually, instead of just providing a wildcard like it's doing now
 
@Kevin FYI pingless reply on random unique stackoverflow.com/questions/56836474/…
Did you factor in O(n) list membership testing by the way? :P
 
No.
 
Thanks guys
 
caveat emptor: about 1% of the time, when I use animation.make_gif, it produces strangely garbled results, even though the output is perfectly fine if I execute the exact same command manually from the command line. I advise that a human should review the output for correctness before being used for anything important.
 
3:00 PM
Everything has blown up and I've already blamed you to my superiors.
 
In turn, I will blame the imagemagick developers, and also the designers of the gif file format.
 
gifsicle only supports gifs, so you can't exactly use it to create an animation unless for some reason your input images are already in gif format
it's more of a postprocessor for gifs
 
Oh, that's just silly
I didn't know that, sorry
 
apology not accepted because I don't know why you're apologizing in the first place :P
 
def accept_apology(apology, reason=None):
    if reason is None:
        return False
    else:
        return True

accept_apology("I'm Sorry!")

# False
 
3:11 PM
Because I mentioned a method to piR which is insuitable for the problem he'd want to use it. Of course the real perpetrators here are the designers of the gif file format.
 
hold my diet coke, I'm getting my pitchfork.
 
I'm sad animated pngs never caught on
 
@piRSquared would if not reason: return False be better? A false reason, or an empty one, should also not be accepted? :)
 
I would really like an animated image format that supports 256**3 colors
 
@RobertGrant like def accept_apology(apology, reason=None): return bool(reason)
 
3:16 PM
Is that your repo @Kevin (the animation lib)?
 
that should trigger Kevin's fight or flight instinct :P
 
We can still pray for FLIF
 
gif's limited palette has caused me a considerable amount of annoyance when I'm working in anything other than greyscale. Even when I'm working in "greyscale plus 0xFF0000", I can't be sure that imagemagick's palette chooser will come up with something reasonable. That's something that would require human-level intelligence I expect
@ReblochonMasque Yeah.
 
Osu!
Thank you!
 
@Aran-Fey neato
 
3:22 PM
I wonder if .webm has unlimited palette size? It's catching on as a gif alternative in a couple of websites I frequent.
 
Sam
Is there a c++ chatroom somewhere?
 
I don't think webm uses a palette... it's a bona fide video format, after all
 
Sam
I have a really important but dumb question that gets 40 downvotes in 2 seconds
i already did that
 
Sam
3:25 PM
thanks
lounge?
 
look further down the page
 
Sam
yes i saw it thanks
 
@piRSquared yes, exactly
 
Sam
there is noone online there, can i ask you a question andras deak?
 
Hmm, I notice that the chat search page filters out "+" from one's query, which makes it hard to find C++ and not, say, C or C#. How troublesome.
 
3:26 PM
@Sam only if it has to do with python
 
Sam
no not really XD
 
asking me a C++ question will be unpleasant to us both
 
Sam
yeah i mean then in the C++ room
oh ok sorry :D
Well, i think its similar to python in a way
 
@Sam there are approximately 18 people in that room. I suggest that you ask your question in there. Even though nobody has said anything for four hours, that doesn't mean they aren't paying attention.
 
Sam
oh ok ill go check
 
3:28 PM
Patience is key. SO chat is asynchronous so you can get answers hours or a day later
 
At the very least I can guarantee that one person is awake in there: me.
(trying to remember whether the Lounge has some kind of vetting process that makes it hard for newish users to post in there... I guess we'll find out shortly)
 
lounge has a history of questionable events and some freezes
 
3:43 PM
Correction: two people are awake. If the number of awake people in the Lounge continues to double at this rate, then the entire population of the earth will be watching the room in 33 minutes.
 
Sam
lol
 
3:58 PM
> Ebooks Purchased From Microsoft Will Be Deleted This Month
Oh, boy. We truly live in the future.
 
Yup. I don't buy DRM'd products as a matter of policy.
 
Is this related to the decommissioning of Microsoft Virtual Academy?
 
At least when Amazon withdraw book they credit you for the purchase price (or did last time I was aware of the issue).
 
MS also gives a refund gizmodo.com/…
I can't wait for a defunct publisher to break into my house and replace my books on the shelf with money in a grotesque tooth fairyesque manner
 
How does MS delete books from one's computer?
 
4:13 PM
through the backdoor
it's connected to the DRM server being taken down, the files were probably never on one's computer to begin with
 
ok, that makes more sense, thanks @AndrasDeak
 
Fermi Paradox solution #815322: most alien civilizations die out when economic forces accidentally revoke access to all documentation pertaining to science, technology, medicine, and nuclear power plant maintenance.
 
"Oh for Flurx' sake, Burblax forgot to renew all the certificates!"
 
"No problem, we'll renew the certificates now... Oops, the certificate renewal API is inaccessible without a certificate"
 
typical Burblax
 
4:36 PM
cbg
 
cbg
 
What are decent ways you can think of to create a scope in Python via a context manager?
 
Not sure what you mean, could you elaborate?
 
Like, create a scope so that some value can be used only within that scope, and not out of it. As an exercise, not anything serious
Like, you can set an attribute when you __enter__ and then delete it when you __exit__. Or similarly set a boolean attribute to say whether we've entered or exited the context manager and check that via a property, but that's kinda ugly.
Wondering if there's other interesting options
 
How can you ensure it was deleted upon exit?
 
4:43 PM
when does del self.attr not delete?
 
When there's nobody there to hear it fall?
 
lol
 
does pathlib provide a way to remove a file? or do I have to os.remove?
 
```python
a = 123
c = [a]
b = c
del(a)
b, c
```
 
4:46 PM
@Aran-Fey huh! I was fooled into thinking that was just for unlinking. Thanks
 
unsure of how that is relevant in this context? The attribute would be deleted when __exit__ is called by the context manager
e.g.
 
wait, there's a difference between deleting and unlinking?
 
class VariableScope:
    """Creates a local scope for the attribute 'value' when used as a context manager."""

    def __init__(self, value):
        self._value = value

    def __enter__(self):
        self.value = self._value
        return self

    def __exit__(self, *args, **kwargs):
        del self.value


with VariableScope("asdf") as scope:
    print("original val in scope:", scope.value)
    scope.value = "qwerty"
    print("modified val in scope:", scope.value)

try:
    print(scope.value)
 
@alkasm The contextvars module may or may not be useful
 
@Aran-Fey no... (idk) I'd made a distinction in my mind that wasn't there
 
4:49 PM
    I had a question about the `@property` decorater. From what I understood it, it is primarily usable when you have a dynamic attribute linked with the attributes already defined via `__init__` and you need to modify the attribute according to the attributes already defined

    So something like this

    class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    @property
    def coord(self):
        return self.x, self.y

p = Point(1,2)
print(p.coord)
p.x+=1
p.y+=2
 
class Scope:
    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.__dict__ = {}
add transaction and preserving initial state as desired
 
@Aran-Fey dope
 
that's what I thought too until I tried to actually use it and it confused the hell out of me :D
 
lol
 
@DeveshKumarSingh what's the question?
 
4:52 PM
see here about __del__
 
@MisterMiyagi the question was that, is property also usable in other contexts? where some existing code using classes can be refactored via property?
 
@property
def now(self) -> float:
    """The current simulation time"""
    return __LOOP_STATE__.LOOP.time
like this?
 
@MisterMiyagi what is __LOOP_STATE__.LOOP ? Is this something from a code you wrote?
 
it is some stacked thread-local state of an event loop
 
@MisterMiyagi That's a nice way of doing it, though has the same shortcomings as the other, namely that the only thing that happens is that the attributes get deleted upon exit, but you can still set and use normally after the context, too.
 
4:58 PM
in most cases, a property uses the state of a class because that's the point of having a class
 
00:00 - 17:0017:00 - 00:00

« first day (3180 days earlier)      last day (1769 days later) »