« first day (4276 days earlier)      last day (894 days later) » 

01:03
stackoverflow.com/questions/12453580 It's surprisingly difficult to find the canonical with either a search engine or a site search. I didn't expect it to actually use terminology like concatenate because of the introductory level of the material. It won't come up with any variation of the obvious searches for stuff about joining strings - which will give you a huge field of results for more complex questions.
I had to go digging (over on CV) to resolve this confusion:
9
Q: Information gain and mutual information: different or equal?

jcsunI'm very confused about the difference between Information gain and mutual information. to make it even more confusing is that I can find both sources defining them as identical and other which explain their differences: Information gain and Mutual information are the same: Feature Selection: ...

...also, anyone here personally calculate Information Gain for a Wordle guess? (I see 32K hits on the web)
...Diego Unzueta's blog on that is quite good: towardsdatascience.com/…
 
2 hours later…
03:28
Anyone in chat have a better idea what the reason behind this SyntaxError is?

    a = {'a': 1, 'b': 2}
    b = {'c': 4}
    # { **c for c in [a, b] } # SyntaxError: dict unpacking cannot be used in dict comprehension

I took a look at this question (stackoverflow.com/questions/62099681/…) but the answer doesn't inspire much faith...
And  this bit of PEP 448 (peps.python.org/pep-0448/#variations) makes it seem like the devs just said "no, don't want to".
Seems to me like that would add a lot of complexity for very little benefit
That answer's bad :(
And you can do a | b in Python 3.9+, which is much better than that dict comprehension IMO
03:44
But what if you wanted to merge an arbitrary number of dicts? I guess it's relatively trivial to just create a new dictionary and make the union of them all, but it seems a bit strange to not have a built-in?
@0x263A there is no guarantee that all elements inside the items yielded by the underlying expression will always be a mapping - yes while you can clearly see [a, b] is a sequence of dicts, handling a failure from a mismatched type in a comprehension expression might be too ugly for devs to consider
also ChainMap is a built-in, just an import away
and that the comprehension expression with that unpacking can introduce ambiguity - imagine {**d for d in some_sequence} - what if some_sequence is already a dict, what happens?
sure you could say d would normally represent as items from d.keys() and that could result in an error, but you see if we have to debate this, it shows this might already be a bad idea...
@metatoaster Hm, but how is throwing an expression for that different than for say, an unhashable type? e.g. {item for item in ["", {}]} seems like you could just throw "not a mapping"
@metatoaster Oh neat, thanks didn't know about this
I guess I'd expect it to behave the way {**a,**b,**c} or rather {**a,**b, ... ,**n} would
yes, sure, but again, that introduce a lot more complexity, but really Python is also inconsistent with how it's been going lately so who am I to judge what's sensible
04:14
@0x263A What you're asking for is just a bit too magical. The point of a comprehension is that each element of the input generates (conditionally) one element of output. It exists to transform the input. The equivalent with lists doesn't work either.
a = {0:0}
b = {1:2}
c = {3:4}
dicts_=[a,b,c]
merged = eval("{"+','.join(["**"+str(foo) for foo in locals()["dicts_"]])+"}")
print(merged)
Become ungovernable!
@KarlKnechtel the notion of wanting to keep comprehensions at a 1:1 action->thing ratio makes sense, but the PEP I linked only mentions readability not functionality.
+ the idea doesn't seem that strange when this {**a,**b,**c} exists? (from a syntax perspective idk about under the hood)
also forgot to mention is that comprehension also has a conditional part that's often ignore, i.e. {k: v for k, v in seq if ...}
too often people just treat comprehension as a hammer they can slap on any problem
if you think you can define the semantics unambiguously, it might be more of a question for the Python mailing list
04:38
stackoverflow.com/questions/36250353 I'm very much not a fan of how this question is titled. This is a canonical for one possible cause of the problem, and the title doesn't communicate what that cause is (because OP didn't recognize the cause, obviously)
05:35
@KarlKnechtel apologies, but while I'm aware those exist I don't know which you are defaulting to? Mind pointing me somewhere?
@0x263A I'm pretty sure the same is also forbidden in list comps.
yeah and the given reason is just "readability issues" which feels half-baked? Especially when things like:

>>> f = lambda **kwargs: print(kwargs)
>>> f(a='boo')
{'a': 'boo'}

exist.
05:50
Not sure how that is related
06:03
I have vague memories of an argument that if [*val for val in lst] is valid then so is (*val for val in lst), but then foo(*val for val in lst) looks a bit ambiguous.
@AndrasDeak--СлаваУкраїні I'd clump that and something like a comprehension that wraps {dict_0,...,dict_n} in the same bucket in my head as "things that are obvious if you know a couple other things, but probably not in isolation"
06:23
IIRC the problem was with the old parser. [*val ...] was ambiguous whether it proceeded as for val ... or , other_val.
For PEG this should be trivial.
Readability counts (for the parser)
06:52
@0x263A I had in mind the most general one, mail.python.org/mailman/listinfo/python-list, but there are indeed many to choose from
07:02
stackoverflow.com/questions/3294889 an interesting case here. The question as titled and answered is about iterating over a dictionary, but the question as intended was almost surely about for loop syntax generally. The latter I have seen elsewhere on the internet to be an extremely common misconception.
 
2 hours later…
08:38
TIL that open already supports exclusive creation. goes fetch the code reaper hat of old code cleanup +1
the x mode yeah?
i've personally never had to use it but seen it in some code bases before, i think every time i've seen it, its been used incorrectly, so there's that :P (things like rwx or so on, probably some linux influence there)
@ParitoshSingh never seen it in code before... it's normally x to set the executable bit for file permissions on *nix systems...
@ParitoshSingh It's useful for low-effort exclusive program execution. Often enough I don't want to bother using dependencies for simple automation scripts, so having it directly available is neat.
09:45
-1
Q: How to compile python?

Dawid LipowczanPreparation to job interview Why is it not working? Thanks for help in advance I have google job interview tomorrow x = 'x' print = x def function(): if function: print = def

flag as spam, it's obviously a troll
@MisterMiyagi I find it hard to understand the use case for this
(also, when I try to search with that term, I get a lot of irrelevant nonsense)
@Hakaishin I'm not entirely convinced of that. although I'm also generally surprised how little trolling we get
(unless the spam detection routines catch it accidentally?)
10:12
@KarlKnechtel It's a cheap locking mechanism. When the program starts it tries to exclusive-create the file, otherwise it knows there is already a program instance running.
For example, I'm writing an automation for managing a compute node – draining processing tasks, triggering a reboot or even re-installation. Doesn't make sense to have multiple instances running at the same time, since their actions would conflict.
10:37
@MisterMiyagi you mean like lock files?
@KarlKnechtel there's bots and chatrooms running to watch the front page
@AndrasDeak--СлаваУкраїні Yep.
 
2 hours later…
12:17
The other day I bought a game on Steam called "A=B". It's a programming game where you write algorithms in an esolang that can only do string substitution. It's a neat concept.
12:28
Much to my surprise, it's Turing Complete. It definitely is by chapter 3, when they introduce the "execute this line exactly once and then never again" directive. But I think you can get arbitrary computations just from the basic operations in chapter 1.
@KarlKnechtel Weird,,,, their only other post looked reasonably okay-ish... shrugs
12:59
Is stackoverflow.com/questions/44258903 really a better canonical than stackoverflow.com/questions/52965952? I feel like it should be closed the other way around. The interesting and surprising thing is that the except block doesn't simply have its own scope (as one might suspect; Python does kinda special case some things, like list comprehensions), but actively dels the name
13:22
Here is a rudimentary implementation of the A=B esolang, or at least something like it. I've included a sample program that counts consecutive B characters in the input.
It's fairly efficient -- exec(source, "a" + "b"*10000) runs in about one second. exec(source, "a" + "b"*100000) takes considerably longer. Decidedly not O(len(input)).
I salute the procrastination there. Excellent.
#given a string containing only X, a, b, and c, move all "X"es to the end of the string.
source="""
Xa = aX
Xb = bX
Xc = cX
"""
s = "XacbaaacXacXccacXcbcX"
print(exec(source, s)) #output: acbaaacacccaccbcXXXXX
Here's a pattern that I find myself using frequently in the game. I wish I could express the program more concisely by using wildcards. Something like X[a-c] = \1X. It would only be syntactical sugar, so it wouldn't detract from the fun parts of the challenge.
 
1 hour later…
14:48
That sounds pretty cool, I guess lambda calculus only needs string substition to work so you're probably right with the Turing Completeness
Ever played tis-100 btw? It's more like super-constrained assemby-level programming but also quite fun
It's pretty easy to implement an actual turing machine in A=B. Suppose the input string is guaranteed to start with "0|", and this is guaranteed to be the only "|" in the input. The pipe represents the position of the turing machine's header. The 0 is its starting state. The rest of the string is the tape. You define the state transition table with the program, using one line for each state-and-header combination.
For example, "0|Q=R3|" means "if the header points to 'Q' and the state is 0, overwrite 'Q' with 'R', move the header right one cell, and change the state to 3". Moving the header left is possible, but less concise
Yes, I have played TIS-100. The credits for A=B specifically name TIS-100 as its primary inspiration.
heh, that's indeed pretty clean
They're pretty similar in presentation, but I'd say it's still a novel experience, since A=B involves challenges that are unique to One Instruction Set Computers. TIS-100 gets a whole assembly instruction set, in comparison :-p
15:29
Here is a janky implementation that does arithmetic on inputs that contain digits and "+". Runs in about O(rightmost operand) time.
Or, hmm, it's more expensive when there's more than one "+".
O(sum of all operands except the leftmost one), perhaps.
Has someone run Linux reboot from inside a Python script? Does the script finish gracefully (including atexit) or do things just die a fiery death of a phoenix?
Philosophers have long pondered the fate of the snake that eats its own tail
It's probably going to have some problems on the loo...
I'm not so sure. I watched The Human Centipede documentary and it seemed pretty conclusive that it could probably survive. I also watched the sequel (albeit drunk) and I think the experiment was successfully replicated
And, of course, The Human Cent-i-pad from South Park but that's more of a Plos One source, so I took it with a grain of salt
15:45
Thank goodness that humanity has invented moving pictures to enshrine useful information!
If South Park and the Simpsons were to agree on POSIX semantics, I would take that as a reliable source.
Sometimes I do think science goes too far
Well, it's difficult finding the breaks of your move-o-mat while doing sciency stuff.
waves at their fellow meatbags Jolly cabbage!
 
2 hours later…
17:37
@MisterMiyagi try on docker?
Wouldn't that send SIGSOMETHING to the python process?
TERM, probably
Hey people, how's it going?
I changed my handle, but it's still me, Aaron Hall. :P
@MisterMiyagi Have you tried setting a flag and having your Python command followed in your shell with a check for that flag and the reboot command? It just feels like the wrong thing to be trying to do inside Python... how complex is your Python environment? do you have a lot going on in atexit?
My three cents (why not two? inflation.)
17:48
Miyagi has... *shudder*... users
@MisterMiyagi Does the Python run with admin privileges?
@CPDatascience please don't ask for help here with fresh questions on the main site as per our rules
brainstorming you could set a flag (like a file maybe) and have an admin job that looks for the flag as a request to reboot and does so (don't forget to unset the flag.) I've been using systemd for my website checking job and it's pretty cool. a better example here (uses NixOS to generate the job): nixos.wiki/wiki/Nix_Cookbook#Creating_periodic_services
18:09
@RussiaMustRemovePutin It's a rewrite of a bash script; the bash version (unsafely) cleaned up everything manually before rebooting.
@RussiaMustRemovePutin Yes, it needs to prepare several system services for the reboot, then clean up after itself for the reboot itself.
$ cat demo.sh
set -e

python - << 'EOF'
import sys
print('hello')
EOF

echo "reboot command here"
$ . demo.sh
hello
reboot command here
You could use a heredoc like the above ^^^
you stay in bash, do the python stuff that Python does well, then reboot BAU (Business As Usual).
or instead of embedding a heredoc just write a separate Python module and call it with python -m mycleanupmodule
I always loved embedding Python in shell scripts for some reason...
18:33
Let's say I create a list of lists of letters (e.g. [["C", "T", "A"], ["V", "F", "S"], ...], and I want to verify that the created list does not have two consecutive letters that are the same in the same position (so the example above is fine, but [["C", "T", "A"], ["C", "F", "S"], ...] is not). How could I go about doing this? Here is a nearly-working solution:
I say nearly working because I am unsure if I set the flags in the right place. Does this loop actually do what I mean for it to do, or is it only resampling once, which is most of the time good enough to ensure the constraint?
18:49
@Catyre "two consecutive letters"?
Hmm this is rather difficult to word, give me a sec haha
You could use a collections.Counter (or defaultdict) to register (character, index) pairs. All counts must be 1.
Two of the same letter in the same position in consecutive lists
Only consecutive lists, back to back?
yes
18:52
Then iterate with a 2-length window and just compare (c1 != c2 for c1, c2 in zip(prev, current))
# e.g.
shifted = iter(lst)
next(shifted)
for prev, current in zip(lst, shifted):
    ...
Borderline OK to use a nested comprehension here.
What's a good example of Clean Code in Python?
@AndrasDeak--СлаваУкраїні What is lst here? The list of lists of letters, or one of the lists of letters?
@Catyre try to understand what the first snippet does, then the second, and try to figure that out.
19:10
What's a good example of Uncle Bob's "Clean Architecture" in Python, was what I intended to ask :P
Every code base I have ever laid eyes upon has been unclean
So its myth. Do people at least pretend to try? :P
19:32
I think lots of people really do try. But it's hard.
for it is written: practicality beats purity
and it is also written: "yeah, that's legacy"
The path of the righteous man is beset on all sides
hey guys, where is the location of pip corresponding to /usr/lib/python2.7/ ?
@Mahesha999 What do you mean? Where it puts its installed packages?
Or the pip executable specifically?
The latter would be a trick question: your best bet is always using /usr/lib/python2.7 -m pip or equivalent.
19:45
the packages are at '/usr/lib/python2.7/dist-packages/, want to know where exactly pip is located that installs in this directory
Ah, /lib, sorry, I misread. Probably /usr/bin/pip.
/usr/lib/python2.7 -m pip - python2.7 is directory
Simply uninstall python 2.7, and then it will no longer matter where its pip used to be
@Mahesha999 I assume you have multiple python installs which makes which pip unreliable
@Mahesha999 perhaps dpkg -L python-pip | grep 'pip$' helps
19:48
@davidism whoah, epic
time to archive it
But does it adhere to Uncle Bob's "Clean Architecture"?
let's see if github has a dumb badge for that :P
@Kevin But my app need python 2.7
Uninstall the app. If you need the app for your job, quit your job.
19:52
actually am getting django not found error while starting vscode debugging.

So I tried to print list of installed packages from within python. It printed this:
['argparse==1.2.1', 'gyp==0.1', 'mercurial==4.8.2', 'python==2.7.16', 'setuptools==40.8.0', 'wheel==0.32.3', 'wsgiref==0.1.2']

Then I did `print(setuptools.__path__)`, it printed `['/usr/lib/python2.7/dist-packages/setuptools']`

I checked vscode's settings.json, it has `"python.pythonPath": "/usr/local/bin/python"`
Also doing pip install django says: `Requirement already satisfied: Django==1.9.5 in /usr/local/lib/python2.7/site-pa
@Kevin very creative solution!!!
Django works with Python 3, if that helps
So you want me to migrate app from python2.7 to python3?
If yes, thats work in progress, but before that we need to support current version in python2.7
Again, why not use your_favourite_python_version -m pip?
I do want you to migrate the app to python3, yes. Of course, you don't have to do what I want, and there are no consequences for ignoring me.
20:17
@KarlKnechtel There's a typo in your first link
2026
Q: How to read a file line-by-line into a list?

Julie RaswickHow do I read every line of a file in Python and store each line as an element in a list? I want to read the file line by line and append each line to the end of the list.

That one. I don't understand why some parts of the Stack Overflow UI leave off the https://stackoverflow.com part, but I apparently forgot to fix it when pasting
@AndrasDeak--СлаваУкраїні After more thought, I think I better understand the question in my head now. Your example works for validating that the list fits within the constraints (which, to be fair, is all I said it needed to do initially), but my question isn't actually about implementing the constraint itself. In actuality I generate a new list of letters in the loop if it doesn't fit the constraint, and I want to keep doing that until it does.
My question is about how to stay in the loop that generates the new list until it fits the constraint, and only exit it if it does. After a rewrite of my original code, here is a slightly improved (but still wrong) version: pastebin.com/X2i72jcm. The problem is not checking that they are equal, it is that once boolean is true, a new random sample is made, but that random sample still has a chance of including a repeat letter. But this loop will not catch the resampled's mistake.
@KarlKnechtel Ok, really strange
@Catyre without opening that link: the general approach to that problem is a while True loop which you only break out of when you are happy with what you have.
yeah, I can't find anything remotely as popular as that, for "how do I write a list to file line by line?". My searching turned up e.g. stackoverflow.com/questions/4653480/… which is in fact about something completely unrelated (and also just all around bad)
20:21
or a while it_is_not_OK: <do thing>, but that usually means you have to do the initial iteration separately
OMG. this is unbelievably bad. Several answers down in my external searching, I find something that actually has some upvotes: https://stackoverflow.com/questions/7138686/how-to-write-a-list-to-a-file-with-newlines-in-python3

and it's **terrible**.
+51, 108k views... and the question doesn't address the topic, is actually a stealth debugging request, and the code is full of problems to debug that are unrelated to the problem. At least the answers indirectly get at the right code eventually.
@AndrasDeak--СлаваУкраїні This was my approach in the first pastebin link, but my conditions/flags seemed to not be in the right place, which was my original question.
that one at least links to a better written question, stackoverflow.com/questions/5429064/…, but that one is still much too complex
@Catyre well your original paste looks good to me. Are you sure it doesn't work as-is?
The "right place" for flag = False is where it already is.
But again, the way I would do it is something like this:
while True:
    chars = sample(alphabet, 3)
    if any(c1 == c2 for c1, c2 in zip(prev_chars, chars)):
        # need to generate again
        continue
    # else we've got a good sample
    stream.append(chars)
    prev_chars = chars
    break
and it's generally better to ask your actual question the first time around
21:09
Hmm looks like I mixed up the output of the correct version sandwiched between the outputs of two wrong versions, so I missed it as a solution.
how embarassing :/
 
2 hours later…
22:47
@KarlKnechtel fixed its title, downvoted and closed. Daily janitorial.
23:09
Much appreciated.
I asked a general question on Meta about how to clean up messes like this. In the comments, I got stackoverflow.com/questions/899103/… proposed as a canonical. I think there are some issues, but it's undeniably more popular than anything I was finding
Given how the answers interpreted the question, I don't think it can be used well for the specific question I had in mind.
It's closer to a generic "what are my options for storing a list's data in a file, and recovering it later?"
@KarlKnechtel By the way, we have to push back much harder on new users (coming from Java, JS etc.) calling a list an 'array' or a dict an 'object'.
I try
(that said, they're justified in that if the question also is )
the thing with that question is, it's titled and asked properly for what I want, but somehow the large majority of people interpreted it as the generic serialization question.
(That seems like a motivation for retitling and editing the question.)
@KarlKnechtel No because if they don't learn to ask Python questions in Python terms, there's no point moaning the lack of response or that people can't read their minds.
no, I mean the JSON standard uses the terms object and array for the grammar production rules in question
@KarlKnechtel Again the title needed to be changed explicitly to Writing a list to a file with Python, with newlines. There's a big difference between simply "writing a list to file", because to write line-endings in a platform-independent way, we have to open it in the correct mode.
23:15
oh, I just realized that title change is yours, and new.
I don't think that works. I haven't formally chosen this as canonical yet, and the answer section is full of incompatible responses.
@KarlKnechtel I'm very aware of that, I've been dealing with those sort of questions for years. If they mean "JSON object" then they should say "JSON object". If they mean "dict" they should say "dict". If they only say "object" in a generic Python context, users would interpret that as Python object.
(I feel bad for OP)
@smci okay, that's valid yes
so I do try to clear that kind of thing up
@KarlKnechtel Well, the title and body were incompatible. Not cleaning up that mess causes more confusion. So, pick which confusion. Remember, if you make this a canonical, people won't expect its answers to do something different to what the title says. (Also of course, we often get the users posting code that only works on Windows ("Idontcare this works onWindows")).
separately re json, I feel the lack of
Q. I used `json` to parse this file / `response.json()` to get parsed data from a `requests` Response; now how do I access (XYZ)?
A. The parsed response is **just** a data structure composed of *perfectly ordinary* Python lists and dicts; so you do that access in *the same way* that you would if you had gotten *the same data structure* in *any other way*
The title and answers were compatible, and the answers are tons more edit weight. Lots of them are unsalvageable for the question as intended. So my vote is to restore the title and edit the question, and use it as not this canonical
@KarlKnechtel 0h deary... it looked good as a canonical at first glance. I'm getting a headache. How many messed-up ways can people write a list to a file?
23:19
and keep looking for the canonical I want.
4
Q: How to key into deeply nested dictionary and list structure

nilabha1512In the given dict = {'d1':[1,2,{'d2':['this is tricky',{'tough':[1,2,['me']]}]}]} The questions asks me to print 'me'. I tried to understand the given keys and values in the dictionary to find any relationship based on the key was unable to do so. Is there a certain function is should be aware o...

I think I linked that one before
huh, that's in my bookmarks. I really have amnesia for this kind of thing apparently.
-2
Q: Difficulty separating levels of a deeply nested dictionary and list structure

DougI've reviewed this post: How to key into deeply nested dictionary and list structure and attempted to break down this list structure, however I continue to fail as this example has the final "me" in [] while my problem does not :( session.my_position(symbol="BTCUSDT") {'ret_code': 0, 'ret_msg': ...

a good bit of advice from a new user
but yeah, these questions are just basically "pls gib teh codez"
@metatoaster cyf tvo gru pbqrm sounds better. Almost Klingon
@metatoaster that cites the first one and honestly is a duplicate of it. "I didn't understand how to apply this technique; please show the same steps on another concrete example" doesn't seem useful
but the first one could use another answer talking about the technique in a more abstract way, perhaps?
and perhaps slightly polish the question, give a title that adds mention of json but leaves it as a generic data-structure question
I can't actually decipher *what OP meant* by
> I tried to understand the given keys and values in the dictionary to find any relationship based on the key was unable to do so.
It seems that OP never came back after asking.
23:52
@smci I appreciate your effort, but the question is a year old and it seems unlikely that OP will provide any more feedback, having not been seen since.
@KarlKnechtel By definition when you have a 1-rep user who was never seen again, clarification ain't gonna happen, so unless the intent can be discerned, the question is likely not salvageable. So just give up, add a comment stating what's unclear, vote-to-close, downvote if merited...
@KarlKnechtel Agreed. I already voted-to-close
[whining] but I'm trying to make a canonnnnnicalllll....
@KarlKnechtel Well, anything still standing after the flamethrower stops might be a candidate. Have you see the end of The Thing?
@JonClements Shrugged at which end of that proposition...?
@KarlKnechtel Maybe they meant "there was no (easy) way to get the lookup expression from the target result". Or maybe they didn't.
mm
you're right, I should search more first. I already found stackoverflow.com/questions/12788217/…
that's relatively good (might not be able to do better) but needs a lot of work to not be idiosyncratic and to explain technique.

« first day (4276 days earlier)      last day (894 days later) »