« first day (3650 days earlier)      last day (1523 days later) » 
02:00 - 19:0019:00 - 00:00

 
1 hour later…
03:57
ok -_-
04:34
cbg
04:50
Hi, I am looking to reorder legend labels displayed when plot_likert() used in sjPlot package. As default, legend labels are alphabetically ordered. I want them to be ordered logically.Does anyone know how to do that ?
 
3 hours later…
07:22
Did you make sure to migrate? If it was previously an int field the database might be getting upset. You need to migrate after every change to your choicesfields.

If I may, I'd recommend not using choices and instead using a model to store your keyword -> imgur link (LinksModel), and a model for urls (UrlModel) that has a foreignkey to the LinksModel.

I also noticed your keys and values are backward. If you want the database to store the link, then you'll want to put the link first, e.g.
Choices = (
("imgur.com/goodpicture", "1"),
)

Apologies for the double message, reflexively hit enter for the new line.
 
1 hour later…
08:36
lets say i have a list of fruits so i will ask user to input any lets say he inputs only "app", i want to auto complete the word to "apple" after he presses tab how can i do tht in python?
do you want to auto-complete during or after typing?
like after pressing the tab key
same as in command prompt
the readline module might be what you are looking for.
it's what powers the REPL as well
i get an error while installing readline
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
i tried "pip install readline"
it is a standard library module
08:46
no it doesnt work on windows
@Praveen I dont think completion works in cmd as well on Windows
ohh ok then does it work when i make a gui?
if yes then how can i do it in gui?
tkinter
@Praveen Try pipwin install readline but make sure you have pipwin installed
this helped me thank you
i will try pipwin too
09:02
pipwin is slow and it takes alot of time to build cache
words1 = {word: i for i, word in enumerate(words)}
words = ["abcd","dcba","lls","s","sssll"]
this returns {'abcd': 0, 'dcba': 1, 'lls': 2, 's': 3, 'sssll': 4}
@Praveen Well in my case pip takes more time then pipwin
which is strange because i cant see how word is matched to the word in enumerate?
ive asked this as a question now because i think its interesting for many
0
Q: Matching keys to returns from enumerate()

Permianwords = ["abcd","dcba","lls","s","sssll"] words1 = {word: i for i, word in enumerate(words)} this returns {'abcd': 0, 'dcba': 1, 'lls': 2, 's': 3, 'sssll': 4} I find this strange because I was expecting all the i's for each word. How is word from the key matched to word from the enumerate() fun...

@Permian I think you should be familiar with the channel rules by now, no?
i cant delete that link to my question now sorry
09:22
FWIW, this seems much more suitable for chat than SO. There seems to be some serious misunderstanding of, well, many fundamental things at play here.
@MisterMiyagi im not some stupid idiot
ive used enumerate() many times before
i realise im missing something though
09:34
@Permian It was not my intention to make a statement of intelligence.
Since such misunderstandings mean that asker and answerers are working with different assumptions, the back-and-forth of chat can be better suited to identify which assumption is the source of the difference.
Max
Max
Hello, I'm new to Python, I'm stuck since severals days for an invalid json after I tried to encode a "request" in utf-8. Could someone help me please ? I have a screen capture of my script. Many thanks
@MisterMiyagi ive misunderstood that this is a dictionary comprehension
i rarely see these
Max
Max
If you have an hint or tips for me. It would be awesome :)
Don't create JSON using string operations. Create your data as a dict and pass it to requests as the data argument.
So you would do data = {'Text': paragraphe}
(In chat, we generally prefer short code snippets to be posted as fixed-font text, not as images.) ("short" == "less than 10 preferred, definitely less than 20")
Ah, the room rules state: If your code is longer than about 12 lines, use an external paste tool such as dpaste.com.
Max
Max
09:49
Sorry for the image. Should i send it again as text ?

That looks way less messy ahah. I think i've done that because i followed step by step the tutorial from microsoft azure translator, and I'm a newbie so I didn't now how to add my var correctly ahah.

I'm going to try with new piece of code.
@Permian I just popped in, but this message is way off. Please assume good faith. We see many confused users here, and it's not unreasonable to think that there's some fundamental misunderstanding on the asker's side. Furthermore, if a regular here thinks you're confused it's probably more your fault than theirs. Communicate transparently to clear up misunderstandings, rather than throwing a fit.
im not throwing a fit
i understand thats its a dictionary comprehension now and am grateful
@Max Just post the call to requests.post (follow the formatting guide)
09:51
@Max You might want to have a look at the code formatting guide. It includes a sandbox to practice a few rounds. Formatting in chat can be non-intuitive at first, sadly.
Max
Max
Ok now it's a dict, I can see it when i try to output the "data" var.
reponse = requests.post('https://api.cognitive.microsofttranslator.com//detect?api-version=3.0', headers=headers, params=params, data=data_enc)
oh
You have 2 minutes to edit a post. Just indent that line 4 spaces.
@Max please read the code formatting guide now before continuing, and practice in the sandbox if necessary
Max
Max
@AndrasDeak I did it correctly or no ?
i'm not good at english sorry
@Max you did, in three tries, and multiline messages are harder to format
@Max that's fine, you're perfectly clear to understand, don't worry about it
09:55
Yes, if you create that dict as I showed above, then just pass the dict as reponse = requests.post('https://api.cognitive.microsofttranslator.com//detect?api-version=3.0', headers=headers, params=params, data=data)
Max
Max
i don't know sand box
Now you know why I asked you to read the guide and practice in the sandbox
@Max if you had read the guide you'd know
Max
Max
I mean i didn't know the word, but i think i get it now
it a place where nobody care
Ah, I see, sorry :)
Yes, it's a place where people can play around and not bother anyone
in programming it's also an isolated environment where a user can't do any harm while they try some features
Max
Max
10:02
Ok, i tried, it was because of the ' that my code wasn't working.

I don't remember exactly what I was saying, but I tried as you told me Paul, and it output :

I hope the formating will work ahah



I believe it's cause the request is sent as latin-1 and no utf-8.
damn..
it worked in sandbox i don't get it
{"error":{"code":400000,"message":"One of the request inputs is not valid."}}
here we are
 
1 hour later…
11:16
Hi, I have to create exam checking application. students data is in text file. Firstly I think to convert this data to json and store it in database,, but how can I get statistical data from this json
@sevdimali why do you think you need json?
Max
Max
11:29
@PaulMcG This is the error code i have now :
'latin-1' codec can't encode characters in position 10-23: Body ('シャーリー・フィールドは、サ') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.
That's why I was talking about latin-1
11:40
Can you try this with an ascii translation, like "Hola Mundo"? Let's at least get all your connectivity bits working.
how do I do this:
@AnttiHaapala you don't
I've got 2 lists... and I want the intersection in order that's as possibly close to the common ordering as possible
whatever that would mean
lol
What do you mean by "common ordering"?
idk what that means...
because order matters in the list then I do not want totally unordered set intersection
11:46
What if the two lists are each other's reverse?
idk. In this case they aren't
your best bet is probably just keeping the order from the first list
if the items are ordered wrong across the two lists you'll just have to choose either anyway
@AndrasDeak I think it will be easy for handling,, the data comes like this, NAME01 SURNAME01 O00034 11AIAAEACC CAAB BEBD BBADDDBAD CD CC ACBDDBCDEBEBCADEBACABBEBECDCBCA18
classic
Hey guys quick one when having a feature that allows a user to send an email from inside the app to another user is it a good idea to keep a history of this considering that they should have a history in their email servers? basically its using their emails that are linked to their accounts to send the email form inside the web app
and just wondering if I should think on keeping a history of this inside the webapp or is it just wasting space in the app
12:00
@Kwsswart you should probably also ask yourself if you want to be responsible for all that data, and if you want to follow up GDPR requests asking for their deletion etc.
Makes sense so it is probably a better idea to allow them the functionality of sending the emails but not to store it myself
I am trying to set limits to my matplotlib chart:
 plt.ylim(min_y*1.10, max_y*1.10)
I tried printing the types of each min_y and max_y
 print(type(min_y), type(max_y))
<class 'sympy.core.numbers.Float'> <class 'int'>
I get this error when trying to set plt.ylim(): TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
@Pherdindy well do you see something off with the types you printed?
Yeah definitely different but i'm not sure how matplotlib treats em
The max is a python int, but the min is a sympy float. It's clear that matplotlib doesn't know how to handle sympy floats. Call float() on your minimum when you pass it to pyplot.
(and watch out for the case when min_y >0, in that case you'd lose data points)
12:10
Yeah python floats work but sympy floats doesn't
@Pherdindy yes
Ah right lol simply just add a float(min_y)
which is what I said, yes
@Max I'm not sure where latin-1 is coming into play here. You can always take matters into your own hands, by using json.dumps to convert the data dict (as I posted previously) to JSON, and then to bytes using encode, and pass that as the data argument - i.e., data_bytes = json.dumps({'text': "japanese text"}).encode('utf-8') and then pass data_bytes as the data argument to requests.post.
You might also want to get acquainted with this site: requests.readthedocs.io/en/latest/api which will guide you through more details on using the requests package than you will find in the Azure tutorial pages.
cbg. Has anyone used thonny before?
I am looking for a good alternate of IDLE (for competitive only). I already have PyCharm and sublime & notepad++. If any of you remembers we also had a conversation over atom, sciTE (it was suggested by Paul i guess)

I have decided to give atom & thonny a try. I know atom is definitely good but any reviews on thonny if someone has used it before?
12:28
@sevdimali maybe you can use csv file
it is better that way
12:46
@PSSolanki Yes, I'm usually the one to pitch using SciTE. I also did a quick install/tryout of thonny. It seemed like a decent learning editor for single-script-at-a-time coding (typical for homeworks and little projects), and the "variables" pane is a nice dashboard of the local vars, easy to visualize what is going on inside your script.
cbg, docs.python.org/3/library/random.html#random.randrange states "Keyword arguments should not be used ..." can anyone tell me what that means? randrange(start=1,stop=3) works fine
Random guess: There is no guarantee that randrange is a Python function which even understands keyword arguments.
you mean the C implementation if any, does not understand kwargs? idk if C has the concept of kwargs
Evidence A: range(start=1,stop=3) is a TypeError.
@python_learner The Python C-API does understand kwargs, but at a performance costs. Keyword support is thus optional. Various builtin functions do not accept keyword arguments.
13:02
help(range) gives me range(start, stop[, step]) -> range object help(randrange) gives randrange(start, stop=None, step=1, _int=<class 'int'>)so in this case start, stop and step are kwargs, right?
or kwargs only applied to the **kwargs part?
The term "keyword arguments" is usually used loosely to mean both. Technically **kwargs are "variadic keyword arguments".
I have used these but didnt know the right terms
that aside, is it possible to have a function that can not take keyword arguments? def foo(arg_1,arg_2):pass, can I change this so foo(arg_1=1,arg_2=2) fails?
13:20
Yes, recent Python versions added / to separate positional_only from position_or_named arguments.
def foo(arg_1,arg_2, /):pass
Just one of those things that I forget exists until I hear about it again
See you in an another six months, positional only arguments
will look into the docs for this then, thanks
For the record it looks like CPython's randrange is an ordinary Python function.
I'm sure the language spec doesn't want to make any assumptions about how any standard module functions are defined, but it seems odd that the warning is only on this one
Maybe it's a historical thing. Time to check the 3.0.0 branch...
is it difficult for GitHub to have hyperlinks in its py files? eg: clicking on self._randbelow(width) should take me to its definition
13:36
Harder for Python than your average explicitly typed language, since in general you can't prove that _randbelow is even a function unless you run the code up to that line
Python method resolution can be "non-trivial" even before one adds inheritance and such. Doubt that feature would be worth it for GitHub.
... But I don't think GitHub has "jump to definition" even for languages where it would be relatively easy to implement
I certainly have wished for it in the past, myself
In python split ,is it possible to use multiple delimiters ?
Consider using re.split if you require fancy delimiter logic
if its optional you can use regex split
13:38
@Janith what did the docs say?
str.split ?
laurel, high rep users are fast at trying :p
"http ntp,ftp telnet ssh,rsync,tftp".split(" " or ",") is it correct ?
IIRC the only time that str.split recognizes multiple delimiters is its zero argument form, which splits on all whitespace
@Janith Nope, " " or "," evaluates down to just " "
13:40
morning cabbages, all
Sometimes I think Python gets too much credit for having friendly syntax, because it leads users into thinking that their code will work as long as it looks like English
"split on space or comma" is certainly something that 99% of English speakers would understand, but alas, Python is dumb
@Janith really?
Oh and incidentally I endorse Andras' frustration that you asked "what does this function do? Does this code work?" apparently without looking up the documentation or running your code yourself
No point in asking "is this correct?" when you can paste it into your own console and get an answer a hundred times faster
some in python are easy to understand, I personally find str.strip behavior confusing until I realize the string is treated as individual letters
>>> '123'.strip('301')
'2'
@python_learner 3.9 will help you
13:45
hooray for 3.9's remove_prefix or whatever the heck it's called
no underscore
Second best addition behind functools.cache
PEP616, I see that in release notes now
@AndrasDeak new functions are still being made that don't adhere to PEP 8, in current year? ಠ_ಠ
@PaulMcG Thank you for the try out :) . I'll try all 3 of 'em (sciTE, atom & thonny) and see which one(s) do i keep. I don't really need a feature rich editor as I already have PyCharm, sublime, notepad++. Just something for competitives. Apologies to Kevin & Andras for hijacking their ongoing convo :D
13:46
@Kevin there's rationale about following naming conventions of related methods
I don't remember the rationale, just that there is one
Yeah, but I'm going to keep being mad anyway
@PSSolanki directed replies make interleaved discussions feasible, don't worry about it
It says it in PEP 8's preface somewhere. Consistency is the... goblin... Of deranged lunatics. Something like that.
@Kevin Python everybody's favourite, friendly, neighbourhood crack dealer. Knows how to get you addicted, just too good to stop.
3
This is true.
13:48
@Kevin Isn't that literally just functools.lru_cache(maxsize=None)?
Yeah, isn't it wonderful (◕‿◕)
I'll allocate 10 minutes per project to decide which one to use
Rewinding back three topics, bugs.python.org/issue9379 appears to be responsible for the "Keyword arguments should not be used because the function may use them in unexpected ways." in randrange's documentation
TLDR: [randrange(10, step=5) for i in range(10)] does not have a step of 5.
"the range() signature is complicated to express in pure Python," says rhettinger, and by extension, the same is true for randrange
Maybe they'll clean this up the next time they're allowed to break backwards compatibility
14:07
thanks for clearing that up, how did you end up at that page? thats some serious google skills to me
I went to Python's github repository, searched for "randrange", filtered the results to reStructured Text only, found the .rst file corresponding to the documentation page, clicked "blame", found the last commit that made changes to the "keyword arguments should not be used" line...
it's the bug tracker website for cpython implementation... and the github PRs and issues on cpython often link to this website.
Github blame FTW :D
Hi guys,

I don't suppose anyone can offer me a quicker way of deleting duplicates than this function can you? This would take almost 3 hours to do each 300K records :/

def DelDupes(Data):
    NData = []

    Data = list(reversed(Data)) #This is so that the latest values get kept

    Len = len(Data)

    i = 0
    for line in Data:
        Found = False
        for point in Data[i + 1:]:
            if point[1] == line[1] and point[2] == line[2]:
                Found = True
                break
I clicked on the issues in the commit's title, noticed that none of the linked issues had anything to do with randrange, guessed that the numbers had been recycled in the last ten years*, went to bugs.python.org to see if they had the originals, entered "9379" into the search bar, and found the issue
that is still a lot, I just have to find an use case for this the next time
14:11
@Kevin there's some scary stuff in there D:
(* or they weren't recycled and the bugs.python.org issue numbers and github issue numbers are simply independent, and the commit simply linked to the wrong one)
That would cause some real chaos :D
@JamesMcIntyre a) always prefer the in operator to check if an item is in a collection versus explicit iteration b) always prefer sets when the in operator is appropriate.
obligatory question: are all items hashable? is order important?
@JamesMcIntyre Why not use a set? And as MisterMiyagi asked is order important?
Yeah, why not use a set? And how important is order?
14:16
he mentioned latest values get kept, so order is important?
How would I do that in this case? I understand if it was a straight duplicate (all columns matching) I could use the set function but here I'm regarding a duplicate as 2nd and 3rd columns matching.

The order doesn't matter, as long as the first column (datetime) is kept.

I'm not sure what hashable means :/
an object is hashable if hash(the_object) doesn't crash
Only hashable objects can be added to a set, or used as the key in a dict
so the list could be made a set but as the first column is a datetime, it would remove nothing. I need to remove anthing which is a duplicate in terms of 2nd and 3rd columns
Consult en.wikipedia.org/wiki/Hash_function for a technical explanation
@JamesMcIntyre you could use a dict where the key is val[1:3]
bonus: dicts are insertion-order preserving now
14:19
I'm thinking something like:
def remove_dupes(seq, keyfunc):
    seen = set()
    result = []
    for item in seq:
        key = keyfunc(item)
        if key not in seen:
            result.append(item)
            seen.add(key)
    return result
So just do seens[val[1:3]] = row for each row and the resulting dict will have your data in seens.values(). If val is not hashable then tuple(val[1:3]) will probably be.
Then you can do data = remove_dupes(data, lambda x: (x[1], x[2]))
@Kevin itemgetter(1, 2)!
Never!
You can't make me import things ;_;
I like this use case
14:24
I've not learned how to use dictionaries yet :( I'm currently trying to work out what your function is doing Kevin... the 'key' is somthing to help identify the columns relvent for duplicate?

hmm... itemgetter is a function which will get the 2nd and 3rd rows in this case?
operator.itemgetter(1, 2) is the same as Kevin's lambda
Yes, the 'key' is something to help identify the columns relevant for duplicate.
There are no dicts in my function, so you don't have to learn how they work yet :-)
what is the best way to do that kind of tasks (without wasting processing power)?is this?
>>> i=[]
>>> y=""
>>> for x in "http ntp,ftp telnet ssh,rsync,tftp":
... if x in (","," "):
... i.append(y)
... y=""
... else:
... y+=x
...
>>> if y:
... i.append(y)
ahhh ok, so with my original list (Data)... I would do Data = remove_dupes(Data, keyfunc) and then Data = remove_dupes(Data, lambda x: (x[1], x[2]))? But then would I not need to define keyfunc or is that a standard library thing?
@JamesMcIntyre keyfunc is being defined using a lambda function. anonymous function.
as Andras said itemgetter(1, 2) will work the same as keyfunc.
14:29
51 mins ago, by Kevin
Consider using re.split if you require fancy delimiter logic
How many iteration rounds it will use or other method?
@JamesMcIntyre You shouldn't call remove_dupes twice, no
@Janith O(N) in your case, I expect
In other words, about as good as str.split
@Kevin ahh yes... good point
how it works?
@JamesMcIntyre, perhaps I have overcomplicated the solution. If this is a one-off problem, there's no need to introduce lambdas and functions-as-arguments. You can just do the indexing directly inside the function.
def remove_dupes(seq):
    seen = set()
    result = []
    for item in seq:
        key = (item[1], item[2])
        if key not in seen:
            result.append(item)
            seen.add(key)
    return result
@Janith The regular expression engine is a complicated piece of tech. Most people (me included) don't know how it works, and hopefully don't need to.
14:33
@Kevin You were right that I was scratching my head at the lamdas and functions-as-arguements. Thank you very much for this. This is really helpful
Or, if you're asking "how do I properly call the function?", try re.split("[ ,]", "foo bar,baz qux")
I know it already
Cool 👍
but,if it is more longer,processing power may be problem ... I had some cases with regex processing power ... it takes more when expression is longer.... I attempted to crawl web using regex after move to beautifulsoup .... regex takes more resources than beautifulsoup.
14:40
If one thing is certain in life, it is that you should not use regex to parse HTML
yeah
In this case, the expression is very small, so it shouldn't be a problem
Even if the string you're splitting is huge
@Janith since the builtins are usually much faster than explicit iteration, it is often best to first split on ",", then split each result on " ", then flatten the result.
try to split on the most frequent separator first, if that is known.
Your solution Kevin has sorted me out completely! I'm trying to genuinely understand it so that I can do it for myself in future and so I've tried replacing the 'key' from a set to a list and it runs much slower. Are sets just fundamentally faster to work with than lists?
It depends on what you're trying to do
14:50
or was it splitting on the least frequent separator first, to keep user-land iterations low? mumbles
wiki.python.org/moin/TimeComplexity gives a breakdown of the complexities of various operations for the built-in types. The one most pertinent to your situation is x in s. For lists, it's O(N). For sets, it's O(1). O(1) is usually much better than O(N).
In other words, if you give the function a list with 2342 items, then the list-based approach will be 2342 times slower than the set-based approach
@Kevin So that means a set would always be faster or the same speed because a list of len 1 would be the same?
Let's say "almost always". In practice, functions with lower complexity are very often faster than functions with higher complexity. But things get fuzzy at the edges.
@Kevin Magic (y)
Big O complexity doesn't measure clock time, and it doesn't account for constant slowdown rates. An O(1) function might always take 8 hours to complete, and an O(N) function might take N*5 minutes to complete. Then the O(N) function is faster as long as N is less than 96.
15:05
It seems to me the last time I did some comparisons for "in" testing between lists and sets, lists were faster up to 3 or 4 items, and then sets were faster from then on. YMMV. Plus it sounds like James has ≫ 4 items.
Sets require a bit more initialization than lists, so that conclusion makes sense to me
Sets need a handful of hash table bits and bobs, but lists are just an array plus a header
... Or maybe I'm wrong, because make_new_set is fewer lines than PyList_New, and makes fewer function calls. So initialization isn't the problem necessarily.
Maybe set.add gets faster after you add a couple items? Because by then it's had a chance to rearrange the hash table a bit to reduce collisions
hey guys if this is being sent by email to a client why doesn't the url_for generate the link to send them to reply via the app dpaste.com/4KNT93JU3 instead it generates "" invalid URL (http: /// email / Kieron).""
the email sends perfectly just the link doesn't generate correctly
15:20
Wild guess: url_for generates a relative address, but you can only use absolute addresses in an email. Try setting url_for's _external parameter to True.
I have a feeling that this isn't a good permanent solution, since one should usually not touch variables that start with a single underscore. But it's worth trying just to narrow down the problem.
that worked but what would a permanent solution be
Good question. I don't know what kind of best practices are advised when rendering an HTML email with Flask. Maybe it's not a common enough problem that there are best practices?
Naturally googling "flask html email" gives one million irrelevant results
Yeah its part of the problem I have been finding a lot of weird references while working through this although this seems to work could it cause serious problems in the future?
I think the worst that could happen is the link will be wrong
Really I'm hoping that one of the local Flask pros will descend from the clouds and say "actually it's pretty safe to use an _underscore parameter in a Flask method call, it's more to indicate that the feature is 'advanced' than it is 'private'"
I don't know one way or the other, having used Flask for a total of two hours over the course of my life
Ah, I just got bait-and-switched on a problem I'm trying to google. I found an answer saying "here is exactly the code you require :-)" and then I scroll down and see "update: this no longer works for versions 1.1 and above of WidgetReticulatorLib"
Please give 1.1 solution tia ༼ つ ◕_◕ ༽つ
15:54
Late to the party, but... never dismiss sets because you have only "few" items.
In recent Python versions, I've found set to be worth it versus list for as few as 2 items.
Optimising for the case of your container having less than 2 items is not exactly an indication for good software design.
I just ignore efficiency concerns and go with whatever communicates my intent most clearly :-)
Optimization is a problem for Future Kevin
Same here. Good old class Solution... "\/(o_O)\/"
class ThingDoer: #does the thing
16:13
If the models.py of a flask project is getting very large in and starting to get a bit large is it a good idea to separate it off before moving to a separate piece or is it better practice to keep the entire project models together?
I had a "Have you ever seen this" question.
Matplotlib 3.3.1 mousing over the axis of the plot makes it just disappear.
3.3.2 excuse me
@Kwsswart If both "one big file" and "lots of smaller files" work, I think it's mostly a matter of taste.
I like lots of smaller files but YMMV
Just trying to think what is the standard convention in order to keep it as neat as possible and as presentable as possible (Not good with messes)
In my adventures through open source projects, I've seen both styles employed without much problem
@Pandasncode Hmm, I don't think I've ever seen that.
Fantastic :D
16:25
Am I allowed to request a re-review of answers? I updated it to be more specific to the user's question and flagged the question as a dupe as requested by the mod.
https://stackoverflow.com/a/64268475/1679019

I am honestly a bit upset it got removed for that and got me soft-banned because I spent three hours figuring that out and didn't have flag permissions until someone upvoted my other answer, so I wasn't able to flag it like he suggested. I was just trying to be helpful as I found both questions via google.
shudder Just seen for m≥p≥1 in pseudo-code. Wish more people would just dump their Python code...
@Alex I understand your frustration. The new edit looks good to me. But it looks like I can't vote to undelete, since the moderator's delete has priority over my undelete... I sent a flag asking them to re-review the situation.
@Alex You can flag your own answer for mod-attention. I recommend to take some time until you are less upset, though. The initial mod action seemed justified, so try to focus not on your initial frustration but on the content being proper now.
Try not to take it too personally... SO is a big hedge in need of trimming and sometimes the mods cut off a finger or two during their frenzied work ;-)
@MisterMiyagi Yes, but I also wish that m≥p≥1 was valid Python syntax.
At a glance, you might want to change typing.Mapping to typing.MutableMapping by the way. The regular dict is mutable, which affects both capabilities and restrictions of the type.
16:38
@Kwsswart I think Kevin's assessment is correct
Appreciate it. Sorry if I am being whiny, it just seemed a bit unfair. I agree that my original answer wasn't up to snuff and definitely deserved a slap on the wrist, but I was just upset that I basically got soft-banned for what was technically correct.

Thank you my friends. I know I shouldn't take it too personally, but human emotion and all that, lol. I should be more understanding since I mod default subreddits and remove thousands of comments a day
It is probably fine to alter the underscored parameter because url_for finds uses all over Flask and very rarely would you need to resolve it to an absolute address. This, however, would be one such case
Getting mad when people don't find my help helpful, is extremely relatable
Cherish me damnit
Ok great thanks mate so it shoud work as a permanent solution?
@Kevin Request permission to commence the paddlin', Sir!
16:40
Paddle at will cadet
Thanks, I'll update that.

Haha, Kevin I agree. I am also way to attached to fake internet numbers.
@Kwsswart Yes, my feeling is that it is the correct solution to your problem. It would not, however, be appropriate in a template within a blueprint referring to the static folder, though, for example because you need to set the base of the path in that case; there the default makes sense and changing it would break the app
Ok I get what you mean, however when needing it to reference a link within an external source i.e a separate email server then it would be good?
You wouldn't use url_for there because it can't be resolved to a route that isn't part of your application
I feel like I could construct a compelling argument for "just hardcode it", but I'm not invested enough to put in the energy
16:48
For this question is it okay to say `I need more info to solve the error you're having, but I also think there's a better way to do what you're wanting`?

https://stackoverflow.com/questions/64326189/django-models-automatically-pick-and-return-a-value-by-the-choice-option
"I need more info" usually fits better in a comment than an answer, even if you go on to give lots of constructive advice. The downvote brigade tends to jump to conclusions based on the first sentence of your post
Alright, I'll just stay out then. Not enough rep to comment.
"here's a way to do the thing you're trying to do, completely different from your current code" is usually safe unless the asker is really explicit that they want their approach specifically to work
In this particular question the OP seems more interested in anything that will work, regardless of whether it resembles his first draft
"here's a different way to do X" is not to be confused with "doing X is silly, you should want to do Y instead, and here's how", which often irritates the asker
It's a fine line that divides those, sometimes
17:05
Hmm, I wanna help, but I can't afford the downvotes if I cross that line. I already got soft-banned yesterday, lol. I was going to suggest moving the links into a model because choicesfield is more for database_value -> human_readable value than it is a way to link things together.
I'm confused by mypy...
Given B > A, I'd expect a: List[A] = [B()] to be invalid because List is invariant.
mypy does not think so and happily accepts it.
Yet when I do a: List[A] = [B()] + [], MyPy suddenly realises that Incompatible types in assignment (expression has type "List[B]", variable has type "List[A]")
if __name__ == "__main__":
    # notifyMe("Tanish", "Hello")
    mydata = htmlData("https://www.mohfw.gov.in")
    soup = BeautifulSoup(mydata,'html.parser')
    print(soup.prettify().encode('utf-8'))
    # print(mydata)
    for table in soup.find_all('table'):
        print(table)
**Getting an error as:**
Traceback(most recent call last):
File "c:\Users\User\3D Objects\Covid-Notif system\main.py", line 26, in <module >
print(table)
File "C:\Users\User\AppData\Local\Programs\Python\Python38-32\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input, self.errors, encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 201-202: character maps to < undefined
I get that error sometimes when my console doesn't know how to display a unicode character.
@Kevin What can I do?
Usually I open the input file in notepad and delete the character ;-)
If you're using a Windows cmd prompt, sometimes it helps to run chcp 65001 before running your python program
17:20
@Kevin OK , will try that!
@Kevin Thanks its helpful! :)
If all else fails, you can do print(table.encode()) which will ensure that printing succeeds, at the expense of perhaps mangling any remotely fancy character
17:33
I should have run the code in terminal of VS code instead of running it in the output console. Now I am facing no issue in the program ;)
👍
Yeah in my experience IDE output windows are usually better at rendering unicode than cmd
@Kevin ;)
17:56
Does anyone know why collections.defaultdict gives me a KeyError? I thought that was the entire purpose of the dang thing to give me a default value
In [428]: d = collections.defaultdict()

In [429]: d[1]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-429-abe283337115> in <module>
----> 1 d[1]

KeyError: 1

In [430]: 1 in d
Out[430]: False
should not d[1] give me None in this case?
it behaves like a regular dict if you don't pass it a default_factory
What default value did you have in mind?
a = defaultdict(lambda: None) would give None
a = defaultdict(int) gives default values of 0
17:59
really?! 0_0
has defaultdict changed over the last few years? or is this just the first time I've faced this issue?
More likely you used to know this, but have paged it out.
No, it just takes some callable. It happens that int() just returns 0. Maybe it takes more than just callables as the default_factory but that's how I've come to know and love defaultdicts
holy jibberjabber! Many melons Paul, Josh, Aran :)
yup! that worked like a charm. What was I even thinking?
Yeah, a callable. From the docs: "If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned."
No, it only takes callables that take no args. So any class whose constructor accepts class() can be passed. str, int, float, list, dict, set are all legit.
18:03
I just always thought that if the default_factory were None, then it defaults to lambda: None
"If the default_factory attribute is None, this raises a KeyError exception with the key as argument.". It's in the docs :/
Sometimes it is nice to have a defaultdict that takes the new key as a single arg. But you have to write a custom defaultkeydict class for that. I think one of the popular collections add-on packages has that.
Not sure I follow what that would look like? Would it not be easier/cleaner just to take an initial if not key in my_dict: step instead of custom classes?
Hmm, if you had asked me ten minutes ago I would have guessed that zero-argument defaultdict would use None for your default.
@roganjosh he just means a default factory that accepts a single arg
18:12
Intuitively I would think that defaultdict would never raise a KeyError under any circumstances. So it surprises me that you can force it to do otherwise.
<brain suddenly lurches into deja vu mode>
I seem remember a discussion between Martijn and Wim about this a while back that allowing a default falsey value would allow .get() steps down the line giving a falsey result but it would be impossible to know whether or not that key had been checked somewhere else in the process and given the default None result
Am just surprised that collections.defaultdict() itself is not an error already. Why use a defaultdict without a default?
Well, not impossible, but rather, not at all immediately obvious as to whether the specific .get() gave a None result because it was originally actually assigned that value from some previous check or whether the key just doesn't exist. You could certainly check for it, but I think the logic Martijn talked about was that it was ripe for misconceptions in program flow. Or... he was talking about something else entirely
If I were BDFL I would forbid zero argument defaultdict entirely
If you need KeyErrors, use a regular dict. Next!
18:21
@wim Ah, I got half of it right :) Thanks for doing the search
We would have breaking changes every week if I were BDFL, so perhaps it's a good thing I'm not BDFL.
that's called an MDFL
You can have a stable interface when you pry it from my cold dead hands
@wim Though I seem to remember there being a post-mortem around this in the chat room with Martijn. I've upvoted both the question and the answer and I feel like the discussion around it occurred here that made me read your question
I apparently upvoted the question long ago, but as usual I have no memory of it
The accepted answer gives a decent overview of why defaultdict(None) ought to be allowed, but kind of skims over why defaultdict() should exist
wim
wim
18:31
Init signature: collections.defaultdict(self, /, *args, **kwargs) is happy to be wrong too
I think I'm getting wires crossed from the discussion that starts here:
Sep 18 '18 at 17:51, by wim
anyone else think this discrepancy is a little weird?
thanks for the inputs, folks. As always, in my time of need, it's Room6 to the rescue!
(and then some more interesting reading for later, which I just read)
18:45
Phew, I had to mock out a million dependencies, but I finally locally replicated the error that's been hounding me all month
> link: When Guido van Rossum initially proposed a DefaultDict that had a default value [...] that set at during construction and be read-only
What is this sentence sorcery?
I can't seem to find a way to understand what is being said there
I interpret it as "Guido van Rossum initially proposed a DefaultDict that had a default value that was set during construction and was thereafter read-only". It's certainly not syntactically valid as-is.
So x = defaultDict(23) would work, and x.default_value = 42 would fail. Later he decided to make the argument a callable, and make the attribute mutatable.
Ahh ok. Thanks.
02:00 - 19:0019:00 - 00:00

« first day (3650 days earlier)      last day (1523 days later) »