« first day (3176 days earlier)      last day (1997 days later) » 
00:00 - 18:0018:00 - 00:00

00:00
Is there a way to see which tags are most popular used in combination with python on SO?
@smci weird, if I google that I only get kinky results. I should tell both google and duckduckgo that they are several decades behind in lingo ;)
Can someone maybe mark this as dup? stackoverflow.com/questions/56782322/…
@AndrasDeak or it's a private club and you have to be invited... Hmm maybe the Silicon Valley/US slang on restrictive coding standards is more risque than rest-of-world... sounds like good fodder for a Reddit AMA
@Erfan good find. You can use for that here in chat, see this. And please check dupes and add the generic tag so that gold badgers can hammer them with a single vote.
I see, thank you for the information, didn't know that. Cheers @AndrasDeak
00:18
@AndrasDeak Less than 10 years ago, the thought that Google would do evil things was so unthinkable that Randall could joke about it... m.xkcd.com/792
Well they did have "Don't be evil" in their manifesto back then...
00:34
Personally, I don't mind them "fingerprinting" my browser. I just wish they weren't being slimy about it.
I do. If I wanted them to track me I would allow it in firefox. Then again I'm not personally affected by any of this because I use noscript with very strict settings
I don't think I've ever seen anything other than SO job ads on SO
I guess they don't actually need to do that stuff to me anyway, since I'm normally logged into my Google account anyway. I figure they're entitled to make some cash from my data, as long as they don't compromise my privacy. After all, I do make lots of Google searches. But if they do slimy stuff, how do I know that they aren't compromising my privacy?
You can know for a fact that they compromise your privacy whenever they can. The ad market is explicitly about making money, and you are the product. If they wanted to make a profit and value your privacy they'd have gone into curtain manufacturing instead.
:D
Given the Google ads I see, they aren't actually very competent at profiling me correctly. I suppose I should spend a little more time telling them what ads are irrelevant to me. Eg, I don't drive, so it's pointless showing me car ads.
But thanks for the heads-up. I just linked that SO meta page over in The h Bar.
 
2 hours later…
02:47
cabbage y'all
to an empty room!
 
1 hour later…
03:52
Hi Guys
I am having dataframe called df which had column called date ( ex: April 20th, 2008, Marcg 16th, 2012...) I want to remove the year only from this column so I used df['date'] = df['Match_date'].str.extract('(\d\d\d\d)', expand = True). And it is working fine.
However, If I used to pass the same to a user-defined function, am getting an error "type object 'str' has no attribute 'extract'" Could you please advise whats wrong here? This is my code def extract_year(x):
x = str.extract('(\d\d\d\d)', expand = True)
x = x.astype(float)
return (x)
df['Year'] = df['Match_date'].apply(extract_year)
04:25
cbg
user10984358
>>> a
'/Volumes/Learning/College/Lab/Image Analysis/att_faces/s34/10.pgm'
>>> a.replace(' ','\ ')
'/Volumes/Learning/College/Lab/Image\\ Analysis/att_faces/s34/10.pgm'
user10984358
can anyone tell me why I am getting '\\' instead of \ ' in the above snippet
user10984358
I am replacing space (' ') with a \ followed by a space ('\ ')
@Jason are you looking for pd.to_datetime(df['Match_date']).dt.strftime('%B %d') for only year pd.to_datetime(df['Match_date']).dt.strftime('%Y')
user10984358
my intended output should be
/Volumes/Learning/College/Lab/Image\ Analysis/att_faces/s34/10.pgm'
user10984358
04:33
I know spaces in path is evil but out of curiosity why am I getting such an output?
@anky_91 Yes it is working with daetime too. But it is not working when I pass it to user defined function as I have 15 columns needs to be converted
04:58
@Jason dont thing str has an attribute extract() , you can write a func with re
else
def extract_year(x):
      x = pd.to_datetime(x).strftime('%Y')
      x = float(x)
      return x
this works too i guess
05:17
@TheNamesAlc Your string only contains a single backslash. The interpreter is showing you the repr of the string, which makes backslash escape sequences visible. The escape sequence for backslash is a doubled backslash. If you print the string, it will look correct.
This is no different to what happens if you do a = 'hello\nworld'. If you do print(a), you get hello and world printed on separate lines.
But if you just do a, you see the quote marks and the \n escape sequence.
@anky_91 It's working thank you.
Cheers.!!
@anky_91 I am learning regex function. Do you recommend any good books for the same? I am a Data Analyst and spending a lot of time in data wrangling for my job. Appreciate your guidance.
05:32
@Jason i am currently learning the same. You can take a look here
Thaks let me have a look now.
@anky_91 It's definitely better to use strftime and strptime when working with times & dates. It's too easy to mess it up if you try to do it manually.
@PM2Ring absolutely, I agree on this. Gives you so much flexibility and user friendly. :)
rbrb for an hr. :)
 
1 hour later…
07:11
cbg
wow yikes.
i can't imagine browsing websites without ad-block anymore, so atleast this advertisment doesn't affect me directly.
But it is unacceptable
voted
Closed
08:51
considering the number of commits to panda-server I'm quite surprised I've only just encountered a mix-up in tagging with pandas. I've never even heard of it.
09:24
Hello
Hello
PanDA is pretty domain specific for high energy physics
our people usually don't ask for help publicly
I was looking through its documentation, pretty cool to get a response about "our people" :)
I have an issue where my python script creates an xlsx file, and then pushes it up to an SFTP. I get 'erno cannot find file error'. I think this is because Python is faster than the file directory representing the new xlsx file.

At the moment I am using the following code:

`#Wait for file to be created
import os.path
import time
while not os.path.exists(file_name):
time.sleep(1)`

Is there a better way do you think?
@roganjosh We have people everywhere :)
09:28
In any case, it was just complete confusion from the OP because they were asking about whether to use panda-server or MariaDB, and tagged it with pandas. They've deleted since, so you might maintain your stealthiness yet :)
@Andy ...how are you creating the file?
@Aran-Fey dataframe.to_excel()
So you have two completely independent processes, one that writes a file and one that acts when it's created?
yes
well the sequence is dataframe.to_excel() and then a function is called that pushes this to an sftp
But that would suggest that they're not independent
09:31
its all in the same script:
df.to_excel(bdridge_sftp_dict['my_input'])

#Upload to Broadridge
sftp_push(bdridge_sftp_dict,bdridge_sftp_dict['my_input'])
So why does the sftp function have to wait?
as above this is just in a mainflow function
argh i cant annotate code properly
it says in the FAQ to use `
for single-line code, yes
for multiple lines you press ctrl+k
ah thank you
am i being unclear with my example?
its all in the same script, first create xls from dataframe and then call a function to upload to ftp
unless pandas is doing something weird, the file should exist by the time df.excel(...) returns. But this is pandas we're talking about, what are the odds of it not doing something weird?
09:35
At least for me, yes. I still don't understand why anything needs to wait for the file to be created because it will be done serially
@Aran-Fey ok thanks. So i wasn't sure if that was the case with df.excel()
i'll plug away a bit more now knowing it should be done serially
@Aran-Fey @roganjosh thanks for help
Before you go, does this mean you assumed that the code would be async?
From what you posted, I don't think it's possible for the file to not exist before the file transfer starts, but that doesn't mean I'm right; maybe you have reason to feel that it's not the case
@roganjosh i didn't know that df.to_excel() would wait until the file was accessable in file explorer
in the past (not pandas) i have had sync issues with code and file directories, where the code is just too fast
(and not python)
so i am going to try work out now if df.to_excel() does wait for a ping back that the file is ready
Ok, then my experience tells me that you don't need to wait. to_csv() should complete fully
@roganjosh ok thank you
really helpful
09:44
Cbg, all.
I have downloaded my dataset from my SQL. columns types become the object. I converted the same into a float by using this code..churn.iloc[:, 6:20] = churn.iloc[:, 6:20].apply(convert). Churn is my data frame name. However, I checked the dtypes of my data frame again and it is not converting into the float. I am not getting any error when I executed the above code. Could you please advise whats wrong here? my dataset is clean.
def convert(x):
x = x.astype(str).astype(float)
return x --- This is my user defined function
This is probably what you're looking for
@roganjosh Can you please advise?
Did you read the canonical that I linked?
09:56
Yes I tried this also but not successful.
Please give an MCVE of the issue after trying the answers in that link
ok
@rogan
@roganjosh It's working if I copy the selected columns into new dataframe.
df = churn.iloc[:, 6:20]
df = df.apply(pd.to_numeric)
But If I use this code : churn.iloc[:, 6:20] = churn.iloc[:, 6:20].apply(pd.to_numeric).. It is not converting. But the code is working and it's not showing any error. Can you please advise what is the reason?
10:17
Ok, I don't actually know why that doesn't work
df = pd.DataFrame({'a': ['a', 'b', 'c'],
                   'b': ['0.1', '0.2', '0.3'],
                   'c': ['0.4', '0.5', '0.6']})

df.iloc[:, 1] = df.iloc[:, 1].astype(float)
print(df.dtypes)

df = pd.DataFrame({'a': ['a', 'b', 'c'],
                   'b': ['0.1', '0.2', '0.3'],
                   'c': ['0.4', '0.5', '0.6']})
df.iloc[:, 1:] = df.iloc[:, 1:].astype(float)
print(df.dtypes)
print(df.iloc[:, 1:])
Especially since this does work for assigning back to multiple columns:
df.iloc[:, 1:] = np.array([['test', 'test2'], ['test', 'test2'], ['test', 'test2']])
df = pd.DataFrame({'a': ['a', 'b', 'c'],
'b': ['0.1', '0.2', '0.3'],
'c': ['0.4', '0.5', '0.6']})
df.iloc[:, 1:] = df.iloc[:, 1:].astype(float)
print(df.dtypes)
print(df.iloc[:, 1:]) --- This is not converting into float. But code is working
when selecting multiple columns.
I understand the issue and I posted with code formatting. What I don't understand is why there is a discrepancy.
Thanks. Do you think any other solution is there to sort out the issue?. I copied into seperate dataframe and converted. Then merged into main one.
10:35
The link I gave should help. I don't understand the issue with the .iloc approach at all, my brain is screaming that I'm missing something basic
ok.
@Jason i think you can use df.infer_objects().dtypes here
@anky_91 let me try and confirm.
sure
Do you have any insight into what's going on here?
It seems to be a limitation on astype as far as I can gather
df = pd.DataFrame({'a': ['a', 'b', 'c'],
                   'b': [0.1, 0.2, 0.3],
                   'c': [0.4, 0.5, 0.6]})
print(df.dtypes)
df.iloc[:, 1:] = np.array([['test', 'test2'],
                          ['test', 'test2'],
                          ['test', 'test2']])
print(df.dtypes)
10:44
yes
So the assignment to the slice is fine, and the df will change column dtypes in this case
@roganjosh check this
yep it should work
yes. :(
Oh well, at least for my sanity, it's flagged as a bug. I was going a bit crazy then trying to understand what I was missing :)
10:47
@anky_91 I tried this code: churn.iloc[:, 6:20] = churn.iloc[:, 6:20].apply(pd.to_numeric), churn.iloc[:, 6:20].infer_objects().dtypes -->> it converts into float. However, when i check the churn.dtypes it comes object again.
hmm, the problem is with .iloc[], you can try doing churn=churn.infer_objects()
found another post now similar to this
@anky_91 it's working . code: churn.iloc[:, 6:20] = churn.iloc[:, 6:20].apply(pd.to_numeric), churn = churn.infer_objects(), churn.dtypes --> it's converted..
I don't know what's the problem in iloc here.
The last line of that answer is not correct, because you can change the dtype by assignment as I just showed
@Jason It's a bug. I thought we established that part?
i thought he reffered the bug is not letting it do so. -\/-
@roganjosh ok understood
10:58
Hi guys
hello
@anky_91 I read it as a mix. The bug doesn't seem to allow dtype changes, but you can get dtype changes simply by changing the data in the columns (i.e. like I converted floats to strings)
If I do this on a dataframe
adr_data['postal_code'] = adr_data['postal_code'].astype(str).str.strip()
Do I need to call 'str' again after converting the column to string ?
No idea, did you check the dtype of the column?
Its of object datatype
11:01
Then didn't you answer your own question?
@roganjosh yes
will have to test this more
But some days back when I used a string function it failed
I couldn't call a string method before applying 'str' I mean even though I read the data in string format
is there a generator version of glob glob?
Let me ask this question instead:
.str is an accessor
11:04
s.strip() is for a string, .str.strip() for series if that is what your question is
Ok I guess that answers it @roganjosh
@ParitoshSingh iglob rings a bell
If you had an actual string, then you wouldn't need '.str'. Instead you have a Series of strings, so you need to use the accessor if you want to apply some function to all the strings in the Series
@AndrasDeak sweet, thanks!
Got it thanks @roganjosh
Hi @AndrasDeak
Do you remember you suggested me to use a generator expression/list comprehension for a piece of code I posted here?
for i in columns:
    adr_data[i] = adr_data[i].str.strip().str.lower()
How do I convert it to list comp? I know the basic format but when I write like this
adr_data[i] = [adr_data[i].str.strip().str.lower()]
it gives an error
11:12
That isn't a list comprehension
the syntax of a list comprehension [<expression> for <names> in <iterable>]
sorry I shared the wrong code
adr_data[i] = [adr_data[i].str.strip().str.lower() for i in columns]
adr_data[i].str.strip().str.lower() is going to implicitly go through all the rows, but you can't just slap [] around it to make it a list comprehension
How do I do it?@roganjosh
@RaphX I never suggested that. Check again what I did suggest
22 hours ago, by Andras Deak
I'd also try using a native python reconstruction of the column, in case that hasn't been tried yet (hence my remarks that sometimes native python is faster). adr_data[i] = (s.strip().lower() for s in adr_data[i]) or the same in a list comp if the genex doesn't unpack right
at least copy-paste right
11:21
But even though I wrote the wrong code even in this case it would give an error like 'i is not defined' right?
s is the dataframe here right?
or is it the list of columns ?
12 mins ago, by RaphX
for i in columns:
    adr_data[i] = adr_data[i].str.strip().str.lower()
So i would be defined. It's not clear what you're asking now
Ok you want me to use the gen exp inside the for loop?@AndrasDeak
@ParitoshSingh I think you are looking for glob.iglob
@RaphX You can do whatever you want :P
But yes
Ah, I see @AndrasDeak got there before me. never mind.
11:25
@holdenweb Superior linkage ;)
for i in columns:
    adr_data[i] = [item.strip().lower() for item in adr_data[i].values.tolist()]
Ok that makes sense now
Thanks! @roganjosh@AndrasDeak
Jun 6 at 11:37, by Andras Deak
@RaphX Please try harder. And read how not to be a help vampire. You are seriously depleting patience of the users here, which is a non-renewable resource.
Something along those lines, you might not need tolist()
Read a python tutorial too, please, @RaphX
@roganjosh why the double indirection if you can just iterate the series?
11:28
Couldn't be bothered setting up a test case so went with the safest option
RaphX has enough troubles cargo culting
:D
@AndrasDeak Ok @AndrasDeak
It's not really funny, I'm rightly being reprimanded for giving you a sort-of-in-the-right-direction answer because you're not very focused about the issue
No the fault is mine, I was too fixated about writing the list comp/gen exp in one line as we normally do @roganjosh
11:53
stackoverflow.com/questions/56776724/… Can someone take a look at this. I have marked this as too-broad but it's not reviewed yet.
voted
voted as too broad, 1 vote to go
closed
12:24
Actually I think it's very clear what the OP was asking: "Can you make my life easier, please?" Not terribly good SO material.
@holdenweb now that's definitely a duplicate :P
12:44
Hey, I have a problem with some filename manipulation. I have lots of files (30000) and there are duplicates files on that fileset. The files are named ssn_filename_uniqueid.filetype (uniqueid is _123_123_123 last three numbers are changing) Now I need to find those duplicate files and transfer them to different folder. Code is here, and the print dupes is not printing the value i would like it to print, any idea where should i look that problem?
if each[0] in dup: will never evaluate to True because dup starts out empty and the only way to add to it is if that conditional succeeds, but it never does
Kevin'd again :/
please don't name your variables after builtins, i.e. list
how can you possibly have duplicates with this naming scheme?
ssn_filename_123_111_192.exe and ssn_filename_123_111_192.bin?
There are a couple of ways to identify duplicate items in a list. You can probably find them with a google search, but here's a couple.
from collections import Counter
def getDupes(seq):
    c = Counter(item[0] for item in seq)
    return [filename for filename, count in c.items() if count > 1]


def getDupes(seq):
    seen = set()
    dupes = []
    for item in seq:
        if item[0] in seen:
            dupes.append(item[0])
        seen.add(item[0])
    return dupes
Filenames is duplicated, and I need only to get those duplicated files. Oh good point on those variable naming.
12:50
help me out here... you cannot have files with the same name in the same directory
I agree that you cannot have files with the same name in the same directory.
I suspect the base names are the same and they have different extensions?
I've been operating under the assumption that two files are "duplicates" if their names are identical after stripping out some particular data, such as the file extension or some part of the filename that we don't care about
But that's not what the code implies.
(different extension, not what you said: timing accident)
# Set files to list ['filename','unique_id','file_type'] suggests to me that two files could be named, say, "foo_123.txt" and "foo_456.dat" and they'd still be considered dupes because we don't care about unique id and file type
12:53
Yeh, i strip out the uniqueid and I got the basename that could be duplicate. @Kevin Yeah just like that.
Incidentally I think renameFiles is not the best possible name for a function that doesn't actually rename files on the disk
Maybe split_filenames or something would be good
Agreed. Plus, it would read much better as a generator function, yielding each one rather than appending to a list and returning that.
Style tips aside, I'm now worried that my getDupes implementations will be insufficient, since they return only the item[0] component of the file information. For example, if we pass in the splitted form of the two "foo" files from my previous example, then getDupes returns just ["foo"]. How do you decide which of foo_123.txt or foo_456.dat needs to be renamed? How do you even find them again?
Thanks for style tips, kinda new with python scripts so these help a lot! @Kevin Yeah, your script did get me almost the data I need thanks! I don´t need to rename those files, I only move duplicated files to different folder (both of them).
13:08
Here's an alternate implementation that I've got in mind. pastebin.com/pdkCbAFf
Using collect instead of getDupes is the important part. Basically collect reorganizes a list into a dict, assigning each item to a key based on its category. In this case, the category is the first part of the filename's name.
Once you have the dict, you can iterate over each category and determine whether any duplicates exist just by checking the length. Then you can iterate over the filenames in that category and rename them or move them or whatever.
This is maybe a little bit of overkill since all you're interested in doing is moving every duplicate file, and you could still do that using getDupes as long as it returned a list of complete unsplitted filenames and not just the first third of each filename.
But I think the collect design is a little more robust against future changes to requirements. If your boss says "great job, but actually we don't want to move every duplicate file. We actually need to keep the first file in each category where it is, and only move all the ones that collide with it", then you can do that with a three-character change to the collect-based approach, but the getDupes based approach would need more substantial refactoring
Come to think of it, it's actually pretty hard to make getDupes return a list of complete unsplitted filenames. Unless you store them in a dict, but then you're basically reimplementing collect, so why bother.
13:25
Thanks going to check that collect code, need to learn about it a bit. And yeah this is a one time use only because of some mistakes with those files.
And I did got the full filename by printing print(item[0]+item[1]+"."+item[2]) it like this on getDupes.
I did forget to mention that in my pastebin I modified renameFiles to add the complete unsplit form of the filename as the fourth item of each list. But if you can unambiguously reconstruct the full filename from the first three components, that's not necessary
The problem with adding print(item[0]+item[1]+"."+item[2]) to getDupes is that, if you put it right before the dupes.append call, it won't print the first duplicate of each category. For example, the following code does not print "foo123.txt" despite that file colliding with "foo456.dat"
def getDupes(seq):
    seen = set()
    dupes = []
    for item in seq:
        if item[0] in seen:
            print(item[0]+item[1]+"."+item[2])
            dupes.append(item[0])
        seen.add(item[0])
    return dupes

splitted_filenames = [
    ("foo", "123", "txt"),
    ("foo", "456", "dat"),
    ("bar", "789", "py")
]

getDupes(splitted_filenames)
#result:
#foo456.dat
In this case it sure would be nice if your boss did come in and say "actually just leave the first file in each category where it is"
13:44
Yeah, did notice that myself too, it dont move all files. Going to check that collection next.
14:06
Got it working now, need to understand what is happening on collect, but thanks for help!
If you find it intimidating to use non-builtin types like defaultdict and itemgetter, here's a rough equivalent that uses only regular dicts and lists.
def collect(seq):
    d = {}
    for item in seq:
        key = item[0]
        if key not in d:
            d[key] = []
        d[key].append(item)
    return d
There's no predicate argument in this one because that's another bit of overkill that's really only useful if you intend to call collect more than once using different categorizations. But you're not, so you may as well just do index[0] right there in the body of collect
14:30
Education horror story: my coworker is taking an online course for Flask. The course uses a custom flask server launcher whose code is read-only. The launcher contains a try: <entire program goes here>; except: pass block. My coworker's project is mysteriously exiting prematurely with no stack trace.
He should demand his money back
assuming he paid for that
Possibly related: werkzeug 0.15 is installed, but the custom read-only server launcher is using modules that were deprecated after 0.14.
wow, that's some course huh
So I tell a lie when I say there's no stack trace. There are two stack traces complaining of DeprecationWarnings. But I'm 60% sure that they aren't the cause of the crash
cabbages continuous learners
14:33
If the program keeps on trucking after the first DeprecationWarning, it would be weird if the second one killed the process
Still not entirely sure how a DeprecationWarning is even displaying a stack trace, since one generally does not raise a DeprecationWarning directly, and werkzeug specifically does not raise it in this case, instead calling warnings.warn like you're supposed to
wim
wim
deprecation warnings just print to stderr, if you have it enabled
stack traces won't print unless exception is unhandled
if there are deprecation warnings perhaps there's something even older that now raises
look for things deprecated even earlier than what throws the warning
or: your friend should put their own code inside their own try/except and catch 'em all to see what happens
He can't downgrade werkzeug back to 0.14, btw. That's locked down as well.
wim
wim
14:39
@AndrasDeak hah, now that's fighting fire with fire
that's probably just about the best thing you can do in this setup.
get those errors into your own hands, print/write them somewhere and reraise
I suspect the silent exit is occurring somewhere in the guts of the custom flask launcher in a spot that's not so easy to put a try-catch around without write access to the launcher.
@ParitoshSingh why reraise? :P
i just supposed might as well let get the original behaviour mimicing as close as possible, but now it just sounds foolish to me too.
the original behaviour is silly. this just recreates silly One way or another. It would be caught anyways if i understand correctly
My patience ran out on the problem (mostly because I couldn't remember how to exit vim) and I advised {coworker} to send an email to the system administrator. I am led to believe that the working environment was rolled out recently, so they're probably still ironing out the kinks.
14:44
using linux also helps with exiting vim
wim
wim
..it does?
It does. You try ctrl+c and it tells you
> Type :qa! and press <Enter> to abandon all changes and exit Vim
windows users won't try ctrl+c
If you use Windows, you will never successfully exit vim because you will never enter vim because Windows does not have vim*. If your goal is to maximize the number of times you exit vim, then linux is a better choice comparatively.
tries ctrl+c
14:47
vim is just how German's pronounce wim.
(* ok, apparently vim.org/download.php#pc is a thing. Revision: "Windows does not have vim installed by default")
wim
wim
well, so it does. guess I never tried to send sigint while in vim
@piRSquared dutch too
classic tweet
huh, the one-box turned off for twitter now?
The last tweet I posted didn't one-box despite me trying several variations on the url, so I'm inclined to say "yes"
Hello. Quick question: is for lst[-1] in lst: undefined behaviour?
nope. "For each element in the list, assign that element to lst[-1]."
14:53
My vote is for "well defined, but not something you should do in serious code"
Hmm...never thought about iterating lists this way, maybe it has it's uses...
I don't think I've ever used indexing or attribute access in a for loop target.
wim
wim
nice hammer
>>> for (print("This is dumb") or [0])[0] in range(3):
...     pass
...
This is dumb
This is dumb
This is dumb
I'd kinda like to see a piece of python code that's purposely programmed terribly. Would be pretty fun to see what kind of garbage people come up with. Like, instead of writing l2[:len(l1)] = l1 we can now write for i, l2[i] in enumerate(l1): pass
wim
wim
15:10
umm, just look at anything from ajax1234
✝_(º_º)
I wanna see more than 10 lines of garbage code though
15:24
You could check my github ;)
wim
wim
I think some voting ring or automated process is still going around indiscriminately downvoting old, closed dupes. Are any others here experiencing that too?
I don't have old closed dupes so I can't say.
are they also getting delvoted?
wim
wim
not the last bunch, no
they may have realized that delvotes are not anonymous
I don't have very many, but nobody's been touching my closed dupes
15:26
Have you ever pinged pnuts or someone else about the earlier deletions?
wim
wim
I pinged devesh and got told I was harassing him
I didn't ping pnuts, he's not a python guy
15:41
The Wikipedia page on alpha-beta pruning needs about ten more paragraphs of explanation and at least three illustrated examples with bright friendly color coding
I object to the use of "the core idea" as a section title without there being a section following that labeled "the entire idea"
cbg \o
i was notified today that my current stop-gap contract won't be renewed at the end of next week. If anyone knows of short-term contracting opportunities, maybe you could let me know.
I'll keep you in my thoughts, though opportunities are scarce in my department
morning cabbage
15:56
en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning#/media/… gives an ostensibly thorough explanation of AB pruning but I feel like a gif is not the best way to present discrete slides of text. Frames with little text takes too long to advance, and frames with a lot of text take too little.
When will Wikipedia allow embedded powerpoint files, c'mon devs
16:17
I'm testing out a little coding idiom, what do you think?
sorted(list_of_names, key=len)

vs

by_length = {'key': len}
sorted(list_of_names, **by_length)
Not a fan. ** only saves you 2 characters compared to key=, and the latter is something every python coder understands.
Saving keystrokes was not the goal
Yeah, I'm honestly not sure what the motivation was. What's wrong with key=len?
Just an experiment - it actually reads more sentence-like "I want the the names sorted by length"
wim
wim
not a fan
16:22
I'll admit that sorted(... by_length) is... in a weird way... readable, but the ** ruins it IMO
wim
wim
this looks like needless obfuscation
And often when using groupby, you have to precede with a sort using the same function as the key for groupby. Both could sort "by_length" and then groupby "by_length"
Or whatever. I just picked len as an easy cut-paste example
i think one very important consideration is whether the candidate it's replacing is tough to read or not.
I guarantee that every person who reads the line sorted(list_of_names, **by_length) will think "wtf is by_length" and immediately look up where it's defined
in case of key=len, i think it's fairly easy to pick up, and nice to read once you're used to it. That alone makes attempts to replace it more hurtful than helpful
wim
wim
16:26
and IDE may get confused too
can use splatty-splat when the kwargs are, necessarily, dynamic. otherwise just use plain keyword args.
What about key=lambda s: ''.join(c for c in s if c.isprintable() else "<{:02x}>".format(ord(c)))
that function needs a self-documenting name, but there's no reason to stuff it into a {'key': <func>} dict
wim
wim
syntax error?
the conditional needs to be before the loop, doesn't it?
I have some other code that has various named args to carry around across multiple method calls, and I'm finding ** a decent way to keep thing DRY.
@wim Oh, yes, very possibly
yeah, if can go in the end, but if else cant.
16:31
I think I'm past the 2-minute edit window
wim
wim
hate lambda and hate ternary conditionals, so -2 for that
Just need to add a walrus operator to hit the trifecta
@PaulMcG If you have a whole bundle of arguments then I don't mind the use of a dict. Though you could also consider encapsulating them all in a class instead, depending on the context
I like ternaries in principle, but they recently foiled a promising answer of mine on the main site when I determined that they're one of the few syntactical elements (the only syntactical element?) whose AST node has a different iteration order than the order of the elements as they appear in the source code.
In other words, if you iterate over the AST of 1 if 2 else 3, you'll visit 2, then 1, then 3
This is very annoying if you want to extract all of the integer literals from a source file in the order they appear
Long story short, one demerit to ternaries for having a highly obscure implementation detail that almost never matters
@Kevin Chained assignment is also out of order
>>> def z():
...    c = 1
...    a = b = c
...
>>> dis.dis(z)
  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (c)

  3           6 LOAD_FAST                0 (c)
              9 DUP_TOP
             10 STORE_FAST               1 (a)
             13 STORE_FAST               2 (b)
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE
(I'm assuming that dis output follows the AST, but could be wrong)
16:48
I think a = b = c still meets my (admittedly murkily defined) standards despite the names not appearing in order in the dis:
>>> ast.dump(ast.parse("a = b = c"))
"Module(body=[Assign(targets=[Name(id='a', ctx=Store()), Name(id='b', ctx=Store())], value=Name(id='c', ctx=Load()))])"
a comes before b and b comes before c, so we're good
Is it possible to initialize correctly defaultdict in constructor, e.g defualtdict(list, [('k1',1), ('k1',2)]) creates {'k1':[1, 2]}?
I see, but defualtdict(list, [('k1',1), ('k1',2)]) creates defaultdict(<class 'list'>, {'k1': 2}), the values aren't appended to list
wim
wim
sorry, I didn't read correctly your result
you don't only want to initialize key-values, you also want to accumulate
I would say, in that case, just use a plain old for-loop
Yes, I was just wondering if it's possible
wim
wim
16:59
nah, don't think so.
Just this morning I wrote a function collect that does approximately this. I don't think you can do it with a single call to defaultdict unless you're willing to perform some O(N^2) preprocessing
maybe with groupby()
wim
wim
groupby sucks because you would have to sort
groupby could do it, but you have to sort the key-value collection first. So O(n log n)ish.
^^hooray for independent verification
>>> items = [('k1',1), ('k1',2), ("z9", 3)]
>>> {k: [item[1] for item in items if item[0] == k] for k in {k for k,v in items}}
{'z9': [3], 'k1': [1, 2]}
Here's the O(N^2) version that you should only use if your Enter key is broken
>>> import itertools
>>> import operator
>>> {k: [item[1] for item in v] for k,v in itertools.groupby(sorted(items, key=operator.itemgetter(0)), key=operator.itemgetter(0))}
{'k1': [1, 2], 'z9': [3]}
Ok :) I see that classic for-loop will be better in this case
17:04
And here's sort-then-groupby
merge_with?
from toolz.dicttoolz import merge_with
from collections import defaultdict

items = [('k1',1), ('k1',2), ("z9", 3)]
defaultdict(list, merge_with(list, [{k: v} for k, v in items]))
Third-party library toolz has a method groupby which does the same thing as my homebrew collect. It doesn't seamlessly fix your problem though since toolz.groupby(operator.itemgetter(0), items) returns {'k1': [('k1', 1), ('k1', 2)], 'z9': [('z9', 3)]}
Hmm, two posts recommending different functions from the same lib. A rare half-kevinning.
semi-kevin
for loop I'd use
d = {}
for k, v in items:
    d.setdefault(k, []).append(v)

d = defaultdict(list, d)
Define your very own subclass
class lict(dict):
    def __init__(self, items):
        for k, v in items:
            self[k].append(v)

    def __getitem__(self, item):
        return self.setdefault(item, [])

lict(items)
17:26
Seems overkill to me, something like using Pandas in some questions...
I use pandas to wash my dishes and make my sandwiches... what's wrong with that?
Haha...nothing ;)
I mean other than animal cruelty. I shouldn't be making an herbivore prepare a turkey sandwich.
17:48
ha ha. don't know when will I be privileged to taste a turkey ..!!
00:00 - 18:0018:00 - 00:00

« first day (3176 days earlier)      last day (1997 days later) »