« first day (3318 days earlier)      last day (1629 days later) » 
00:00 - 21:0021:00 - 00:00

12:57 AM
Any ML/statistical modeling people opinions on this? How to convert Python datetime dates to decimal/float years is a good question and I'm going to add it to the canon. But that quantity is called "time index". Should we leave title as is, and just have a mention in the question body?
 
1:52 AM
I think people who know that term will be able to equate the description in the question title, while those who don't wouldn't know to search for that term. I'm not sure I'd even put it in the question body - why put words in the OP's mouth, especially one they don't even know from the sounds of it? Just include it in a comment or in the body of your answer.
In fact, when I google "what is time index", I'm not sure that it actually does mean the same as floating number of years. google.com/…
 
2:13 AM
Ah, a floating number of years is one form of a time index. Just as Julian date could be a time index, or Unix timestamp number of seconds a different time index, or Excel timestamp decimal number of days since 1/1/1900 another kind of time index. They are all ways to convert a yy/mm/dd hh:mm:ss timestamp to a linear timeline.
 
2:40 AM
0
Q: Delay timer to use a function in python

Irinel IovanI want to do a function that allow me to use another function each 5 seconds. When the first call of function is started another variable will store last execution time.. I calculated the 5 seconds interval and return if 5 seconds not passed. class MyClass(): def __init__(self): last...

 
2:59 AM
@IrinelIovan - you just posted that question about 20 minutes ago. Chat room rules say you should give the general populace a chance to answer before posting in this chat. You'll also get more responses if you leave the f-bomb variable names out of your sample code.
 
3:10 AM
I am kind of confused just what you are asking though. Wouldn't a "call every 5 seconds" thread do what you want? If not, how does what you want differ? Maybe give a more concrete example of how you want a delay timer to work? It looks like a couple people want to help, so clearing up just what you are asking might get you more helpful responses.
 
That code is for a game.
Some players spam the pet summon
When a pet is summoned this function is called Foo let's say
I want to make a delay to summon a PET
summon a pet now, you can't call summon a pet again if 5 seconds not passed since last summon
got it now ?
@PaulMcG
 
 
1 hour later…
4:24 AM
That is much clearer. But you aren't really trying to code a delay in the code, as much as detecting if X amount of time has elapsed since the last call. If you include that game scenario in your question, you should get some good answers in a very short time.
 
4:59 AM
What should be the name of python virtual environment?
like $project_initials_{env}?
 
5:09 AM
@PaulMcG You might like to use docs.python.org/3/library/time.html#time.perf_counter for that.
 
@PM2Ring - oh nice. I think this OP might still be mired in Py2-Land, tho. But thanks, I will make a note for use at work, we do quite a bit of timing bits for automated testing.
@Zeta.Investigator I am not aware of any naming conventions or recommendations around virtual envs. If I have multiple venvs for different Python versions, I probably put the version in the venv name. But you are free to name how you please. (I think venvs are particularly difficult to rename though. so it is worth thinking about up front.)
 
@PaulMcG Ah, right. I didn't notice that tag. I thought perf_counter got backported, but I just checked. Oh well.
 
5:34 AM
It's not totally clear - he did put parens around his print arguments, which is usually a good Py3 telltale. But I wasn't sure, so I didn't use nonlocal, but one of the Py2 hacks to work around not having nonlocal.
 
5:47 AM
I could see something like time.perf_counter being a solution (or at least a mitigation) to en.wikipedia.org/wiki/Year_2038_problem on 32-bit systems.
 
@PaulMcG The decorator is amazing, now i have one last error. global name elapsed not declared
 
6:37 AM
weekend cbg folks.
Unfortunately couldn't attend yesterday's meeting, going through the transcript now.
 
 
1 hour later…
7:53 AM
Nicely conducted by Kevin, I'd say it was fruitful overall. I'd prefer bit.ly links (room desc.) or if we are okay with tinyurl, maybe we could get a SOpython website functionality for our own shortener :-p
 
8:39 AM
stackoverflow.com/questions/58888671/… unclear. Even if you don't know Flask, you can see the bizarre discussion I've had with the OP under the answer
TIL I learned that code fails by way of simply not existing
 
9:01 AM
"TIL I learned". I'm not doing so well myself, time for a brew :/
 
9:35 AM
HI all, I want some help to understand - why would one want to run multiple instances of the same application in the same process? See point number 2 here - flask.palletsprojects.com/en/1.1.x/patterns/appfactories
If you could tell me a situation as an example then it would make sense
 
Good question, I've never really understood that myself. An application factory makes sense for testing but you've reminded me that I was also confused by that statement
"you can have multiple instances of the same application running in the same application process which can be handy" is the kicker. I could imagine someone having an app that they sell to two other companies. Each company has their own "portal"... but that doesn't merit running them in the same application process, so I get lost there
 
9:53 AM
I might be wrong, but I think it's got to do with working on multiple requests in parallel. Flask stores the request state in a threadlocal object that is magically made available to all functions decorated as routes. As a consequence, you can only work on one request at a time per thread, and working on multiple requests at the same time requires multiple threads.
 
That would be handled by e.g. gunicorn, though?
 
@variable erm, it says so right there in point 2. "Imagine you want to run different versions of the same application."
 
That would launch the app in multiple processes/threads (configurable) but they would still create the same app from the factory. It would be confusing if they used the factory to produce different apps :P
But I think you're on the right lines, Arne. I just don't quite get a practical use case
@MisterMiyagi But then the logic falls apart for me in the latter part of that point
 
how so?
 
10:08 AM
Because I couldn't see why, practically, you'd want to mix two apps in this way. I'm talking about implementation, not theory here. Beyond a live version and a staging version, I don't know whether people would actually make use of this facet of Flask
Spin up an instance and have a dedicated app instead
 
I've stopped questioning why people do the things they do on the web
 
Teach me your ways :P
 
seriously now, a) I think it's good software design to design everything as instances, not singletons, and b) I see zero reason to risk side-effects from shared process state only to avoid running more processes.
in theory, you could benefit from in-app caches if instances serve similar content. Not sure if that is a frequent use-case.
 
39 mins ago, by variable
If you could tell me a situation as an example then it would make sense
That was the initial question, so in light of what you're saying, I think it's pretty valid
I'm less concerned that Flask went down the route of supporting this, but "pretty handy" as a qualifier in the point that we're referring to suggests that people actually want to do this.
(Also, in case it was misread, "teach me your ways" was in reference to giving up questioning what people do, not how Flask should work)
 
10:38 AM
Thanks. Another question - I understand about flask dev server. To move flask to production, I know about gunicorn and nginx (pip install gunicorn; pip install nginx). Does it make more sense to keep one server with nginx and one server with gunicorn? Or better to keep both on one server?
 
Presumably you mean instance and not server
 
I dont get this part
Both servers will have the app instance isnt it
I know gunicorn is app server (good to handle python); and nginx is web server (good for static pages)
 
A computer can run multiple servers. I'm assuming you bought something on AWS or DigitalOcean etc
 
No Im reseraching my options - I am even thinking about docker'izing this
@roganjosh assuming I got 2 servers on a computer. Each server is an independant entity. Is it better to put nginx on one and gunicorn on other. Or shall I use only 1 server and have both nginx and gunicorn on that one server.
 
It depends on scale. Let's assume this is an app with relatively low-volume traffic
@variable unless I'm missing something, that doesn't make sense
What is a server to you?
 
10:45 AM
My understandign is - the request will go to the nginx server first, if static file then it will handle it. If python req then it will forward it to gunicorn.
 
Ok, but what is a "server" here?
 
An independant machine/VM (independant in the sense - it has its own OS)
 
That's what I thought :) IT will talk about physical machines as servers
 
you can think of it as separate computer
Thanks you are being very patient today!
 
That's not the case. You're actually talking about a program that just listens on a particular port
 
10:48 AM
you mean nginx and gunicorn are programs that listen on a port? Sorry this area is new to me
 
spot on. So, a server is not the machine itself. We brand them together as an oversimplification
 
So, firstly you need to drop the idea that "server" refers to some block of hardware that just does .... serving?
 
but nginx and gunicorn are the servers. the machines running them are not
It's just "Easier" to dedicate a machine to just be running a server, and then brand that machine as "the server"
 
Ah so even if they are on same machine then they are servers in their own sense (not phisical server)
Ok making sense
 
exactly
 
10:49 AM
Correct, because physical servers is an oversimplification
 
So is it good to have nnginx and gunicorn servers on one PC OR each on an independant PC
 
That's where scale comes into it
 
I'd opt for "simple is good, and YAGNI" approaches. Consider multiple machines only if you need it.
 
Ok so you mean for example depending on volume or traffic - we could have 1 nginx and multiple gunicorn servers. And decide if they gonna be on independant machine or not
 
All NginX is going to do (I'm massively oversimplifying) is take a request and pass it on. If it passes it on to something else listening on the same machine, that's fine
 
10:50 AM
no. volumes or traffic
 
got it
 
or well, id let roganjosh clarify. but scale usually refers to much much traffic and requests you need to handle
 
we can scale it as per volume/traffic requirement
 
So nginx is going to be a middleman. You can, btw, run your app on gunicorn and never touch nginx
 
I see. ok so its just that nginx handles static files better so it is mentioned for use
 
10:52 AM
correct
 
It takes the burden off the server hosting the app, yes. But it's not needed if you're talking small-scale
 
and I also read about supervisor - a tools that auto restarts the gunicorn if the gunicorn goes down.
 
If you're gonna get hammered by requests then nginx can distribute those requests to multiple servers hosting your app. I suspect this is an unlikely case here
Yes, you'll probably want supervisor
 
Ok so I am thinking of using docker - within the docker image I wil do pip install gunicorn and pip install my flask application and do gunicorn run [or what ever is the command ot run flask via gunicorn]. That should be sufficent then for a basic setup. and for scalability I can use something like service fabric cluster to scale it
 
docker I can't really help with. I've used it sparingly but I can't answer anything on it tbh
 
10:55 AM
Ok it is makign sense to me now. Thanks for the help with server
Do you think it is an overkill to implement factory and blueprint pattern for small rest api app? I am thinking that we can use OS environment to configure the app object. Just want to know general opinion about this
 
I don't think it's a waste of time using blueprints if it logically separates your code
 
Even if there is just one main blueprint ? - example only 4 endpoints - like /a, /b, /c, /d
Yes I agree it beings separation
 
If there's one blueprint then there need not be blueprints
 
So then all code will go in the app factory?
 
err, that's a strong leap
 
11:01 AM
Is there a way to split the views in separate file? Because if I do that, then current_app will not be available - so need to use with app.context while using the view file int he factory? Hope makign sense
 
You still probably want a views.py and a models.py. I don't quite see how this fits into the factory pattern
Ok, something seems to have gone wonky long before you're trying to host this
 
Ok so all code was in app.py. I have made a new package (say pkg) and moved all code from app.py into pkg.__init__.py file
 
you can import things from other files right? Like, write the logics anywhere, and write imports in your app.py and so on?
 
The init.py file has got function called create_app() which returns the configured flask app object
 
Right, but why does everything need to be in that file?
 
11:06 AM
If I move the routes to view.py, then there is no app object in the view.py file. So in view.py if I use current_app, and then in init.py if i do from pkg import view - this will fail as there is no current app.context so current_app will fail. So am I right to say i need to manually push app context before using from pkg import view
 
No. This is very broken. You import the app into your views.py but I can't see what's going on here so I'm running blind
 
I cant import app in view.py because app is returned from factory present in the init file.
So what I was saying above is, if I try to use current_app in the view.py, to setup the routes, then, in init.py, in the factory, after creating app object when I will do 'from pkg improt views' it will fail isnt it?
 
The best I can do here, I think, is point you to sopython for structuring an app
It sounds like the structure is fundamentally wrong, and I'm not going to be able to help with that via chat sorry
 
Code in the pkg.__init__.py
>>from flask import Flask
>>
>>def create_app():
>> app = Flask(__name__)
>> from pkg import views
>> return app
Code in pkg\views.py

>>from flask import current_app
>>
>>@current_app.route('/')
>>def hello_world():
>> return 'Hello, World!'
Error: RuntimeError: Working outside of application context.
 
Didn't I just say it was "very broken"?
 
11:19 AM
Question: Do I need to manually push applicationn context when doing the "from pkg import views" ? Is there any alreadnattive
Oh ok
 
@variable as a room owner I'm telling you to read sopython.com/wiki/… and practice code formatting in the sandbox before you post code here again
 
salutations pupster
 
pupster hey? Must be my new fandangled street name or something? :p
 
11:25 AM
I like ninja doggo more than pupster
cbg
 
What's worse is that I tent to use that word in real life too :P
 
I think it's forgivable... as long as you're not going around saying "cowabunga dude" or "eat my shorts man" or something :p
 
Oh, those days are now so far away :/
 
so far away... doesn't anybody stay in one place anymore? :p
 
(I don't think I ever even used either but it's distressing to see childhood being so far back)
 
11:30 AM
have you seen my childhood? I'm searching for the world that I come from :p
 
Can you advise if this is bad practice? stackoverflow.com/a/57565474/1779091 It solves my problem
*pushing the app context
 
anyway... I'll stop doing that typing out lyrics now... it's annoying even me - wonder if there's any decent Python stuff to answer this morning... goes and has a quick peek
 
@variable you're mis-diagnosing your problem IMHO
Application factories don't necessitate blueprints
 
Yes agree lets take blueprint out of the picture
My above code is a packge and factory
 
I'm having a bit of a tough time trying to piece together the isolated bits of info that you're knitting together here.
 
11:33 AM
All I am trying to do is move the routes into a views.py
 
Did you look at sopython on github?
And actually try and understand it
 
Yes I did and I cant figure out where to start
 
Oh come on now. Pushing app contexts is way beyond the fundamental restructuring that I'm suggesting
I will say this, since it's not the first time I'm trying to help you; you're overstretching your knowledge. I'm in the position all the time. But you're missing a hell of a lot of things along the way and you have something of a responsibility to yourself to get to grips with it. At the moment, your app cannot hold water because it has leaks everywhere; take a step back
 
You've also been at it for literally two hours
 
11:51 AM
Please be considerate when pointing me to sopython containing 100s of files that I dont know where to start. I am not arguing, I know I need to know a lot more and I am trying. But the question I asked here was - I am having a project where all code is in app.py. Now I want to make this better by moving to package and factory pattern.
So I moved code from the app.py into the pkg_init_.py. Now, within init I have implemented the create_app factory method. Now, I wish to move the routes into a new file view.py which I did using current_app and then when I replaced the routes from the factory with 'from pkg import views' it gave me the error related to missing context. Which I subsequently fixed by manually pushing the app.context just before doing the 'from pkg import views'.
Now you are saying I need to take step back. Please be considerate to tell me in few words in what context are you saying to take step back.
Thanks.
 
"take a step back" is a suggestion that you might want to fill in the gaps in your flask knowledge. It's not an insult; if I intended to insult you, it would be more obvious. However, are you going to argue with me that you're putting a diverse range of problems to me?
What I am saying is that you can't expect this all to fall into place in the space of a couple of weeks with no experience. That's not meant to be an insult to you, I'm sorry if you've seen it that way, but it wasn't intended
Also, I have a bad habit of saying "argue" when I mean "debate". I don't see them as separate entities, regardless of how heated (or not), but maybe I misspoke
 
Sorry if it came across that way i didn't mean to suggest you are insulting. Just request be more considerate when pointing towards the direction
 
 
1 hour later…
1:13 PM
got 3.8 compiling to have a play with - going to take a break from keyboard for a bit... rbrb for now
 
2:02 PM
Can anybody please help me with a Json to Dict question, apparently I have hit a wall here
 
we might, but only if you actually ask your question
 
playing around with google cloud api, I get what i think is a Json string, need to put into a dict to then put into a df in pandas. Looked around, but keep getting into different errors... if I print what i get from google: translations {
translated_text: "Bolivian street clashes leave 5 dead and 22 injured"
}
looks like that.. json.loads() not working for me
 
I need some help with deploying flask app on windows using waitress.
 
error: raise TypeError(f'the JSON object must be str, bytes or bytearray,
 
That's definitely not json. Can you show us the output of print(repr(the_google_response))?
 
2:12 PM
tried str() and .decode('utf-8')
 
I want to draw something like this diagram with Python, any suggestions? hlab.stanford.edu/brian/euclidean_distance_in.html
 
translations {
translated_text: "Bolivian street clashes leave 5 dead and 22 injured"
}
get the same thing
 
Uff. print(type(the_google_response)), then?
Also we'll probably need to know how you obtained the response in the first place. You're using a google module?
 
aran,... this returned []. lol... you might be on to something
            bloben = client.translate_text(parent=parent,
                                           contents=[blob],
                                           mime_type='text/plain',
                                           source_language_code='pt',
                                           target_language_code='en')
it may be in the mime_type, should be something else?
 
What's client though? What module is this from?
 
2:20 PM
google cloud
translate api
 
next time I'll just ask for a M(CV)E instead...
 
<class 'google.cloud.translate_v3.types.TranslateTextResponse'>
 
thats the type, i had misread: Type: <class 'google.cloud.translate_v3.types.TranslateTextResponse'>
What i want is to put just the translated text into a python variable, without the trash
 
You read the docs and still can't figure it out? (Serious question)
 
2:31 PM
Sorry, could help a little light
could use a little light
not sure how to make this into the correct code: translated_text
Field google.cloud.translation.v3.Translation.translated_text
 
ugh, those docs are really pretty dang useless
this is why I hate google modules
uh, what kind of object is response.translations?
(and if it's a list, what kind of objects are inside?)
I don't suppose I could convince you to throw the google module in the trash and use the REST api directly, could I?
 
<class 'google.protobuf.pyext._message.RepeatedCompositeContainer'>
translated_text: "Bolivian street clashes leave 8 dead and 125 injured"
This is a dry run for using other apis within the google cloud
i guess i could use regex at this point in a moment of desesperation
but it would be nice to extract a clean string directly
 
I can't even find the docs for that class...
 
me neither
damn you google
so close yet so far
 
2:50 PM
Honestly, using the REST api is most likely going to be easier
 
what is the rest API
Sorry, i am new to this
taking the next 6 months to get better
i am really good at pandas, but not so good in other things
 
It means sending HTTP requests: cloud.google.com/translate/docs/reference/rest
You send a POST request to https://translation.googleapis.com/v3/{parent=projects/*}:translateText and get a JSON response. Easier than dealing with google's junk code, ain't it?
Though I guess implementing the OAuth authentication is a bit of a hurdle if you've never done it before
 
This is good
I will keep hammering at it, and look into the rest API, should keep me busy for a bit
thanks!!!
 
3:22 PM
Hello Everyone,
 
 
1 hour later…
4:47 PM
Is there a smarter way to parse a duration than this abomination?
>>> int((dt.strptime('12:34', '%M:%S') - dt.strptime('', '')).total_seconds())
754
(that's 12 minutes and 34 seconds converted to 754 seconds)
 
Hmm if I have a set of factory methods to create objects: would it be best if those factory methods are "free" methods, static methods or even class methods?
 
class methods if it makes sense for them to be in the class, otherwise regular functions. Definitely not static methods.
 
5:12 PM
Since by "factory" you mean "creates class instances", you will probably want to make them class methods, and use the 'cls' argument as a way to find the relevant class to use in constructing the instances.
For instance, I'll often create an abstract base class that knows how to find the correct subclass given some selection criterion. The base class then implements a classmethod that take criteria, finds the correct subclass by navigating cls.__subclasses__, and then returns it to the caller, or creates a default class instance and returns that.
 
Well it's mainly "utility functions", ie I need to define a (keplerian) orbit. Which is normally done by giving semi-major axis, eccentricity, inclination, argument periapsis and longitude ascending node. However there are lots of "variations": ie for parabolic orbits the semi major axis is replaced by semi latus rectum. Or you can just use state variables at a point (position + velocity in 3 dimensions). Or you could replace the semi major axis + eccentricity by peri + apo apsis.
 
Ideally, the criteria matching is done in the subclasses, so that subclass-finding code in the base class never changes.
 
So I have a few utility functions. I once tried that by using keyword arguments, but then the error checking for "did I have enough and not too many constraints" got overwhelming.
If I make them class methods I never use the cls variable so any checker might fall over that
 
A factory that doesn't use cls? How?
 
So you could have a base AbstractOrbit class, then have the subclasses implement a class-level list of required arguments. The base class has a make_orbit takes a **kwargs, and iterates over cls.__subclasses__ to find the one with matching required kwargs, and then returns an instance of that.
 
5:21 PM
Because it just "normallizes" the variables and then uses the standard constructor. - Which is hard coded.
 
There's your problem. Why's it hard coded when you could be using cls instead?
 
Doesn't 3.8 implement multi dispatch? That might be the way to go.
 
Because it makes little sense to me to use anything else? "MakeOrbitFromStateVariables(position: (float, float, float), velocity: (float, float, float)) -> Orbit"
 
One classmethod with multiple signatures.
 
That would be the (almost) full signature of one such utility function.
 
5:23 PM
And what if someone wants to subclass Orbit? Then the factory methods just won't work for them because you decided to hard-code Orbit?
 
Hmm physically that wouldn't make sense. But I guess indeed for programming tools you should allow that.
Side question: how would I type hint this though ;P
 
def from_vars(cls: Type[T]) -> T
 
ty that's a snippet I'll have to remember.
Wait but that would allow any to be the type of cls (now I know the compiler doesn't do that, but from a purely static type analysis one cannot know).
 
I guess you don't really need the complexity of the class hierarchy. Just define a make_orbit classmethod on Orbit that takes **kwargs and does the mix-and-match validation.
 
@PaulMcG That is a pain with the amount of variables, there are 6 independent ones necessary out of a pool of 18 (some of which are dependent). And then there are a lot of combinations that "officially" work, but are just a pain to implement and never needed.
 
5:46 PM
Numpy has np.array as a utility that instantiates ndarrays. Not that numpy is always a showcase of ideal design.
 
Would something like this work? Or be helpful in localizing at least the validation part? gist.github.com/ptmcg/86a3f26fb03fe521ceb43dceb8439f89
 
np.ndarray is never called directly
 
Here is a little example of multi-dispatch using __subclasses__ (skip the first translated-directly-from-Java example and jump down to the but-Python-is-not-Java version): python-3-patterns-idioms-test.readthedocs.io/en/latest/…
You could also have make_orbit call a kwargs-normalizing method, to reduce the amount of which-kwargs-did-I-get logic in Orbit.__init__.
 
@PaulMcG Well the big problem is that there's a lot of "simplifications" on the calculation to the base 6 keplerian variables. But I guess having a single constructor could make sense. But then I can just as well use a constructor instead of a factory.
 
I'm going to try opencv, I guess....
 
6:00 PM
When I hear "factory" I tend to think in class-level logic, so my first thought was the AbstractOrbit.make_orbit. But you could also have various methods to normalize one set of args to another, and have make_orbit (or even just __new__) convert the given args to a normalized set, and then write Orbit's __init__ to just take the normalized set of kwargs.
By comparison, you could have a Line class that is constructed with a slope and y-intercept, and define normalization methods to convert Line construction using 2 points, or a point and a slope, or any other geometric relation that resolves to a line in the x-y plane; have the method convert the args to slope and y-intercept, and then return Line(resolved_slope, resolved_y_intercept)
 
@AaronHall it's nice, if at times a bit pedestrian
And docs can be hard to find
 
Here's what I'm trying to do:
4 hours ago, by Aaron Hall
I want to draw something like this diagram with Python, any suggestions? https://hlab.stanford.edu/brian/euclidean_distance_in.html
 
I'd use tikz in latex for that, so no idea ;)
 
tikz? really?
 
Pyplot would probably also be easy, just mpre manual than typical pyplot
@AaronHall oh yeah
 
6:07 PM
now that I think about it would probably be great for that...
 
But some parts (dashed hidden things) would either be manual or very advanced. Then again this goes for other methods too.
 
I'll look into pyplot first, then maybe tikz...
 
that makes sense in terms of hands-onness
Actually, you can use a legit 3d plot :) it would work like a charm except for the hidden dashed thing
 
6:25 PM
@AaronHall PIL has some basic drawing commands. But IMHO that diagram ought to be done with vector graphics rather than bitmap. You could code it directly in SVG, although it can be fun to use Python to create SVG.
Of course, that requires knowing some SVG, but it's pretty easy to pick up the basics. There are various tutorials around; I used this one a few years ago. Dashed lines are easy in SVG.
Hi, @AndrasDeak. Sorry I missed the room meeting. I simply forgot about it. :( I've read the transcript, and have no disagreements.
 
@PM2Ring dashed lines are easy everywhere, we're talking about lines that transition to dashed when "hidden" (behind a surface)
 
I've used opencv for analysis image data (edge detection etc) to some good extend in the past. It's not that hard, just "ugly".
 
@PM2Ring cbg, I'm glad to hear that :)
 
Never used it (or anything really) for drawing.
On that topic, which GUI, or actually "state memory" would you recommend for python? Like "creating" a set of data and then selecting the function to use (which might modify data). Currently I use an interactive python shell for those things. But it gets messy at times.
 
@AndrasDeak Ah, right. SVG can't do much about that, since it's a 2D program. I suppose it wouldn't be too hard to handle hidden lines in Python, but I've never tried.
 
6:36 PM
TikZ can usually do "intersect this line with this line" that would make this not-so-messy
 
@paul23 That's too vague for me. Can you give an example?
 
Well say currently: I work on a tool to quickly calculate orbit transitions and make a budget for a mission.
 
@paul23 does that include ipython/jupyter?
Lots of bells and whistles there
 
However to "select" which transitions it does I currently rebuild the earth-moon system. Then create the initial setup and add transitions using code. It would be nice if there's just a select box that says "perform function xyz on object abc".
@AndrasDeak I think pycharm uses ipython internally when creating an interactive python shell?
 
Could be
Perhaps you can make do with jupyter.org/widgets
 
6:42 PM
What does "rebuild the earth moon system" mean? I'm probably being dumb here but it's not my area. A GUI in itself won't alleviate this but isn't it something you could store? So you have two components; storage of state and user interaction?
 
@roganjosh of course I could store this, the "problem" is that in a linear (command line) interface non linear operations (load state, modify state, show results, now further modifications/calculations) tend to get unreadable.
 
If it always has to be calculated on-the-fly, that'll remove the db aspect, and you're left with tkinter, pyqt and then web interfaces like flask/django. Any of those can do the job for the user interface
 
@paul23 I suppose you could use Tkinter, which has the advantage of now being part of the stdlib. And it's small so it's pretty easy to learn, although it has less features than big frameworks like GTK or Qt. Here's something I was messing around with a year ago. gist.github.com/PM2Ring/d6a19f5062b39467ac669a4fb4715779
 
Hmm well I was mainly wondering if there's something akin the gui-builder for C# in visual studio (so something I ought to learn anyways :P).
 
@PM2Ring yeah, that's what I really wanted to do I think... svg is easy for others to recreate...
whereas tikz probably requires a whole tex live install.
 
6:48 PM
Probably.
 
@AaronHall And all modern (and most not so modern) browsers can display SVG.
SVG has some nice animation features, and you can do even more anim stuff by inlining JavaScript, although doing that means you can't use simple SVG viewers / editors like Inkscape to display it.
 
@paul23 to my knowledge, no, there's nothing like what you're expecting. I could probably throw a Flask app together with your dropdowns etc in 10 mins, I never really got a grip of tkinter. But whichever route you take, you're gonna be coding it out yourself I think
 
I had started to make a Python library to generate html (for documentation and my own edification more than any other reason) so I might even do something like that... here's some sample usage: github.com/aaronchall/HTML5.py/blob/master/html5/__main__.py
now that I look at it I actually did include some svg in it... :D
 
@roganjosh At that point it might just be easier to use javascript and a flavour of python-in-browser/python-to-js
 
Eh, really? I disagree with that for sure.
 
6:54 PM
 SVG([Circle(cx=50, cy=50, r=40, stroke="green", fill="yellow")], #stroke-width=4,
            width=100, height=100),
 
Well since I have to use javascript (full stack) for my normal job writing a react application isn't hard.. And I only really miss numpy toolset.
 
How will you call numpy? That's a mega hit for calculations, like orders of magnitude in calculation time
 
@paul23 And the HTML5 Canvas is a rather nice graphic environment...
 
@roganjosh Yeah as I said: I miss that.
 
7:03 PM
cbg
 
@AaronHall Interesting! My HTML is a little rusty, but it'd be nice to generate HTML from Python.
 
2 days ago, by roganjosh
@smci What would be bad about the outcome is that, if you used something like bootstrap, I think it would be impossible for pandas to ever get a grip of the CSS so the output of to_html seems like it would never really fit in any site.... which is why I wondered whether it had a use
 
The idea was to declare Python objects you could instantiate with the right arguments and when printed they would look like html...
 
So the styling would likely suffer. Plus you have the task of dealing with responsive apps
 
@roganjosh Tkinter's not hard to learn, especially if you've ever used a GUI framework before, in any language. And if you haven't, Tkinter is a reasonable first framework. The hardest part of doing GUI stuff is getting used to the concept of event-driven programming.
 
7:14 PM
@roganjosh So i kinda just saw this conversation randomly, and i want to say that i think we did use df.to_html() in one of our flask apps, routing the html to a jinja template, where the frontend uses bootstrap without issues?
 
Good evening good people
 
@AaronHall I only had a brief look, browsing Github on a phone is a bit annoying. But it looks good from what I saw.
 
And by randomly, i meant i kept clicking the "reply to earlier message" till your post made sense to me, but that made me see the df.to_html question
Our goal was fairly simple though, make one of the tables in our database accessible to the user on the browser, with the option to download a csv of their current selection as well.
 
@ParitoshSingh I'd be really interested to see that implementation :) There wouldn't be a technical issue, but certainly I think there could be problems visually
 
Let me pull up my work laptop and see if i have anything related to it with me. I potentially might not though, I wasn't the one who built that portion. In which case if you remind me on Monday i can get my hands on it
 
7:17 PM
Even just adding the "table" class from bootstrap. How did you do that?
 
If i had to guess, we probably "filled" a table class from the html of our dataframe dynamically.
That way the table was ready with every styling element directly because that was on html/css side of things
It might have been a bit hacky, but it worked like a charm
 
Huh, ok. Maybe I'm behind the curve here :)
 
Oh i doubt that. The folks i worked with on that particular project, they're masters of getting things done quick and dirty. So, im half afraid to see what i'll find exactly if i dig in too deep :P
(Which is to say, im actually very impressed by their ability to try things out till they get it right. Very quick learners too. I wish we had more folks like that in our team)
Oh dear
Scratch that, it no longer uses .to_html
 
Boo. I was looking forward to being proven wrong there :)
 
Well, would you like to see what lies here instead? :D
    col_headers = [x[0] for x in cur.description]
    col_headers.insert(0, 'Entry Number')
    col_headers = ''.join(['<th><b> '+i+'</b> </th>' for i in col_headers])
    table = '<table id= "datatable" class="table table-bordered table-striped"><thead><tr>'+col_headers+'</tr></thead><tbody>'
    row_number = 1
    for row in data:
        table += '<tr>'+'<td>' + str(row_number) + '</td>'
        for element in row:
            table += '<td>' + str(element) + '</td>'
        table += '</tr>'
See what i mean about quick and dirty? :P I can't complain, it got the job done. but oh dear. haha
 
7:29 PM
Oh my. Well, Jinja gets a light shift :P
 
Looks like we decided to construct the html by hand in python at the end of the day.
That is true! haha
5 years down the line: some developer who inherited this code curses the devs and uploads it on codinghorror or something like that
 
why wait? :P
Gosh, that's quite surprising actually. I wonder why they ditched Jinja
 
Haha. Because i know exactly the circumstances under which they must have come up with that. Considering they essentially had to teach themselves just about everything, i can understand this probably seemed like the best possible way to do things at the time. Im willing to bet, right now, if they see this code again, they'll probably want to refactor it too right away.
My bet: we didn't quite know what jinja was when we wrote this far.
Or understand it enough to work with it.
 
Fair enough. That's an interesting insight, thanks :)
 
If i had to give some context that would make everything "click": We outsourced UI work on our project. It came back in PHP, and it was SO bad we had to take matters in our own hands, and prematurely end the contract.
 
7:34 PM
@ParitoshSingh That's not so bad. Those for loops that populate the table could use .join and listcomps. Although it'd be more readable if it used Aaron's html5 module.
 
Only problem: No one knew anything about building UIs. And im still very proud of the folks for coming up with what we're running as of today.
@PM2Ring Aye, though i wonder if a case should be made for letting this looping happen over at jinja instead of constructing the string in python or not. I'd imagine doing this in a templating engine is considered better.
I am assuming it's better suited to be done on templating side. (Please correct me if im assuming wrong.)
 
Back before HTML5 we used to do crazy things with tables. One friend of mine used them for simple bitmap graphics. They were a bit slow, but it was better than nothing.
 
In terms of speed, I actually have no numbers or actually an idea of how I'd time it but it logically (to me at least) belongs in the template
I guess it's a case of just timing render_template with all Jinja vs all the string concatenation
 
@ParitoshSingh Oh, sure. Doing it directly in plain Python isn't ideal, but it's tolerable for simple stuff.
 
Yeah HTML5 was pretty huge, wasn't it? We take it for granted today, and HTML5 has been around whenever i've done anything on the web, but i've heard about the time it wasn't a thing
I do remember, as a kid, playing games online that required adobe flash and stuff though :P
 
7:44 PM
It was a huge leap forward. Also, back then there were major browser incompatibilities, so it was almost impossible to make anything (apart from very simple pages) look good on all the major browsers, which is why stuff like jQuery became so popular.
@roganjosh Python string concatenation in a loop is pretty slow, mostly because strings are immutable. It has been optimized a fair bit since the early days of Python 2, but those optimizations only go so far, and things bog down when the strings are long.
 
Sure. I was just trying to think about how I could set up a %timeit test case
I'm so used to actually serving pages with render_template but actually, that's only gonna call Jinja and doesn't actually have to return anything. So it's relatively easy to benchmark the timing
@ParitoshSingh how big is the table?
 
It's around 31 columns and perhaps only, say, 500 rows so far
It's super small for all intents and purposes. But i'd be curious to see timeits for larger tables too
 
I'm actually curious now. I don't like the code, but I also am conscious that I offload a lot onto Jinja just on a hunch that I don't actually know about
Hmm, does string size play a part in the speed of concatenation?
In setting up the test case, it's easy for me to take ints at random, convert them to strings, and concat them. But maybe I'm missing something in that vs. concatenating an address
 
8:01 PM
I'd assume yes, 100%. You need to allocate a new area for the whole new string, so the length makes a difference.
 
So what's a reasonable test case here? 20 character strings for each column?
 
Sure. Honestly, i expect even the ints to work just fine in that sense, the number of rows and columns introduce much more concatenations and should make a much greater impact by themselves
 
All that creating & destroying of the destination string object tends to fragment the memory pools after a while.
 
8:16 PM
This is gonna take me some time to be fair in timings. I expect it tomorrow, not tonight, sorry
 
all good, im expecting jinja to win outright, but should be interesting
 
Bit off more than I can chew for a Saturday evening :)
I suspect Jinja to win but that's an interesting problem that I created for myself
 
8:51 PM
misunderstanding, unlikely to help future readers stackoverflow.com/questions/58894890/…
 
wim
@Aran-Fey maybe
>>> timedelta(**parse("{minutes:d}:{seconds:d}", "12:34").named)
datetime.timedelta(seconds=754)
this is python-parse, the opposite of str.format.
 
interesting lib
I ended up just splitting on colons and summing up the segments though, because sometimes the minutes could actually exceed 60
 
00:00 - 21:0021:00 - 00:00

« first day (3318 days earlier)      last day (1629 days later) »