« first day (3481 days earlier)      last day (1484 days later) » 
00:00 - 20:0020:00 - 22:00

12:23 AM
hello
I need some help with parallelization
From my understanding, if I want to use multiprocessing, then in order to pass object, they have to be pickled
Right nwo I am getting lots of TypeError: can't pickle module objects
how do you structure your code for parallezation?
 
1:10 AM
I'm writing a wrapper around a HTTP rest API. I can't decide how to do the error handling. For example, if the API returns a 404, should I a) pass that exception to the user b) return an empty list/string and log the exception c) return a dictionary, with one field containing a success/error indicator and another field containing the actual content if any.
 
 
2 hours later…
3:19 AM
cbg
TIL a feature I had assumed would be difficult to implement is essentially a one-liner for 90%/good enough to go on with.
 
Hi, I'm new to this chat rooms
 
3:56 AM
@AndrasDeak wdym by too broad ?
 
4:46 AM
I find it a little annoying when I write a huge answer to a question, then a few minutes later the post gets deleted by the OP. Is it just me? Do you think this is a little rude too?
 
Yup, definitely sucks. If you think the question has merit, you can ask some high-rep users to undelete it
 
Yeah I know they can be revived. It's just weird that this happened several times this week. Next time I write a long answer, I'll put something like, "Please read the rest if you are not going to delete your post" :)
 
5:33 AM
@JoshuaVarghese not sure what you are replying to; this is the close reason which is now called "needs details or clarity". Perhaps see also stackoverflow.com/help/dont-ask
@iamvegan not sure that makes sense ... maybe don't answer very fresh posts by new users (speculating of course because I don't know if that was actually true for the posts you are talking about)
 
5:59 AM
@tripleee You have a point. Most of them were indeed new users. There was also an experienced user. I guess some people feel silly or something when they hear the answer to their question. I don't get that, this is a place to learn. There is nothing to be ashamed of. I ask silly questions too :)
 
agree, but there is not much you can do if it's a low-quality question and the OP decides to delete it after receiving an answer
there should be a penalty for that but I don't think there currently is
and anyway, low-rep users might just abandon their account and start over
 
@tripleee Yes there should be a penalty!
 
Maybe there should be a review process for deleting questions?
 
there are many legitimate reasons to delete your own question and something we suggest for problematic questions. I think there may be a bot in SObotics which alerts for certain types of deletions
 
6:18 AM
@jigglypuff You can look how other projects do it. aiohttp has a middleware that catches exceptions and tries to turn build meaningful stati and responses, or allows you to raise HTTPException instances yourself if you already know what kind of error took place.
 
@tripleee @RoadRunner Something like this would be nice: Say you write a comment or an answer to a question, then later you realized the owner deleted the post. Now you should have an option to give the owner something like a feedback. Maybe downvote them or send a message. Otherwise it leaves a sense of annoyance or waste of time
 
Hello everyone,

I am facing some issues with Django can someone from here help?
 
@FarkhodSadykov Please have a look at the room rules. If you have a question, just ask.
 
6:34 AM
@iamvegan you can nominate for undeleting when you have enough rep; if you don't, maybe bring it up here, or (if it's not Python-related) in SOCVR
@FarkhodSadykov we seem to get more Django questions than answers in this room (but part of the reason is surely that many of them are as vague as yours)
 
Hello everyone,

How are you guys doing? I am running my django application on top of Kubernetes and I implemented social auth and facing some issues with that.

```
failed: The redirect_uri MUST match the registered callback URL for this application.
```

Output on logs
```
AuthFailed at /oauth/complete/github/
Authentication failed: The redirect_uri MUST match the registered callback URL for this application.
Request Method: GET
Request URL: http://dev.academy.domain.com/oauth/complete/github/
 
Next have a look at the code formatting guide: tinyurl.com/urnzp7k
But assuming the protocol is the only issue here; I guess you are using some helper or some such to generate the redirect URI you use in your OAuth request? And maybe that helper then generates http:// URIs due to some configuration, or automatic sensing of protocol in use (if running behind a LB, proxy or some such)?
 
6:51 AM
Yes I am running behind ingress Nginx also I put ACCOUNT_DEFAULT_HTTP_PROTOCOL='https' didn't work
 
Disclaimer: I've last used Django some 10 years ago.
 
What framework you would use for your backend?
 
Pyramid, due to familiarity.
 
You mean Flask?
 
No, that's yet another framework. trypyramid.com is what I meant.
 
6:56 AM
I see, Django has already builded and pre-configured models and other features that's why I am trying to develop with Django
 
And every time you make any changes to the code, make sure they go live on the testing server before you start the testing.
 
I did check that issue before and same things
This is not option for me on top of kubernets

`127.0.0.1 example.com`
 
I'm not that familiar with kubernetes, but I don't understand why your development server would also be on top of it.
IMO, the issue still lies in the configuration or the configuration change did not propagate to the server.
 
7:20 AM
I just fixed an issue with the ingress controller. I am using ingress controller and forced to use https connection kubernetes.io/ingress.allow-http: "false"
Thank you, everyone :)
 
@FarkhodSadykov That's insecure. You may (rare, but possible) leak your user's credentials (github access keys)
 
My domain name is using https so I should not have any problem with that
I personly don't like that is using Http on Github app
 
No, but the redirect is to an insecure (http) route. That route is open to MITM leaks.
Making it http is not a solution, it's a workaround.
 
7:37 AM
Yes, you are right but what do you think what is the problem? Ny domain is using https and I configured on the Github application to https and it stops working.
 
25 mins ago, by shad0w_wa1k3r
IMO, the issue still lies in the configuration or the configuration change did not propagate to the server.
Configuration issue can be with Django or kubernetes routing or your server (apache / nginx / etc.)
 
@iamvegan One reason that askers delete their question as soon as they have an answer is that they are cheating on their homework or an exam, and are trying to hide the evidence. This is probably more of an issue at present, with so many people doing online study & exams.
@iamvegan If you suspect that's the case, definitely mention it here & we'll try to fix it. They can't delete their question if it has an upvoted or accepted answer.
 
@tripleee there is cc @iamvegan. Question ban kicks in much faster.
 
7:53 AM
yeah, but no immediate penalty
 
@AndrasDeak Good point. Also, I'm sure plenty of regulars will avoid answering questions from such OPs, if they recognize their name. OTOH, I expect many homework cheats use "burner" accounts anyway, so they don't care about rep, bans, or being recognized. :(
 
@iamvegan by the way this usually happens when you write people's code for them (think spoon-feeding).
 
hey why do I get IndentationError: expected an indented block looks fine to me
def adddata(data):
    print(data)
 
Yeah, those 2 lines are fine.
 
@Aran-Fey lol forgot something in lines before, :)
 
8:05 AM
I suppose the error will tell you the line number as well.
 
I forgot to insert a pass in one function and the IDLE told me that there is an error at the last function for some reason
 
8:18 AM
@shad0w_wa1k3r often it doesn't; Python reports an error for code which is fine when you have an unclosed block or opening parenthesis somewhere below but it can't guess where it was supposed to be closed
 
@iamvegan Yes, but with new unknown users it's always a danger, that's why many people here don't pay attention to low-rep askers, or at least don't spend huge effort on writing an answer. Also, you get to know which questions look like homework, assignments, plagiarized assignments, interview coding tests, exams, currently-open hackathons, challenges from Kaggle, leetcode etc.
@tripleee True, but there are also many bogus reasons for OPs to delete theirn own question after getting an answer. I see more of the bogus than legit.
 
What tripleee said. The Python parser methodically works its way forward through the source, it doesn't look ahead or jump back. So the line number it reports tells you how far it got before it can't continue translating the source, it doesn't necessarily tell you the line number that's the real cause of the indentation / syntax error.
One common symptom of homework problems is that the language style of the problem statement doesn't match the style of the rest of the question or the OP's comments. This is especially noticeable when the OP isn't a native speaker. OTOH, with homework dumps, there may not be any other text in the question, or comments with feedback from the OP.
 
Those are easy to close
 
8:38 AM
Sure. "Needs focus" or maybe "Needs debugging details" usually apply. It'd be even better if we could train the new answerers to not spoon-feed, though. ;)
 
@FarkhodSadykov not all frameworks are Flask/Django.
 
I hear real $gender use Twisted
 
9:06 AM
Thanks @PM2Ring @AndrasDeak @smci . I agree with spoon-feeding. Out of curiosity, would you consider my respond here as spoon-feeding? The post was recently deleted.
 
as a rule of thumb, I always ignore question of the form "I've been working on <unclear problem> for a few days and I think I am close to figuring it out". 9 out of 10 cases, the OP has no idea what they are trying to do. Giving them an answer only highlights all the edge-cases they were not aware of, making their initial Y not solvable by this X.
 
user12867493
How can I extract the ISBN number from this URL? ...?genre=book&isbn=978-0-387-84858-7 With the hyphens in tact? So 978-0-387-84858-7?
 
@iamvegan No, you weren't spoon-feeding. And at least the OP posted some relevant code. It sounds like the problem is from a coding challenge site, but maybe it's an online homework checker. That style of question is a common homework task, as well as a coding challenge task.
@MisterMiyagi The OP did post code, though. OTOH, they may have lifted it from an answer to a related question, and they're trying to convert it, using "cargo-cult" logic.
I'm inclined to undelete it, if anyone here agrees with me.
 
I disagree with it being deleted, if that counts for something ;)
 
@MisterMiyagi That counts. :)
 
9:19 AM
def auth_partners_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        print(request.user)
I am getting AnonymousUser when trying to use above decorator for my class view. But everything works If i remove the decorator, I am sure I am including Token while sending the request. And earlier it was working just fine. I am using using Django
 
@PM2Ring Such code snippets actually make me more suspicious. These problems usually are simple, and the OP should be able to describe their approach in words very close to how the code should look (even if it is not correct). If they present some messy code and cannot describe their approach, it usually means to me they don't know what they are doing.
 
I have removed parts of decorator, even with Token it shows AnonymousUser but if I remove decorator it works fine.
 
@neferpitou neither the decorator nor the wrapper return anything. is that intentional?
 
@MisterMiyagi I have removed many chunks in order to make it smaller. As said it was working before only addition I did was add more decorator to same class view. Now I get AnonymousUser for every request with decorator.
 
@Daniil look at the stuff available in urllib.parse...
 
9:25 AM
@MisterMiyagi For sure, and the total lack of response by the OP when asked to explain their logic is pretty damning evidence.
 
I will post the whole code just in case
 
cbg all
 
def auth_partners_user(view_func):
    def wrapper_func(request, *args, **kwargs):
        print(request.user)
        try:
            if request.user.roles == 5:
                return view_func(request, *args, **kwargs)
            else:
                response = {
                    'status': False,
                    'detail': 'You are not allowed'
                }
                return JsonResponse(response, safe=False)
        except AttributeError:
            response = {
                'status': False,
trying something like this
 
@Daniil answered "by accident" in another room
 
9:38 AM
@neferpitou it looks like there is a typo in the last response. ['AnonymousUser' has a lone opening bracket.
 
@JonClements I don't think urllib.parse has anything for ISBN numbers; that it's embedded in a URL seems completely tangential to the problem anyway
(though might introduce additional issues because of URL encoding etc)
 
@MisterMiyagi sorry for that It happened while trying to copy it here,
 
so to be completely general you'd have to cope with the dash being encoded as %2D etc
 
@tripleee okay... just going by the fact it looks to be part of a query string and for that, there's a very handy function that'll allow you to isolate that
 
@tripleee it's just an URL key-value pair, urllib.parse can handle these. doesn't matter that it's ISBN.
 
9:41 AM
@tripleee eg: parse_qs(urlparse('http://example.com?genre=book&isbn=978-0-387-84858-7').query)['isbn']
 
user12867493
@tripleee can you help, it isn't working
 
the above looks like a better solution than an ad hoc regex anyway
 
@neferpitou are you sure that AttributeError is triggered by request.user.roles? Not by something else, e.g. view_func?
 
user12867493
@JonClements what do i need to import for that?
 
user12867493
I did:
 
user12867493
9:45 AM
> from urllib.parse import urlparse
 
user12867493
And it's saying that:
 
user12867493
> NameError: name 'parse_qs' is not defined
 
then also import that from the same place then?
 
you obviously need to import parse_qs too
from urllib.parse import urlparse, parse_qs
 
user12867493
Is there any better way to do it as it gives me:
 
user12867493
9:47 AM
> ['978-0-387-84858-7']
 
user12867493
I need:
 
user12867493
> '978-0-387-84858-7'
 
it gives you a list because there could be several matches
 
user12867493
Or just remove the '[' ']' manually?
 
if you only need the first, add [0]
or better loop over all the matches
(maybe convert them to a set to avoid getting duplicates)
 
user12867493
9:48 AM
Ok, thanks
 
@Daniil That's almost never the right way to handle situations like that.
 
@MisterMiyagi Thanks for the advice I noticed in some views I get AnonymousUser' object has no attribute 'roles and in others Authentication credentials were not provided.
 
user12867493
It worked! Thanks @JonClements @tripleee
 
Sure, it's slightly more complex getting the string you want out of a list (or tuple). But consider: it'd be even more complicated if it returned a string if there was one match & a list of strings for the other cases.
 
A lot of people didn't get that memo... :/
 
10:10 AM
@PM2Ring was an interesting caller into LBC today: lbc.co.uk/radio/presenters/nick-ferrari/…
 
@JonClements At least that's a fairly harmless conspiracy theory, compared to some of the other covid-19 conspiracy theories.
 
10:27 AM
if request.user.is_anonymous:
    response = {
            'status': False,
            'detail': 'AnonymousUser'
    }
    return JsonResponse(response, safe=False)
else:
    if request.user.roles == 5:
        return view_func(request, *args, **kwargs)
    else:
        response = {
            'status': False,
            'detail': 'Unauthorized access'
    }
        return JsonResponse(response, safe=False)
I have updated the inside of wrapper function to this. But I still get Anonymous User even for valid request. But when I remove if request.user.is_anonymous it works fine and I get error whenever there is Anonymous user. Is there any way where I can handle Anonymous user?
 
user12867493
@JonClements @tripleee what license are your contributions under? Can I use that line you gave me in a public piece of code?
 
user12867493
Do I need to give credit?
 
too small and trivial to even discuss
 
user12867493
@tripleee ok, just wanted to check :)
 
thanks for checking, it's definitely good form
though trying to enforce a license on something posted in public chat would be pretty much doomed
Stack Overflow answers are CC-BY-SA and stackoverflow.com/help/licensing sort of implies that this extends to chat, too
currently CC-BY-SA version 4 but older content had an older license
 
 
2 hours later…
12:32 PM
@PM2Ring Yes, exactly. @iamvegan, I'd lead the OP towards a solution with a comment/answer by making them figure out why s(A) should be 7, not 9; where that subsequence of length-7 should start and finish in A. If they genuinely have spent a few days on it, they haven't figured out the flaw yet (if all their testcases only had 'islands' of a single 0 or 1 in the maximal subsequence then those won't tickle the flaw). Then they should throw away their approach with result, r and rewrite it.
...I wouldn't post a single line of code until they reason out exactly why their current approach will fail on s(A) being 7
...you're not spoonfeeding, but the OP has to actually reason out why the current approach won't work, and they haven't managed to. Until then, all code is worthless.
 
Hi. Does anyone know why this regex doesn't match the digits at the end of a string?
```
regex = r"\d+$"
match = re.match(regex, "foobar021")
```
 
because match() matches at the start of the string. You want search()
 
also, please read up on what re.match does
 
1:15 PM
The tree in my front yard is blooming, which means it will be six months before I can enjoy the view of all the nice things directly behind it
I must applaud the prescience of the HOA for releasing a newsletter yesterday reminding us that cutting down trees for one's personal convenience is not allowed
I guess this is a common problem
 
I've heard... things about HOAs
 
You aren't allowed to cut down your own tree in your own yard? O.o
 
I might be tempted to write a rant about HOAs infringing upon my God-given right to cut down trees, but technically the tree is in my neighbor's yard. So even in the counterfactual universe where HOAs don't exist, I would still have a hard time justifying it
 
you just have to convince Washington to chop it down so that Jefferson can stop being chilly
 
It's right on the property line (or where I imagine the property line to be). Maybe alternate me could cut off the branches on the left side?
 
1:23 PM
@Kevin I'm afraid to ask, but... what's a HOA?
 
Home Owner's Association
 
it brings up bad associations in a lot of people
I can certainly relate; one of the reasons I want to move away from an apartment complex eventually is so that other random people would no longer be able to tell me what to do
 
I, too, have heard things about HOAs, but I liked the property enough to buy it anyway. In the last 3ish years I have encountered zero unreasonable rules. So either 1) I got lucky with a HOA that isn't mad with power; or 2) all horror stories on the internet are from people who are unjustifiably angry that they can't run a charcoal grill in their garage
I'm leaning towards 90% 1, 10% 2
 
My bets are also on the "loud minority".
 
Oh, I forgot 3) since I'm in the 99th percentile for "indoorsy", the vast majority of rules dictating what I'm allowed to do outside sail over my head, because I almost never do anything outside
There may indeed be a dumb unreasonable rule like "all kiddie pools must be periwinkle blue", but I'll never be made aware of it
 
1:57 PM
I'm confused by some weird, totally irrelevant but intriguing failure in a recent Q
def test_factory(a):
    class Test:
        a = a
    return Test
calling this fails with a NameError for the a = a line.
It seems like the assignment makes a "class local", which I though classes explicitly don't do.
 
I dimly recall having a similar problem in the past, which boiled down to "name resolution is extra weird in class bodies"
The rules are well-documented, although difficult for mortals like me to parse
 
Found it in the docs: "These references follow the normal rules for name resolution with an exception that unbound local variables are looked up in the global namespace."
 
That's the one.
 
That's indeed extra weird. Why would one want to read these from the global namespace?
 
My first guess is that the language devs want everybody to declare their classes in the global scope, so they make it intentionally difficult to construct classes using non-globally-scoped values
But this strikes me as a little more hand-holdy than normal
 
2:10 PM
I'm a bit surprised that it doesn't just raise UnboundLocalError as for function locals, but makes the extra effort to rummage through globals.
 
As an exercise, I'm trying to determine where this rule is enforced in the source... github.com/python/cpython/blob/… looks suspicious but I don't know if a counts as a "free" variable in your example, so maybe it's unrelated
free: set of all symbol names referenced but not bound in child scopes. But Test doesn't have any child scopes. Unless its body counts?
github.com/python/cpython/blob/… talks about class block semantics but doesn't give us any new information aside from admitting that the system is "slightly odd"
 
Sorry, I already had my share of digging through C in the past two weeks.
 
@MisterMiyagi But this works
def test_factory(a):
    return type("Test", (), {'a':a})

print(test_factory(100).a)
 
@Kevin For modules it makes sense to me - there's only globals and builtins sandwiched on top of each other. But class scopes can be so far removed from globals...
 
@MisterMiyagi That's fine, I never expect anyone to join me on my source diving adventures. I almost never find design rationale in comments in the source, so this is more an amusing diversion than a real fact-finding expedition
<half-serious> conversations about CPython should be in the C room, anyway
 
2:22 PM
Oh, usually I'd be happy to scour the depths of CPython with you. But I've just got the confirmation that three weeks of debugging pain are only because some wiseguy didn't wrap glibc correctly.
@Kevin I'm tempted to try that experiment one day.
 
@PaulMcG Right, you can work around class body semantics by not actually using class. I had something like that in mind when I wrote "[the devs] make it intentionally difficult" rather than "intentionally impossible"
Disallowing non-globals in a type() call would probably require the devs to solve the Halting Problem, anyway
git blame on the slightly odd semantics line indicates that it's been this way for at least 15 years
 
Were class blocks ever restricted to top-level scope?
Might also be a leftover from when there was only builtin -> global -> local name resolution.
 
No interesting hits for "resolution" in the big history file
 
It shows that nested scopes were added in 2.1, though
 
Yeah, I'm looking at the notes for Python 2.1 alpha 2 now
I see a reference to PEP 227 -- Statically Nested Scopes, which may hold some insight
 
2:37 PM
Sadly only the unhelpful "[class] references follow the normal rules for name resolution."
 
Ha, the introduction talks about how it's cumbersome to pass locals into lambdas in the style of Button(root, text="Click here", command=lambda root=root: root.test.configure(text="...")), but I see code like that all the time in present day, because it's still the easiest way to bind callbacks correctly in a loop
Some things never change
python.org/dev/peps/pep-0227/… -- assexp's primordial ancestor spotted?!?
 
it's more like golang's :=, just in reverse
hm, or perhaps they planned this all along...
 
3:15 PM
Python's argparse: how do
Okay nvm this isn't intrinsically an argparse problem but it does show that I can't just ask for arguments in a loop
I want to turn a string argument into an array of substrings; these strings are directory names
 
I think last time I got tripped up by assuming that this class semantic wackiness always applies, when really it only applies if you would normally expect an UnboundLocalError. For example, these classes are happy to use nonlocals:
def test_factory(b):
    class Test:
        a = b
    return Test
test_factory(1)


def test_factory(a):
    b = a
    class Test:
        a = b
    return Test
test_factory(1)
 
I was going to do args.input_string.split(" "), but one problem:
What if the inputted string has a space in it?
 
I was thinking of it as "class bodies are more restrictive in how they resolve names" when the truth is "class bodies are less restrictive in how they resolve names". They resolve names the way a normal scope does*, and in addition can resolve names that would normally cause an UnboundLocalError
 
Instead of taking a single argument and splitting it, just take multiple arguments in the first place
nargs='+' or something
 
parser.add_argument("-r", "--restrict", help="Restrict certain directory names")
How do you make several arguments an option?
An arbitrary amount?
 
3:21 PM
The devs aren't making it harder for us, they're making it easier
 
I don't remember, but check out the nargs argument
 
So the question becomes "why didn't they make it even more easier, by making would-be UnboundLocalErrors look in all higher scopes, rather than just the global scope?" Perhaps the answer is "there isn't a pre-existing bytecode instruction for 'look everywhere but locally', and we couldn't be bothered to make one"
We do already have a bytecode instruction for "look locally, and if that doesn't work, look globally": LOAD_NAME. So it was easy to slot that in.
 
Thanks fey, very cool
 
(confidence that this explanation has no glaring errors: 75%)
This seems to be one of the rare instances where the scope of a name can't be determined at compile time
a = 1
def test_factory(x):
    class Test:
        a = 2
        if x:
            del a
        a = a
        #   ^ can't determine whether this is the local or global a unless you solve the Halting Problem
    return Test
print(test_factory(True).a)     #1
print(test_factory(False).a)    #2
 
@JohnnyApplesauce use nargs="*" for zero-or-more and nargs="+" for one-or-more
@Kevin The problem with determining class names at compile time is that the class scope is initialised by METACLASS.__prepare__, which can do very META things. Such as pre-initialising the namespace, ignoring assignments or making stuff up.
 
 
1 hour later…
wim
4:40 PM
@AndrasDeak interested in your opinion on this comment
as far as I can see it can not be true, since the truncation and the reverse should both be views with O(1)
however, the comment is highly upvoted, so maybe there was something to it? is there some case where numpy would take a copy here?
 
I have the following as a path to save file
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
how do I pass this path as a string to a function? I tried using pathlib Path() but it did not work.
 
os.path.join already provides a string
 
@wim no
Slicing doesn't ever copy, because you can always map them to strides.
 
@MisterMiyagi Ah , thanks.
 
so yeah, both should be O(1) views
 
4:48 PM
if file and allowed_file(file.filename):
    filename = secure_filename(file.filename)
    file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(file_path)

    abc.abc(open(file_path))
 
semantically speaking I'd take a single slice from the back with [-n:]
oh, they want reverse order, OK
doesn't really matter where one reverses
 
THe above if statement should send the file path to the function to process but it requires string so @MisterMiyagi the function call isn't getting executed.
 
wim
@AndrasDeak Does argsort work in place, or use a copy?
oh it must return a copy of course
stupid question sorry
 
@AshwinPhadke Why should the if depend to the os.path.join output? The if is executed first.
Can clarify perhaps what you are trying to do, and how exactly this does not work?
 
@wim by the way:
>>> arr = np.arange(10)
... one = arr[-3:][::-1]
... other = arr[::-1][:3]
... one.base is other.base is arr
True
 
4:58 PM
@MisterMiyagi Yeah. the if is to check if the user has uploaded the correct file in the webapp, flasks way to do it. Now after the user uploads the file I am sendig it to the abc.abc(file_path) to further process. But once the user uploads the file nothing happens with it, like the function I am passing the uploaded the file to has a lot of checks that show up on terminal, so I know that the function isn't getting executed.
 
@JoshuaVarghese no, "too broad". New name: "needs focus".
 
@AshwinPhadke Okay, so to paraphrase you know that your if condition does not pass, because it's body should trigger output which is not present. Is that correct?
 
An MCVE would be useful here, said Kevin, fully aware that it's impossible to make an MCVE from a flask problem
 
5:14 PM
@MisterMiyagi yes
 
@AshwinPhadke Okay, so that means file and allowed_file(file.filename) does not evaluate to true. Do you know whether it ever passes the first check? What does the second check do?
 
@MisterMiyagi yes it passes the first check, I tried printing out the saved file_path and it returns the file path correctly, but the function call does nothing, I have passed that same file path to the function call but still nothing. The second check flashes the message to the user that the user had done something wrong and it is missing file to upload.
 
what do you mean by "does nothing"?
 
@MisterMiyagi does nothing as in does not show a output to the terminal, (well some print statements I have put in the other script where the function definition resides ) , I also have a display function call in that same script that displays the file locally, so if isn;t displaying the uploaded file locally, I am using the function isn't getting called.
I don't know how to debug a flask app, trying to debug the python script
am I making it confusing lol
 
All problems start out confusing
 
5:27 PM
@Kevin hehe
Okay to put it into simple terms : How do I pass the uploaded file which was uploaded using flask web server to some other script
 
@Kevin gotta love projects where a full MCVE includes all the boiler plate needed to get it to actually run. Android is notorious for this as well.
 
wim
>>> x = 1
>>> def f(x):
...     class A:
...         print(x)
...     class B:
...         x = x
...         print(x)
...
>>> f(2)
# guess the output
 
wait, we talked about that before
 
wim
yes this riddle is inspired by your discussion
 
5:50 PM
Here it is the full and actual question @MisterMiyagi and everyone : stackoverflow.com/q/61465131/7792580
 
cv2 and flask, brave ;)
before anyone jumps on them: it's OK to post questions here when they are the result of discussion in the room
 
@AndrasDeak yeah , can you suggest any other options?
 
If the module, class, and method are all named abc, you need to do abc.abc(file_path).abc() to call the method
 
nah, I barely know cv2 and I don't know anything about web dev
I just know that cv2 alone is a pain
 
abc.abc(file_path) merely creates an instance of the abc class, living in the abc module, and calls its __init__ method.
 
5:53 PM
@Kevin no they are not all named abc
@AndrasDeak oh it is
@Kevin so what should I do in that case? Do I pass it to init
 
Ok, if just the class and method are named abc and the module is named something else, then do somethingelse.abc(file_path).abc()
Incidentally just from the code available to me I don't see any good reason to use a class over an ordinary function. If you're getting confused by classes and inits, consider simply not having them
 
@Kevin all are named differently .
@Kevin let me try that meanwhile
people have already started downvoting lol
 
So you're saying that the class and method have different names? But I'm looking directly at your code and they're both named abc
Whatever. If the module, class, and method are named different things, then do modulename.classname(file_path).method_name()
 
hey I dont get it why I get this IndexError: list index out of range
listoflist = [[],[],[],[],[]]


def insertdata():
    for i in listoflist:
        print(i[0])

insertdata()
 
@HoboCoder there's an empty list in listoflist
oh, plenty of them actually
try breaking down what it does, remove the loop and manually check for i = []
 
5:59 PM
yes i want to do that with empty lists
 
OK.
 
Remember that for whatever in seq: binds the elements of seq to whatever, rather than binding its indices
In other words, for i in ["a", "b", "c"]: print(i) prints a, b, and c, not 0 1 and 2
 
I'm not even sure this is about that
 
Hmm, you may be right
 
@HoboCoder what output do you expect?
 
6:00 PM
@Kevin I removed all the class and init stuff, how do I import just the function from that ther script then and pass it a argument?
 
"A variable with the name of i is always an integer" is so deeply grained into my psyche that I didn't digest the rest of the code
 
I want to get the empty list like `print(listoflist[0])
as an output
 
Then do that, since that's what you want.
 
@AshwinPhadke from the_module import the_function, then the_function(file_path)
 
so Kevin might have been right
 
6:04 PM
sorry I dont understand the explanation
listoflist = [[],[],[],[],[]]


def insertdata():
    for i in listoflist:
        print(i)

insertdata()
 
Is that better?
 
gives me all empty lists as en output but I can not access a specific empty list
 
Sure you can. You did so in each iteration, during printing.
 
@Kevin that ducking worked , thanks a lot.
@AndrasDeak he's always right lol
 
his crystal ball is in fact quite clear
 
6:08 PM
hehe lol
Credited kevin for the answer to the question @Kevin stackoverflow.com/a/61465563/7792580
 
👍
 
wim
@AshwinPhadke the answer is unlikely to help future readers and may as well delete the question (I am not your downvoter)
 
did a doubletake when I saw my name there
 
6:36 PM
stackoverflow.com/a/25251804/2124148 seems inaccurate. Can't it just be time.sleep(time.time() % 60)?
Some guy posted time.sleep(60 - time.time() % 60) as the solution but that's mathematically the same as what I just said
 
If time is 1 second, sleep 1 second. If time is 59 seconds, sleep 59 seconds...
 
time.time() % 60 will always be between 0 and 59 just like 60 - time.time() % 60. There is no difference.
 
@JossieCalderon the task is not "execute function in a random amount of time but at most a minute". It is "execute function every minute".
try reading my message 2 up to see how that would work in practice, repeatedly
 
So both are wrong
 
if you assume that execution takes 0 time and time.sleep is exact, one is right
Your version, starting from 00:01: sleep 1 second -> sleep 2 seconds -> sleep 4 seconds -> sleep 8 seconds -> ...
The other version, starting from 00:01: sleep 59 seconds -> sleep 60 seconds -> sleep 60 seconds -> sleep 60 seconds -> ...
 
6:45 PM
The other version being time.sleep(60 - time.time() % 60)?
 
yes
lay it out on paper with a pencil
 
Using time.sleep(60 - time.time() % 60), Assume time.time() % 60 is 32. Then time.sleep(60 - 32) causes it to sleep 28 seconds.
 
indeed
Where would that put the time in the next step?
 
time.time() + 28 which is equivalent to 0 + x mod 60 where x is the amount of time it took the code to run
 
You said the time mod 60 is 32
that was your premise for the 28-second figure
 
6:52 PM
and when it sleeps 28 seconds it's now equivalent to 0 mod 60 (because 32 + 28 = 60)
 
Exactly. And what happens in the next sleep cycle? (Assuming x=0; sorry, I misunderstood your previous answer)
 
it sleeps 60 seconds. But now my concern is when x is not 0. The guy who suggested this solution commented: 'There is no need to subtract your starttime if you begin by syncing it to a certain time: time.sleep(60 - time.time() % 60) has been working fine for me. I've used it as time.sleep(1200 - time.time() % 1200) and it gives me logs on the :00 :20 :40, exactly as I wanted." So that is disconcerting.
 
Which part is disconcerting?
The x != 0 case?
 
Yes. If x != 0, it will not sleep 60 seconds, but maybe 59 or 58. But the disconcerting part is he said it has been working fine for him. And he got upvotes for it.
 
well people get upvotes for all sorts of things, that's a different matter
If their script runs for 10 seconds then they won't notice any issues if they time it to run every 20 minutes
Although the effect of x is probably not that bad...let's see
 
6:58 PM
I could just use time.sleep(60) then
 
Assume that in the first run you exit the work at time y. Then you compute the next time and make it so that the next execution happens at 0 mod 60 (sticking with out original schedule). Then it's run again, you exit at x -> but then you again compute the time so that it starts running at 0.
@JossieCalderon then you would always wait 60 seconds between exit and entry.
With OP's code you always start at the same time in a minute/hour/whatever, assuming that your runtime is smaller than the length of the scheduled interval.
 
Well, that works. What about an event scheduler, as shown in "https://stackoverflow.com/a/474543/2124148"?
 
that's probably the right solution, if you mean something like celery
for instance time.sleep doesn't guarantee that it sleeps n seconds, it just guarantees that it sleeps at least n seconds
if you schedule something fast over 20 minutes this is likely less of an issue...although you might want to use something OS-level, like (ana)cron
 
Great. Thanks a lot!
I just realized, by the way: If the function takes 5 seconds to run, then time will be 55. So you still get time.sleep(60)
 
7:13 PM
Yes, that's what I was trying to say there
 
My brain lagged
 
7:29 PM
cbg-evening
question: What is the elements() in counter module from Collections library for? I'm reading some text about it and I can't get it
 
Cbg. Did the official docs say anything helpful?
 
@AndrasDeak helpful, depends for whom elements() is one of the functions of Counter class, when invoked on the Counter object will return an itertool of all the known elements in the Counter object.
 
OK, that's medium level helpful
 
Doesn't look like the wording from the official docs, or is that from an older version?
 
also good point
"an itertool of all the known elements" is very suspicious
 
7:34 PM
I spy with my little eye w3schools or some such.
 
@AndyK can you post the URL where you read that?
 
@AndyK that...is not the official docs. Not even close.
I just googled "python collections official docs" and it was terribly helpful
 
gfg: now on my naughty list.
 
Hi. is there anyway to add a field name to a class during its constructor call using __init__? like self.random_val when I pass random_val=10 to the class' constructor.
 
7:40 PM
@FarhoodET to a class or an instance?
 
to an instance of a class
 
@FarhoodET exactly like that, then
def __init__(self, random_val):
    self.random_val = random_val
 
def __init__(self, **kwargs):
    vars(self).update(kwargs)
 
@AndyK much better, is it not?
@Aran-Fey ah, I see
 
7:43 PM
@AndrasDeak much better; I heard the light going on in my head
 
Thanks!
 
@AndyK my suggestion: read tutorials to see how the pieces go together in a rough way, but always look up the official library reference to know how each piece actually works and what else they can do
 
@AndrasDeak cheers for the advice. Adding the official doc in my bookmark bar.
 
You can also type "python collections.Counter.elements" into duckduckgo and it'll automatically pop up a preview of the official docs
 
@Aran-Fey I should use more often duckduckgo, not a fan though
 
00:00 - 20:0020:00 - 22:00

« first day (3481 days earlier)      last day (1484 days later) »