« first day (4237 days earlier)      last day (694 days later) » 

1:12 AM
https://meta.stackoverflow.com/questions/296157 https://meta.stackoverflow.com/questions/418239

looks like my usual rant in this room is nothing new to anyone ;) but there are signs of people showing interest in turning the site around, too.
@Aran-Fey re ` "composition over inheritance" always sounds like "apples over oranges" to me`

It's true that composition and inheritance model different relationships, and as such, serve different purposes strictly speaking. The adage is meant to be interpreted specifically *in the context of ways to achieve code reuse*; and the underlying idea is "here are some ways that you can reinterpret the problem, such that you can devise a different model, such that you have "have-a" rather than "is-a" relationships, which lets you use composition and thus get code reuse that works better."
 
1:59 AM
I just prefer to do away with the idea of "classes" together and do it the rust way, i.e. using traits
 
 
1 hour later…
3:20 AM
stackoverflow.com/questions/72342874 a clear dupe, it got hammered away by the one who posted an answer
 
 
2 hours later…
5:21 AM
@metatoaster seems like it's sorted out now. "Hammered away" got me confused; usually it's called "unhammered".
 
yeah I meant unhammered, but indeed it's fixed
 
5:51 AM
anyone good with pandas here?
 
 
1 hour later…
7:05 AM
@SebastianNin in general you should just ask your question and see if anyone can help, but if this is about your fresh question on the main site we ask that you wait 2 days before also asking here, see sopython.com/chatroom
 
 
2 hours later…
9:20 AM
same user posted duplicate answers to many questions in 2019, this one didn't have the tag so I could not hammer it stackoverflow.com/questions/58610004/…
 
gently strokes hammer
 
swoosh, swoosh, clonk, clonk
 
much obliged
 
10:14 AM
@tripleee did you modflag?
 
not at the time, it seemed like somebody already had done that in 2019 but I suppose I could throw another one ... many of the posts are gone now, though
did so now, thanks for prodding
 
10:41 AM
do we have a better canonical for "I want to add new data to each line in a file (without rewriting the file)" than stackoverflow.com/questions/56587469/…?
 
hi, I am trying to get a list of values to have its own newline when the user inputs multiple data using a function when it writes to the text file. For example, when the user inputs multiple records, it will get stored into a list `["1", "Sports", "2", "Entertainment"]`, but when the function writes it to the file, the result is like this

category_id, category_name
1, Sports, 2, Entertainment

The result I'm expecting should be like this:

category_id, category_name
1, Sports
2, Entertainment
The solution I currently have is to use `enumerate`.

    def write_data_to_file(filename: str, record_details: list) -> None:
        try:
            with open(filename, "a") as file:
                for id, name in enumerate(record_details):
                    file.write(f"{', '.join([str(id + 1), name])}\n")
        except EnvironmentError:
            print("Error writing to file")
 
why do you join these? that's exactly the wrong thing to do
 
Currently, it works. But it doesn't if I extend the headers for the file. For example, adding one more column "subcategory" in the category file..
 
                file.write(f"{id},{name}\n")`
simply
you can use enumerate(record_details, 1) to avoid having to add 1
 
@tripleee The data is stored in a list
 
10:52 AM
why do you anticipate EnvironmentError?
@CoreVisional when you loop over the list (with or without enumerate), you receive one item from the list in each iteration
your input must look like [["Sports", "Entertainment"]` for your code to make sense, though
if you want to pull out two items at a time, try
for idx in range(0, len(record_details), 2):
    file.write(f"{record_details[idx]},{record_details[idx+1]}\n")
this is easy enough to play around with in the REPL
>>> record_details = ["1", "foo", "2", "bar"]
>>> for idx in range(0, len(record_details), 2):
...   print(f"{record_details[idx]},{record_details[idx+1]}")
...
1,foo
2,bar
 
Yeah that is actually another one of my solutions. But if I have more columns, then I'll have to manually increase the step in range
 
the absolutely best solution would be then to have the input list organized as a list of lists of strings, one per record
 
Well, can you automatically figure out how many columns you need?
 
Yes, I already have a function that handles headers based on the number of values in the list. Idk if this will make sense but using the second solution, I could maybe loop based on the length of the headers in the list.
I did something like this

    headers = ["category_id", "category_name", "subcategory"]

    records = ["1", "Sports", "Badminton", "2", "Entertainment", "Comedy"]

    len_headers = len(headers)

    for i in range(len(records) // len_headers):
        x = records[len_headers * i : len_headers * (i + 1)]
        print(", ".join(x))
 
but still why do you have your records in a single list? It would make a lot more sense for your subsequent processing to have records = [["1", "Sports", "Badminton"], ["2", "Entertainment", "Comedy"]]
if your input is just a series of labels, maybe preprocess them into this format and then the remainder of the code will be simple and obvious
records = [[records[idx], records[idx+1], records[idx+2]] for idx in range(0, len(records), 3)]
 
11:07 AM
Or just records[idx:idx+3]?
 
yup, thanks, good catch
 
11:32 AM
@tripleee The input is actually data that will be written to a file called category. But the prompt is based on the number of headers that has been written to the file. I figured I could use enumerate to generate the IDs by joining the list.
 
Speaking of "simple and obvious" code, I saw some C# today and now I'm glad sorting in python doesn't look like some_list.sort(lambda a, b: b-a)
 
@tripleee I'm not actually sure how this solution works because it either returns indexerror or typeerror when I'm trying to loop over it
 
@CoreVisional it simply shows how to divide a simple list into a list of lists with three elements in each; it obviously needs to contain a multiple of three elements
it should be obvious how to adapt it to a different multiplier, though note that you need to change both the slice at the beginning and the skip element in range at the end
>>> records = ["1", "one", "Phoenix", "Arizona", "2", "two", "Sacramento", "California", "3", "three", "Anchorage", "Alaska"]
>>> records = [records[idx:idx+4] for idx in range(0, len(records), 4)]
>>> records
[['1', 'one', 'Phoenix', 'Arizona'], ['2', 'two', 'Sacramento', 'California'], ['3', 'three', 'Anchorage', 'Alaska']]
then simply loop over records to get one of the sublists at a time
>>> for idx, label, city, state in records:
...    print(idx, label, city, state)
...
1 one Phoenix Arizona
2 two Sacramento California
3 three Anchorage Alaska
 
11:56 AM
but if I'm writing it to a file, shouldn't I be using join on the lists tho?
 
You should probably be using the csv module to be honest
But either way, whether you feed it into csv.writer or str.join, you need a list with all the elements. So it's weird that your input isn't already formatted like that.
 
@Aran-Fey I'd already be using csv module if it wasn't for the requirement. As for the formatting part, would it make sense then to loop over these elements with each list of elements having its own row by looping over the number of columns? Because it seems like the solution provided above requires me to specify each column in the for loop
 
I didn't catch the start of this discussion. Was there "no csv module" among the requirements?
Because that would be a peculiar requirement.
 
@CoreVisional I don't understand what you mean, could you show an example?
 
12:12 PM
Re: "the solution provided above requires me to specify each column in the for loop". Perhaps you're saying "how am I supposed to write for idx, label, city, state in records: if I don't know the names of the columns or the number of columns ahead of time? I might have four, or I might have twenty". It's not strictly necessary to provide more than one variable name here. for row in records: would also work.
 
A function depends on a JSON (converted to dict), how should I have this dict? Should I read this from the JSON (inside the function)at each call or should I somehow pass the dict to this function (when called from main)?
for all the calls, the json will be the same
 
@Jake I prefer the second approach
 
Depending on context, you could also parse the JSON file once and then store the dict in a global variable
 
but the part that makes me question that approach is having to pass the same dict again and again, when it is assured (in my case) it will be the same
 
@AndrasDeak--СлаваУкраїні no modules should be imported except for your own, datetime, and sys and dictionary datatype is not allowed, only lists. So yes, my program will be filled with slicing, splitting, and joining.
 
12:16 PM
@CoreVisional so this is homework or a job interview problem?
"dictionary datatype is not allowed"
 
@Aran-Fey so this is one of those cases where having a global is ok then?
thanks for your replies Kevin and Aran-Fey
 
I don't know. It might be.
 
@Jake If you're concerned about performance, don't worry -- passing a dict to a function is very fast, even if it has a huge number of items.
On the more academic/aesthetic side, passing the dict is more elegant than using a global, IMO.
 
If you're concerned about performance, don't worry -- Python is slow anyway ;)
 
@Kevin performance is one of the concerns but its good to know this wont affect it
 
12:20 PM
Some languages perform expensive copy operations on objects that are passed to a function. Python is not one of those languages.
 
@AndrasDeak--СлаваУкраїні I know people tell this, but when you are surrounded by leet code interviewers it actually matters
said interviewers are actually people who review code so I have to end up explaining
 
@Jake what matters is probably opting for an O(n) algorithm instead of an O(n^2) one, but not the number of arguments a function takes, or whether str.join is passed a generator comprehension or a list comprehension.
 
If a leet code interviewer chooses applicant A because their C++ program ran 1 ms faster than applicant B's Python program, you don't want to work for them
 
you both make fair points as usual lol
@Kevin this seems kinda WET having to pass, but if its better in some consensus like academic I guess it is good approach
is there a python library that uses global in a way that is not frowned upon?
 
Now that I think about it, I'm curious why you need to call the same function with the same argument more than once
 
12:26 PM
@Jake python libraries (specifically, python standard libraries) observe bad practices fairly often
but using globals is probably not the kind of thing you see as an end-user of the library
 
@Kevin it is sort of a "search key exists in JSON", where it would return true or false based on the key it is passed, key is nested, so its not a case of my_dict.get(key) is not None
 
Even if a module uses the global statement, it can't see variables in the file that's importing it
 
Power move: use a cached function for the JSON -> dict conversion, and decorate all your functions that need the dict with a wrapper that passes in the dict :P
 
I did think about using partial, but felt like kinda too much
 
@Jake if the function could be named find_thing_in_dict() then you should absolutely put the dict in its signature.
 
12:28 PM
Agreed
 
then the fact that you always pass the same dict is a bit of an implementation detail
Perhaps if we use a class that has the converted dict as an instance attr, and a set of wrapper methods that passes in that dict... :P
 
@AndrasDeak--СлаваУкраїні what about things in pypi? its always "global is evil" so I never really know where it is "not evil"
 
@Jake global is not evil, global is to be avoided because it can easily lead to spaghetti code
in some cases globals are the least bad solution to a problem
 
global constants are fine, global variables are bad
 
eval is evil, and so is its dastardly cousin exec.
 
12:31 PM
@Kevin I didnt get this, wdym
 
@Jake globals are used for lots of things. Almost every function and class is global. globals are only tricky when they are mutated to share state, they are perfectly fine for sharing constants.
 
so this similar to what Aran-Fey said, constant global is fine then
 
In other words, globals don't give the module any more power than it would have otherwise. Nobody is going to say "Module XYZ is allowed to use globals, because there's no other way to do what it's doing". There's always another way.
 
just use a frozendict ;)
 
wants
 
is this out? it says 3.9
 
no, it says "draft" in the status, it's a work in progress
 
well, we've got types.MappingProxyType which is almost sorta kinda enough...
 
so the 3.9 is the version at which the draft began?
 
12:37 PM
@MisterMiyagi fair enough
 
That PEP is dancing with the dodos right now, as far as I can tell
 
Just del original_dict and BOOM, frozendict (give or take some silly time complexity concerns)
 
> PEPs will typically have a Python-Version header which indicates the version of Python that the feature will be released with.
(From PEP 1)
 
that is how I understood the PEP, so either PEP 1 must be changed or PEP 603 must be edited
 
it was probably created like that at around 3.7 or 3.8, and nobody has touched it since
 
12:42 PM
I suspect the number doesn't get revised even if it becomes impossible
 
you can look at github.com/python/peps/blame/main/pep-0603.rst for some history info
> Ignore revisions
You can now hide commits e.g. from automated formatters.
ohoho!
 
How are people supposed to know I'm working when all my "oops, forgot black" messages are hidden?
 
Skimming through the guidance for proper maintenance of PEPs, it doesn't say specifically that Draft type PEPs should have their Python-Version value be continually updated with fresh estimates. But it doesn't not say it either. Contrast with "Accepted, Final, Rejected or Superseded" type PEPs, which are pretty much set in stone.
@Marco I don't think there are going to be many resources for that kind of problem, because it's not something that professional developers deal with on a regular basis.
 
12:51 PM
Ok :( I appreciate if anyone can recommend me any reference
 
maybe look at figlet and banner and other legacy solutions which do this
 
I would say "how do I draw letters/shapes using *?" is not much different from "how does a computer draw letters/shapes using pixels?". A good entry point to that rabbit hole is fonts.
 
Ok, thanks to both!!
 
cowsay is written in Perl if you prefer that over C code
 
Nice, thanks!
 
12:55 PM
oh wait, it doesn't draw letters, just speech bubbles
here's a Python banner github.com/jbn/banner_comment but it seems unmaintained
oh it uses figlet behind the scenes anyway
here's an ambitious and nicely named Python package pypi.org/project/fart
 
@MisterMiyagi pre-commit hook?
 
Skynet, take the wheel? They'll have to pry it from my cold, dead Austrian accent!
 
@MisterMiyagi you either have natural intelligence or make use of an artificial one...
apparently the ignore-revs thing has been in beta since late March github.blog/changelog/…
 
'Ё' draws a box (-:
 
1:03 PM
@tripleee ok, but I didn't want a package that did things automatically hahaha :P
I wanted to learn things at hand
But thanks for the infos
 
reading and understanding code which solves the problem is sometimes the best way to learn, even if you ultimately want to implement it yourself
 
Ok, perfect, thanks
 
1:51 PM
Semi-relatedly, I've been playing with the box-drawing category of unicode characters, to see if I can pretty up my program output. Here's a sample, not sure if it will get rendered properly:
┌──┬────────────┬──────────┐
│Id│Name        │Color     │
├──┼────────────┼──────────┤
│0 │Kevin       │green     │
├──┼────────────┼──────────┤
│1 │Andras      │also green│
├──┼────────────┼──────────┤
│2 │MisterMiyagi│off-white │
└──┴────────────┴──────────┘
Bah, the page's line-height: 1.5em CSS rule is putting space between the vertical bits. In Notepad++ it's all seamless.
 
Box drawing is a mess since there is no space character in the box drawing character set.
It depends on the font whether spaces are the same size as the boxes.
 
Fortunately the fonts I'm using meet that criteria
... Provided I put the box in a code block. If I don't, it's not so pretty.
┌──┬────────────┬──────────┐
│Id│Name │Color │
├──┼────────────┼──────────┤
│0 │Kevin │green │
├──┼────────────┼──────────┤
│1 │Andras │also green│
├──┼────────────┼──────────┤
│2 │MisterMiyagi│off-white │
└──┴────────────┴──────────┘
Ha, even the horizontal lines are misaligned. I didn't expect that.
 
That's the state of the internet in a box for you.
 
Mine are aligned
 
The markdown engine shares some of the blame because it squishes multiple spaces into a single space. The result would be misaligned even without space-squishing though.
Here's where it looks misaligned on my system, in case it's environment-dependent
Do you guys ever need to display information in a nicely aligned grid? What kind of tools would you use for that? Spin up a flask server and render a full HTML <table>?
 
2:10 PM
14 months of pretty much weekly pressure from me and finally the Engineering team have ripping ShinyProxy out of our python webapp deployment architecture on their agenda :')
 
hi guys, if anyone has experience with tweepy, any idea why I am getting error in this
post_ids = [1528738814960668673]
post_ids.append(api.update_status(status=chunks[0],in_reply_to_status_id = post_ids[0], auto_populate_reply_metadata=True).id)
for idx in range(1,len(chunks)):

    print(post_ids[idx])
    post_ids.append(api.update_status(status=chunks[idx],in_reply_to_status_id = post_ids[idx], auto_populate_reply_metadata=True).id)
    time.sleep(60)
tweepy.errors.Unauthorized: 401 Unauthorized
89 - Invalid or expired token.
 
Seems self-explanatory
 
Option 3: You didn't provide a token at all
 
how do i provide a token
 
What does tweepy's documentation say about this?
 
2:15 PM
i looked but couldn't find something solid
 
If you're following along with a tutorial, it probably covers tokens at some point. If it doesn't, find a better tutorial. If there is no tutorial and you wrote the code yourself just by looking at the documentation, look through the documentation some more.
 
@DeepakVerma how about the Authentication section in docs.tweepy.org/en/stable?
 
@Kevin latex table... but I would not recommend it :P
 
alright, thanks. I'll see to the documentation better.
 
I toyed around with grids in tkinter but it gets sluggish once I have 20 rows and 10 columns. Excel it ain't.
 
2:32 PM
@Aran-Fey are these the tokens you talked about?
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
i couldn't see anything about token for update_status in the doc
 
yes
 
yes, I have these but I am still getting the error
 
Well, then it must be either wrong or expired
Hmm, I've never seen an access_token_secret, what the heck is that
 
3:01 PM
it's just key and secret
 
3:24 PM
@Kevin Nice, thank you very much!
 
Well that's the thing, I've never seen an access token secret before and I don't understand what its purpose is. And googling has been... unfruitful
fruitempty, one might say
 
3:47 PM
Alas, "fruitless" beat you to it :/
 
Not even "fruitles", to be consistent? Who designed this language?
 
Does anyone recommend a good course on PyTorch?
 
@Aran-Fey I bet you're a big fan of "fulfil" then :P
If it's a positive word, maybe the language designers knew that you'd want fewer keystrokes to be able to convey your joy on twitter? Some might say they were way ahead of their time
 
I don't really mind "fulfil" because it's not made of "full" and "fill", it's just a coincidentally similar. (I think.) I still have to think about how to write it correctly every time though
 
I can't help but believe that it derives from full and fill. To the Etymology Cave!
Well that was probably the quickest bit of research to spoil someone's day I've done for a while. You're welcome :( . late Old English fullfyllan ‘fill up, make full’
 
4:00 PM
Thank you for going to such lengths to make me annoyed by a new word :P
 
If it makes you feel any better, I also didn't know and now I'll be bugged by that for life
Small consolation?
 
It could be "fullfill", then
 
Suffering together is better than suffering alone, for sure
 
Not only that, but now my annoyance at this will mean I don't have to brute-force my spell-checker so there are definitely productivity gains to be had
 
Which is the English language's GitHub? :P
I bet Aran-Fey will suggest changes to the repository
 
4:08 PM
nah, it's all notabug anyway
 
haha
You must like the Austrian language better
Oops, German
 
No, english is much better. If only the spelling would match the pronunciation, it would be a great language
I just got a captcha that read "I am human". I see the criteria is getting stricter. They must've had too many dogs in a trenchcoat log into their service
 
Ok, nice. Sorry for think that existed the Austrian language.
 
@Aran-Fey dogs were too good at identifying what was a lamppost
 
@Aran-Fey Poor Ford Prefect
 
 
6 hours later…
10:22 PM
So I have this webserver, and I was wondering, A. how would I send a small packet of info to the server, and B. server side, how could I process what was sent?
 
Well, webservers are pretty good at accepting packets of data that look like this:

POST /some/endpoint HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 29

who=sir+robin&action=ran+away
 
10:40 PM
It's possible to run IPython code in .py file?
 
11:12 PM
Solved, I just needed to use get_ipython() function (ipython.readthedocs.io/en/stable/api/generated/…)
 

« first day (4237 days earlier)      last day (694 days later) »